a9c0ece970e8ae9bbd4da4ce58a969424d876bfb
[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.1.  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 ** 6279 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-08-05 21:36:42 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.752 2008/08/04 20:13:27 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 ** Exactly one of the following macros must be defined in order to
379 ** specify which memory allocation subsystem to use.
380 **
381 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
382 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
383 **     SQLITE_MEMORY_SIZE            // internal allocator #1
384 **     SQLITE_MMAP_HEAP_SIZE         // internal mmap() allocator
385 **     SQLITE_POW2_MEMORY_SIZE       // internal power-of-two allocator
386 **
387 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
388 ** the default.
389 */
390 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
391     defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
392     defined(SQLITE_POW2_MEMORY_SIZE)>1
393 # error "At most one of the following compile-time configuration options\
394  is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG, SQLITE_MEMORY_SIZE,\
395  SQLITE_MMAP_HEAP_SIZE, SQLITE_POW2_MEMORY_SIZE"
396 #endif
397 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
398     defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
399     defined(SQLITE_POW2_MEMORY_SIZE)==0
400 # define SQLITE_SYSTEM_MALLOC 1
401 #endif
402
403 /*
404 ** If SQLITE_MALLOC_SOFT_LIMIT is defined, then try to keep the
405 ** sizes of memory allocations below this value where possible.
406 */
407 #if defined(SQLITE_POW2_MEMORY_SIZE) && !defined(SQLITE_MALLOC_SOFT_LIMIT)
408 # define SQLITE_MALLOC_SOFT_LIMIT 1024
409 #endif
410
411 /*
412 ** We need to define _XOPEN_SOURCE as follows in order to enable
413 ** recursive mutexes on most unix systems.  But Mac OS X is different.
414 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
415 ** so it is omitted there.  See ticket #2673.
416 **
417 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
418 ** implemented on some systems.  So we avoid defining it at all
419 ** if it is already defined or if it is unneeded because we are
420 ** not doing a threadsafe build.  Ticket #2681.
421 **
422 ** See also ticket #2741.
423 */
424 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
425 #  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
426 #endif
427
428 #if defined(SQLITE_TCL) || defined(TCLSH)
429 # include <tcl.h>
430 #endif
431
432 /*
433 ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
434 ** Setting NDEBUG makes the code smaller and run faster.  So the following
435 ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
436 ** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
437 ** feature.
438 */
439 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
440 # define NDEBUG 1
441 #endif
442
443 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
444 /************** Begin file sqlite3.h *****************************************/
445 /*
446 ** 2001 September 15
447 **
448 ** The author disclaims copyright to this source code.  In place of
449 ** a legal notice, here is a blessing:
450 **
451 **    May you do good and not evil.
452 **    May you find forgiveness for yourself and forgive others.
453 **    May you share freely, never taking more than you give.
454 **
455 *************************************************************************
456 ** This header file defines the interface that the SQLite library
457 ** presents to client programs.  If a C-function, structure, datatype,
458 ** or constant definition does not appear in this file, then it is
459 ** not a published API of SQLite, is subject to change without
460 ** notice, and should not be referenced by programs that use SQLite.
461 **
462 ** Some of the definitions that are in this file are marked as
463 ** "experimental".  Experimental interfaces are normally new
464 ** features recently added to SQLite.  We do not anticipate changes
465 ** to experimental interfaces but reserve to make minor changes if
466 ** experience from use "in the wild" suggest such changes are prudent.
467 **
468 ** The official C-language API documentation for SQLite is derived
469 ** from comments in this file.  This file is the authoritative source
470 ** on how SQLite interfaces are suppose to operate.
471 **
472 ** The name of this file under configuration management is "sqlite.h.in".
473 ** The makefile makes some minor changes to this file (such as inserting
474 ** the version number) and changes its name to "sqlite3.h" as
475 ** part of the build process.
476 **
477 ** @(#) $Id: sqlite.h.in,v 1.387 2008/08/05 17:53:23 drh Exp $
478 */
479 #ifndef _SQLITE3_H_
480 #define _SQLITE3_H_
481 #include <stdarg.h>     /* Needed for the definition of va_list */
482
483 /*
484 ** Make sure we can call this stuff from C++.
485 */
486 #if 0
487 extern "C" {
488 #endif
489
490
491 /*
492 ** Add the ability to override 'extern'
493 */
494 #ifndef SQLITE_EXTERN
495 # define SQLITE_EXTERN extern
496 #endif
497
498 /*
499 ** Ensure these symbols were not defined by some previous header file.
500 */
501 #ifdef SQLITE_VERSION
502 # undef SQLITE_VERSION
503 #endif
504 #ifdef SQLITE_VERSION_NUMBER
505 # undef SQLITE_VERSION_NUMBER
506 #endif
507
508 /*
509 ** CAPI3REF: Compile-Time Library Version Numbers {H10010} <S60100>
510 **
511 ** The SQLITE_VERSION and SQLITE_VERSION_NUMBER #defines in
512 ** the sqlite3.h file specify the version of SQLite with which
513 ** that header file is associated.
514 **
515 ** The "version" of SQLite is a string of the form "X.Y.Z".
516 ** The phrase "alpha" or "beta" might be appended after the Z.
517 ** The X value is major version number always 3 in SQLite3.
518 ** The X value only changes when backwards compatibility is
519 ** broken and we intend to never break backwards compatibility.
520 ** The Y value is the minor version number and only changes when
521 ** there are major feature enhancements that are forwards compatible
522 ** but not backwards compatible.
523 ** The Z value is the release number and is incremented with
524 ** each release but resets back to 0 whenever Y is incremented.
525 **
526 ** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()].
527 **
528 ** INVARIANTS:
529 **
530 ** {H10011} The SQLITE_VERSION #define in the sqlite3.h header file shall
531 **          evaluate to a string literal that is the SQLite version
532 **          with which the header file is associated.
533 **
534 ** {H10014} The SQLITE_VERSION_NUMBER #define shall resolve to an integer
535 **          with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z
536 **          are the major version, minor version, and release number.
537 */
538 #define SQLITE_VERSION         "3.6.1"
539 #define SQLITE_VERSION_NUMBER  3006001
540
541 /*
542 ** CAPI3REF: Run-Time Library Version Numbers {H10020} <S60100>
543 ** KEYWORDS: sqlite3_version
544 **
545 ** These features provide the same information as the [SQLITE_VERSION]
546 ** and [SQLITE_VERSION_NUMBER] #defines in the header, but are associated
547 ** with the library instead of the header file.  Cautious programmers might
548 ** include a check in their application to verify that
549 ** sqlite3_libversion_number() always returns the value
550 ** [SQLITE_VERSION_NUMBER].
551 **
552 ** The sqlite3_libversion() function returns the same information as is
553 ** in the sqlite3_version[] string constant.  The function is provided
554 ** for use in DLLs since DLL users usually do not have direct access to string
555 ** constants within the DLL.
556 **
557 ** INVARIANTS:
558 **
559 ** {H10021} The [sqlite3_libversion_number()] interface shall return
560 **          an integer equal to [SQLITE_VERSION_NUMBER].
561 **
562 ** {H10022} The [sqlite3_version] string constant shall contain
563 **          the text of the [SQLITE_VERSION] string.
564 **
565 ** {H10023} The [sqlite3_libversion()] function shall return
566 **          a pointer to the [sqlite3_version] string constant.
567 */
568 SQLITE_API const char sqlite3_version[];
569 SQLITE_API const char *sqlite3_libversion(void);
570 SQLITE_API int sqlite3_libversion_number(void);
571
572 /*
573 ** CAPI3REF: Test To See If The Library Is Threadsafe {H10100} <S60100>
574 **
575 ** SQLite can be compiled with or without mutexes.  When
576 ** the [SQLITE_THREADSAFE] C preprocessor macro is true, mutexes
577 ** are enabled and SQLite is threadsafe.  When that macro is false,
578 ** the mutexes are omitted.  Without the mutexes, it is not safe
579 ** to use SQLite concurrently from more than one thread.
580 **
581 ** Enabling mutexes incurs a measurable performance penalty.
582 ** So if speed is of utmost importance, it makes sense to disable
583 ** the mutexes.  But for maximum safety, mutexes should be enabled.
584 ** The default behavior is for mutexes to be enabled.
585 **
586 ** This interface can be used by a program to make sure that the
587 ** version of SQLite that it is linking against was compiled with
588 ** the desired setting of the [SQLITE_THREADSAFE] macro.
589 **
590 ** This interface only reports on the compile-time mutex setting
591 ** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
592 ** SQLITE_THREADSAFE=1 then mutexes are enabled by default but
593 ** can be fully or partially disabled using a call to [sqlite3_config()]
594 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
595 ** or [SQLITE_CONFIG_MUTEX].  The return value of this function shows
596 ** only the default compile-time setting, not any run-time changes
597 ** to that setting.
598 **
599 ** INVARIANTS:
600 **
601 ** {H10101} The [sqlite3_threadsafe()] function shall return nonzero if
602 **          SQLite was compiled with the its mutexes enabled by default
603 **          or zero if SQLite was compiled such that mutexes are
604 **          permanently disabled.
605 **
606 ** {H10102} The value returned by the [sqlite3_threadsafe()] function
607 **          shall not change when mutex setting are modified at
608 **          runtime using the [sqlite3_config()] interface and 
609 **          especially the [SQLITE_CONFIG_SINGLETHREAD],
610 **          [SQLITE_CONFIG_MULTITHREAD], [SQLITE_CONFIG_SERIALIZED],
611 **          and [SQLITE_CONFIG_MUTEX] verbs.
612 */
613 SQLITE_API int sqlite3_threadsafe(void);
614
615 /*
616 ** CAPI3REF: Database Connection Handle {H12000} <S40200>
617 ** KEYWORDS: {database connection} {database connections}
618 **
619 ** Each open SQLite database is represented by a pointer to an instance of
620 ** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
621 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
622 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
623 ** is its destructor.  There are many other interfaces (such as
624 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
625 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
626 ** sqlite3 object.
627 */
628 typedef struct sqlite3 sqlite3;
629
630 /*
631 ** CAPI3REF: 64-Bit Integer Types {H10200} <S10110>
632 ** KEYWORDS: sqlite_int64 sqlite_uint64
633 **
634 ** Because there is no cross-platform way to specify 64-bit integer types
635 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
636 **
637 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
638 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
639 ** compatibility only.
640 **
641 ** INVARIANTS:
642 **
643 ** {H10201} The [sqlite_int64] and [sqlite3_int64] type shall specify
644 **          a 64-bit signed integer.
645 **
646 ** {H10202} The [sqlite_uint64] and [sqlite3_uint64] type shall specify
647 **          a 64-bit unsigned integer.
648 */
649 #ifdef SQLITE_INT64_TYPE
650   typedef SQLITE_INT64_TYPE sqlite_int64;
651   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
652 #elif defined(_MSC_VER) || defined(__BORLANDC__)
653   typedef __int64 sqlite_int64;
654   typedef unsigned __int64 sqlite_uint64;
655 #else
656   typedef long long int sqlite_int64;
657   typedef unsigned long long int sqlite_uint64;
658 #endif
659 typedef sqlite_int64 sqlite3_int64;
660 typedef sqlite_uint64 sqlite3_uint64;
661
662 /*
663 ** If compiling for a processor that lacks floating point support,
664 ** substitute integer for floating-point.
665 */
666 #ifdef SQLITE_OMIT_FLOATING_POINT
667 # define double sqlite3_int64
668 #endif
669
670 /*
671 ** CAPI3REF: Closing A Database Connection {H12010} <S30100><S40200>
672 **
673 ** This routine is the destructor for the [sqlite3] object.
674 **
675 ** Applications should [sqlite3_finalize | finalize] all [prepared statements]
676 ** and [sqlite3_blob_close | close] all [BLOB handles] associated with
677 ** the [sqlite3] object prior to attempting to close the object.
678 ** The [sqlite3_next_stmt()] interface can be used to locate all
679 ** [prepared statements] associated with a [database connection] if desired.
680 ** Typical code might look like this:
681 **
682 ** <blockquote><pre>
683 ** sqlite3_stmt *pStmt;
684 ** while( (pStmt = sqlite3_next_stmt(db, 0))!=0 ){
685 ** &nbsp;   sqlite3_finalize(pStmt);
686 ** }
687 ** </pre></blockquote>
688 **
689 ** If [sqlite3_close()] is invoked while a transaction is open,
690 ** the transaction is automatically rolled back.
691 **
692 ** INVARIANTS:
693 **
694 ** {H12011} A successful call to [sqlite3_close(C)] shall destroy the
695 **          [database connection] object C.
696 **
697 ** {H12012} A successful call to [sqlite3_close(C)] shall return SQLITE_OK.
698 **
699 ** {H12013} A successful call to [sqlite3_close(C)] shall release all
700 **          memory and system resources associated with [database connection]
701 **          C.
702 **
703 ** {H12014} A call to [sqlite3_close(C)] on a [database connection] C that
704 **          has one or more open [prepared statements] shall fail with
705 **          an [SQLITE_BUSY] error code.
706 **
707 ** {H12015} A call to [sqlite3_close(C)] where C is a NULL pointer shall
708 **          return SQLITE_OK.
709 **
710 ** {H12019} When [sqlite3_close(C)] is invoked on a [database connection] C
711 **          that has a pending transaction, the transaction shall be
712 **          rolled back.
713 **
714 ** ASSUMPTIONS:
715 **
716 ** {A12016} The C parameter to [sqlite3_close(C)] must be either a NULL
717 **          pointer or an [sqlite3] object pointer obtained
718 **          from [sqlite3_open()], [sqlite3_open16()], or
719 **          [sqlite3_open_v2()], and not previously closed.
720 */
721 SQLITE_API int sqlite3_close(sqlite3 *);
722
723 /*
724 ** The type for a callback function.
725 ** This is legacy and deprecated.  It is included for historical
726 ** compatibility and is not documented.
727 */
728 typedef int (*sqlite3_callback)(void*,int,char**, char**);
729
730 /*
731 ** CAPI3REF: One-Step Query Execution Interface {H12100} <S10000>
732 **
733 ** The sqlite3_exec() interface is a convenient way of running one or more
734 ** SQL statements without having to write a lot of C code.  The UTF-8 encoded
735 ** SQL statements are passed in as the second parameter to sqlite3_exec().
736 ** The statements are evaluated one by one until either an error or
737 ** an interrupt is encountered, or until they are all done.  The 3rd parameter
738 ** is an optional callback that is invoked once for each row of any query
739 ** results produced by the SQL statements.  The 5th parameter tells where
740 ** to write any error messages.
741 **
742 ** The error message passed back through the 5th parameter is held
743 ** in memory obtained from [sqlite3_malloc()].  To avoid a memory leak,
744 ** the calling application should call [sqlite3_free()] on any error
745 ** message returned through the 5th parameter when it has finished using
746 ** the error message.
747 **
748 ** If the SQL statement in the 2nd parameter is NULL or an empty string
749 ** or a string containing only whitespace and comments, then no SQL
750 ** statements are evaluated and the database is not changed.
751 **
752 ** The sqlite3_exec() interface is implemented in terms of
753 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()].
754 ** The sqlite3_exec() routine does nothing to the database that cannot be done
755 ** by [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()].
756 **
757 ** INVARIANTS:
758 **
759 ** {H12101} A successful invocation of [sqlite3_exec(D,S,C,A,E)]
760 **          shall sequentially evaluate all of the UTF-8 encoded,
761 **          semicolon-separated SQL statements in the zero-terminated
762 **          string S within the context of the [database connection] D.
763 **
764 ** {H12102} If the S parameter to [sqlite3_exec(D,S,C,A,E)] is NULL then
765 **          the actions of the interface shall be the same as if the
766 **          S parameter were an empty string.
767 **
768 ** {H12104} The return value of [sqlite3_exec()] shall be [SQLITE_OK] if all
769 **          SQL statements run successfully and to completion.
770 **
771 ** {H12105} The return value of [sqlite3_exec()] shall be an appropriate
772 **          non-zero [error code] if any SQL statement fails.
773 **
774 ** {H12107} If one or more of the SQL statements handed to [sqlite3_exec()]
775 **          return results and the 3rd parameter is not NULL, then
776 **          the callback function specified by the 3rd parameter shall be
777 **          invoked once for each row of result.
778 **
779 ** {H12110} If the callback returns a non-zero value then [sqlite3_exec()]
780 **          shall abort the SQL statement it is currently evaluating,
781 **          skip all subsequent SQL statements, and return [SQLITE_ABORT].
782 **
783 ** {H12113} The [sqlite3_exec()] routine shall pass its 4th parameter through
784 **          as the 1st parameter of the callback.
785 **
786 ** {H12116} The [sqlite3_exec()] routine shall set the 2nd parameter of its
787 **          callback to be the number of columns in the current row of
788 **          result.
789 **
790 ** {H12119} The [sqlite3_exec()] routine shall set the 3rd parameter of its
791 **          callback to be an array of pointers to strings holding the
792 **          values for each column in the current result set row as
793 **          obtained from [sqlite3_column_text()].
794 **
795 ** {H12122} The [sqlite3_exec()] routine shall set the 4th parameter of its
796 **          callback to be an array of pointers to strings holding the
797 **          names of result columns as obtained from [sqlite3_column_name()].
798 **
799 ** {H12125} If the 3rd parameter to [sqlite3_exec()] is NULL then
800 **          [sqlite3_exec()] shall silently discard query results.
801 **
802 ** {H12131} If an error occurs while parsing or evaluating any of the SQL
803 **          statements in the S parameter of [sqlite3_exec(D,S,C,A,E)] and if
804 **          the E parameter is not NULL, then [sqlite3_exec()] shall store
805 **          in *E an appropriate error message written into memory obtained
806 **          from [sqlite3_malloc()].
807 **
808 ** {H12134} The [sqlite3_exec(D,S,C,A,E)] routine shall set the value of
809 **          *E to NULL if E is not NULL and there are no errors.
810 **
811 ** {H12137} The [sqlite3_exec(D,S,C,A,E)] function shall set the [error code]
812 **          and message accessible via [sqlite3_errcode()],
813 **          [sqlite3_errmsg()], and [sqlite3_errmsg16()].
814 **
815 ** {H12138} If the S parameter to [sqlite3_exec(D,S,C,A,E)] is NULL or an
816 **          empty string or contains nothing other than whitespace, comments,
817 **          and/or semicolons, then results of [sqlite3_errcode()],
818 **          [sqlite3_errmsg()], and [sqlite3_errmsg16()]
819 **          shall reset to indicate no errors.
820 **
821 ** ASSUMPTIONS:
822 **
823 ** {A12141} The first parameter to [sqlite3_exec()] must be an valid and open
824 **          [database connection].
825 **
826 ** {A12142} The database connection must not be closed while
827 **          [sqlite3_exec()] is running.
828 **
829 ** {A12143} The calling function should use [sqlite3_free()] to free
830 **          the memory that *errmsg is left pointing at once the error
831 **          message is no longer needed.
832 **
833 ** {A12145} The SQL statement text in the 2nd parameter to [sqlite3_exec()]
834 **          must remain unchanged while [sqlite3_exec()] is running.
835 */
836 SQLITE_API int sqlite3_exec(
837   sqlite3*,                                  /* An open database */
838   const char *sql,                           /* SQL to be evaluated */
839   int (*callback)(void*,int,char**,char**),  /* Callback function */
840   void *,                                    /* 1st argument to callback */
841   char **errmsg                              /* Error msg written here */
842 );
843
844 /*
845 ** CAPI3REF: Result Codes {H10210} <S10700>
846 ** KEYWORDS: SQLITE_OK {error code} {error codes}
847 ** KEYWORDS: {result code} {result codes}
848 **
849 ** Many SQLite functions return an integer result code from the set shown
850 ** here in order to indicates success or failure.
851 **
852 ** New error codes may be added in future versions of SQLite.
853 **
854 ** See also: [SQLITE_IOERR_READ | extended result codes]
855 */
856 #define SQLITE_OK           0   /* Successful result */
857 /* beginning-of-error-codes */
858 #define SQLITE_ERROR        1   /* SQL error or missing database */
859 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
860 #define SQLITE_PERM         3   /* Access permission denied */
861 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
862 #define SQLITE_BUSY         5   /* The database file is locked */
863 #define SQLITE_LOCKED       6   /* A table in the database is locked */
864 #define SQLITE_NOMEM        7   /* A malloc() failed */
865 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
866 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
867 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
868 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
869 #define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
870 #define SQLITE_FULL        13   /* Insertion failed because database is full */
871 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
872 #define SQLITE_PROTOCOL    15   /* NOT USED. Database lock protocol error */
873 #define SQLITE_EMPTY       16   /* Database is empty */
874 #define SQLITE_SCHEMA      17   /* The database schema changed */
875 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
876 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
877 #define SQLITE_MISMATCH    20   /* Data type mismatch */
878 #define SQLITE_MISUSE      21   /* Library used incorrectly */
879 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
880 #define SQLITE_AUTH        23   /* Authorization denied */
881 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
882 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
883 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
884 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
885 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
886 /* end-of-error-codes */
887
888 /*
889 ** CAPI3REF: Extended Result Codes {H10220} <S10700>
890 ** KEYWORDS: {extended error code} {extended error codes}
891 ** KEYWORDS: {extended result code} {extended result codes}
892 **
893 ** In its default configuration, SQLite API routines return one of 26 integer
894 ** [SQLITE_OK | result codes].  However, experience has shown that many of
895 ** these result codes are too coarse-grained.  They do not provide as
896 ** much information about problems as programmers might like.  In an effort to
897 ** address this, newer versions of SQLite (version 3.3.8 and later) include
898 ** support for additional result codes that provide more detailed information
899 ** about errors. The extended result codes are enabled or disabled
900 ** on a per database connection basis using the
901 ** [sqlite3_extended_result_codes()] API.
902 **
903 ** Some of the available extended result codes are listed here.
904 ** One may expect the number of extended result codes will be expand
905 ** over time.  Software that uses extended result codes should expect
906 ** to see new result codes in future releases of SQLite.
907 **
908 ** The SQLITE_OK result code will never be extended.  It will always
909 ** be exactly zero.
910 **
911 ** INVARIANTS:
912 **
913 ** {H10223} The symbolic name for an extended result code shall contains
914 **          a related primary result code as a prefix.
915 **
916 ** {H10224} Primary result code names shall contain a single "_" character.
917 **
918 ** {H10225} Extended result code names shall contain two or more "_" characters.
919 **
920 ** {H10226} The numeric value of an extended result code shall contain the
921 **          numeric value of its corresponding primary result code in
922 **          its least significant 8 bits.
923 */
924 #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
925 #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
926 #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
927 #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
928 #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
929 #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
930 #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
931 #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
932 #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
933 #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
934 #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
935 #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
936 #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
937 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
938
939 /*
940 ** CAPI3REF: Flags For File Open Operations {H10230} <H11120> <H12700>
941 **
942 ** These bit values are intended for use in the
943 ** 3rd parameter to the [sqlite3_open_v2()] interface and
944 ** in the 4th parameter to the xOpen method of the
945 ** [sqlite3_vfs] object.
946 */
947 #define SQLITE_OPEN_READONLY         0x00000001
948 #define SQLITE_OPEN_READWRITE        0x00000002
949 #define SQLITE_OPEN_CREATE           0x00000004
950 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008
951 #define SQLITE_OPEN_EXCLUSIVE        0x00000010
952 #define SQLITE_OPEN_MAIN_DB          0x00000100
953 #define SQLITE_OPEN_TEMP_DB          0x00000200
954 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400
955 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800
956 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000
957 #define SQLITE_OPEN_SUBJOURNAL       0x00002000
958 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000
959 #define SQLITE_OPEN_NOMUTEX          0x00008000
960
961 /*
962 ** CAPI3REF: Device Characteristics {H10240} <H11120>
963 **
964 ** The xDeviceCapabilities method of the [sqlite3_io_methods]
965 ** object returns an integer which is a vector of the these
966 ** bit values expressing I/O characteristics of the mass storage
967 ** device that holds the file that the [sqlite3_io_methods]
968 ** refers to.
969 **
970 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
971 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
972 ** mean that writes of blocks that are nnn bytes in size and
973 ** are aligned to an address which is an integer multiple of
974 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
975 ** that when data is appended to a file, the data is appended
976 ** first then the size of the file is extended, never the other
977 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
978 ** information is written to disk in the same order as calls
979 ** to xWrite().
980 */
981 #define SQLITE_IOCAP_ATOMIC          0x00000001
982 #define SQLITE_IOCAP_ATOMIC512       0x00000002
983 #define SQLITE_IOCAP_ATOMIC1K        0x00000004
984 #define SQLITE_IOCAP_ATOMIC2K        0x00000008
985 #define SQLITE_IOCAP_ATOMIC4K        0x00000010
986 #define SQLITE_IOCAP_ATOMIC8K        0x00000020
987 #define SQLITE_IOCAP_ATOMIC16K       0x00000040
988 #define SQLITE_IOCAP_ATOMIC32K       0x00000080
989 #define SQLITE_IOCAP_ATOMIC64K       0x00000100
990 #define SQLITE_IOCAP_SAFE_APPEND     0x00000200
991 #define SQLITE_IOCAP_SEQUENTIAL      0x00000400
992
993 /*
994 ** CAPI3REF: File Locking Levels {H10250} <H11120> <H11310>
995 **
996 ** SQLite uses one of these integer values as the second
997 ** argument to calls it makes to the xLock() and xUnlock() methods
998 ** of an [sqlite3_io_methods] object.
999 */
1000 #define SQLITE_LOCK_NONE          0
1001 #define SQLITE_LOCK_SHARED        1
1002 #define SQLITE_LOCK_RESERVED      2
1003 #define SQLITE_LOCK_PENDING       3
1004 #define SQLITE_LOCK_EXCLUSIVE     4
1005
1006 /*
1007 ** CAPI3REF: Synchronization Type Flags {H10260} <H11120>
1008 **
1009 ** When SQLite invokes the xSync() method of an
1010 ** [sqlite3_io_methods] object it uses a combination of
1011 ** these integer values as the second argument.
1012 **
1013 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1014 ** sync operation only needs to flush data to mass storage.  Inode
1015 ** information need not be flushed. The SQLITE_SYNC_NORMAL flag means
1016 ** to use normal fsync() semantics. The SQLITE_SYNC_FULL flag means
1017 ** to use Mac OS-X style fullsync instead of fsync().
1018 */
1019 #define SQLITE_SYNC_NORMAL        0x00002
1020 #define SQLITE_SYNC_FULL          0x00003
1021 #define SQLITE_SYNC_DATAONLY      0x00010
1022
1023 /*
1024 ** CAPI3REF: OS Interface Open File Handle {H11110} <S20110>
1025 **
1026 ** An [sqlite3_file] object represents an open file in the OS
1027 ** interface layer.  Individual OS interface implementations will
1028 ** want to subclass this object by appending additional fields
1029 ** for their own use.  The pMethods entry is a pointer to an
1030 ** [sqlite3_io_methods] object that defines methods for performing
1031 ** I/O operations on the open file.
1032 */
1033 typedef struct sqlite3_file sqlite3_file;
1034 struct sqlite3_file {
1035   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1036 };
1037
1038 /*
1039 ** CAPI3REF: OS Interface File Virtual Methods Object {H11120} <S20110>
1040 **
1041 ** Every file opened by the [sqlite3_vfs] xOpen method populates an
1042 ** [sqlite3_file] object (or, more commonly, a subclass of the
1043 ** [sqlite3_file] object) with a pointer to an instance of this object.
1044 ** This object defines the methods used to perform various operations
1045 ** against the open file represented by the [sqlite3_file] object.
1046 **
1047 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1048 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1049 ** The second choice is a Mac OS-X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1050 ** flag may be ORed in to indicate that only the data of the file
1051 ** and not its inode needs to be synced.
1052 **
1053 ** The integer values to xLock() and xUnlock() are one of
1054 ** <ul>
1055 ** <li> [SQLITE_LOCK_NONE],
1056 ** <li> [SQLITE_LOCK_SHARED],
1057 ** <li> [SQLITE_LOCK_RESERVED],
1058 ** <li> [SQLITE_LOCK_PENDING], or
1059 ** <li> [SQLITE_LOCK_EXCLUSIVE].
1060 ** </ul>
1061 ** xLock() increases the lock. xUnlock() decreases the lock.
1062 ** The xCheckReservedLock() method checks whether any database connection,
1063 ** either in this process or in some other process, is holding a RESERVED,
1064 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
1065 ** if such a lock exists and false otherwise.
1066 **
1067 ** The xFileControl() method is a generic interface that allows custom
1068 ** VFS implementations to directly control an open file using the
1069 ** [sqlite3_file_control()] interface.  The second "op" argument is an
1070 ** integer opcode.  The third argument is a generic pointer intended to
1071 ** point to a structure that may contain arguments or space in which to
1072 ** write return values.  Potential uses for xFileControl() might be
1073 ** functions to enable blocking locks with timeouts, to change the
1074 ** locking strategy (for example to use dot-file locks), to inquire
1075 ** about the status of a lock, or to break stale locks.  The SQLite
1076 ** core reserves all opcodes less than 100 for its own use.
1077 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1078 ** Applications that define a custom xFileControl method should use opcodes
1079 ** greater than 100 to avoid conflicts.
1080 **
1081 ** The xSectorSize() method returns the sector size of the
1082 ** device that underlies the file.  The sector size is the
1083 ** minimum write that can be performed without disturbing
1084 ** other bytes in the file.  The xDeviceCharacteristics()
1085 ** method returns a bit vector describing behaviors of the
1086 ** underlying device:
1087 **
1088 ** <ul>
1089 ** <li> [SQLITE_IOCAP_ATOMIC]
1090 ** <li> [SQLITE_IOCAP_ATOMIC512]
1091 ** <li> [SQLITE_IOCAP_ATOMIC1K]
1092 ** <li> [SQLITE_IOCAP_ATOMIC2K]
1093 ** <li> [SQLITE_IOCAP_ATOMIC4K]
1094 ** <li> [SQLITE_IOCAP_ATOMIC8K]
1095 ** <li> [SQLITE_IOCAP_ATOMIC16K]
1096 ** <li> [SQLITE_IOCAP_ATOMIC32K]
1097 ** <li> [SQLITE_IOCAP_ATOMIC64K]
1098 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
1099 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
1100 ** </ul>
1101 **
1102 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1103 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1104 ** mean that writes of blocks that are nnn bytes in size and
1105 ** are aligned to an address which is an integer multiple of
1106 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1107 ** that when data is appended to a file, the data is appended
1108 ** first then the size of the file is extended, never the other
1109 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1110 ** information is written to disk in the same order as calls
1111 ** to xWrite().
1112 */
1113 typedef struct sqlite3_io_methods sqlite3_io_methods;
1114 struct sqlite3_io_methods {
1115   int iVersion;
1116   int (*xClose)(sqlite3_file*);
1117   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1118   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1119   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1120   int (*xSync)(sqlite3_file*, int flags);
1121   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1122   int (*xLock)(sqlite3_file*, int);
1123   int (*xUnlock)(sqlite3_file*, int);
1124   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1125   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1126   int (*xSectorSize)(sqlite3_file*);
1127   int (*xDeviceCharacteristics)(sqlite3_file*);
1128   /* Additional methods may be added in future releases */
1129 };
1130
1131 /*
1132 ** CAPI3REF: Standard File Control Opcodes {H11310} <S30800>
1133 **
1134 ** These integer constants are opcodes for the xFileControl method
1135 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1136 ** interface.
1137 **
1138 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1139 ** opcode causes the xFileControl method to write the current state of
1140 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1141 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1142 ** into an integer that the pArg argument points to. This capability
1143 ** is used during testing and only needs to be supported when SQLITE_TEST
1144 ** is defined.
1145 */
1146 #define SQLITE_FCNTL_LOCKSTATE        1
1147
1148 /*
1149 ** CAPI3REF: Mutex Handle {H17110} <S20130>
1150 **
1151 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1152 ** abstract type for a mutex object.  The SQLite core never looks
1153 ** at the internal representation of an [sqlite3_mutex].  It only
1154 ** deals with pointers to the [sqlite3_mutex] object.
1155 **
1156 ** Mutexes are created using [sqlite3_mutex_alloc()].
1157 */
1158 typedef struct sqlite3_mutex sqlite3_mutex;
1159
1160 /*
1161 ** CAPI3REF: OS Interface Object {H11140} <S20100>
1162 **
1163 ** An instance of the sqlite3_vfs object defines the interface between
1164 ** the SQLite core and the underlying operating system.  The "vfs"
1165 ** in the name of the object stands for "virtual file system".
1166 **
1167 ** The value of the iVersion field is initially 1 but may be larger in
1168 ** future versions of SQLite.  Additional fields may be appended to this
1169 ** object when the iVersion value is increased.  Note that the structure
1170 ** of the sqlite3_vfs object changes in the transaction between
1171 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1172 ** modified.
1173 **
1174 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1175 ** structure used by this VFS.  mxPathname is the maximum length of
1176 ** a pathname in this VFS.
1177 **
1178 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1179 ** the pNext pointer.  The [sqlite3_vfs_register()]
1180 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1181 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1182 ** searches the list.  Neither the application code nor the VFS
1183 ** implementation should use the pNext pointer.
1184 **
1185 ** The pNext field is the only field in the sqlite3_vfs
1186 ** structure that SQLite will ever modify.  SQLite will only access
1187 ** or modify this field while holding a particular static mutex.
1188 ** The application should never modify anything within the sqlite3_vfs
1189 ** object once the object has been registered.
1190 **
1191 ** The zName field holds the name of the VFS module.  The name must
1192 ** be unique across all VFS modules.
1193 **
1194 ** {H11141} SQLite will guarantee that the zFilename parameter to xOpen
1195 ** is either a NULL pointer or string obtained
1196 ** from xFullPathname().  SQLite further guarantees that
1197 ** the string will be valid and unchanged until xClose() is
1198 ** called. {END}  Because of the previous sentense,
1199 ** the [sqlite3_file] can safely store a pointer to the
1200 ** filename if it needs to remember the filename for some reason.
1201 ** If the zFilename parameter is xOpen is a NULL pointer then xOpen
1202 ** must invite its own temporary name for the file.  Whenever the 
1203 ** xFilename parameter is NULL it will also be the case that the
1204 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1205 **
1206 ** {H11142} The flags argument to xOpen() includes all bits set in
1207 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1208 ** or [sqlite3_open16()] is used, then flags includes at least
1209 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. {END}
1210 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1211 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1212 **
1213 ** {H11143} SQLite will also add one of the following flags to the xOpen()
1214 ** call, depending on the object being opened:
1215 **
1216 ** <ul>
1217 ** <li>  [SQLITE_OPEN_MAIN_DB]
1218 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1219 ** <li>  [SQLITE_OPEN_TEMP_DB]
1220 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1221 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1222 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
1223 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1224 ** </ul> {END}
1225 **
1226 ** The file I/O implementation can use the object type flags to
1227 ** change the way it deals with files.  For example, an application
1228 ** that does not care about crash recovery or rollback might make
1229 ** the open of a journal file a no-op.  Writes to this journal would
1230 ** also be no-ops, and any attempt to read the journal would return
1231 ** SQLITE_IOERR.  Or the implementation might recognize that a database
1232 ** file will be doing page-aligned sector reads and writes in a random
1233 ** order and set up its I/O subsystem accordingly.
1234 **
1235 ** SQLite might also add one of the following flags to the xOpen method:
1236 **
1237 ** <ul>
1238 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1239 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1240 ** </ul>
1241 **
1242 ** {H11145} The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1243 ** deleted when it is closed.  {H11146} The [SQLITE_OPEN_DELETEONCLOSE]
1244 ** will be set for TEMP  databases, journals and for subjournals.
1245 **
1246 ** {H11147} The [SQLITE_OPEN_EXCLUSIVE] flag means the file should be opened
1247 ** for exclusive access.  This flag is set for all files except
1248 ** for the main database file.
1249 **
1250 ** {H11148} At least szOsFile bytes of memory are allocated by SQLite
1251 ** to hold the  [sqlite3_file] structure passed as the third
1252 ** argument to xOpen. {END}  The xOpen method does not have to
1253 ** allocate the structure; it should just fill it in.
1254 **
1255 ** {H11149} The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1256 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1257 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1258 ** to test whether a file is at least readable. {END}  The file can be a
1259 ** directory.
1260 **
1261 ** {H11150} SQLite will always allocate at least mxPathname+1 bytes for the
1262 ** output buffer xFullPathname. {H11151} The exact size of the output buffer
1263 ** is also passed as a parameter to both  methods. {END}  If the output buffer
1264 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1265 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1266 ** to prevent this by setting mxPathname to a sufficiently large value.
1267 **
1268 ** The xRandomness(), xSleep(), and xCurrentTime() interfaces
1269 ** are not strictly a part of the filesystem, but they are
1270 ** included in the VFS structure for completeness.
1271 ** The xRandomness() function attempts to return nBytes bytes
1272 ** of good-quality randomness into zOut.  The return value is
1273 ** the actual number of bytes of randomness obtained.
1274 ** The xSleep() method causes the calling thread to sleep for at
1275 ** least the number of microseconds given.  The xCurrentTime()
1276 ** method returns a Julian Day Number for the current date and time.
1277 */
1278 typedef struct sqlite3_vfs sqlite3_vfs;
1279 struct sqlite3_vfs {
1280   int iVersion;            /* Structure version number */
1281   int szOsFile;            /* Size of subclassed sqlite3_file */
1282   int mxPathname;          /* Maximum file pathname length */
1283   sqlite3_vfs *pNext;      /* Next registered VFS */
1284   const char *zName;       /* Name of this virtual file system */
1285   void *pAppData;          /* Pointer to application-specific data */
1286   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1287                int flags, int *pOutFlags);
1288   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1289   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1290   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1291   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1292   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1293   void *(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol);
1294   void (*xDlClose)(sqlite3_vfs*, void*);
1295   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1296   int (*xSleep)(sqlite3_vfs*, int microseconds);
1297   int (*xCurrentTime)(sqlite3_vfs*, double*);
1298   int (*xGetLastError)(sqlite3_vfs*, int, char *);
1299   /* New fields may be appended in figure versions.  The iVersion
1300   ** value will increment whenever this happens. */
1301 };
1302
1303 /*
1304 ** CAPI3REF: Flags for the xAccess VFS method {H11190} <H11140>
1305 **
1306 ** {H11191} These integer constants can be used as the third parameter to
1307 ** the xAccess method of an [sqlite3_vfs] object. {END}  They determine
1308 ** what kind of permissions the xAccess method is looking for.
1309 ** {H11192} With SQLITE_ACCESS_EXISTS, the xAccess method
1310 ** simply checks whether the file exists.
1311 ** {H11193} With SQLITE_ACCESS_READWRITE, the xAccess method
1312 ** checks whether the file is both readable and writable.
1313 ** {H11194} With SQLITE_ACCESS_READ, the xAccess method
1314 ** checks whether the file is readable.
1315 */
1316 #define SQLITE_ACCESS_EXISTS    0
1317 #define SQLITE_ACCESS_READWRITE 1
1318 #define SQLITE_ACCESS_READ      2
1319
1320 /*
1321 ** CAPI3REF: Initialize The SQLite Library {H10130} <S20000><S30100>
1322 **
1323 ** The sqlite3_initialize() routine initializes the
1324 ** SQLite library.  The sqlite3_shutdown() routine
1325 ** deallocates any resources that were allocated by sqlite3_initialize().
1326 **
1327 ** A call to sqlite3_initialize() is an "effective" call if it is
1328 ** the first time sqlite3_initialize() is invoked during the lifetime of
1329 ** the process, or if it is the first time sqlite3_initialize() is invoked
1330 ** following a call to sqlite3_shutdown().  Only an effective call
1331 ** of sqlite3_initialize() does any initialization.  All other calls
1332 ** are harmless no-ops.
1333 **
1334 ** Among other things, sqlite3_initialize() shall invoke
1335 ** sqlite3_os_init().  Similarly, sqlite3_shutdown()
1336 ** shall invoke sqlite3_os_end().
1337 **
1338 ** The sqlite3_initialize() routine returns SQLITE_OK on success.
1339 ** If for some reason, sqlite3_initialize() is unable to initialize
1340 ** the library (perhaps it is unable to allocate a needed resource such
1341 ** as a mutex) it returns an [error code] other than SQLITE_OK.
1342 **
1343 ** The sqlite3_initialize() routine is called internally by many other
1344 ** SQLite interfaces so that an application usually does not need to
1345 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1346 ** calls sqlite3_initialize() so the SQLite library will be automatically
1347 ** initialized when [sqlite3_open()] is called if it has not be initialized
1348 ** already.  However, if SQLite is compiled with the SQLITE_OMIT_AUTOINIT
1349 ** compile-time option, then the automatic calls to sqlite3_initialize()
1350 ** are omitted and the application must call sqlite3_initialize() directly
1351 ** prior to using any other SQLite interface.  For maximum portability,
1352 ** it is recommended that applications always invoke sqlite3_initialize()
1353 ** directly prior to using any other SQLite interface.  Future releases
1354 ** of SQLite may require this.  In other words, the behavior exhibited
1355 ** when SQLite is compiled with SQLITE_OMIT_AUTOINIT might become the
1356 ** default behavior in some future release of SQLite.
1357 **
1358 ** The sqlite3_os_init() routine does operating-system specific
1359 ** initialization of the SQLite library.  The sqlite3_os_end()
1360 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
1361 ** performed by these routines include allocation or deallocation
1362 ** of static resources, initialization of global variables,
1363 ** setting up a default [sqlite3_vfs] module, or setting up
1364 ** a default configuration using [sqlite3_config()].
1365 **
1366 ** The application should never invoke either sqlite3_os_init()
1367 ** or sqlite3_os_end() directly.  The application should only invoke
1368 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1369 ** interface is called automatically by sqlite3_initialize() and
1370 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1371 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1372 ** are built into SQLite when it is compiled for unix, windows, or os/2.
1373 ** When built for other platforms (using the SQLITE_OS_OTHER=1 compile-time
1374 ** option) the application must supply a suitable implementation for
1375 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1376 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1377 ** must return SQLITE_OK on success and some other [error code] upon
1378 ** failure.
1379 */
1380 SQLITE_API int sqlite3_initialize(void);
1381 SQLITE_API int sqlite3_shutdown(void);
1382 SQLITE_API int sqlite3_os_init(void);
1383 SQLITE_API int sqlite3_os_end(void);
1384
1385 /*
1386 ** CAPI3REF: Configuring The SQLite Library {H10145} <S20000><S30200>
1387 ** EXPERIMENTAL
1388 **
1389 ** The sqlite3_config() interface is used to make global configuration
1390 ** changes to SQLite in order to tune SQLite to the specific needs of
1391 ** the application.  The default configuration is recommended for most
1392 ** applications and so this routine is usually not necessary.  It is
1393 ** provided to support rare applications with unusual needs.
1394 **
1395 ** The sqlite3_config() interface is not threadsafe.  The application
1396 ** must insure that no other SQLite interfaces are invoked by other
1397 ** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1398 ** may only be invoked prior to library initialization using
1399 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1400 ** Note, however, that sqlite3_config() can be called as part of the
1401 ** implementation of an application-defined [sqlite3_os_init()].
1402 **
1403 ** The first argument to sqlite3_config() is an integer
1404 ** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines
1405 ** what property of SQLite is to be configured.  Subsequent arguments
1406 ** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option]
1407 ** in the first argument.
1408 **
1409 ** When a configuration option is set, sqlite3_config() returns SQLITE_OK.
1410 ** If the option is unknown or SQLite is unable to set the option
1411 ** then this routine returns a non-zero [error code].
1412 */
1413 SQLITE_API int sqlite3_config(int, ...);
1414
1415 /*
1416 ** CAPI3REF: Configure database connections  {H10180} <S20000>
1417 ** EXPERIMENTAL
1418 **
1419 ** The sqlite3_db_config() interface is used to make configuration
1420 ** changes to a [database connection].  The interface is similar to
1421 ** [sqlite3_config()] except that the changes apply to a single
1422 ** [database connection] (specified in the first argument).  The
1423 ** sqlite3_db_config() interface can only be used immediately after
1424 ** the database connection is created using [sqlite3_open()],
1425 ** [sqlite3_open16()], or [sqlite3_open_v2()].  
1426 **
1427 ** The second argument to sqlite3_db_config(D,V,...)  is the
1428 ** configuration verb - an integer code that indicates what
1429 ** aspect of the [database connection] is being configured.
1430 ** The only choice for this value is [SQLITE_DBCONFIG_LOOKASIDE].
1431 ** New verbs are likely to be added in future releases of SQLite.
1432 ** Additional arguments depend on the verb.
1433 */
1434 SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1435
1436 /*
1437 ** CAPI3REF: Memory Allocation Routines {H10155} <S20120>
1438 ** EXPERIMENTAL
1439 **
1440 ** An instance of this object defines the interface between SQLite
1441 ** and low-level memory allocation routines.
1442 **
1443 ** This object is used in only one place in the SQLite interface.
1444 ** A pointer to an instance of this object is the argument to
1445 ** [sqlite3_config()] when the configuration option is
1446 ** [SQLITE_CONFIG_MALLOC].  By creating an instance of this object
1447 ** and passing it to [sqlite3_config()] during configuration, an
1448 ** application can specify an alternative memory allocation subsystem
1449 ** for SQLite to use for all of its dynamic memory needs.
1450 **
1451 ** Note that SQLite comes with a built-in memory allocator that is
1452 ** perfectly adequate for the overwhelming majority of applications
1453 ** and that this object is only useful to a tiny minority of applications
1454 ** with specialized memory allocation requirements.  This object is
1455 ** also used during testing of SQLite in order to specify an alternative
1456 ** memory allocator that simulates memory out-of-memory conditions in
1457 ** order to verify that SQLite recovers gracefully from such
1458 ** conditions.
1459 **
1460 ** The xMalloc, xFree, and xRealloc methods must work like the
1461 ** malloc(), free(), and realloc() functions from the standard library.
1462 **
1463 ** xSize should return the allocated size of a memory allocation
1464 ** previously obtained from xMalloc or xRealloc.  The allocated size
1465 ** is always at least as big as the requested size but may be larger.
1466 **
1467 ** The xRoundup method returns what would be the allocated size of
1468 ** a memory allocation given a particular requested size.  Most memory
1469 ** allocators round up memory allocations at least to the next multiple
1470 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1471 **
1472 ** The xInit method initializes the memory allocator.  (For example,
1473 ** it might allocate any require mutexes or initialize internal data
1474 ** structures.  The xShutdown method is invoked (indirectly) by
1475 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1476 ** by xInit.  The pAppData pointer is used as the only parameter to
1477 ** xInit and xShutdown.
1478 */
1479 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1480 struct sqlite3_mem_methods {
1481   void *(*xMalloc)(int);         /* Memory allocation function */
1482   void (*xFree)(void*);          /* Free a prior allocation */
1483   void *(*xRealloc)(void*,int);  /* Resize an allocation */
1484   int (*xSize)(void*);           /* Return the size of an allocation */
1485   int (*xRoundup)(int);          /* Round up request size to allocation size */
1486   int (*xInit)(void*);           /* Initialize the memory allocator */
1487   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1488   void *pAppData;                /* Argument to xInit() and xShutdown() */
1489 };
1490
1491 /*
1492 ** CAPI3REF: Configuration Options {H10160} <S20000>
1493 ** EXPERIMENTAL
1494 **
1495 ** These constants are the available integer configuration options that
1496 ** can be passed as the first argument to the [sqlite3_config()] interface.
1497 **
1498 ** New configuration options may be added in future releases of SQLite.
1499 ** Existing configuration options might be discontinued.  Applications
1500 ** should check the return code from [sqlite3_config()] to make sure that
1501 ** the call worked.  The [sqlite3_config()] interface will return a
1502 ** non-zero [error code] if a discontinued or unsupported configuration option
1503 ** is invoked.
1504 **
1505 ** <dl>
1506 ** <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1507 ** <dd>There are no arguments to this option.  This option disables
1508 ** all mutexing and puts SQLite into a mode where it can only be used
1509 ** by a single thread.</dd>
1510 **
1511 ** <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1512 ** <dd>There are no arguments to this option.  This option disables
1513 ** mutexing on [database connection] and [prepared statement] objects.
1514 ** The application is responsible for serializing access to
1515 ** [database connections] and [prepared statements].  But other mutexes
1516 ** are enabled so that SQLite will be safe to use in a multi-threaded
1517 ** environment.</dd>
1518 **
1519 ** <dt>SQLITE_CONFIG_SERIALIZED</dt>
1520 ** <dd>There are no arguments to this option.  This option enables
1521 ** all mutexes including the recursive
1522 ** mutexes on [database connection] and [prepared statement] objects.
1523 ** In this mode (which is the default when SQLite is compiled with
1524 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1525 ** to [database connections] and [prepared statements] so that the
1526 ** application is free to use the same [database connection] or the
1527 ** same [prepared statement] in different threads at the same time.
1528 **
1529 ** <p>This configuration option merely sets the default mutex 
1530 ** behavior to serialize access to [database connections].  Individual
1531 ** [database connections] can override this setting
1532 ** using the [SQLITE_OPEN_NOMUTEX] flag to [sqlite3_open_v2()].</p></dd>
1533 **
1534 ** <dt>SQLITE_CONFIG_MALLOC</dt>
1535 ** <dd>This option takes a single argument which is a pointer to an
1536 ** instance of the [sqlite3_mem_methods] structure.  The argument specifies
1537 ** alternative low-level memory allocation routines to be used in place of
1538 ** the memory allocation routines built into SQLite.</dd>
1539 **
1540 ** <dt>SQLITE_CONFIG_GETMALLOC</dt>
1541 ** <dd>This option takes a single argument which is a pointer to an
1542 ** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
1543 ** structure is filled with the currently defined memory allocation routines.
1544 ** This option can be used to overload the default memory allocation
1545 ** routines with a wrapper that simulations memory allocation failure or
1546 ** tracks memory usage, for example.</dd>
1547 **
1548 ** <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1549 ** <dd>This option takes single argument of type int, interpreted as a 
1550 ** boolean, which enables or disables the collection of memory allocation 
1551 ** statistics. When disabled, the following SQLite interfaces become 
1552 ** non-operational:
1553 **   <ul>
1554 **   <li> [sqlite3_memory_used()]
1555 **   <li> [sqlite3_memory_highwater()]
1556 **   <li> [sqlite3_soft_heap_limit()]
1557 **   <li> [sqlite3_status()]
1558 **   </ul>
1559 ** </dd>
1560 **
1561 ** <dt>SQLITE_CONFIG_SCRATCH</dt>
1562 ** <dd>This option specifies a static memory buffer that SQLite can use for
1563 ** scratch memory.  There are three arguments:  A pointer to the memory, the
1564 ** size of each scratch buffer (sz), and the number of buffers (N).  The sz
1565 ** argument must be a multiple of 16. The sz parameter should be a few bytes
1566 ** larger than the actual scratch space required due internal overhead.
1567 ** The first
1568 ** argument should point to an allocation of at least sz*N bytes of memory.
1569 ** SQLite will use no more than one scratch buffer at once per thread, so
1570 ** N should be set to the expected maximum number of threads.  The sz
1571 ** parameter should be 6 times the size of the largest database page size.
1572 ** Scratch buffers are used as part of the btree balance operation.  If
1573 ** The btree balancer needs additional memory beyond what is provided by
1574 ** scratch buffers or if no scratch buffer space is specified, then SQLite
1575 ** goes to [sqlite3_malloc()] to obtain the memory it needs.</dd>
1576 **
1577 ** <dt>SQLITE_CONFIG_PAGECACHE</dt>
1578 ** <dd>This option specifies a static memory buffer that SQLite can use for
1579 ** the database page cache.  There are three arguments: A pointer to the
1580 ** memory, the size of each page buffer (sz), and the number of pages (N).
1581 ** The sz argument must be a power of two between 512 and 32768.  The first
1582 ** argument should point to an allocation of at least sz*N bytes of memory.
1583 ** SQLite will use the memory provided by the first argument to satisfy its
1584 ** memory needs for the first N pages that it adds to cache.  If additional
1585 ** page cache memory is needed beyond what is provided by this option, then
1586 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1587 ** The implementation might use one or more of the N buffers to hold 
1588 ** memory accounting information. </dd>
1589 **
1590 ** <dt>SQLITE_CONFIG_HEAP</dt>
1591 ** <dd>This option specifies a static memory buffer that SQLite will use
1592 ** for all of its dynamic memory allocation needs beyond those provided
1593 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
1594 ** There are three arguments: A pointer to the memory, the number of
1595 ** bytes in the memory buffer, and the minimum allocation size.  If
1596 ** the first pointer (the memory pointer) is NULL, then SQLite reverts
1597 ** to using its default memory allocator (the system malloc() implementation),
1598 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  If the
1599 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
1600 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
1601 ** allocator is engaged to handle all of SQLites memory allocation needs.</dd>
1602 **
1603 ** <dt>SQLITE_CONFIG_MUTEX</dt>
1604 ** <dd>This option takes a single argument which is a pointer to an
1605 ** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
1606 ** alternative low-level mutex routines to be used in place
1607 ** the mutex routines built into SQLite.</dd>
1608 **
1609 ** <dt>SQLITE_CONFIG_GETMUTEX</dt>
1610 ** <dd>This option takes a single argument which is a pointer to an
1611 ** instance of the [sqlite3_mutex_methods] structure.  The
1612 ** [sqlite3_mutex_methods]
1613 ** structure is filled with the currently defined mutex routines.
1614 ** This option can be used to overload the default mutex allocation
1615 ** routines with a wrapper used to track mutex usage for performance
1616 ** profiling or testing, for example.</dd>
1617 **
1618 ** <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1619 ** <dd>This option takes two arguments that determine the default
1620 ** memory allcation lookaside optimization.  The first argument is the
1621 ** size of each lookaside buffer slot and the second is the number of
1622 ** slots allocated to each database connection.</dd>
1623 **
1624 ** </dl>
1625 */
1626 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
1627 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
1628 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
1629 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
1630 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
1631 #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
1632 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
1633 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
1634 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
1635 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
1636 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
1637 #define SQLITE_CONFIG_CHUNKALLOC   12  /* int threshold */
1638 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
1639
1640 /*
1641 ** CAPI3REF: Configuration Options {H10170} <S20000>
1642 ** EXPERIMENTAL
1643 **
1644 ** These constants are the available integer configuration options that
1645 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
1646 **
1647 ** New configuration options may be added in future releases of SQLite.
1648 ** Existing configuration options might be discontinued.  Applications
1649 ** should check the return code from [sqlite3_db_config()] to make sure that
1650 ** the call worked.  The [sqlite3_db_config()] interface will return a
1651 ** non-zero [error code] if a discontinued or unsupported configuration option
1652 ** is invoked.
1653 **
1654 ** <dl>
1655 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
1656 ** <dd>This option takes three additional arguments that determine the 
1657 ** [lookaside memory allocator] configuration for the [database connection].
1658 ** The first argument (the third parameter to [sqlite3_db_config()] is a
1659 ** pointer to a memory buffer to use for lookaside memory.  The first
1660 ** argument may be NULL in which case SQLite will allocate the lookaside
1661 ** buffer itself using [sqlite3_malloc()].  The second argument is the
1662 ** size of each lookaside buffer slot and the third argument is the number of
1663 ** slots.  The size of the buffer in the first argument must be greater than
1664 ** or equal to the product of the second and third arguments.</dd>
1665 **
1666 ** </dl>
1667 */
1668 #define SQLITE_DBCONFIG_LOOKASIDE    1001  /* void* int int */
1669
1670
1671 /*
1672 ** CAPI3REF: Enable Or Disable Extended Result Codes {H12200} <S10700>
1673 **
1674 ** The sqlite3_extended_result_codes() routine enables or disables the
1675 ** [extended result codes] feature of SQLite. The extended result
1676 ** codes are disabled by default for historical compatibility considerations.
1677 **
1678 ** INVARIANTS:
1679 **
1680 ** {H12201} Each new [database connection] shall have the
1681 **          [extended result codes] feature disabled by default.
1682 **
1683 ** {H12202} The [sqlite3_extended_result_codes(D,F)] interface shall enable
1684 **          [extended result codes] for the  [database connection] D
1685 **          if the F parameter is true, or disable them if F is false.
1686 */
1687 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
1688
1689 /*
1690 ** CAPI3REF: Last Insert Rowid {H12220} <S10700>
1691 **
1692 ** Each entry in an SQLite table has a unique 64-bit signed
1693 ** integer key called the "rowid". The rowid is always available
1694 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
1695 ** names are not also used by explicitly declared columns. If
1696 ** the table has a column of type INTEGER PRIMARY KEY then that column
1697 ** is another alias for the rowid.
1698 **
1699 ** This routine returns the rowid of the most recent
1700 ** successful INSERT into the database from the [database connection]
1701 ** in the first argument.  If no successful INSERTs
1702 ** have ever occurred on that database connection, zero is returned.
1703 **
1704 ** If an INSERT occurs within a trigger, then the rowid of the inserted
1705 ** row is returned by this routine as long as the trigger is running.
1706 ** But once the trigger terminates, the value returned by this routine
1707 ** reverts to the last value inserted before the trigger fired.
1708 **
1709 ** An INSERT that fails due to a constraint violation is not a
1710 ** successful INSERT and does not change the value returned by this
1711 ** routine.  Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
1712 ** and INSERT OR ABORT make no changes to the return value of this
1713 ** routine when their insertion fails.  When INSERT OR REPLACE
1714 ** encounters a constraint violation, it does not fail.  The
1715 ** INSERT continues to completion after deleting rows that caused
1716 ** the constraint problem so INSERT OR REPLACE will always change
1717 ** the return value of this interface.
1718 **
1719 ** For the purposes of this routine, an INSERT is considered to
1720 ** be successful even if it is subsequently rolled back.
1721 **
1722 ** INVARIANTS:
1723 **
1724 ** {H12221} The [sqlite3_last_insert_rowid()] function returns the rowid
1725 **          of the most recent successful INSERT performed on the same
1726 **          [database connection] and within the same or higher level
1727 **          trigger context, or zero if there have been no qualifying inserts.
1728 **
1729 ** {H12223} The [sqlite3_last_insert_rowid()] function returns the
1730 **          same value when called from the same trigger context
1731 **          immediately before and after a ROLLBACK.
1732 **
1733 ** ASSUMPTIONS:
1734 **
1735 ** {A12232} If a separate thread performs a new INSERT on the same
1736 **          database connection while the [sqlite3_last_insert_rowid()]
1737 **          function is running and thus changes the last insert rowid,
1738 **          then the value returned by [sqlite3_last_insert_rowid()] is
1739 **          unpredictable and might not equal either the old or the new
1740 **          last insert rowid.
1741 */
1742 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
1743
1744 /*
1745 ** CAPI3REF: Count The Number Of Rows Modified {H12240} <S10600>
1746 **
1747 ** This function returns the number of database rows that were changed
1748 ** or inserted or deleted by the most recently completed SQL statement
1749 ** on the [database connection] specified by the first parameter.
1750 ** Only changes that are directly specified by the INSERT, UPDATE,
1751 ** or DELETE statement are counted.  Auxiliary changes caused by
1752 ** triggers are not counted. Use the [sqlite3_total_changes()] function
1753 ** to find the total number of changes including changes caused by triggers.
1754 **
1755 ** A "row change" is a change to a single row of a single table
1756 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
1757 ** are changed as side effects of REPLACE constraint resolution,
1758 ** rollback, ABORT processing, DROP TABLE, or by any other
1759 ** mechanisms do not count as direct row changes.
1760 **
1761 ** A "trigger context" is a scope of execution that begins and
1762 ** ends with the script of a trigger.  Most SQL statements are
1763 ** evaluated outside of any trigger.  This is the "top level"
1764 ** trigger context.  If a trigger fires from the top level, a
1765 ** new trigger context is entered for the duration of that one
1766 ** trigger.  Subtriggers create subcontexts for their duration.
1767 **
1768 ** Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
1769 ** not create a new trigger context.
1770 **
1771 ** This function returns the number of direct row changes in the
1772 ** most recent INSERT, UPDATE, or DELETE statement within the same
1773 ** trigger context.
1774 **
1775 ** Thus, when called from the top level, this function returns the
1776 ** number of changes in the most recent INSERT, UPDATE, or DELETE
1777 ** that also occurred at the top level.  Within the body of a trigger,
1778 ** the sqlite3_changes() interface can be called to find the number of
1779 ** changes in the most recently completed INSERT, UPDATE, or DELETE
1780 ** statement within the body of the same trigger.
1781 ** However, the number returned does not include changes
1782 ** caused by subtriggers since those have their own context.
1783 **
1784 ** SQLite implements the command "DELETE FROM table" without a WHERE clause
1785 ** by dropping and recreating the table.  (This is much faster than going
1786 ** through and deleting individual elements from the table.)  Because of this
1787 ** optimization, the deletions in "DELETE FROM table" are not row changes and
1788 ** will not be counted by the sqlite3_changes() or [sqlite3_total_changes()]
1789 ** functions, regardless of the number of elements that were originally
1790 ** in the table.  To get an accurate count of the number of rows deleted, use
1791 ** "DELETE FROM table WHERE 1" instead.
1792 **
1793 ** INVARIANTS:
1794 **
1795 ** {H12241} The [sqlite3_changes()] function shall return the number of
1796 **          row changes caused by the most recent INSERT, UPDATE,
1797 **          or DELETE statement on the same database connection and
1798 **          within the same or higher trigger context, or zero if there have
1799 **          not been any qualifying row changes.
1800 **
1801 ** {H12243} Statements of the form "DELETE FROM tablename" with no
1802 **          WHERE clause shall cause subsequent calls to
1803 **          [sqlite3_changes()] to return zero, regardless of the
1804 **          number of rows originally in the table.
1805 **
1806 ** ASSUMPTIONS:
1807 **
1808 ** {A12252} If a separate thread makes changes on the same database connection
1809 **          while [sqlite3_changes()] is running then the value returned
1810 **          is unpredictable and not meaningful.
1811 */
1812 SQLITE_API int sqlite3_changes(sqlite3*);
1813
1814 /*
1815 ** CAPI3REF: Total Number Of Rows Modified {H12260} <S10600>
1816 **
1817 ** This function returns the number of row changes caused by INSERT,
1818 ** UPDATE or DELETE statements since the [database connection] was opened.
1819 ** The count includes all changes from all trigger contexts.  However,
1820 ** the count does not include changes used to implement REPLACE constraints,
1821 ** do rollbacks or ABORT processing, or DROP table processing.
1822 ** The changes are counted as soon as the statement that makes them is
1823 ** completed (when the statement handle is passed to [sqlite3_reset()] or
1824 ** [sqlite3_finalize()]).
1825 **
1826 ** SQLite implements the command "DELETE FROM table" without a WHERE clause
1827 ** by dropping and recreating the table.  (This is much faster than going
1828 ** through and deleting individual elements from the table.)  Because of this
1829 ** optimization, the deletions in "DELETE FROM table" are not row changes and
1830 ** will not be counted by the sqlite3_changes() or [sqlite3_total_changes()]
1831 ** functions, regardless of the number of elements that were originally
1832 ** in the table.  To get an accurate count of the number of rows deleted, use
1833 ** "DELETE FROM table WHERE 1" instead.
1834 **
1835 ** See also the [sqlite3_changes()] interface.
1836 **
1837 ** INVARIANTS:
1838 **
1839 ** {H12261} The [sqlite3_total_changes()] returns the total number
1840 **          of row changes caused by INSERT, UPDATE, and/or DELETE
1841 **          statements on the same [database connection], in any
1842 **          trigger context, since the database connection was created.
1843 **
1844 ** {H12263} Statements of the form "DELETE FROM tablename" with no
1845 **          WHERE clause shall not change the value returned
1846 **          by [sqlite3_total_changes()].
1847 **
1848 ** ASSUMPTIONS:
1849 **
1850 ** {A12264} If a separate thread makes changes on the same database connection
1851 **          while [sqlite3_total_changes()] is running then the value
1852 **          returned is unpredictable and not meaningful.
1853 */
1854 SQLITE_API int sqlite3_total_changes(sqlite3*);
1855
1856 /*
1857 ** CAPI3REF: Interrupt A Long-Running Query {H12270} <S30500>
1858 **
1859 ** This function causes any pending database operation to abort and
1860 ** return at its earliest opportunity. This routine is typically
1861 ** called in response to a user action such as pressing "Cancel"
1862 ** or Ctrl-C where the user wants a long query operation to halt
1863 ** immediately.
1864 **
1865 ** It is safe to call this routine from a thread different from the
1866 ** thread that is currently running the database operation.  But it
1867 ** is not safe to call this routine with a [database connection] that
1868 ** is closed or might close before sqlite3_interrupt() returns.
1869 **
1870 ** If an SQL operation is very nearly finished at the time when
1871 ** sqlite3_interrupt() is called, then it might not have an opportunity
1872 ** to be interrupted and might continue to completion.
1873 **
1874 ** An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
1875 ** If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
1876 ** that is inside an explicit transaction, then the entire transaction
1877 ** will be rolled back automatically.
1878 **
1879 ** A call to sqlite3_interrupt() has no effect on SQL statements
1880 ** that are started after sqlite3_interrupt() returns.
1881 **
1882 ** INVARIANTS:
1883 **
1884 ** {H12271} The [sqlite3_interrupt()] interface will force all running
1885 **          SQL statements associated with the same database connection
1886 **          to halt after processing at most one additional row of data.
1887 **
1888 ** {H12272} Any SQL statement that is interrupted by [sqlite3_interrupt()]
1889 **          will return [SQLITE_INTERRUPT].
1890 **
1891 ** ASSUMPTIONS:
1892 **
1893 ** {A12279} If the database connection closes while [sqlite3_interrupt()]
1894 **          is running then bad things will likely happen.
1895 */
1896 SQLITE_API void sqlite3_interrupt(sqlite3*);
1897
1898 /*
1899 ** CAPI3REF: Determine If An SQL Statement Is Complete {H10510} <S70200>
1900 **
1901 ** These routines are useful for command-line input to determine if the
1902 ** currently entered text seems to form complete a SQL statement or
1903 ** if additional input is needed before sending the text into
1904 ** SQLite for parsing.  These routines return true if the input string
1905 ** appears to be a complete SQL statement.  A statement is judged to be
1906 ** complete if it ends with a semicolon token and is not a fragment of a
1907 ** CREATE TRIGGER statement.  Semicolons that are embedded within
1908 ** string literals or quoted identifier names or comments are not
1909 ** independent tokens (they are part of the token in which they are
1910 ** embedded) and thus do not count as a statement terminator.
1911 **
1912 ** These routines do not parse the SQL statements thus
1913 ** will not detect syntactically incorrect SQL.
1914 **
1915 ** INVARIANTS:
1916 **
1917 ** {H10511} A successful evaluation of [sqlite3_complete()] or
1918 **          [sqlite3_complete16()] functions shall
1919 **          return a numeric 1 if and only if the last non-whitespace
1920 **          token in their input is a semicolon that is not in between
1921 **          the BEGIN and END of a CREATE TRIGGER statement.
1922 **
1923 ** {H10512} If a memory allocation error occurs during an invocation
1924 **          of [sqlite3_complete()] or [sqlite3_complete16()] then the
1925 **          routine shall return [SQLITE_NOMEM].
1926 **
1927 ** ASSUMPTIONS:
1928 **
1929 ** {A10512} The input to [sqlite3_complete()] must be a zero-terminated
1930 **          UTF-8 string.
1931 **
1932 ** {A10513} The input to [sqlite3_complete16()] must be a zero-terminated
1933 **          UTF-16 string in native byte order.
1934 */
1935 SQLITE_API int sqlite3_complete(const char *sql);
1936 SQLITE_API int sqlite3_complete16(const void *sql);
1937
1938 /*
1939 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {H12310} <S40400>
1940 **
1941 ** This routine sets a callback function that might be invoked whenever
1942 ** an attempt is made to open a database table that another thread
1943 ** or process has locked.
1944 **
1945 ** If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
1946 ** is returned immediately upon encountering the lock. If the busy callback
1947 ** is not NULL, then the callback will be invoked with two arguments.
1948 **
1949 ** The first argument to the handler is a copy of the void* pointer which
1950 ** is the third argument to sqlite3_busy_handler().  The second argument to
1951 ** the handler callback is the number of times that the busy handler has
1952 ** been invoked for this locking event.  If the
1953 ** busy callback returns 0, then no additional attempts are made to
1954 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
1955 ** If the callback returns non-zero, then another attempt
1956 ** is made to open the database for reading and the cycle repeats.
1957 **
1958 ** The presence of a busy handler does not guarantee that it will be invoked
1959 ** when there is lock contention. If SQLite determines that invoking the busy
1960 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
1961 ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
1962 ** Consider a scenario where one process is holding a read lock that
1963 ** it is trying to promote to a reserved lock and
1964 ** a second process is holding a reserved lock that it is trying
1965 ** to promote to an exclusive lock.  The first process cannot proceed
1966 ** because it is blocked by the second and the second process cannot
1967 ** proceed because it is blocked by the first.  If both processes
1968 ** invoke the busy handlers, neither will make any progress.  Therefore,
1969 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
1970 ** will induce the first process to release its read lock and allow
1971 ** the second process to proceed.
1972 **
1973 ** The default busy callback is NULL.
1974 **
1975 ** The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
1976 ** when SQLite is in the middle of a large transaction where all the
1977 ** changes will not fit into the in-memory cache.  SQLite will
1978 ** already hold a RESERVED lock on the database file, but it needs
1979 ** to promote this lock to EXCLUSIVE so that it can spill cache
1980 ** pages into the database file without harm to concurrent
1981 ** readers.  If it is unable to promote the lock, then the in-memory
1982 ** cache will be left in an inconsistent state and so the error
1983 ** code is promoted from the relatively benign [SQLITE_BUSY] to
1984 ** the more severe [SQLITE_IOERR_BLOCKED].  This error code promotion
1985 ** forces an automatic rollback of the changes.  See the
1986 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
1987 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
1988 ** this is important.
1989 **
1990 ** There can only be a single busy handler defined for each
1991 ** [database connection].  Setting a new busy handler clears any
1992 ** previously set handler.  Note that calling [sqlite3_busy_timeout()]
1993 ** will also set or clear the busy handler.
1994 **
1995 ** INVARIANTS:
1996 **
1997 ** {H12311} The [sqlite3_busy_handler(D,C,A)] function shall replace
1998 **          busy callback in the [database connection] D with a new
1999 **          a new busy handler C and application data pointer A.
2000 **
2001 ** {H12312} Newly created [database connections] shall have a busy
2002 **          handler of NULL.
2003 **
2004 ** {H12314} When two or more [database connections] share a
2005 **          [sqlite3_enable_shared_cache | common cache],
2006 **          the busy handler for the database connection currently using
2007 **          the cache shall be invoked when the cache encounters a lock.
2008 **
2009 ** {H12316} If a busy handler callback returns zero, then the SQLite interface
2010 **          that provoked the locking event shall return [SQLITE_BUSY].
2011 **
2012 ** {H12318} SQLite shall invokes the busy handler with two arguments which
2013 **          are a copy of the pointer supplied by the 3rd parameter to
2014 **          [sqlite3_busy_handler()] and a count of the number of prior
2015 **          invocations of the busy handler for the same locking event.
2016 **
2017 ** ASSUMPTIONS:
2018 **
2019 ** {A12319} A busy handler must not close the database connection
2020 **          or [prepared statement] that invoked the busy handler.
2021 */
2022 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2023
2024 /*
2025 ** CAPI3REF: Set A Busy Timeout {H12340} <S40410>
2026 **
2027 ** This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2028 ** for a specified amount of time when a table is locked.  The handler
2029 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2030 ** have accumulated. {H12343} After "ms" milliseconds of sleeping,
2031 ** the handler returns 0 which causes [sqlite3_step()] to return
2032 ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2033 **
2034 ** Calling this routine with an argument less than or equal to zero
2035 ** turns off all busy handlers.
2036 **
2037 ** There can only be a single busy handler for a particular
2038 ** [database connection] any any given moment.  If another busy handler
2039 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
2040 ** this routine, that other busy handler is cleared.
2041 **
2042 ** INVARIANTS:
2043 **
2044 ** {H12341} The [sqlite3_busy_timeout()] function shall override any prior
2045 **          [sqlite3_busy_timeout()] or [sqlite3_busy_handler()] setting
2046 **          on the same [database connection].
2047 **
2048 ** {H12343} If the 2nd parameter to [sqlite3_busy_timeout()] is less than
2049 **          or equal to zero, then the busy handler shall be cleared so that
2050 **          all subsequent locking events immediately return [SQLITE_BUSY].
2051 **
2052 ** {H12344} If the 2nd parameter to [sqlite3_busy_timeout()] is a positive
2053 **          number N, then a busy handler shall be set that repeatedly calls
2054 **          the xSleep() method in the [sqlite3_vfs | VFS interface] until
2055 **          either the lock clears or until the cumulative sleep time
2056 **          reported back by xSleep() exceeds N milliseconds.
2057 */
2058 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2059
2060 /*
2061 ** CAPI3REF: Convenience Routines For Running Queries {H12370} <S10000>
2062 **
2063 ** Definition: A <b>result table</b> is memory data structure created by the
2064 ** [sqlite3_get_table()] interface.  A result table records the
2065 ** complete query results from one or more queries.
2066 **
2067 ** The table conceptually has a number of rows and columns.  But
2068 ** these numbers are not part of the result table itself.  These
2069 ** numbers are obtained separately.  Let N be the number of rows
2070 ** and M be the number of columns.
2071 **
2072 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2073 ** There are (N+1)*M elements in the array.  The first M pointers point
2074 ** to zero-terminated strings that  contain the names of the columns.
2075 ** The remaining entries all point to query results.  NULL values result
2076 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2077 ** string representation as returned by [sqlite3_column_text()].
2078 **
2079 ** A result table might consist of one or more memory allocations.
2080 ** It is not safe to pass a result table directly to [sqlite3_free()].
2081 ** A result table should be deallocated using [sqlite3_free_table()].
2082 **
2083 ** As an example of the result table format, suppose a query result
2084 ** is as follows:
2085 **
2086 ** <blockquote><pre>
2087 **        Name        | Age
2088 **        -----------------------
2089 **        Alice       | 43
2090 **        Bob         | 28
2091 **        Cindy       | 21
2092 ** </pre></blockquote>
2093 **
2094 ** There are two column (M==2) and three rows (N==3).  Thus the
2095 ** result table has 8 entries.  Suppose the result table is stored
2096 ** in an array names azResult.  Then azResult holds this content:
2097 **
2098 ** <blockquote><pre>
2099 **        azResult&#91;0] = "Name";
2100 **        azResult&#91;1] = "Age";
2101 **        azResult&#91;2] = "Alice";
2102 **        azResult&#91;3] = "43";
2103 **        azResult&#91;4] = "Bob";
2104 **        azResult&#91;5] = "28";
2105 **        azResult&#91;6] = "Cindy";
2106 **        azResult&#91;7] = "21";
2107 ** </pre></blockquote>
2108 **
2109 ** The sqlite3_get_table() function evaluates one or more
2110 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2111 ** string of its 2nd parameter.  It returns a result table to the
2112 ** pointer given in its 3rd parameter.
2113 **
2114 ** After the calling function has finished using the result, it should
2115 ** pass the pointer to the result table to sqlite3_free_table() in order to
2116 ** release the memory that was malloced.  Because of the way the
2117 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2118 ** function must not try to call [sqlite3_free()] directly.  Only
2119 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2120 **
2121 ** The sqlite3_get_table() interface is implemented as a wrapper around
2122 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2123 ** to any internal data structures of SQLite.  It uses only the public
2124 ** interface defined here.  As a consequence, errors that occur in the
2125 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2126 ** reflected in subsequent calls to [sqlite3_errcode()] or [sqlite3_errmsg()].
2127 **
2128 ** INVARIANTS:
2129 **
2130 ** {H12371} If a [sqlite3_get_table()] fails a memory allocation, then
2131 **          it shall free the result table under construction, abort the
2132 **          query in process, skip any subsequent queries, set the
2133 **          *pazResult output pointer to NULL and return [SQLITE_NOMEM].
2134 **
2135 ** {H12373} If the pnColumn parameter to [sqlite3_get_table()] is not NULL
2136 **          then a successful invocation of [sqlite3_get_table()] shall
2137 **          write the number of columns in the
2138 **          result set of the query into *pnColumn.
2139 **
2140 ** {H12374} If the pnRow parameter to [sqlite3_get_table()] is not NULL
2141 **          then a successful invocation of [sqlite3_get_table()] shall
2142 **          writes the number of rows in the
2143 **          result set of the query into *pnRow.
2144 **
2145 ** {H12376} A successful invocation of [sqlite3_get_table()] that computes
2146 **          N rows of result with C columns per row shall make *pazResult
2147 **          point to an array of pointers to (N+1)*C strings where the first
2148 **          C strings are column names as obtained from
2149 **          [sqlite3_column_name()] and the rest are column result values
2150 **          obtained from [sqlite3_column_text()].
2151 **
2152 ** {H12379} The values in the pazResult array returned by [sqlite3_get_table()]
2153 **          shall remain valid until cleared by [sqlite3_free_table()].
2154 **
2155 ** {H12382} When an error occurs during evaluation of [sqlite3_get_table()]
2156 **          the function shall set *pazResult to NULL, write an error message
2157 **          into memory obtained from [sqlite3_malloc()], make
2158 **          **pzErrmsg point to that error message, and return a
2159 **          appropriate [error code].
2160 */
2161 SQLITE_API int sqlite3_get_table(
2162   sqlite3 *db,          /* An open database */
2163   const char *zSql,     /* SQL to be evaluated */
2164   char ***pazResult,    /* Results of the query */
2165   int *pnRow,           /* Number of result rows written here */
2166   int *pnColumn,        /* Number of result columns written here */
2167   char **pzErrmsg       /* Error msg written here */
2168 );
2169 SQLITE_API void sqlite3_free_table(char **result);
2170
2171 /*
2172 ** CAPI3REF: Formatted String Printing Functions {H17400} <S70000><S20000>
2173 **
2174 ** These routines are workalikes of the "printf()" family of functions
2175 ** from the standard C library.
2176 **
2177 ** The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2178 ** results into memory obtained from [sqlite3_malloc()].
2179 ** The strings returned by these two routines should be
2180 ** released by [sqlite3_free()].  Both routines return a
2181 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2182 ** memory to hold the resulting string.
2183 **
2184 ** In sqlite3_snprintf() routine is similar to "snprintf()" from
2185 ** the standard C library.  The result is written into the
2186 ** buffer supplied as the second parameter whose size is given by
2187 ** the first parameter. Note that the order of the
2188 ** first two parameters is reversed from snprintf().  This is an
2189 ** historical accident that cannot be fixed without breaking
2190 ** backwards compatibility.  Note also that sqlite3_snprintf()
2191 ** returns a pointer to its buffer instead of the number of
2192 ** characters actually written into the buffer.  We admit that
2193 ** the number of characters written would be a more useful return
2194 ** value but we cannot change the implementation of sqlite3_snprintf()
2195 ** now without breaking compatibility.
2196 **
2197 ** As long as the buffer size is greater than zero, sqlite3_snprintf()
2198 ** guarantees that the buffer is always zero-terminated.  The first
2199 ** parameter "n" is the total size of the buffer, including space for
2200 ** the zero terminator.  So the longest string that can be completely
2201 ** written will be n-1 characters.
2202 **
2203 ** These routines all implement some additional formatting
2204 ** options that are useful for constructing SQL statements.
2205 ** All of the usual printf() formatting options apply.  In addition, there
2206 ** is are "%q", "%Q", and "%z" options.
2207 **
2208 ** The %q option works like %s in that it substitutes a null-terminated
2209 ** string from the argument list.  But %q also doubles every '\'' character.
2210 ** %q is designed for use inside a string literal.  By doubling each '\''
2211 ** character it escapes that character and allows it to be inserted into
2212 ** the string.
2213 **
2214 ** For example, assume the string variable zText contains text as follows:
2215 **
2216 ** <blockquote><pre>
2217 **  char *zText = "It's a happy day!";
2218 ** </pre></blockquote>
2219 **
2220 ** One can use this text in an SQL statement as follows:
2221 **
2222 ** <blockquote><pre>
2223 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2224 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2225 **  sqlite3_free(zSQL);
2226 ** </pre></blockquote>
2227 **
2228 ** Because the %q format string is used, the '\'' character in zText
2229 ** is escaped and the SQL generated is as follows:
2230 **
2231 ** <blockquote><pre>
2232 **  INSERT INTO table1 VALUES('It''s a happy day!')
2233 ** </pre></blockquote>
2234 **
2235 ** This is correct.  Had we used %s instead of %q, the generated SQL
2236 ** would have looked like this:
2237 **
2238 ** <blockquote><pre>
2239 **  INSERT INTO table1 VALUES('It's a happy day!');
2240 ** </pre></blockquote>
2241 **
2242 ** This second example is an SQL syntax error.  As a general rule you should
2243 ** always use %q instead of %s when inserting text into a string literal.
2244 **
2245 ** The %Q option works like %q except it also adds single quotes around
2246 ** the outside of the total string.  Additionally, if the parameter in the
2247 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2248 ** single quotes) in place of the %Q option.  So, for example, one could say:
2249 **
2250 ** <blockquote><pre>
2251 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2252 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2253 **  sqlite3_free(zSQL);
2254 ** </pre></blockquote>
2255 **
2256 ** The code above will render a correct SQL statement in the zSQL
2257 ** variable even if the zText variable is a NULL pointer.
2258 **
2259 ** The "%z" formatting option works exactly like "%s" with the
2260 ** addition that after the string has been read and copied into
2261 ** the result, [sqlite3_free()] is called on the input string. {END}
2262 **
2263 ** INVARIANTS:
2264 **
2265 ** {H17403}  The [sqlite3_mprintf()] and [sqlite3_vmprintf()] interfaces
2266 **           return either pointers to zero-terminated UTF-8 strings held in
2267 **           memory obtained from [sqlite3_malloc()] or NULL pointers if
2268 **           a call to [sqlite3_malloc()] fails.
2269 **
2270 ** {H17406}  The [sqlite3_snprintf()] interface writes a zero-terminated
2271 **           UTF-8 string into the buffer pointed to by the second parameter
2272 **           provided that the first parameter is greater than zero.
2273 **
2274 ** {H17407}  The [sqlite3_snprintf()] interface does not write slots of
2275 **           its output buffer (the second parameter) outside the range
2276 **           of 0 through N-1 (where N is the first parameter)
2277 **           regardless of the length of the string
2278 **           requested by the format specification.
2279 */
2280 SQLITE_API char *sqlite3_mprintf(const char*,...);
2281 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2282 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2283
2284 /*
2285 ** CAPI3REF: Memory Allocation Subsystem {H17300} <S20000>
2286 **
2287 ** The SQLite core  uses these three routines for all of its own
2288 ** internal memory allocation needs. "Core" in the previous sentence
2289 ** does not include operating-system specific VFS implementation.  The
2290 ** Windows VFS uses native malloc() and free() for some operations.
2291 **
2292 ** The sqlite3_malloc() routine returns a pointer to a block
2293 ** of memory at least N bytes in length, where N is the parameter.
2294 ** If sqlite3_malloc() is unable to obtain sufficient free
2295 ** memory, it returns a NULL pointer.  If the parameter N to
2296 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2297 ** a NULL pointer.
2298 **
2299 ** Calling sqlite3_free() with a pointer previously returned
2300 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2301 ** that it might be reused.  The sqlite3_free() routine is
2302 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2303 ** to sqlite3_free() is harmless.  After being freed, memory
2304 ** should neither be read nor written.  Even reading previously freed
2305 ** memory might result in a segmentation fault or other severe error.
2306 ** Memory corruption, a segmentation fault, or other severe error
2307 ** might result if sqlite3_free() is called with a non-NULL pointer that
2308 ** was not obtained from sqlite3_malloc() or sqlite3_free().
2309 **
2310 ** The sqlite3_realloc() interface attempts to resize a
2311 ** prior memory allocation to be at least N bytes, where N is the
2312 ** second parameter.  The memory allocation to be resized is the first
2313 ** parameter.  If the first parameter to sqlite3_realloc()
2314 ** is a NULL pointer then its behavior is identical to calling
2315 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2316 ** If the second parameter to sqlite3_realloc() is zero or
2317 ** negative then the behavior is exactly the same as calling
2318 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2319 ** sqlite3_realloc() returns a pointer to a memory allocation
2320 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
2321 ** If M is the size of the prior allocation, then min(N,M) bytes
2322 ** of the prior allocation are copied into the beginning of buffer returned
2323 ** by sqlite3_realloc() and the prior allocation is freed.
2324 ** If sqlite3_realloc() returns NULL, then the prior allocation
2325 ** is not freed.
2326 **
2327 ** The memory returned by sqlite3_malloc() and sqlite3_realloc()
2328 ** is always aligned to at least an 8 byte boundary. {END}
2329 **
2330 ** The default implementation of the memory allocation subsystem uses
2331 ** the malloc(), realloc() and free() provided by the standard C library.
2332 ** {H17382} However, if SQLite is compiled with the
2333 ** SQLITE_MEMORY_SIZE=<i>NNN</i> C preprocessor macro (where <i>NNN</i>
2334 ** is an integer), then SQLite create a static array of at least
2335 ** <i>NNN</i> bytes in size and uses that array for all of its dynamic
2336 ** memory allocation needs. {END}  Additional memory allocator options
2337 ** may be added in future releases.
2338 **
2339 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2340 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2341 ** implementation of these routines to be omitted.  That capability
2342 ** is no longer provided.  Only built-in memory allocators can be used.
2343 **
2344 ** The Windows OS interface layer calls
2345 ** the system malloc() and free() directly when converting
2346 ** filenames between the UTF-8 encoding used by SQLite
2347 ** and whatever filename encoding is used by the particular Windows
2348 ** installation.  Memory allocation errors are detected, but
2349 ** they are reported back as [SQLITE_CANTOPEN] or
2350 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2351 **
2352 ** INVARIANTS:
2353 **
2354 ** {H17303}  The [sqlite3_malloc(N)] interface returns either a pointer to
2355 **           a newly checked-out block of at least N bytes of memory
2356 **           that is 8-byte aligned, or it returns NULL if it is unable
2357 **           to fulfill the request.
2358 **
2359 ** {H17304}  The [sqlite3_malloc(N)] interface returns a NULL pointer if
2360 **           N is less than or equal to zero.
2361 **
2362 ** {H17305}  The [sqlite3_free(P)] interface releases memory previously
2363 **           returned from [sqlite3_malloc()] or [sqlite3_realloc()],
2364 **           making it available for reuse.
2365 **
2366 ** {H17306}  A call to [sqlite3_free(NULL)] is a harmless no-op.
2367 **
2368 ** {H17310}  A call to [sqlite3_realloc(0,N)] is equivalent to a call
2369 **           to [sqlite3_malloc(N)].
2370 **
2371 ** {H17312}  A call to [sqlite3_realloc(P,0)] is equivalent to a call
2372 **           to [sqlite3_free(P)].
2373 **
2374 ** {H17315}  The SQLite core uses [sqlite3_malloc()], [sqlite3_realloc()],
2375 **           and [sqlite3_free()] for all of its memory allocation and
2376 **           deallocation needs.
2377 **
2378 ** {H17318}  The [sqlite3_realloc(P,N)] interface returns either a pointer
2379 **           to a block of checked-out memory of at least N bytes in size
2380 **           that is 8-byte aligned, or a NULL pointer.
2381 **
2382 ** {H17321}  When [sqlite3_realloc(P,N)] returns a non-NULL pointer, it first
2383 **           copies the first K bytes of content from P into the newly
2384 **           allocated block, where K is the lesser of N and the size of
2385 **           the buffer P.
2386 **
2387 ** {H17322}  When [sqlite3_realloc(P,N)] returns a non-NULL pointer, it first
2388 **           releases the buffer P.
2389 **
2390 ** {H17323}  When [sqlite3_realloc(P,N)] returns NULL, the buffer P is
2391 **           not modified or released.
2392 **
2393 ** ASSUMPTIONS:
2394 **
2395 ** {A17350}  The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2396 **           must be either NULL or else pointers obtained from a prior
2397 **           invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2398 **           not yet been released.
2399 **
2400 ** {A17351}  The application must not read or write any part of
2401 **           a block of memory after it has been released using
2402 **           [sqlite3_free()] or [sqlite3_realloc()].
2403 */
2404 SQLITE_API void *sqlite3_malloc(int);
2405 SQLITE_API void *sqlite3_realloc(void*, int);
2406 SQLITE_API void sqlite3_free(void*);
2407
2408 /*
2409 ** CAPI3REF: Memory Allocator Statistics {H17370} <S30210>
2410 **
2411 ** SQLite provides these two interfaces for reporting on the status
2412 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2413 ** routines, which form the built-in memory allocation subsystem.
2414 **
2415 ** INVARIANTS:
2416 **
2417 ** {H17371} The [sqlite3_memory_used()] routine returns the number of bytes
2418 **          of memory currently outstanding (malloced but not freed).
2419 **
2420 ** {H17373} The [sqlite3_memory_highwater()] routine returns the maximum
2421 **          value of [sqlite3_memory_used()] since the high-water mark
2422 **          was last reset.
2423 **
2424 ** {H17374} The values returned by [sqlite3_memory_used()] and
2425 **          [sqlite3_memory_highwater()] include any overhead
2426 **          added by SQLite in its implementation of [sqlite3_malloc()],
2427 **          but not overhead added by the any underlying system library
2428 **          routines that [sqlite3_malloc()] may call.
2429 **
2430 ** {H17375} The memory high-water mark is reset to the current value of
2431 **          [sqlite3_memory_used()] if and only if the parameter to
2432 **          [sqlite3_memory_highwater()] is true.  The value returned
2433 **          by [sqlite3_memory_highwater(1)] is the high-water mark
2434 **          prior to the reset.
2435 */
2436 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2437 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2438
2439 /*
2440 ** CAPI3REF: Pseudo-Random Number Generator {H17390} <S20000>
2441 **
2442 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2443 ** select random ROWIDs when inserting new records into a table that
2444 ** already uses the largest possible ROWID.  The PRNG is also used for
2445 ** the build-in random() and randomblob() SQL functions.  This interface allows
2446 ** applications to access the same PRNG for other purposes.
2447 **
2448 ** A call to this routine stores N bytes of randomness into buffer P.
2449 **
2450 ** The first time this routine is invoked (either internally or by
2451 ** the application) the PRNG is seeded using randomness obtained
2452 ** from the xRandomness method of the default [sqlite3_vfs] object.
2453 ** On all subsequent invocations, the pseudo-randomness is generated
2454 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2455 ** method.
2456 **
2457 ** INVARIANTS:
2458 **
2459 ** {H17392} The [sqlite3_randomness(N,P)] interface writes N bytes of
2460 **          high-quality pseudo-randomness into buffer P.
2461 */
2462 SQLITE_API void sqlite3_randomness(int N, void *P);
2463
2464 /*
2465 ** CAPI3REF: Compile-Time Authorization Callbacks {H12500} <S70100>
2466 **
2467 ** This routine registers a authorizer callback with a particular
2468 ** [database connection], supplied in the first argument.
2469 ** The authorizer callback is invoked as SQL statements are being compiled
2470 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2471 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  At various
2472 ** points during the compilation process, as logic is being created
2473 ** to perform various actions, the authorizer callback is invoked to
2474 ** see if those actions are allowed.  The authorizer callback should
2475 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2476 ** specific action but allow the SQL statement to continue to be
2477 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2478 ** rejected with an error.  If the authorizer callback returns
2479 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2480 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2481 ** the authorizer will fail with an error message.
2482 **
2483 ** When the callback returns [SQLITE_OK], that means the operation
2484 ** requested is ok.  When the callback returns [SQLITE_DENY], the
2485 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2486 ** authorizer will fail with an error message explaining that
2487 ** access is denied.  If the authorizer code is [SQLITE_READ]
2488 ** and the callback returns [SQLITE_IGNORE] then the
2489 ** [prepared statement] statement is constructed to substitute
2490 ** a NULL value in place of the table column that would have
2491 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2492 ** return can be used to deny an untrusted user access to individual
2493 ** columns of a table.
2494 **
2495 ** The first parameter to the authorizer callback is a copy of the third
2496 ** parameter to the sqlite3_set_authorizer() interface. The second parameter
2497 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2498 ** the particular action to be authorized. The third through sixth parameters
2499 ** to the callback are zero-terminated strings that contain additional
2500 ** details about the action to be authorized.
2501 **
2502 ** An authorizer is used when [sqlite3_prepare | preparing]
2503 ** SQL statements from an untrusted source, to ensure that the SQL statements
2504 ** do not try to access data they are not allowed to see, or that they do not
2505 ** try to execute malicious statements that damage the database.  For
2506 ** example, an application may allow a user to enter arbitrary
2507 ** SQL queries for evaluation by a database.  But the application does
2508 ** not want the user to be able to make arbitrary changes to the
2509 ** database.  An authorizer could then be put in place while the
2510 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2511 ** disallows everything except [SELECT] statements.
2512 **
2513 ** Applications that need to process SQL from untrusted sources
2514 ** might also consider lowering resource limits using [sqlite3_limit()]
2515 ** and limiting database size using the [max_page_count] [PRAGMA]
2516 ** in addition to using an authorizer.
2517 **
2518 ** Only a single authorizer can be in place on a database connection
2519 ** at a time.  Each call to sqlite3_set_authorizer overrides the
2520 ** previous call.  Disable the authorizer by installing a NULL callback.
2521 ** The authorizer is disabled by default.
2522 **
2523 ** Note that the authorizer callback is invoked only during
2524 ** [sqlite3_prepare()] or its variants.  Authorization is not
2525 ** performed during statement evaluation in [sqlite3_step()].
2526 **
2527 ** INVARIANTS:
2528 **
2529 ** {H12501} The [sqlite3_set_authorizer(D,...)] interface registers a
2530 **          authorizer callback with database connection D.
2531 **
2532 ** {H12502} The authorizer callback is invoked as SQL statements are
2533 **          being compiled.
2534 **
2535 ** {H12503} If the authorizer callback returns any value other than
2536 **          [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY], then
2537 **          the [sqlite3_prepare_v2()] or equivalent call that caused
2538 **          the authorizer callback to run shall fail with an
2539 **          [SQLITE_ERROR] error code and an appropriate error message.
2540 **
2541 ** {H12504} When the authorizer callback returns [SQLITE_OK], the operation
2542 **          described is processed normally.
2543 **
2544 ** {H12505} When the authorizer callback returns [SQLITE_DENY], the
2545 **          [sqlite3_prepare_v2()] or equivalent call that caused the
2546 **          authorizer callback to run shall fail
2547 **          with an [SQLITE_ERROR] error code and an error message
2548 **          explaining that access is denied.
2549 **
2550 ** {H12506} If the authorizer code (the 2nd parameter to the authorizer
2551 **          callback) is [SQLITE_READ] and the authorizer callback returns
2552 **          [SQLITE_IGNORE], then the prepared statement is constructed to
2553 **          insert a NULL value in place of the table column that would have
2554 **          been read if [SQLITE_OK] had been returned.
2555 **
2556 ** {H12507} If the authorizer code (the 2nd parameter to the authorizer
2557 **          callback) is anything other than [SQLITE_READ], then
2558 **          a return of [SQLITE_IGNORE] has the same effect as [SQLITE_DENY].
2559 **
2560 ** {H12510} The first parameter to the authorizer callback is a copy of
2561 **          the third parameter to the [sqlite3_set_authorizer()] interface.
2562 **
2563 ** {H12511} The second parameter to the callback is an integer
2564 **          [SQLITE_COPY | action code] that specifies the particular action
2565 **          to be authorized.
2566 **
2567 ** {H12512} The third through sixth parameters to the callback are
2568 **          zero-terminated strings that contain
2569 **          additional details about the action to be authorized.
2570 **
2571 ** {H12520} Each call to [sqlite3_set_authorizer()] overrides
2572 **          any previously installed authorizer.
2573 **
2574 ** {H12521} A NULL authorizer means that no authorization
2575 **          callback is invoked.
2576 **
2577 ** {H12522} The default authorizer is NULL.
2578 */
2579 SQLITE_API int sqlite3_set_authorizer(
2580   sqlite3*,
2581   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2582   void *pUserData
2583 );
2584
2585 /*
2586 ** CAPI3REF: Authorizer Return Codes {H12590} <H12500>
2587 **
2588 ** The [sqlite3_set_authorizer | authorizer callback function] must
2589 ** return either [SQLITE_OK] or one of these two constants in order
2590 ** to signal SQLite whether or not the action is permitted.  See the
2591 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2592 ** information.
2593 */
2594 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2595 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2596
2597 /*
2598 ** CAPI3REF: Authorizer Action Codes {H12550} <H12500>
2599 **
2600 ** The [sqlite3_set_authorizer()] interface registers a callback function
2601 ** that is invoked to authorize certain SQL statement actions.  The
2602 ** second parameter to the callback is an integer code that specifies
2603 ** what action is being authorized.  These are the integer action codes that
2604 ** the authorizer callback may be passed.
2605 **
2606 ** These action code values signify what kind of operation is to be
2607 ** authorized.  The 3rd and 4th parameters to the authorization
2608 ** callback function will be parameters or NULL depending on which of these
2609 ** codes is used as the second parameter.  The 5th parameter to the
2610 ** authorizer callback is the name of the database ("main", "temp",
2611 ** etc.) if applicable.  The 6th parameter to the authorizer callback
2612 ** is the name of the inner-most trigger or view that is responsible for
2613 ** the access attempt or NULL if this access attempt is directly from
2614 ** top-level SQL code.
2615 **
2616 ** INVARIANTS:
2617 **
2618 ** {H12551} The second parameter to an
2619 **          [sqlite3_set_authorizer | authorizer callback] is always an integer
2620 **          [SQLITE_COPY | authorizer code] that specifies what action
2621 **          is being authorized.
2622 **
2623 ** {H12552} The 3rd and 4th parameters to the
2624 **          [sqlite3_set_authorizer | authorization callback]
2625 **          will be parameters or NULL depending on which
2626 **          [SQLITE_COPY | authorizer code] is used as the second parameter.
2627 **
2628 ** {H12553} The 5th parameter to the
2629 **          [sqlite3_set_authorizer | authorizer callback] is the name
2630 **          of the database (example: "main", "temp", etc.) if applicable.
2631 **
2632 ** {H12554} The 6th parameter to the
2633 **          [sqlite3_set_authorizer | authorizer callback] is the name
2634 **          of the inner-most trigger or view that is responsible for
2635 **          the access attempt or NULL if this access attempt is directly from
2636 **          top-level SQL code.
2637 */
2638 /******************************************* 3rd ************ 4th ***********/
2639 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2640 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2641 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2642 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2643 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2644 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2645 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2646 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2647 #define SQLITE_DELETE                9   /* Table Name      NULL            */
2648 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2649 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2650 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2651 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2652 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2653 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2654 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2655 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2656 #define SQLITE_INSERT               18   /* Table Name      NULL            */
2657 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2658 #define SQLITE_READ                 20   /* Table Name      Column Name     */
2659 #define SQLITE_SELECT               21   /* NULL            NULL            */
2660 #define SQLITE_TRANSACTION          22   /* NULL            NULL            */
2661 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2662 #define SQLITE_ATTACH               24   /* Filename        NULL            */
2663 #define SQLITE_DETACH               25   /* Database Name   NULL            */
2664 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2665 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
2666 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2667 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2668 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2669 #define SQLITE_FUNCTION             31   /* Function Name   NULL            */
2670 #define SQLITE_COPY                  0   /* No longer used */
2671
2672 /*
2673 ** CAPI3REF: Tracing And Profiling Functions {H12280} <S60400>
2674 ** EXPERIMENTAL
2675 **
2676 ** These routines register callback functions that can be used for
2677 ** tracing and profiling the execution of SQL statements.
2678 **
2679 ** The callback function registered by sqlite3_trace() is invoked at
2680 ** various times when an SQL statement is being run by [sqlite3_step()].
2681 ** The callback returns a UTF-8 rendering of the SQL statement text
2682 ** as the statement first begins executing.  Additional callbacks occur
2683 ** as each triggered subprogram is entered.  The callbacks for triggers
2684 ** contain a UTF-8 SQL comment that identifies the trigger.
2685 **
2686 ** The callback function registered by sqlite3_profile() is invoked
2687 ** as each SQL statement finishes.  The profile callback contains
2688 ** the original statement text and an estimate of wall-clock time
2689 ** of how long that statement took to run.
2690 **
2691 ** INVARIANTS:
2692 **
2693 ** {H12281} The callback function registered by [sqlite3_trace()] is
2694 **          whenever an SQL statement first begins to execute and
2695 **          whenever a trigger subprogram first begins to run.
2696 **
2697 ** {H12282} Each call to [sqlite3_trace()] overrides the previously
2698 **          registered trace callback.
2699 **
2700 ** {H12283} A NULL trace callback disables tracing.
2701 **
2702 ** {H12284} The first argument to the trace callback is a copy of
2703 **          the pointer which was the 3rd argument to [sqlite3_trace()].
2704 **
2705 ** {H12285} The second argument to the trace callback is a
2706 **          zero-terminated UTF-8 string containing the original text
2707 **          of the SQL statement as it was passed into [sqlite3_prepare_v2()]
2708 **          or the equivalent, or an SQL comment indicating the beginning
2709 **          of a trigger subprogram.
2710 **
2711 ** {H12287} The callback function registered by [sqlite3_profile()] is invoked
2712 **          as each SQL statement finishes.
2713 **
2714 ** {H12288} The first parameter to the profile callback is a copy of
2715 **          the 3rd parameter to [sqlite3_profile()].
2716 **
2717 ** {H12289} The second parameter to the profile callback is a
2718 **          zero-terminated UTF-8 string that contains the complete text of
2719 **          the SQL statement as it was processed by [sqlite3_prepare_v2()]
2720 **          or the equivalent.
2721 **
2722 ** {H12290} The third parameter to the profile callback is an estimate
2723 **          of the number of nanoseconds of wall-clock time required to
2724 **          run the SQL statement from start to finish.
2725 */
2726 SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2727 SQLITE_API void *sqlite3_profile(sqlite3*,
2728    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2729
2730 /*
2731 ** CAPI3REF: Query Progress Callbacks {H12910} <S60400>
2732 **
2733 ** This routine configures a callback function - the
2734 ** progress callback - that is invoked periodically during long
2735 ** running calls to [sqlite3_exec()], [sqlite3_step()] and
2736 ** [sqlite3_get_table()].  An example use for this
2737 ** interface is to keep a GUI updated during a large query.
2738 **
2739 ** If the progress callback returns non-zero, the operation is
2740 ** interrupted.  This feature can be used to implement a
2741 ** "Cancel" button on a GUI dialog box.
2742 **
2743 ** INVARIANTS:
2744 **
2745 ** {H12911} The callback function registered by sqlite3_progress_handler()
2746 **          is invoked periodically during long running calls to
2747 **          [sqlite3_step()].
2748 **
2749 ** {H12912} The progress callback is invoked once for every N virtual
2750 **          machine opcodes, where N is the second argument to
2751 **          the [sqlite3_progress_handler()] call that registered
2752 **          the callback.  If N is less than 1, sqlite3_progress_handler()
2753 **          acts as if a NULL progress handler had been specified.
2754 **
2755 ** {H12913} The progress callback itself is identified by the third
2756 **          argument to sqlite3_progress_handler().
2757 **
2758 ** {H12914} The fourth argument to sqlite3_progress_handler() is a
2759 **          void pointer passed to the progress callback
2760 **          function each time it is invoked.
2761 **
2762 ** {H12915} If a call to [sqlite3_step()] results in fewer than N opcodes
2763 **          being executed, then the progress callback is never invoked.
2764 **
2765 ** {H12916} Every call to [sqlite3_progress_handler()]
2766 **          overwrites any previously registered progress handler.
2767 **
2768 ** {H12917} If the progress handler callback is NULL then no progress
2769 **          handler is invoked.
2770 **
2771 ** {H12918} If the progress callback returns a result other than 0, then
2772 **          the behavior is a if [sqlite3_interrupt()] had been called.
2773 **          <S30500>
2774 */
2775 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2776
2777 /*
2778 ** CAPI3REF: Opening A New Database Connection {H12700} <S40200>
2779 **
2780 ** These routines open an SQLite database file whose name is given by the
2781 ** filename argument. The filename argument is interpreted as UTF-8 for
2782 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
2783 ** order for sqlite3_open16(). A [database connection] handle is usually
2784 ** returned in *ppDb, even if an error occurs.  The only exception is that
2785 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
2786 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
2787 ** object. If the database is opened (and/or created) successfully, then
2788 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.  The
2789 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
2790 ** an English language description of the error.
2791 **
2792 ** The default encoding for the database will be UTF-8 if
2793 ** sqlite3_open() or sqlite3_open_v2() is called and
2794 ** UTF-16 in the native byte order if sqlite3_open16() is used.
2795 **
2796 ** Whether or not an error occurs when it is opened, resources
2797 ** associated with the [database connection] handle should be released by
2798 ** passing it to [sqlite3_close()] when it is no longer required.
2799 **
2800 ** The sqlite3_open_v2() interface works like sqlite3_open()
2801 ** except that it accepts two additional parameters for additional control
2802 ** over the new database connection.  The flags parameter can take one of
2803 ** the following three values, optionally combined with the 
2804 ** [SQLITE_OPEN_NOMUTEX] flag:
2805 **
2806 ** <dl>
2807 ** <dt>[SQLITE_OPEN_READONLY]</dt>
2808 ** <dd>The database is opened in read-only mode.  If the database does not
2809 ** already exist, an error is returned.</dd>
2810 **
2811 ** <dt>[SQLITE_OPEN_READWRITE]</dt>
2812 ** <dd>The database is opened for reading and writing if possible, or reading
2813 ** only if the file is write protected by the operating system.  In either
2814 ** case the database must already exist, otherwise an error is returned.</dd>
2815 **
2816 ** <dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
2817 ** <dd>The database is opened for reading and writing, and is creates it if
2818 ** it does not already exist. This is the behavior that is always used for
2819 ** sqlite3_open() and sqlite3_open16().</dd>
2820 ** </dl>
2821 **
2822 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
2823 ** combinations shown above or one of the combinations shown above combined
2824 ** with the [SQLITE_OPEN_NOMUTEX] flag, then the behavior is undefined.
2825 **
2826 ** If the [SQLITE_OPEN_NOMUTEX] flag is set, then mutexes on the
2827 ** opened [database connection] are disabled and the appliation must
2828 ** insure that access to the [database connection] and its associated
2829 ** [prepared statements] is serialized.  The [SQLITE_OPEN_NOMUTEX] flag
2830 ** is the default behavior is SQLite is configured using the
2831 ** [SQLITE_CONFIG_MULTITHREAD] or [SQLITE_CONFIG_SINGLETHREAD] options
2832 ** to [sqlite3_config()].  The [SQLITE_OPEN_NOMUTEX] flag only makes a
2833 ** difference when SQLite is in its default [SQLITE_CONFIG_SERIALIZED] mode.
2834 **
2835 ** If the filename is ":memory:", then a private, temporary in-memory database
2836 ** is created for the connection.  This in-memory database will vanish when
2837 ** the database connection is closed.  Future versions of SQLite might
2838 ** make use of additional special filenames that begin with the ":" character.
2839 ** It is recommended that when a database filename actually does begin with
2840 ** a ":" character you should prefix the filename with a pathname such as
2841 ** "./" to avoid ambiguity.
2842 **
2843 ** If the filename is an empty string, then a private, temporary
2844 ** on-disk database will be created.  This private database will be
2845 ** automatically deleted as soon as the database connection is closed.
2846 **
2847 ** The fourth parameter to sqlite3_open_v2() is the name of the
2848 ** [sqlite3_vfs] object that defines the operating system interface that
2849 ** the new database connection should use.  If the fourth parameter is
2850 ** a NULL pointer then the default [sqlite3_vfs] object is used.
2851 **
2852 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
2853 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
2854 ** codepage is currently defined.  Filenames containing international
2855 ** characters must be converted to UTF-8 prior to passing them into
2856 ** sqlite3_open() or sqlite3_open_v2().
2857 **
2858 ** INVARIANTS:
2859 **
2860 ** {H12701} The [sqlite3_open()], [sqlite3_open16()], and
2861 **          [sqlite3_open_v2()] interfaces create a new
2862 **          [database connection] associated with
2863 **          the database file given in their first parameter.
2864 **
2865 ** {H12702} The filename argument is interpreted as UTF-8
2866 **          for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16
2867 **          in the native byte order for [sqlite3_open16()].
2868 **
2869 ** {H12703} A successful invocation of [sqlite3_open()], [sqlite3_open16()],
2870 **          or [sqlite3_open_v2()] writes a pointer to a new
2871 **          [database connection] into *ppDb.
2872 **
2873 ** {H12704} The [sqlite3_open()], [sqlite3_open16()], and
2874 **          [sqlite3_open_v2()] interfaces return [SQLITE_OK] upon success,
2875 **          or an appropriate [error code] on failure.
2876 **
2877 ** {H12706} The default text encoding for a new database created using
2878 **          [sqlite3_open()] or [sqlite3_open_v2()] will be UTF-8.
2879 **
2880 ** {H12707} The default text encoding for a new database created using
2881 **          [sqlite3_open16()] will be UTF-16.
2882 **
2883 ** {H12709} The [sqlite3_open(F,D)] interface is equivalent to
2884 **          [sqlite3_open_v2(F,D,G,0)] where the G parameter is
2885 **          [SQLITE_OPEN_READWRITE]|[SQLITE_OPEN_CREATE].
2886 **
2887 ** {H12711} If the G parameter to [sqlite3_open_v2(F,D,G,V)] contains the
2888 **          bit value [SQLITE_OPEN_READONLY] then the database is opened
2889 **          for reading only.
2890 **
2891 ** {H12712} If the G parameter to [sqlite3_open_v2(F,D,G,V)] contains the
2892 **          bit value [SQLITE_OPEN_READWRITE] then the database is opened
2893 **          reading and writing if possible, or for reading only if the
2894 **          file is write protected by the operating system.
2895 **
2896 ** {H12713} If the G parameter to [sqlite3_open(v2(F,D,G,V)] omits the
2897 **          bit value [SQLITE_OPEN_CREATE] and the database does not
2898 **          previously exist, an error is returned.
2899 **
2900 ** {H12714} If the G parameter to [sqlite3_open(v2(F,D,G,V)] contains the
2901 **          bit value [SQLITE_OPEN_CREATE] and the database does not
2902 **          previously exist, then an attempt is made to create and
2903 **          initialize the database.
2904 **
2905 ** {H12717} If the filename argument to [sqlite3_open()], [sqlite3_open16()],
2906 **          or [sqlite3_open_v2()] is ":memory:", then an private,
2907 **          ephemeral, in-memory database is created for the connection.
2908 **          <todo>Is SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE required
2909 **          in sqlite3_open_v2()?</todo>
2910 **
2911 ** {H12719} If the filename is NULL or an empty string, then a private,
2912 **          ephemeral on-disk database will be created.
2913 **          <todo>Is SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE required
2914 **          in sqlite3_open_v2()?</todo>
2915 **
2916 ** {H12721} The [database connection] created by [sqlite3_open_v2(F,D,G,V)]
2917 **          will use the [sqlite3_vfs] object identified by the V parameter,
2918 **          or the default [sqlite3_vfs] object if V is a NULL pointer.
2919 **
2920 ** {H12723} Two [database connections] will share a common cache if both were
2921 **          opened with the same VFS while [shared cache mode] was enabled and
2922 **          if both filenames compare equal using memcmp() after having been
2923 **          processed by the [sqlite3_vfs | xFullPathname] method of the VFS.
2924 */
2925 SQLITE_API int sqlite3_open(
2926   const char *filename,   /* Database filename (UTF-8) */
2927   sqlite3 **ppDb          /* OUT: SQLite db handle */
2928 );
2929 SQLITE_API int sqlite3_open16(
2930   const void *filename,   /* Database filename (UTF-16) */
2931   sqlite3 **ppDb          /* OUT: SQLite db handle */
2932 );
2933 SQLITE_API int sqlite3_open_v2(
2934   const char *filename,   /* Database filename (UTF-8) */
2935   sqlite3 **ppDb,         /* OUT: SQLite db handle */
2936   int flags,              /* Flags */
2937   const char *zVfs        /* Name of VFS module to use */
2938 );
2939
2940 /*
2941 ** CAPI3REF: Error Codes And Messages {H12800} <S60200>
2942 **
2943 ** The sqlite3_errcode() interface returns the numeric [result code] or
2944 ** [extended result code] for the most recent failed sqlite3_* API call
2945 ** associated with a [database connection]. If a prior API call failed
2946 ** but the most recent API call succeeded, the return value from
2947 ** sqlite3_errcode() is undefined.
2948 **
2949 ** The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
2950 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
2951 ** Memory to hold the error message string is managed internally.
2952 ** The application does not need to worry about freeing the result.
2953 ** However, the error string might be overwritten or deallocated by
2954 ** subsequent calls to other SQLite interface functions.
2955 **
2956 ** If an interface fails with SQLITE_MISUSE, that means the interface
2957 ** was invoked incorrectly by the application.  In that case, the
2958 ** error code and message may or may not be set.
2959 **
2960 ** INVARIANTS:
2961 **
2962 ** {H12801} The [sqlite3_errcode(D)] interface returns the numeric
2963 **          [result code] or [extended result code] for the most recently
2964 **          failed interface call associated with the [database connection] D.
2965 **
2966 ** {H12803} The [sqlite3_errmsg(D)] and [sqlite3_errmsg16(D)]
2967 **          interfaces return English-language text that describes
2968 **          the error in the mostly recently failed interface call,
2969 **          encoded as either UTF-8 or UTF-16 respectively.
2970 **
2971 ** {H12807} The strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()]
2972 **          are valid until the next SQLite interface call.
2973 **
2974 ** {H12808} Calls to API routines that do not return an error code
2975 **          (example: [sqlite3_data_count()]) do not
2976 **          change the error code or message returned by
2977 **          [sqlite3_errcode()], [sqlite3_errmsg()], or [sqlite3_errmsg16()].
2978 **
2979 ** {H12809} Interfaces that are not associated with a specific
2980 **          [database connection] (examples:
2981 **          [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()]
2982 **          do not change the values returned by
2983 **          [sqlite3_errcode()], [sqlite3_errmsg()], or [sqlite3_errmsg16()].
2984 */
2985 SQLITE_API int sqlite3_errcode(sqlite3 *db);
2986 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
2987 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
2988
2989 /*
2990 ** CAPI3REF: SQL Statement Object {H13000} <H13010>
2991 ** KEYWORDS: {prepared statement} {prepared statements}
2992 **
2993 ** An instance of this object represents a single SQL statement.
2994 ** This object is variously known as a "prepared statement" or a
2995 ** "compiled SQL statement" or simply as a "statement".
2996 **
2997 ** The life of a statement object goes something like this:
2998 **
2999 ** <ol>
3000 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
3001 **      function.
3002 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
3003 **      interfaces.
3004 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3005 ** <li> Reset the statement using [sqlite3_reset()] then go back
3006 **      to step 2.  Do this zero or more times.
3007 ** <li> Destroy the object using [sqlite3_finalize()].
3008 ** </ol>
3009 **
3010 ** Refer to documentation on individual methods above for additional
3011 ** information.
3012 */
3013 typedef struct sqlite3_stmt sqlite3_stmt;
3014
3015 /*
3016 ** CAPI3REF: Run-time Limits {H12760} <S20600>
3017 **
3018 ** This interface allows the size of various constructs to be limited
3019 ** on a connection by connection basis.  The first parameter is the
3020 ** [database connection] whose limit is to be set or queried.  The
3021 ** second parameter is one of the [limit categories] that define a
3022 ** class of constructs to be size limited.  The third parameter is the
3023 ** new limit for that construct.  The function returns the old limit.
3024 **
3025 ** If the new limit is a negative number, the limit is unchanged.
3026 ** For the limit category of SQLITE_LIMIT_XYZ there is a hard upper
3027 ** bound set by a compile-time C preprocessor macro named SQLITE_MAX_XYZ.
3028 ** (The "_LIMIT_" in the name is changed to "_MAX_".)
3029 ** Attempts to increase a limit above its hard upper bound are
3030 ** silently truncated to the hard upper limit.
3031 **
3032 ** Run time limits are intended for use in applications that manage
3033 ** both their own internal database and also databases that are controlled
3034 ** by untrusted external sources.  An example application might be a
3035 ** webbrowser that has its own databases for storing history and
3036 ** separate databases controlled by JavaScript applications downloaded
3037 ** off the Internet.  The internal databases can be given the
3038 ** large, default limits.  Databases managed by external sources can
3039 ** be given much smaller limits designed to prevent a denial of service
3040 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
3041 ** interface to further control untrusted SQL.  The size of the database
3042 ** created by an untrusted script can be contained using the
3043 ** [max_page_count] [PRAGMA].
3044 **
3045 ** New run-time limit categories may be added in future releases.
3046 **
3047 ** INVARIANTS:
3048 **
3049 ** {H12762} A successful call to [sqlite3_limit(D,C,V)] where V is
3050 **          positive changes the limit on the size of construct C in the
3051 **          [database connection] D to the lesser of V and the hard upper
3052 **          bound on the size of C that is set at compile-time.
3053 **
3054 ** {H12766} A successful call to [sqlite3_limit(D,C,V)] where V is negative
3055 **          leaves the state of the [database connection] D unchanged.
3056 **
3057 ** {H12769} A successful call to [sqlite3_limit(D,C,V)] returns the
3058 **          value of the limit on the size of construct C in the
3059 **          [database connection] D as it was prior to the call.
3060 */
3061 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
3062
3063 /*
3064 ** CAPI3REF: Run-Time Limit Categories {H12790} <H12760>
3065 ** KEYWORDS: {limit category} {limit categories}
3066 **
3067 ** These constants define various aspects of a [database connection]
3068 ** that can be limited in size by calls to [sqlite3_limit()].
3069 ** The meanings of the various limits are as follows:
3070 **
3071 ** <dl>
3072 ** <dt>SQLITE_LIMIT_LENGTH</dt>
3073 ** <dd>The maximum size of any string or BLOB or table row.<dd>
3074 **
3075 ** <dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3076 ** <dd>The maximum length of an SQL statement.</dd>
3077 **
3078 ** <dt>SQLITE_LIMIT_COLUMN</dt>
3079 ** <dd>The maximum number of columns in a table definition or in the
3080 ** result set of a SELECT or the maximum number of columns in an index
3081 ** or in an ORDER BY or GROUP BY clause.</dd>
3082 **
3083 ** <dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3084 ** <dd>The maximum depth of the parse tree on any expression.</dd>
3085 **
3086 ** <dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3087 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>
3088 **
3089 ** <dt>SQLITE_LIMIT_VDBE_OP</dt>
3090 ** <dd>The maximum number of instructions in a virtual machine program
3091 ** used to implement an SQL statement.</dd>
3092 **
3093 ** <dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3094 ** <dd>The maximum number of arguments on a function.</dd>
3095 **
3096 ** <dt>SQLITE_LIMIT_ATTACHED</dt>
3097 ** <dd>The maximum number of attached databases.</dd>
3098 **
3099 ** <dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3100 ** <dd>The maximum length of the pattern argument to the LIKE or
3101 ** GLOB operators.</dd>
3102 **
3103 ** <dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3104 ** <dd>The maximum number of variables in an SQL statement that can
3105 ** be bound.</dd>
3106 ** </dl>
3107 */
3108 #define SQLITE_LIMIT_LENGTH                    0
3109 #define SQLITE_LIMIT_SQL_LENGTH                1
3110 #define SQLITE_LIMIT_COLUMN                    2
3111 #define SQLITE_LIMIT_EXPR_DEPTH                3
3112 #define SQLITE_LIMIT_COMPOUND_SELECT           4
3113 #define SQLITE_LIMIT_VDBE_OP                   5
3114 #define SQLITE_LIMIT_FUNCTION_ARG              6
3115 #define SQLITE_LIMIT_ATTACHED                  7
3116 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3117 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
3118
3119 /*
3120 ** CAPI3REF: Compiling An SQL Statement {H13010} <S10000>
3121 ** KEYWORDS: {SQL statement compiler}
3122 **
3123 ** To execute an SQL query, it must first be compiled into a byte-code
3124 ** program using one of these routines.
3125 **
3126 ** The first argument, "db", is a [database connection] obtained from a
3127 ** prior call to [sqlite3_open()], [sqlite3_open_v2()] or [sqlite3_open16()].
3128 **
3129 ** The second argument, "zSql", is the statement to be compiled, encoded
3130 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3131 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3132 ** use UTF-16.
3133 **
3134 ** If the nByte argument is less than zero, then zSql is read up to the
3135 ** first zero terminator. If nByte is non-negative, then it is the maximum
3136 ** number of  bytes read from zSql.  When nByte is non-negative, the
3137 ** zSql string ends at either the first '\000' or '\u0000' character or
3138 ** the nByte-th byte, whichever comes first. If the caller knows
3139 ** that the supplied string is nul-terminated, then there is a small
3140 ** performance advantage to be gained by passing an nByte parameter that
3141 ** is equal to the number of bytes in the input string <i>including</i>
3142 ** the nul-terminator bytes.
3143 **
3144 ** *pzTail is made to point to the first byte past the end of the
3145 ** first SQL statement in zSql.  These routines only compile the first
3146 ** statement in zSql, so *pzTail is left pointing to what remains
3147 ** uncompiled.
3148 **
3149 ** *ppStmt is left pointing to a compiled [prepared statement] that can be
3150 ** executed using [sqlite3_step()].  If there is an error, *ppStmt is set
3151 ** to NULL.  If the input text contains no SQL (if the input is an empty
3152 ** string or a comment) then *ppStmt is set to NULL.
3153 ** {A13018} The calling procedure is responsible for deleting the compiled
3154 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3155 **
3156 ** On success, [SQLITE_OK] is returned, otherwise an [error code] is returned.
3157 **
3158 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3159 ** recommended for all new programs. The two older interfaces are retained
3160 ** for backwards compatibility, but their use is discouraged.
3161 ** In the "v2" interfaces, the prepared statement
3162 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3163 ** original SQL text. This causes the [sqlite3_step()] interface to
3164 ** behave a differently in two ways:
3165 **
3166 ** <ol>
3167 ** <li>
3168 ** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3169 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3170 ** statement and try to run it again.  If the schema has changed in
3171 ** a way that makes the statement no longer valid, [sqlite3_step()] will still
3172 ** return [SQLITE_SCHEMA].  But unlike the legacy behavior, [SQLITE_SCHEMA] is
3173 ** now a fatal error.  Calling [sqlite3_prepare_v2()] again will not make the
3174 ** error go away.  Note: use [sqlite3_errmsg()] to find the text
3175 ** of the parsing error that results in an [SQLITE_SCHEMA] return.
3176 ** </li>
3177 **
3178 ** <li>
3179 ** When an error occurs, [sqlite3_step()] will return one of the detailed
3180 ** [error codes] or [extended error codes].  The legacy behavior was that
3181 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3182 ** and you would have to make a second call to [sqlite3_reset()] in order
3183 ** to find the underlying cause of the problem. With the "v2" prepare
3184 ** interfaces, the underlying reason for the error is returned immediately.
3185 ** </li>
3186 ** </ol>
3187 **
3188 ** INVARIANTS:
3189 **
3190 ** {H13011} The [sqlite3_prepare(db,zSql,...)] and
3191 **          [sqlite3_prepare_v2(db,zSql,...)] interfaces interpret the
3192 **          text in their zSql parameter as UTF-8.
3193 **
3194 ** {H13012} The [sqlite3_prepare16(db,zSql,...)] and
3195 **          [sqlite3_prepare16_v2(db,zSql,...)] interfaces interpret the
3196 **          text in their zSql parameter as UTF-16 in the native byte order.
3197 **
3198 ** {H13013} If the nByte argument to [sqlite3_prepare_v2(db,zSql,nByte,...)]
3199 **          and its variants is less than zero, the SQL text is
3200 **          read from zSql is read up to the first zero terminator.
3201 **
3202 ** {H13014} If the nByte argument to [sqlite3_prepare_v2(db,zSql,nByte,...)]
3203 **          and its variants is non-negative, then at most nBytes bytes of
3204 **          SQL text is read from zSql.
3205 **
3206 ** {H13015} In [sqlite3_prepare_v2(db,zSql,N,P,pzTail)] and its variants
3207 **          if the zSql input text contains more than one SQL statement
3208 **          and pzTail is not NULL, then *pzTail is made to point to the
3209 **          first byte past the end of the first SQL statement in zSql.
3210 **          <todo>What does *pzTail point to if there is one statement?</todo>
3211 **
3212 ** {H13016} A successful call to [sqlite3_prepare_v2(db,zSql,N,ppStmt,...)]
3213 **          or one of its variants writes into *ppStmt a pointer to a new
3214 **          [prepared statement] or a pointer to NULL if zSql contains
3215 **          nothing other than whitespace or comments.
3216 **
3217 ** {H13019} The [sqlite3_prepare_v2()] interface and its variants return
3218 **          [SQLITE_OK] or an appropriate [error code] upon failure.
3219 **
3220 ** {H13021} Before [sqlite3_prepare(db,zSql,nByte,ppStmt,pzTail)] or its
3221 **          variants returns an error (any value other than [SQLITE_OK]),
3222 **          they first set *ppStmt to NULL.
3223 */
3224 SQLITE_API int sqlite3_prepare(
3225   sqlite3 *db,            /* Database handle */
3226   const char *zSql,       /* SQL statement, UTF-8 encoded */
3227   int nByte,              /* Maximum length of zSql in bytes. */
3228   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3229   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3230 );
3231 SQLITE_API int sqlite3_prepare_v2(
3232   sqlite3 *db,            /* Database handle */
3233   const char *zSql,       /* SQL statement, UTF-8 encoded */
3234   int nByte,              /* Maximum length of zSql in bytes. */
3235   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3236   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3237 );
3238 SQLITE_API int sqlite3_prepare16(
3239   sqlite3 *db,            /* Database handle */
3240   const void *zSql,       /* SQL statement, UTF-16 encoded */
3241   int nByte,              /* Maximum length of zSql in bytes. */
3242   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3243   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3244 );
3245 SQLITE_API int sqlite3_prepare16_v2(
3246   sqlite3 *db,            /* Database handle */
3247   const void *zSql,       /* SQL statement, UTF-16 encoded */
3248   int nByte,              /* Maximum length of zSql in bytes. */
3249   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3250   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3251 );
3252
3253 /*
3254 ** CAPIREF: Retrieving Statement SQL {H13100} <H13000>
3255 **
3256 ** This interface can be used to retrieve a saved copy of the original
3257 ** SQL text used to create a [prepared statement] if that statement was
3258 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3259 **
3260 ** INVARIANTS:
3261 **
3262 ** {H13101} If the [prepared statement] passed as the argument to
3263 **          [sqlite3_sql()] was compiled using either [sqlite3_prepare_v2()] or
3264 **          [sqlite3_prepare16_v2()], then [sqlite3_sql()] returns
3265 **          a pointer to a zero-terminated string containing a UTF-8 rendering
3266 **          of the original SQL statement.
3267 **
3268 ** {H13102} If the [prepared statement] passed as the argument to
3269 **          [sqlite3_sql()] was compiled using either [sqlite3_prepare()] or
3270 **          [sqlite3_prepare16()], then [sqlite3_sql()] returns a NULL pointer.
3271 **
3272 ** {H13103} The string returned by [sqlite3_sql(S)] is valid until the
3273 **          [prepared statement] S is deleted using [sqlite3_finalize(S)].
3274 */
3275 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3276
3277 /*
3278 ** CAPI3REF: Dynamically Typed Value Object {H15000} <S20200>
3279 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3280 **
3281 ** SQLite uses the sqlite3_value object to represent all values
3282 ** that can be stored in a database table. SQLite uses dynamic typing
3283 ** for the values it stores. Values stored in sqlite3_value objects
3284 ** can be integers, floating point values, strings, BLOBs, or NULL.
3285 **
3286 ** An sqlite3_value object may be either "protected" or "unprotected".
3287 ** Some interfaces require a protected sqlite3_value.  Other interfaces
3288 ** will accept either a protected or an unprotected sqlite3_value.
3289 ** Every interface that accepts sqlite3_value arguments specifies
3290 ** whether or not it requires a protected sqlite3_value.
3291 **
3292 ** The terms "protected" and "unprotected" refer to whether or not
3293 ** a mutex is held.  A internal mutex is held for a protected
3294 ** sqlite3_value object but no mutex is held for an unprotected
3295 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
3296 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3297 ** or if SQLite is run in one of reduced mutex modes 
3298 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3299 ** then there is no distinction between protected and unprotected
3300 ** sqlite3_value objects and they can be used interchangeably.  However,
3301 ** for maximum code portability it is recommended that applications
3302 ** still make the distinction between between protected and unprotected
3303 ** sqlite3_value objects even when not strictly required.
3304 **
3305 ** The sqlite3_value objects that are passed as parameters into the
3306 ** implementation of [application-defined SQL functions] are protected.
3307 ** The sqlite3_value object returned by
3308 ** [sqlite3_column_value()] is unprotected.
3309 ** Unprotected sqlite3_value objects may only be used with
3310 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3311 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3312 ** interfaces require protected sqlite3_value objects.
3313 */
3314 typedef struct Mem sqlite3_value;
3315
3316 /*
3317 ** CAPI3REF: SQL Function Context Object {H16001} <S20200>
3318 **
3319 ** The context in which an SQL function executes is stored in an
3320 ** sqlite3_context object.  A pointer to an sqlite3_context object
3321 ** is always first parameter to [application-defined SQL functions].
3322 ** The application-defined SQL function implementation will pass this
3323 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3324 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3325 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3326 ** and/or [sqlite3_set_auxdata()].
3327 */
3328 typedef struct sqlite3_context sqlite3_context;
3329
3330 /*
3331 ** CAPI3REF: Binding Values To Prepared Statements {H13500} <S70300>
3332 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3333 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3334 **
3335 ** In the SQL strings input to [sqlite3_prepare_v2()] and its variants,
3336 ** literals may be replaced by a parameter in one of these forms:
3337 **
3338 ** <ul>
3339 ** <li>  ?
3340 ** <li>  ?NNN
3341 ** <li>  :VVV
3342 ** <li>  @VVV
3343 ** <li>  $VVV
3344 ** </ul>
3345 **
3346 ** In the parameter forms shown above NNN is an integer literal,
3347 ** and VVV is an alpha-numeric parameter name. The values of these
3348 ** parameters (also called "host parameter names" or "SQL parameters")
3349 ** can be set using the sqlite3_bind_*() routines defined here.
3350 **
3351 ** The first argument to the sqlite3_bind_*() routines is always
3352 ** a pointer to the [sqlite3_stmt] object returned from
3353 ** [sqlite3_prepare_v2()] or its variants.
3354 **
3355 ** The second argument is the index of the SQL parameter to be set.
3356 ** The leftmost SQL parameter has an index of 1.  When the same named
3357 ** SQL parameter is used more than once, second and subsequent
3358 ** occurrences have the same index as the first occurrence.
3359 ** The index for named parameters can be looked up using the
3360 ** [sqlite3_bind_parameter_index()] API if desired.  The index
3361 ** for "?NNN" parameters is the value of NNN.
3362 ** The NNN value must be between 1 and the [sqlite3_limit()]
3363 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3364 **
3365 ** The third argument is the value to bind to the parameter.
3366 **
3367 ** In those routines that have a fourth argument, its value is the
3368 ** number of bytes in the parameter.  To be clear: the value is the
3369 ** number of <u>bytes</u> in the value, not the number of characters.
3370 ** If the fourth parameter is negative, the length of the string is
3371 ** the number of bytes up to the first zero terminator.
3372 **
3373 ** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3374 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3375 ** string after SQLite has finished with it. If the fifth argument is
3376 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3377 ** information is in static, unmanaged space and does not need to be freed.
3378 ** If the fifth argument has the value [SQLITE_TRANSIENT], then
3379 ** SQLite makes its own private copy of the data immediately, before
3380 ** the sqlite3_bind_*() routine returns.
3381 **
3382 ** The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3383 ** is filled with zeroes.  A zeroblob uses a fixed amount of memory
3384 ** (just an integer to hold its size) while it is being processed.
3385 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3386 ** content is later written using
3387 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3388 ** A negative value for the zeroblob results in a zero-length BLOB.
3389 **
3390 ** The sqlite3_bind_*() routines must be called after
3391 ** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and
3392 ** before [sqlite3_step()].
3393 ** Bindings are not cleared by the [sqlite3_reset()] routine.
3394 ** Unbound parameters are interpreted as NULL.
3395 **
3396 ** These routines return [SQLITE_OK] on success or an error code if
3397 ** anything goes wrong.  [SQLITE_RANGE] is returned if the parameter
3398 ** index is out of range.  [SQLITE_NOMEM] is returned if malloc() fails.
3399 ** [SQLITE_MISUSE] might be returned if these routines are called on a
3400 ** virtual machine that is the wrong state or which has already been finalized.
3401 ** Detection of misuse is unreliable.  Applications should not depend
3402 ** on SQLITE_MISUSE returns.  SQLITE_MISUSE is intended to indicate a
3403 ** a logic error in the application.  Future versions of SQLite might
3404 ** panic rather than return SQLITE_MISUSE.
3405 **
3406 ** See also: [sqlite3_bind_parameter_count()],
3407 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3408 **
3409 ** INVARIANTS:
3410 **
3411 ** {H13506} The [SQL statement compiler] recognizes tokens of the forms
3412 **          "?", "?NNN", "$VVV", ":VVV", and "@VVV" as SQL parameters,
3413 **          where NNN is any sequence of one or more digits
3414 **          and where VVV is any sequence of one or more alphanumeric
3415 **          characters or "::" optionally followed by a string containing
3416 **          no spaces and contained within parentheses.
3417 **
3418 ** {H13509} The initial value of an SQL parameter is NULL.
3419 **
3420 ** {H13512} The index of an "?" SQL parameter is one larger than the
3421 **          largest index of SQL parameter to the left, or 1 if
3422 **          the "?" is the leftmost SQL parameter.
3423 **
3424 ** {H13515} The index of an "?NNN" SQL parameter is the integer NNN.
3425 **
3426 ** {H13518} The index of an ":VVV", "$VVV", or "@VVV" SQL parameter is
3427 **          the same as the index of leftmost occurrences of the same
3428 **          parameter, or one more than the largest index over all
3429 **          parameters to the left if this is the first occurrence
3430 **          of this parameter, or 1 if this is the leftmost parameter.
3431 **
3432 ** {H13521} The [SQL statement compiler] fails with an [SQLITE_RANGE]
3433 **          error if the index of an SQL parameter is less than 1
3434 **          or greater than the compile-time SQLITE_MAX_VARIABLE_NUMBER
3435 **          parameter.
3436 **
3437 ** {H13524} Calls to [sqlite3_bind_text | sqlite3_bind(S,N,V,...)]
3438 **          associate the value V with all SQL parameters having an
3439 **          index of N in the [prepared statement] S.
3440 **
3441 ** {H13527} Calls to [sqlite3_bind_text | sqlite3_bind(S,N,...)]
3442 **          override prior calls with the same values of S and N.
3443 **
3444 ** {H13530} Bindings established by [sqlite3_bind_text | sqlite3_bind(S,...)]
3445 **          persist across calls to [sqlite3_reset(S)].
3446 **
3447 ** {H13533} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
3448 **          [sqlite3_bind_text(S,N,V,L,D)], or
3449 **          [sqlite3_bind_text16(S,N,V,L,D)] SQLite binds the first L
3450 **          bytes of the BLOB or string pointed to by V, when L
3451 **          is non-negative.
3452 **
3453 ** {H13536} In calls to [sqlite3_bind_text(S,N,V,L,D)] or
3454 **          [sqlite3_bind_text16(S,N,V,L,D)] SQLite binds characters
3455 **          from V through the first zero character when L is negative.
3456 **
3457 ** {H13539} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
3458 **          [sqlite3_bind_text(S,N,V,L,D)], or
3459 **          [sqlite3_bind_text16(S,N,V,L,D)] when D is the special
3460 **          constant [SQLITE_STATIC], SQLite assumes that the value V
3461 **          is held in static unmanaged space that will not change
3462 **          during the lifetime of the binding.
3463 **
3464 ** {H13542} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
3465 **          [sqlite3_bind_text(S,N,V,L,D)], or
3466 **          [sqlite3_bind_text16(S,N,V,L,D)] when D is the special
3467 **          constant [SQLITE_TRANSIENT], the routine makes a
3468 **          private copy of the value V before it returns.
3469 **
3470 ** {H13545} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
3471 **          [sqlite3_bind_text(S,N,V,L,D)], or
3472 **          [sqlite3_bind_text16(S,N,V,L,D)] when D is a pointer to
3473 **          a function, SQLite invokes that function to destroy the
3474 **          value V after it has finished using the value V.
3475 **
3476 ** {H13548} In calls to [sqlite3_bind_zeroblob(S,N,V,L)] the value bound
3477 **          is a BLOB of L bytes, or a zero-length BLOB if L is negative.
3478 **
3479 ** {H13551} In calls to [sqlite3_bind_value(S,N,V)] the V argument may
3480 **          be either a [protected sqlite3_value] object or an
3481 **          [unprotected sqlite3_value] object.
3482 */
3483 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3484 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3485 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3486 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3487 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3488 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3489 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3490 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3491 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3492
3493 /*
3494 ** CAPI3REF: Number Of SQL Parameters {H13600} <S70300>
3495 **
3496 ** This routine can be used to find the number of [SQL parameters]
3497 ** in a [prepared statement].  SQL parameters are tokens of the
3498 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3499 ** placeholders for values that are [sqlite3_bind_blob | bound]
3500 ** to the parameters at a later time.
3501 **
3502 ** This routine actually returns the index of the largest (rightmost)
3503 ** parameter. For all forms except ?NNN, this will correspond to the
3504 ** number of unique parameters.  If parameters of the ?NNN are used,
3505 ** there may be gaps in the list.
3506 **
3507 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3508 ** [sqlite3_bind_parameter_name()], and
3509 ** [sqlite3_bind_parameter_index()].
3510 **
3511 ** INVARIANTS:
3512 **
3513 ** {H13601} The [sqlite3_bind_parameter_count(S)] interface returns
3514 **          the largest index of all SQL parameters in the
3515 **          [prepared statement] S, or 0 if S contains no SQL parameters.
3516 */
3517 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3518
3519 /*
3520 ** CAPI3REF: Name Of A Host Parameter {H13620} <S70300>
3521 **
3522 ** This routine returns a pointer to the name of the n-th
3523 ** [SQL parameter] in a [prepared statement].
3524 ** SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3525 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3526 ** respectively.
3527 ** In other words, the initial ":" or "$" or "@" or "?"
3528 ** is included as part of the name.
3529 ** Parameters of the form "?" without a following integer have no name
3530 ** and are also referred to as "anonymous parameters".
3531 **
3532 ** The first host parameter has an index of 1, not 0.
3533 **
3534 ** If the value n is out of range or if the n-th parameter is
3535 ** nameless, then NULL is returned.  The returned string is
3536 ** always in UTF-8 encoding even if the named parameter was
3537 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3538 ** [sqlite3_prepare16_v2()].
3539 **
3540 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3541 ** [sqlite3_bind_parameter_count()], and
3542 ** [sqlite3_bind_parameter_index()].
3543 **
3544 ** INVARIANTS:
3545 **
3546 ** {H13621} The [sqlite3_bind_parameter_name(S,N)] interface returns
3547 **          a UTF-8 rendering of the name of the SQL parameter in
3548 **          the [prepared statement] S having index N, or
3549 **          NULL if there is no SQL parameter with index N or if the
3550 **          parameter with index N is an anonymous parameter "?".
3551 */
3552 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3553
3554 /*
3555 ** CAPI3REF: Index Of A Parameter With A Given Name {H13640} <S70300>
3556 **
3557 ** Return the index of an SQL parameter given its name.  The
3558 ** index value returned is suitable for use as the second
3559 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  A zero
3560 ** is returned if no matching parameter is found.  The parameter
3561 ** name must be given in UTF-8 even if the original statement
3562 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3563 **
3564 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3565 ** [sqlite3_bind_parameter_count()], and
3566 ** [sqlite3_bind_parameter_index()].
3567 **
3568 ** INVARIANTS:
3569 **
3570 ** {H13641} The [sqlite3_bind_parameter_index(S,N)] interface returns
3571 **          the index of SQL parameter in the [prepared statement]
3572 **          S whose name matches the UTF-8 string N, or 0 if there is
3573 **          no match.
3574 */
3575 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3576
3577 /*
3578 ** CAPI3REF: Reset All Bindings On A Prepared Statement {H13660} <S70300>
3579 **
3580 ** Contrary to the intuition of many, [sqlite3_reset()] does not reset
3581 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3582 ** Use this routine to reset all host parameters to NULL.
3583 **
3584 ** INVARIANTS:
3585 **
3586 ** {H13661} The [sqlite3_clear_bindings(S)] interface resets all SQL
3587 **          parameter bindings in the [prepared statement] S back to NULL.
3588 */
3589 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3590
3591 /*
3592 ** CAPI3REF: Number Of Columns In A Result Set {H13710} <S10700>
3593 **
3594 ** Return the number of columns in the result set returned by the
3595 ** [prepared statement]. This routine returns 0 if pStmt is an SQL
3596 ** statement that does not return data (for example an [UPDATE]).
3597 **
3598 ** INVARIANTS:
3599 **
3600 ** {H13711} The [sqlite3_column_count(S)] interface returns the number of
3601 **          columns in the result set generated by the [prepared statement] S,
3602 **          or 0 if S does not generate a result set.
3603 */
3604 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3605
3606 /*
3607 ** CAPI3REF: Column Names In A Result Set {H13720} <S10700>
3608 **
3609 ** These routines return the name assigned to a particular column
3610 ** in the result set of a [SELECT] statement.  The sqlite3_column_name()
3611 ** interface returns a pointer to a zero-terminated UTF-8 string
3612 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3613 ** UTF-16 string.  The first parameter is the [prepared statement]
3614 ** that implements the [SELECT] statement. The second parameter is the
3615 ** column number.  The leftmost column is number 0.
3616 **
3617 ** The returned string pointer is valid until either the [prepared statement]
3618 ** is destroyed by [sqlite3_finalize()] or until the next call to
3619 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3620 **
3621 ** If sqlite3_malloc() fails during the processing of either routine
3622 ** (for example during a conversion from UTF-8 to UTF-16) then a
3623 ** NULL pointer is returned.
3624 **
3625 ** The name of a result column is the value of the "AS" clause for
3626 ** that column, if there is an AS clause.  If there is no AS clause
3627 ** then the name of the column is unspecified and may change from
3628 ** one release of SQLite to the next.
3629 **
3630 ** INVARIANTS:
3631 **
3632 ** {H13721} A successful invocation of the [sqlite3_column_name(S,N)]
3633 **          interface returns the name of the Nth column (where 0 is
3634 **          the leftmost column) for the result set of the
3635 **          [prepared statement] S as a zero-terminated UTF-8 string.
3636 **
3637 ** {H13723} A successful invocation of the [sqlite3_column_name16(S,N)]
3638 **          interface returns the name of the Nth column (where 0 is
3639 **          the leftmost column) for the result set of the
3640 **          [prepared statement] S as a zero-terminated UTF-16 string
3641 **          in the native byte order.
3642 **
3643 ** {H13724} The [sqlite3_column_name()] and [sqlite3_column_name16()]
3644 **          interfaces return a NULL pointer if they are unable to
3645 **          allocate memory to hold their normal return strings.
3646 **
3647 ** {H13725} If the N parameter to [sqlite3_column_name(S,N)] or
3648 **          [sqlite3_column_name16(S,N)] is out of range, then the
3649 **          interfaces return a NULL pointer.
3650 **
3651 ** {H13726} The strings returned by [sqlite3_column_name(S,N)] and
3652 **          [sqlite3_column_name16(S,N)] are valid until the next
3653 **          call to either routine with the same S and N parameters
3654 **          or until [sqlite3_finalize(S)] is called.
3655 **
3656 ** {H13727} When a result column of a [SELECT] statement contains
3657 **          an AS clause, the name of that column is the identifier
3658 **          to the right of the AS keyword.
3659 */
3660 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3661 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3662
3663 /*
3664 ** CAPI3REF: Source Of Data In A Query Result {H13740} <S10700>
3665 **
3666 ** These routines provide a means to determine what column of what
3667 ** table in which database a result of a [SELECT] statement comes from.
3668 ** The name of the database or table or column can be returned as
3669 ** either a UTF-8 or UTF-16 string.  The _database_ routines return
3670 ** the database name, the _table_ routines return the table name, and
3671 ** the origin_ routines return the column name.
3672 ** The returned string is valid until the [prepared statement] is destroyed
3673 ** using [sqlite3_finalize()] or until the same information is requested
3674 ** again in a different encoding.
3675 **
3676 ** The names returned are the original un-aliased names of the
3677 ** database, table, and column.
3678 **
3679 ** The first argument to the following calls is a [prepared statement].
3680 ** These functions return information about the Nth column returned by
3681 ** the statement, where N is the second function argument.
3682 **
3683 ** If the Nth column returned by the statement is an expression or
3684 ** subquery and is not a column value, then all of these functions return
3685 ** NULL.  These routine might also return NULL if a memory allocation error
3686 ** occurs.  Otherwise, they return the name of the attached database, table
3687 ** and column that query result column was extracted from.
3688 **
3689 ** As with all other SQLite APIs, those postfixed with "16" return
3690 ** UTF-16 encoded strings, the other functions return UTF-8. {END}
3691 **
3692 ** These APIs are only available if the library was compiled with the
3693 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
3694 **
3695 ** {A13751}
3696 ** If two or more threads call one or more of these routines against the same
3697 ** prepared statement and column at the same time then the results are
3698 ** undefined.
3699 **
3700 ** INVARIANTS:
3701 **
3702 ** {H13741} The [sqlite3_column_database_name(S,N)] interface returns either
3703 **          the UTF-8 zero-terminated name of the database from which the
3704 **          Nth result column of the [prepared statement] S is extracted,
3705 **          or NULL if the Nth column of S is a general expression
3706 **          or if unable to allocate memory to store the name.
3707 **
3708 ** {H13742} The [sqlite3_column_database_name16(S,N)] interface returns either
3709 **          the UTF-16 native byte order zero-terminated name of the database
3710 **          from which the Nth result column of the [prepared statement] S is
3711 **          extracted, or NULL if the Nth column of S is a general expression
3712 **          or if unable to allocate memory to store the name.
3713 **
3714 ** {H13743} The [sqlite3_column_table_name(S,N)] interface returns either
3715 **          the UTF-8 zero-terminated name of the table from which the
3716 **          Nth result column of the [prepared statement] S is extracted,
3717 **          or NULL if the Nth column of S is a general expression
3718 **          or if unable to allocate memory to store the name.
3719 **
3720 ** {H13744} The [sqlite3_column_table_name16(S,N)] interface returns either
3721 **          the UTF-16 native byte order zero-terminated name of the table
3722 **          from which the Nth result column of the [prepared statement] S is
3723 **          extracted, or NULL if the Nth column of S is a general expression
3724 **          or if unable to allocate memory to store the name.
3725 **
3726 ** {H13745} The [sqlite3_column_origin_name(S,N)] interface returns either
3727 **          the UTF-8 zero-terminated name of the table column from which the
3728 **          Nth result column of the [prepared statement] S is extracted,
3729 **          or NULL if the Nth column of S is a general expression
3730 **          or if unable to allocate memory to store the name.
3731 **
3732 ** {H13746} The [sqlite3_column_origin_name16(S,N)] interface returns either
3733 **          the UTF-16 native byte order zero-terminated name of the table
3734 **          column from which the Nth result column of the
3735 **          [prepared statement] S is extracted, or NULL if the Nth column
3736 **          of S is a general expression or if unable to allocate memory
3737 **          to store the name.
3738 **
3739 ** {H13748} The return values from
3740 **          [sqlite3_column_database_name | column metadata interfaces]
3741 **          are valid for the lifetime of the [prepared statement]
3742 **          or until the encoding is changed by another metadata
3743 **          interface call for the same prepared statement and column.
3744 **
3745 ** ASSUMPTIONS:
3746 **
3747 ** {A13751} If two or more threads call one or more
3748 **          [sqlite3_column_database_name | column metadata interfaces]
3749 **          for the same [prepared statement] and result column
3750 **          at the same time then the results are undefined.
3751 */
3752 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3753 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3754 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3755 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3756 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3757 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3758
3759 /*
3760 ** CAPI3REF: Declared Datatype Of A Query Result {H13760} <S10700>
3761 **
3762 ** The first parameter is a [prepared statement].
3763 ** If this statement is a [SELECT] statement and the Nth column of the
3764 ** returned result set of that [SELECT] is a table column (not an
3765 ** expression or subquery) then the declared type of the table
3766 ** column is returned.  If the Nth column of the result set is an
3767 ** expression or subquery, then a NULL pointer is returned.
3768 ** The returned string is always UTF-8 encoded. {END}
3769 **
3770 ** For example, given the database schema:
3771 **
3772 ** CREATE TABLE t1(c1 VARIANT);
3773 **
3774 ** and the following statement to be compiled:
3775 **
3776 ** SELECT c1 + 1, c1 FROM t1;
3777 **
3778 ** this routine would return the string "VARIANT" for the second result
3779 ** column (i==1), and a NULL pointer for the first result column (i==0).
3780 **
3781 ** SQLite uses dynamic run-time typing.  So just because a column
3782 ** is declared to contain a particular type does not mean that the
3783 ** data stored in that column is of the declared type.  SQLite is
3784 ** strongly typed, but the typing is dynamic not static.  Type
3785 ** is associated with individual values, not with the containers
3786 ** used to hold those values.
3787 **
3788 ** INVARIANTS:
3789 **
3790 ** {H13761}  A successful call to [sqlite3_column_decltype(S,N)] returns a
3791 **           zero-terminated UTF-8 string containing the declared datatype
3792 **           of the table column that appears as the Nth column (numbered
3793 **           from 0) of the result set to the [prepared statement] S.
3794 **
3795 ** {H13762}  A successful call to [sqlite3_column_decltype16(S,N)]
3796 **           returns a zero-terminated UTF-16 native byte order string
3797 **           containing the declared datatype of the table column that appears
3798 **           as the Nth column (numbered from 0) of the result set to the
3799 **           [prepared statement] S.
3800 **
3801 ** {H13763}  If N is less than 0 or N is greater than or equal to
3802 **           the number of columns in the [prepared statement] S,
3803 **           or if the Nth column of S is an expression or subquery rather
3804 **           than a table column, or if a memory allocation failure
3805 **           occurs during encoding conversions, then
3806 **           calls to [sqlite3_column_decltype(S,N)] or
3807 **           [sqlite3_column_decltype16(S,N)] return NULL.
3808 */
3809 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3810 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3811
3812 /*
3813 ** CAPI3REF: Evaluate An SQL Statement {H13200} <S10000>
3814 **
3815 ** After a [prepared statement] has been prepared using either
3816 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3817 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3818 ** must be called one or more times to evaluate the statement.
3819 **
3820 ** The details of the behavior of the sqlite3_step() interface depend
3821 ** on whether the statement was prepared using the newer "v2" interface
3822 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3823 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
3824 ** new "v2" interface is recommended for new applications but the legacy
3825 ** interface will continue to be supported.
3826 **
3827 ** In the legacy interface, the return value will be either [SQLITE_BUSY],
3828 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3829 ** With the "v2" interface, any of the other [result codes] or
3830 ** [extended result codes] might be returned as well.
3831 **
3832 ** [SQLITE_BUSY] means that the database engine was unable to acquire the
3833 ** database locks it needs to do its job.  If the statement is a [COMMIT]
3834 ** or occurs outside of an explicit transaction, then you can retry the
3835 ** statement.  If the statement is not a [COMMIT] and occurs within a
3836 ** explicit transaction then you should rollback the transaction before
3837 ** continuing.
3838 **
3839 ** [SQLITE_DONE] means that the statement has finished executing
3840 ** successfully.  sqlite3_step() should not be called again on this virtual
3841 ** machine without first calling [sqlite3_reset()] to reset the virtual
3842 ** machine back to its initial state.
3843 **
3844 ** If the SQL statement being executed returns any data, then [SQLITE_ROW]
3845 ** is returned each time a new row of data is ready for processing by the
3846 ** caller. The values may be accessed using the [column access functions].
3847 ** sqlite3_step() is called again to retrieve the next row of data.
3848 **
3849 ** [SQLITE_ERROR] means that a run-time error (such as a constraint
3850 ** violation) has occurred.  sqlite3_step() should not be called again on
3851 ** the VM. More information may be found by calling [sqlite3_errmsg()].
3852 ** With the legacy interface, a more specific error code (for example,
3853 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
3854 ** can be obtained by calling [sqlite3_reset()] on the
3855 ** [prepared statement].  In the "v2" interface,
3856 ** the more specific error code is returned directly by sqlite3_step().
3857 **
3858 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
3859 ** Perhaps it was called on a [prepared statement] that has
3860 ** already been [sqlite3_finalize | finalized] or on one that had
3861 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
3862 ** be the case that the same database connection is being used by two or
3863 ** more threads at the same moment in time.
3864 **
3865 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
3866 ** API always returns a generic error code, [SQLITE_ERROR], following any
3867 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
3868 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
3869 ** specific [error codes] that better describes the error.
3870 ** We admit that this is a goofy design.  The problem has been fixed
3871 ** with the "v2" interface.  If you prepare all of your SQL statements
3872 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
3873 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
3874 ** then the more specific [error codes] are returned directly
3875 ** by sqlite3_step().  The use of the "v2" interface is recommended.
3876 **
3877 ** INVARIANTS:
3878 **
3879 ** {H13202}  If the [prepared statement] S is ready to be run, then
3880 **           [sqlite3_step(S)] advances that prepared statement until
3881 **           completion or until it is ready to return another row of the
3882 **           result set, or until an [sqlite3_interrupt | interrupt]
3883 **           or a run-time error occurs.
3884 **
3885 ** {H15304}  When a call to [sqlite3_step(S)] causes the [prepared statement]
3886 **           S to run to completion, the function returns [SQLITE_DONE].
3887 **
3888 ** {H15306}  When a call to [sqlite3_step(S)] stops because it is ready to
3889 **           return another row of the result set, it returns [SQLITE_ROW].
3890 **
3891 ** {H15308}  If a call to [sqlite3_step(S)] encounters an
3892 **           [sqlite3_interrupt | interrupt] or a run-time error,
3893 **           it returns an appropriate error code that is not one of
3894 **           [SQLITE_OK], [SQLITE_ROW], or [SQLITE_DONE].
3895 **
3896 ** {H15310}  If an [sqlite3_interrupt | interrupt] or a run-time error
3897 **           occurs during a call to [sqlite3_step(S)]
3898 **           for a [prepared statement] S created using
3899 **           legacy interfaces [sqlite3_prepare()] or
3900 **           [sqlite3_prepare16()], then the function returns either
3901 **           [SQLITE_ERROR], [SQLITE_BUSY], or [SQLITE_MISUSE].
3902 */
3903 SQLITE_API int sqlite3_step(sqlite3_stmt*);
3904
3905 /*
3906 ** CAPI3REF: Number of columns in a result set {H13770} <S10700>
3907 **
3908 ** Returns the number of values in the current row of the result set.
3909 **
3910 ** INVARIANTS:
3911 **
3912 ** {H13771}  After a call to [sqlite3_step(S)] that returns [SQLITE_ROW],
3913 **           the [sqlite3_data_count(S)] routine will return the same value
3914 **           as the [sqlite3_column_count(S)] function.
3915 **
3916 ** {H13772}  After [sqlite3_step(S)] has returned any value other than
3917 **           [SQLITE_ROW] or before [sqlite3_step(S)] has been called on the
3918 **           [prepared statement] for the first time since it was
3919 **           [sqlite3_prepare | prepared] or [sqlite3_reset | reset],
3920 **           the [sqlite3_data_count(S)] routine returns zero.
3921 */
3922 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
3923
3924 /*
3925 ** CAPI3REF: Fundamental Datatypes {H10265} <S10110><S10120>
3926 ** KEYWORDS: SQLITE_TEXT
3927 **
3928 ** {H10266} Every value in SQLite has one of five fundamental datatypes:
3929 **
3930 ** <ul>
3931 ** <li> 64-bit signed integer
3932 ** <li> 64-bit IEEE floating point number
3933 ** <li> string
3934 ** <li> BLOB
3935 ** <li> NULL
3936 ** </ul> {END}
3937 **
3938 ** These constants are codes for each of those types.
3939 **
3940 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
3941 ** for a completely different meaning.  Software that links against both
3942 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
3943 ** SQLITE_TEXT.
3944 */
3945 #define SQLITE_INTEGER  1
3946 #define SQLITE_FLOAT    2
3947 #define SQLITE_BLOB     4
3948 #define SQLITE_NULL     5
3949 #ifdef SQLITE_TEXT
3950 # undef SQLITE_TEXT
3951 #else
3952 # define SQLITE_TEXT     3
3953 #endif
3954 #define SQLITE3_TEXT     3
3955
3956 /*
3957 ** CAPI3REF: Result Values From A Query {H13800} <S10700>
3958 ** KEYWORDS: {column access functions}
3959 **
3960 ** These routines form the "result set query" interface.
3961 **
3962 ** These routines return information about a single column of the current
3963 ** result row of a query.  In every case the first argument is a pointer
3964 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
3965 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
3966 ** and the second argument is the index of the column for which information
3967 ** should be returned.  The leftmost column of the result set has the index 0.
3968 **
3969 ** If the SQL statement does not currently point to a valid row, or if the
3970 ** column index is out of range, the result is undefined.
3971 ** These routines may only be called when the most recent call to
3972 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
3973 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
3974 ** If any of these routines are called after [sqlite3_reset()] or
3975 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
3976 ** something other than [SQLITE_ROW], the results are undefined.
3977 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
3978 ** are called from a different thread while any of these routines
3979 ** are pending, then the results are undefined.
3980 **
3981 ** The sqlite3_column_type() routine returns the
3982 ** [SQLITE_INTEGER | datatype code] for the initial data type
3983 ** of the result column.  The returned value is one of [SQLITE_INTEGER],
3984 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
3985 ** returned by sqlite3_column_type() is only meaningful if no type
3986 ** conversions have occurred as described below.  After a type conversion,
3987 ** the value returned by sqlite3_column_type() is undefined.  Future
3988 ** versions of SQLite may change the behavior of sqlite3_column_type()
3989 ** following a type conversion.
3990 **
3991 ** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
3992 ** routine returns the number of bytes in that BLOB or string.
3993 ** If the result is a UTF-16 string, then sqlite3_column_bytes() converts
3994 ** the string to UTF-8 and then returns the number of bytes.
3995 ** If the result is a numeric value then sqlite3_column_bytes() uses
3996 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
3997 ** the number of bytes in that string.
3998 ** The value returned does not include the zero terminator at the end
3999 ** of the string.  For clarity: the value returned is the number of
4000 ** bytes in the string, not the number of characters.
4001 **
4002 ** Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
4003 ** even empty strings, are always zero terminated.  The return
4004 ** value from sqlite3_column_blob() for a zero-length BLOB is an arbitrary
4005 ** pointer, possibly even a NULL pointer.
4006 **
4007 ** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
4008 ** but leaves the result in UTF-16 in native byte order instead of UTF-8.
4009 ** The zero terminator is not included in this count.
4010 **
4011 ** The object returned by [sqlite3_column_value()] is an
4012 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
4013 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
4014 ** If the [unprotected sqlite3_value] object returned by
4015 ** [sqlite3_column_value()] is used in any other way, including calls
4016 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
4017 ** or [sqlite3_value_bytes()], then the behavior is undefined.
4018 **
4019 ** These routines attempt to convert the value where appropriate.  For
4020 ** example, if the internal representation is FLOAT and a text result
4021 ** is requested, [sqlite3_snprintf()] is used internally to perform the
4022 ** conversion automatically.  The following table details the conversions
4023 ** that are applied:
4024 **
4025 ** <blockquote>
4026 ** <table border="1">
4027 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
4028 **
4029 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
4030 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
4031 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
4032 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
4033 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
4034 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
4035 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
4036 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
4037 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
4038 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
4039 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
4040 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
4041 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
4042 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
4043 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
4044 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
4045 ** </table>
4046 ** </blockquote>
4047 **
4048 ** The table above makes reference to standard C library functions atoi()
4049 ** and atof().  SQLite does not really use these functions.  It has its
4050 ** own equivalent internal routines.  The atoi() and atof() names are
4051 ** used in the table for brevity and because they are familiar to most
4052 ** C programmers.
4053 **
4054 ** Note that when type conversions occur, pointers returned by prior
4055 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
4056 ** sqlite3_column_text16() may be invalidated.
4057 ** Type conversions and pointer invalidations might occur
4058 ** in the following cases:
4059 **
4060 ** <ul>
4061 ** <li> The initial content is a BLOB and sqlite3_column_text() or
4062 **      sqlite3_column_text16() is called.  A zero-terminator might
4063 **      need to be added to the string.</li>
4064 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
4065 **      sqlite3_column_text16() is called.  The content must be converted
4066 **      to UTF-16.</li>
4067 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
4068 **      sqlite3_column_text() is called.  The content must be converted
4069 **      to UTF-8.</li>
4070 ** </ul>
4071 **
4072 ** Conversions between UTF-16be and UTF-16le are always done in place and do
4073 ** not invalidate a prior pointer, though of course the content of the buffer
4074 ** that the prior pointer points to will have been modified.  Other kinds
4075 ** of conversion are done in place when it is possible, but sometimes they
4076 ** are not possible and in those cases prior pointers are invalidated.
4077 **
4078 ** The safest and easiest to remember policy is to invoke these routines
4079 ** in one of the following ways:
4080 **
4081 ** <ul>
4082 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
4083 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
4084 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
4085 ** </ul>
4086 **
4087 ** In other words, you should call sqlite3_column_text(),
4088 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
4089 ** into the desired format, then invoke sqlite3_column_bytes() or
4090 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
4091 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
4092 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
4093 ** with calls to sqlite3_column_bytes().
4094 **
4095 ** The pointers returned are valid until a type conversion occurs as
4096 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
4097 ** [sqlite3_finalize()] is called.  The memory space used to hold strings
4098 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
4099 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
4100 ** [sqlite3_free()].
4101 **
4102 ** If a memory allocation error occurs during the evaluation of any
4103 ** of these routines, a default value is returned.  The default value
4104 ** is either the integer 0, the floating point number 0.0, or a NULL
4105 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
4106 ** [SQLITE_NOMEM].
4107 **
4108 ** INVARIANTS:
4109 **
4110 ** {H13803} The [sqlite3_column_blob(S,N)] interface converts the
4111 **          Nth column in the current row of the result set for
4112 **          the [prepared statement] S into a BLOB and then returns a
4113 **          pointer to the converted value.
4114 **
4115 ** {H13806} The [sqlite3_column_bytes(S,N)] interface returns the
4116 **          number of bytes in the BLOB or string (exclusive of the
4117 **          zero terminator on the string) that was returned by the
4118 **          most recent call to [sqlite3_column_blob(S,N)] or
4119 **          [sqlite3_column_text(S,N)].
4120 **
4121 ** {H13809} The [sqlite3_column_bytes16(S,N)] interface returns the
4122 **          number of bytes in the string (exclusive of the
4123 **          zero terminator on the string) that was returned by the
4124 **          most recent call to [sqlite3_column_text16(S,N)].
4125 **
4126 ** {H13812} The [sqlite3_column_double(S,N)] interface converts the
4127 **          Nth column in the current row of the result set for the
4128 **          [prepared statement] S into a floating point value and
4129 **          returns a copy of that value.
4130 **
4131 ** {H13815} The [sqlite3_column_int(S,N)] interface converts the
4132 **          Nth column in the current row of the result set for the
4133 **          [prepared statement] S into a 64-bit signed integer and
4134 **          returns the lower 32 bits of that integer.
4135 **
4136 ** {H13818} The [sqlite3_column_int64(S,N)] interface converts the
4137 **          Nth column in the current row of the result set for the
4138 **          [prepared statement] S into a 64-bit signed integer and
4139 **          returns a copy of that integer.
4140 **
4141 ** {H13821} The [sqlite3_column_text(S,N)] interface converts the
4142 **          Nth column in the current row of the result set for
4143 **          the [prepared statement] S into a zero-terminated UTF-8
4144 **          string and returns a pointer to that string.
4145 **
4146 ** {H13824} The [sqlite3_column_text16(S,N)] interface converts the
4147 **          Nth column in the current row of the result set for the
4148 **          [prepared statement] S into a zero-terminated 2-byte
4149 **          aligned UTF-16 native byte order string and returns
4150 **          a pointer to that string.
4151 **
4152 ** {H13827} The [sqlite3_column_type(S,N)] interface returns
4153 **          one of [SQLITE_NULL], [SQLITE_INTEGER], [SQLITE_FLOAT],
4154 **          [SQLITE_TEXT], or [SQLITE_BLOB] as appropriate for
4155 **          the Nth column in the current row of the result set for
4156 **          the [prepared statement] S.
4157 **
4158 ** {H13830} The [sqlite3_column_value(S,N)] interface returns a
4159 **          pointer to an [unprotected sqlite3_value] object for the
4160 **          Nth column in the current row of the result set for
4161 **          the [prepared statement] S.
4162 */
4163 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
4164 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
4165 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
4166 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
4167 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
4168 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
4169 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
4170 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
4171 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
4172 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
4173
4174 /*
4175 ** CAPI3REF: Destroy A Prepared Statement Object {H13300} <S70300><S30100>
4176 **
4177 ** The sqlite3_finalize() function is called to delete a [prepared statement].
4178 ** If the statement was executed successfully or not executed at all, then
4179 ** SQLITE_OK is returned. If execution of the statement failed then an
4180 ** [error code] or [extended error code] is returned.
4181 **
4182 ** This routine can be called at any point during the execution of the
4183 ** [prepared statement].  If the virtual machine has not
4184 ** completed execution when this routine is called, that is like
4185 ** encountering an error or an [sqlite3_interrupt | interrupt].
4186 ** Incomplete updates may be rolled back and transactions canceled,
4187 ** depending on the circumstances, and the
4188 ** [error code] returned will be [SQLITE_ABORT].
4189 **
4190 ** INVARIANTS:
4191 **
4192 ** {H11302} The [sqlite3_finalize(S)] interface destroys the
4193 **          [prepared statement] S and releases all
4194 **          memory and file resources held by that object.
4195 **
4196 ** {H11304} If the most recent call to [sqlite3_step(S)] for the
4197 **          [prepared statement] S returned an error,
4198 **          then [sqlite3_finalize(S)] returns that same error.
4199 */
4200 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
4201
4202 /*
4203 ** CAPI3REF: Reset A Prepared Statement Object {H13330} <S70300>
4204 **
4205 ** The sqlite3_reset() function is called to reset a [prepared statement]
4206 ** object back to its initial state, ready to be re-executed.
4207 ** Any SQL statement variables that had values bound to them using
4208 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
4209 ** Use [sqlite3_clear_bindings()] to reset the bindings.
4210 **
4211 ** {H11332} The [sqlite3_reset(S)] interface resets the [prepared statement] S
4212 **          back to the beginning of its program.
4213 **
4214 ** {H11334} If the most recent call to [sqlite3_step(S)] for the
4215 **          [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
4216 **          or if [sqlite3_step(S)] has never before been called on S,
4217 **          then [sqlite3_reset(S)] returns [SQLITE_OK].
4218 **
4219 ** {H11336} If the most recent call to [sqlite3_step(S)] for the
4220 **          [prepared statement] S indicated an error, then
4221 **          [sqlite3_reset(S)] returns an appropriate [error code].
4222 **
4223 ** {H11338} The [sqlite3_reset(S)] interface does not change the values
4224 **          of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
4225 */
4226 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
4227
4228 /*
4229 ** CAPI3REF: Create Or Redefine SQL Functions {H16100} <S20200>
4230 ** KEYWORDS: {function creation routines}
4231 ** KEYWORDS: {application-defined SQL function}
4232 ** KEYWORDS: {application-defined SQL functions}
4233 **
4234 ** These two functions (collectively known as "function creation routines")
4235 ** are used to add SQL functions or aggregates or to redefine the behavior
4236 ** of existing SQL functions or aggregates.  The only difference between the
4237 ** two is that the second parameter, the name of the (scalar) function or
4238 ** aggregate, is encoded in UTF-8 for sqlite3_create_function() and UTF-16
4239 ** for sqlite3_create_function16().
4240 **
4241 ** The first parameter is the [database connection] to which the SQL
4242 ** function is to be added.  If a single program uses more than one database
4243 ** connection internally, then SQL functions must be added individually to
4244 ** each database connection.
4245 **
4246 ** The second parameter is the name of the SQL function to be created or
4247 ** redefined.  The length of the name is limited to 255 bytes, exclusive of
4248 ** the zero-terminator.  Note that the name length limit is in bytes, not
4249 ** characters.  Any attempt to create a function with a longer name
4250 ** will result in [SQLITE_ERROR] being returned.
4251 **
4252 ** The third parameter is the number of arguments that the SQL function or
4253 ** aggregate takes. If this parameter is negative, then the SQL function or
4254 ** aggregate may take any number of arguments.
4255 **
4256 ** The fourth parameter, eTextRep, specifies what
4257 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4258 ** its parameters.  Any SQL function implementation should be able to work
4259 ** work with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
4260 ** more efficient with one encoding than another.  It is allowed to
4261 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
4262 ** times with the same function but with different values of eTextRep.
4263 ** When multiple implementations of the same function are available, SQLite
4264 ** will pick the one that involves the least amount of data conversion.
4265 ** If there is only a single implementation which does not care what text
4266 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
4267 **
4268 ** The fifth parameter is an arbitrary pointer.  The implementation of the
4269 ** function can gain access to this pointer using [sqlite3_user_data()].
4270 **
4271 ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
4272 ** pointers to C-language functions that implement the SQL function or
4273 ** aggregate. A scalar SQL function requires an implementation of the xFunc
4274 ** callback only, NULL pointers should be passed as the xStep and xFinal
4275 ** parameters. An aggregate SQL function requires an implementation of xStep
4276 ** and xFinal and NULL should be passed for xFunc. To delete an existing
4277 ** SQL function or aggregate, pass NULL for all three function callbacks.
4278 **
4279 ** It is permitted to register multiple implementations of the same
4280 ** functions with the same name but with either differing numbers of
4281 ** arguments or differing preferred text encodings.  SQLite will use
4282 ** the implementation most closely matches the way in which the
4283 ** SQL function is used.
4284 **
4285 ** INVARIANTS:
4286 **
4287 ** {H16103} The [sqlite3_create_function16()] interface behaves exactly
4288 **          like [sqlite3_create_function()] in every way except that it
4289 **          interprets the zFunctionName argument as zero-terminated UTF-16
4290 **          native byte order instead of as zero-terminated UTF-8.
4291 **
4292 ** {H16106} A successful invocation of
4293 **          the [sqlite3_create_function(D,X,N,E,...)] interface registers
4294 **          or replaces callback functions in the [database connection] D
4295 **          used to implement the SQL function named X with N parameters
4296 **          and having a preferred text encoding of E.
4297 **
4298 ** {H16109} A successful call to [sqlite3_create_function(D,X,N,E,P,F,S,L)]
4299 **          replaces the P, F, S, and L values from any prior calls with
4300 **          the same D, X, N, and E values.
4301 **
4302 ** {H16112} The [sqlite3_create_function(D,X,...)] interface fails with
4303 **          a return code of [SQLITE_ERROR] if the SQL function name X is
4304 **          longer than 255 bytes exclusive of the zero terminator.
4305 **
4306 ** {H16118} Either F must be NULL and S and L are non-NULL or else F
4307 **          is non-NULL and S and L are NULL, otherwise
4308 **          [sqlite3_create_function(D,X,N,E,P,F,S,L)] returns [SQLITE_ERROR].
4309 **
4310 ** {H16121} The [sqlite3_create_function(D,...)] interface fails with an
4311 **          error code of [SQLITE_BUSY] if there exist [prepared statements]
4312 **          associated with the [database connection] D.
4313 **
4314 ** {H16124} The [sqlite3_create_function(D,X,N,...)] interface fails with an
4315 **          error code of [SQLITE_ERROR] if parameter N (specifying the number
4316 **          of arguments to the SQL function being registered) is less
4317 **          than -1 or greater than 127.
4318 **
4319 ** {H16127} When N is non-negative, the [sqlite3_create_function(D,X,N,...)]
4320 **          interface causes callbacks to be invoked for the SQL function
4321 **          named X when the number of arguments to the SQL function is
4322 **          exactly N.
4323 **
4324 ** {H16130} When N is -1, the [sqlite3_create_function(D,X,N,...)]
4325 **          interface causes callbacks to be invoked for the SQL function
4326 **          named X with any number of arguments.
4327 **
4328 ** {H16133} When calls to [sqlite3_create_function(D,X,N,...)]
4329 **          specify multiple implementations of the same function X
4330 **          and when one implementation has N>=0 and the other has N=(-1)
4331 **          the implementation with a non-zero N is preferred.
4332 **
4333 ** {H16136} When calls to [sqlite3_create_function(D,X,N,E,...)]
4334 **          specify multiple implementations of the same function X with
4335 **          the same number of arguments N but with different
4336 **          encodings E, then the implementation where E matches the
4337 **          database encoding is preferred.
4338 **
4339 ** {H16139} For an aggregate SQL function created using
4340 **          [sqlite3_create_function(D,X,N,E,P,0,S,L)] the finalizer
4341 **          function L will always be invoked exactly once if the
4342 **          step function S is called one or more times.
4343 **
4344 ** {H16142} When SQLite invokes either the xFunc or xStep function of
4345 **          an application-defined SQL function or aggregate created
4346 **          by [sqlite3_create_function()] or [sqlite3_create_function16()],
4347 **          then the array of [sqlite3_value] objects passed as the
4348 **          third parameter are always [protected sqlite3_value] objects.
4349 */
4350 SQLITE_API int sqlite3_create_function(
4351   sqlite3 *db,
4352   const char *zFunctionName,
4353   int nArg,
4354   int eTextRep,
4355   void *pApp,
4356   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4357   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4358   void (*xFinal)(sqlite3_context*)
4359 );
4360 SQLITE_API int sqlite3_create_function16(
4361   sqlite3 *db,
4362   const void *zFunctionName,
4363   int nArg,
4364   int eTextRep,
4365   void *pApp,
4366   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4367   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4368   void (*xFinal)(sqlite3_context*)
4369 );
4370
4371 /*
4372 ** CAPI3REF: Text Encodings {H10267} <S50200> <H16100>
4373 **
4374 ** These constant define integer codes that represent the various
4375 ** text encodings supported by SQLite.
4376 */
4377 #define SQLITE_UTF8           1
4378 #define SQLITE_UTF16LE        2
4379 #define SQLITE_UTF16BE        3
4380 #define SQLITE_UTF16          4    /* Use native byte order */
4381 #define SQLITE_ANY            5    /* sqlite3_create_function only */
4382 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
4383
4384 /*
4385 ** CAPI3REF: Deprecated Functions
4386 ** DEPRECATED
4387 **
4388 ** These functions are [deprecated].  In order to maintain
4389 ** backwards compatibility with older code, these functions continue 
4390 ** to be supported.  However, new applications should avoid
4391 ** the use of these functions.  To help encourage people to avoid
4392 ** using these functions, we are not going to tell you want they do.
4393 */
4394 SQLITE_API int sqlite3_aggregate_count(sqlite3_context*);
4395 SQLITE_API int sqlite3_expired(sqlite3_stmt*);
4396 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4397 SQLITE_API int sqlite3_global_recover(void);
4398 SQLITE_API void sqlite3_thread_cleanup(void);
4399 SQLITE_API int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
4400
4401 /*
4402 ** CAPI3REF: Obtaining SQL Function Parameter Values {H15100} <S20200>
4403 **
4404 ** The C-language implementation of SQL functions and aggregates uses
4405 ** this set of interface routines to access the parameter values on
4406 ** the function or aggregate.
4407 **
4408 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4409 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4410 ** define callbacks that implement the SQL functions and aggregates.
4411 ** The 4th parameter to these callbacks is an array of pointers to
4412 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
4413 ** each parameter to the SQL function.  These routines are used to
4414 ** extract values from the [sqlite3_value] objects.
4415 **
4416 ** These routines work only with [protected sqlite3_value] objects.
4417 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4418 ** object results in undefined behavior.
4419 **
4420 ** These routines work just like the corresponding [column access functions]
4421 ** except that  these routines take a single [protected sqlite3_value] object
4422 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4423 **
4424 ** The sqlite3_value_text16() interface extracts a UTF-16 string
4425 ** in the native byte-order of the host machine.  The
4426 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4427 ** extract UTF-16 strings as big-endian and little-endian respectively.
4428 **
4429 ** The sqlite3_value_numeric_type() interface attempts to apply
4430 ** numeric affinity to the value.  This means that an attempt is
4431 ** made to convert the value to an integer or floating point.  If
4432 ** such a conversion is possible without loss of information (in other
4433 ** words, if the value is a string that looks like a number)
4434 ** then the conversion is performed.  Otherwise no conversion occurs.
4435 ** The [SQLITE_INTEGER | datatype] after conversion is returned.
4436 **
4437 ** Please pay particular attention to the fact that the pointer returned
4438 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4439 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4440 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4441 ** or [sqlite3_value_text16()].
4442 **
4443 ** These routines must be called from the same thread as
4444 ** the SQL function that supplied the [sqlite3_value*] parameters.
4445 **
4446 ** INVARIANTS:
4447 **
4448 ** {H15103} The [sqlite3_value_blob(V)] interface converts the
4449 **          [protected sqlite3_value] object V into a BLOB and then
4450 **          returns a pointer to the converted value.
4451 **
4452 ** {H15106} The [sqlite3_value_bytes(V)] interface returns the
4453 **          number of bytes in the BLOB or string (exclusive of the
4454 **          zero terminator on the string) that was returned by the
4455 **          most recent call to [sqlite3_value_blob(V)] or
4456 **          [sqlite3_value_text(V)].
4457 **
4458 ** {H15109} The [sqlite3_value_bytes16(V)] interface returns the
4459 **          number of bytes in the string (exclusive of the
4460 **          zero terminator on the string) that was returned by the
4461 **          most recent call to [sqlite3_value_text16(V)],
4462 **          [sqlite3_value_text16be(V)], or [sqlite3_value_text16le(V)].
4463 **
4464 ** {H15112} The [sqlite3_value_double(V)] interface converts the
4465 **          [protected sqlite3_value] object V into a floating point value and
4466 **          returns a copy of that value.
4467 **
4468 ** {H15115} The [sqlite3_value_int(V)] interface converts the
4469 **          [protected sqlite3_value] object V into a 64-bit signed integer and
4470 **          returns the lower 32 bits of that integer.
4471 **
4472 ** {H15118} The [sqlite3_value_int64(V)] interface converts the
4473 **          [protected sqlite3_value] object V into a 64-bit signed integer and
4474 **          returns a copy of that integer.
4475 **
4476 ** {H15121} The [sqlite3_value_text(V)] interface converts the
4477 **          [protected sqlite3_value] object V into a zero-terminated UTF-8
4478 **          string and returns a pointer to that string.
4479 **
4480 ** {H15124} The [sqlite3_value_text16(V)] interface converts the
4481 **          [protected sqlite3_value] object V into a zero-terminated 2-byte
4482 **          aligned UTF-16 native byte order
4483 **          string and returns a pointer to that string.
4484 **
4485 ** {H15127} The [sqlite3_value_text16be(V)] interface converts the
4486 **          [protected sqlite3_value] object V into a zero-terminated 2-byte
4487 **          aligned UTF-16 big-endian
4488 **          string and returns a pointer to that string.
4489 **
4490 ** {H15130} The [sqlite3_value_text16le(V)] interface converts the
4491 **          [protected sqlite3_value] object V into a zero-terminated 2-byte
4492 **          aligned UTF-16 little-endian
4493 **          string and returns a pointer to that string.
4494 **
4495 ** {H15133} The [sqlite3_value_type(V)] interface returns
4496 **          one of [SQLITE_NULL], [SQLITE_INTEGER], [SQLITE_FLOAT],
4497 **          [SQLITE_TEXT], or [SQLITE_BLOB] as appropriate for
4498 **          the [sqlite3_value] object V.
4499 **
4500 ** {H15136} The [sqlite3_value_numeric_type(V)] interface converts
4501 **          the [protected sqlite3_value] object V into either an integer or
4502 **          a floating point value if it can do so without loss of
4503 **          information, and returns one of [SQLITE_NULL],
4504 **          [SQLITE_INTEGER], [SQLITE_FLOAT], [SQLITE_TEXT], or
4505 **          [SQLITE_BLOB] as appropriate for the
4506 **          [protected sqlite3_value] object V after the conversion attempt.
4507 */
4508 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4509 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4510 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4511 SQLITE_API double sqlite3_value_double(sqlite3_value*);
4512 SQLITE_API int sqlite3_value_int(sqlite3_value*);
4513 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4514 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4515 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4516 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4517 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4518 SQLITE_API int sqlite3_value_type(sqlite3_value*);
4519 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4520
4521 /*
4522 ** CAPI3REF: Obtain Aggregate Function Context {H16210} <S20200>
4523 **
4524 ** The implementation of aggregate SQL functions use this routine to allocate
4525 ** a structure for storing their state.
4526 **
4527 ** The first time the sqlite3_aggregate_context() routine is called for a
4528 ** particular aggregate, SQLite allocates nBytes of memory, zeroes out that
4529 ** memory, and returns a pointer to it. On second and subsequent calls to
4530 ** sqlite3_aggregate_context() for the same aggregate function index,
4531 ** the same buffer is returned. The implementation of the aggregate can use
4532 ** the returned buffer to accumulate data.
4533 **
4534 ** SQLite automatically frees the allocated buffer when the aggregate
4535 ** query concludes.
4536 **
4537 ** The first parameter should be a copy of the
4538 ** [sqlite3_context | SQL function context] that is the first parameter
4539 ** to the callback routine that implements the aggregate function.
4540 **
4541 ** This routine must be called from the same thread in which
4542 ** the aggregate SQL function is running.
4543 **
4544 ** INVARIANTS:
4545 **
4546 ** {H16211} The first invocation of [sqlite3_aggregate_context(C,N)] for
4547 **          a particular instance of an aggregate function (for a particular
4548 **          context C) causes SQLite to allocate N bytes of memory,
4549 **          zero that memory, and return a pointer to the allocated memory.
4550 **
4551 ** {H16213} If a memory allocation error occurs during
4552 **          [sqlite3_aggregate_context(C,N)] then the function returns 0.
4553 **
4554 ** {H16215} Second and subsequent invocations of
4555 **          [sqlite3_aggregate_context(C,N)] for the same context pointer C
4556 **          ignore the N parameter and return a pointer to the same
4557 **          block of memory returned by the first invocation.
4558 **
4559 ** {H16217} The memory allocated by [sqlite3_aggregate_context(C,N)] is
4560 **          automatically freed on the next call to [sqlite3_reset()]
4561 **          or [sqlite3_finalize()] for the [prepared statement] containing
4562 **          the aggregate function associated with context C.
4563 */
4564 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4565
4566 /*
4567 ** CAPI3REF: User Data For Functions {H16240} <S20200>
4568 **
4569 ** The sqlite3_user_data() interface returns a copy of
4570 ** the pointer that was the pUserData parameter (the 5th parameter)
4571 ** of the [sqlite3_create_function()]
4572 ** and [sqlite3_create_function16()] routines that originally
4573 ** registered the application defined function. {END}
4574 **
4575 ** This routine must be called from the same thread in which
4576 ** the application-defined function is running.
4577 **
4578 ** INVARIANTS:
4579 **
4580 ** {H16243} The [sqlite3_user_data(C)] interface returns a copy of the
4581 **          P pointer from the [sqlite3_create_function(D,X,N,E,P,F,S,L)]
4582 **          or [sqlite3_create_function16(D,X,N,E,P,F,S,L)] call that
4583 **          registered the SQL function associated with [sqlite3_context] C.
4584 */
4585 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4586
4587 /*
4588 ** CAPI3REF: Database Connection For Functions {H16250} <S60600><S20200>
4589 **
4590 ** The sqlite3_context_db_handle() interface returns a copy of
4591 ** the pointer to the [database connection] (the 1st parameter)
4592 ** of the [sqlite3_create_function()]
4593 ** and [sqlite3_create_function16()] routines that originally
4594 ** registered the application defined function.
4595 **
4596 ** INVARIANTS:
4597 **
4598 ** {H16253} The [sqlite3_context_db_handle(C)] interface returns a copy of the
4599 **          D pointer from the [sqlite3_create_function(D,X,N,E,P,F,S,L)]
4600 **          or [sqlite3_create_function16(D,X,N,E,P,F,S,L)] call that
4601 **          registered the SQL function associated with [sqlite3_context] C.
4602 */
4603 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4604
4605 /*
4606 ** CAPI3REF: Function Auxiliary Data {H16270} <S20200>
4607 **
4608 ** The following two functions may be used by scalar SQL functions to
4609 ** associate metadata with argument values. If the same value is passed to
4610 ** multiple invocations of the same SQL function during query execution, under
4611 ** some circumstances the associated metadata may be preserved. This may
4612 ** be used, for example, to add a regular-expression matching scalar
4613 ** function. The compiled version of the regular expression is stored as
4614 ** metadata associated with the SQL value passed as the regular expression
4615 ** pattern.  The compiled regular expression can be reused on multiple
4616 ** invocations of the same function so that the original pattern string
4617 ** does not need to be recompiled on each invocation.
4618 **
4619 ** The sqlite3_get_auxdata() interface returns a pointer to the metadata
4620 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4621 ** value to the application-defined function. If no metadata has been ever
4622 ** been set for the Nth argument of the function, or if the corresponding
4623 ** function parameter has changed since the meta-data was set,
4624 ** then sqlite3_get_auxdata() returns a NULL pointer.
4625 **
4626 ** The sqlite3_set_auxdata() interface saves the metadata
4627 ** pointed to by its 3rd parameter as the metadata for the N-th
4628 ** argument of the application-defined function.  Subsequent
4629 ** calls to sqlite3_get_auxdata() might return this data, if it has
4630 ** not been destroyed.
4631 ** If it is not NULL, SQLite will invoke the destructor
4632 ** function given by the 4th parameter to sqlite3_set_auxdata() on
4633 ** the metadata when the corresponding function parameter changes
4634 ** or when the SQL statement completes, whichever comes first.
4635 **
4636 ** SQLite is free to call the destructor and drop metadata on any
4637 ** parameter of any function at any time.  The only guarantee is that
4638 ** the destructor will be called before the metadata is dropped.
4639 **
4640 ** In practice, metadata is preserved between function calls for
4641 ** expressions that are constant at compile time. This includes literal
4642 ** values and SQL variables.
4643 **
4644 ** These routines must be called from the same thread in which
4645 ** the SQL function is running.
4646 **
4647 ** INVARIANTS:
4648 **
4649 ** {H16272} The [sqlite3_get_auxdata(C,N)] interface returns a pointer
4650 **          to metadata associated with the Nth parameter of the SQL function
4651 **          whose context is C, or NULL if there is no metadata associated
4652 **          with that parameter.
4653 **
4654 ** {H16274} The [sqlite3_set_auxdata(C,N,P,D)] interface assigns a metadata
4655 **          pointer P to the Nth parameter of the SQL function with context C.
4656 **
4657 ** {H16276} SQLite will invoke the destructor D with a single argument
4658 **          which is the metadata pointer P following a call to
4659 **          [sqlite3_set_auxdata(C,N,P,D)] when SQLite ceases to hold
4660 **          the metadata.
4661 **
4662 ** {H16277} SQLite ceases to hold metadata for an SQL function parameter
4663 **          when the value of that parameter changes.
4664 **
4665 ** {H16278} When [sqlite3_set_auxdata(C,N,P,D)] is invoked, the destructor
4666 **          is called for any prior metadata associated with the same function
4667 **          context C and parameter N.
4668 **
4669 ** {H16279} SQLite will call destructors for any metadata it is holding
4670 **          in a particular [prepared statement] S when either
4671 **          [sqlite3_reset(S)] or [sqlite3_finalize(S)] is called.
4672 */
4673 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4674 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4675
4676
4677 /*
4678 ** CAPI3REF: Constants Defining Special Destructor Behavior {H10280} <S30100>
4679 **
4680 ** These are special values for the destructor that is passed in as the
4681 ** final argument to routines like [sqlite3_result_blob()].  If the destructor
4682 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4683 ** and will never change.  It does not need to be destroyed.  The
4684 ** SQLITE_TRANSIENT value means that the content will likely change in
4685 ** the near future and that SQLite should make its own private copy of
4686 ** the content before returning.
4687 **
4688 ** The typedef is necessary to work around problems in certain
4689 ** C++ compilers.  See ticket #2191.
4690 */
4691 typedef void (*sqlite3_destructor_type)(void*);
4692 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4693 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4694
4695 /*
4696 ** CAPI3REF: Setting The Result Of An SQL Function {H16400} <S20200>
4697 **
4698 ** These routines are used by the xFunc or xFinal callbacks that
4699 ** implement SQL functions and aggregates.  See
4700 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4701 ** for additional information.
4702 **
4703 ** These functions work very much like the [parameter binding] family of
4704 ** functions used to bind values to host parameters in prepared statements.
4705 ** Refer to the [SQL parameter] documentation for additional information.
4706 **
4707 ** The sqlite3_result_blob() interface sets the result from
4708 ** an application-defined function to be the BLOB whose content is pointed
4709 ** to by the second parameter and which is N bytes long where N is the
4710 ** third parameter.
4711 **
4712 ** The sqlite3_result_zeroblob() interfaces set the result of
4713 ** the application-defined function to be a BLOB containing all zero
4714 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4715 **
4716 ** The sqlite3_result_double() interface sets the result from
4717 ** an application-defined function to be a floating point value specified
4718 ** by its 2nd argument.
4719 **
4720 ** The sqlite3_result_error() and sqlite3_result_error16() functions
4721 ** cause the implemented SQL function to throw an exception.
4722 ** SQLite uses the string pointed to by the
4723 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4724 ** as the text of an error message.  SQLite interprets the error
4725 ** message string from sqlite3_result_error() as UTF-8. SQLite
4726 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
4727 ** byte order.  If the third parameter to sqlite3_result_error()
4728 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4729 ** message all text up through the first zero character.
4730 ** If the third parameter to sqlite3_result_error() or
4731 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4732 ** bytes (not characters) from the 2nd parameter as the error message.
4733 ** The sqlite3_result_error() and sqlite3_result_error16()
4734 ** routines make a private copy of the error message text before
4735 ** they return.  Hence, the calling function can deallocate or
4736 ** modify the text after they return without harm.
4737 ** The sqlite3_result_error_code() function changes the error code
4738 ** returned by SQLite as a result of an error in a function.  By default,
4739 ** the error code is SQLITE_ERROR.  A subsequent call to sqlite3_result_error()
4740 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4741 **
4742 ** The sqlite3_result_toobig() interface causes SQLite to throw an error
4743 ** indicating that a string or BLOB is to long to represent.
4744 **
4745 ** The sqlite3_result_nomem() interface causes SQLite to throw an error
4746 ** indicating that a memory allocation failed.
4747 **
4748 ** The sqlite3_result_int() interface sets the return value
4749 ** of the application-defined function to be the 32-bit signed integer
4750 ** value given in the 2nd argument.
4751 ** The sqlite3_result_int64() interface sets the return value
4752 ** of the application-defined function to be the 64-bit signed integer
4753 ** value given in the 2nd argument.
4754 **
4755 ** The sqlite3_result_null() interface sets the return value
4756 ** of the application-defined function to be NULL.
4757 **
4758 ** The sqlite3_result_text(), sqlite3_result_text16(),
4759 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4760 ** set the return value of the application-defined function to be
4761 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4762 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4763 ** SQLite takes the text result from the application from
4764 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4765 ** If the 3rd parameter to the sqlite3_result_text* interfaces
4766 ** is negative, then SQLite takes result text from the 2nd parameter
4767 ** through the first zero character.
4768 ** If the 3rd parameter to the sqlite3_result_text* interfaces
4769 ** is non-negative, then as many bytes (not characters) of the text
4770 ** pointed to by the 2nd parameter are taken as the application-defined
4771 ** function result.
4772 ** If the 4th parameter to the sqlite3_result_text* interfaces
4773 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4774 ** function as the destructor on the text or BLOB result when it has
4775 ** finished using that result.
4776 ** If the 4th parameter to the sqlite3_result_text* interfaces or
4777 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4778 ** assumes that the text or BLOB result is in constant space and does not
4779 ** copy the it or call a destructor when it has finished using that result.
4780 ** If the 4th parameter to the sqlite3_result_text* interfaces
4781 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4782 ** then SQLite makes a copy of the result into space obtained from
4783 ** from [sqlite3_malloc()] before it returns.
4784 **
4785 ** The sqlite3_result_value() interface sets the result of
4786 ** the application-defined function to be a copy the
4787 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  The
4788 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4789 ** so that the [sqlite3_value] specified in the parameter may change or
4790 ** be deallocated after sqlite3_result_value() returns without harm.
4791 ** A [protected sqlite3_value] object may always be used where an
4792 ** [unprotected sqlite3_value] object is required, so either
4793 ** kind of [sqlite3_value] object can be used with this interface.
4794 **
4795 ** If these routines are called from within the different thread
4796 ** than the one containing the application-defined function that received
4797 ** the [sqlite3_context] pointer, the results are undefined.
4798 **
4799 ** INVARIANTS:
4800 **
4801 ** {H16403} The default return value from any SQL function is NULL.
4802 **
4803 ** {H16406} The [sqlite3_result_blob(C,V,N,D)] interface changes the
4804 **          return value of function C to be a BLOB that is N bytes
4805 **          in length and with content pointed to by V.
4806 **
4807 ** {H16409} The [sqlite3_result_double(C,V)] interface changes the
4808 **          return value of function C to be the floating point value V.
4809 **
4810 ** {H16412} The [sqlite3_result_error(C,V,N)] interface changes the return
4811 **          value of function C to be an exception with error code
4812 **          [SQLITE_ERROR] and a UTF-8 error message copied from V up to the
4813 **          first zero byte or until N bytes are read if N is positive.
4814 **
4815 ** {H16415} The [sqlite3_result_error16(C,V,N)] interface changes the return
4816 **          value of function C to be an exception with error code
4817 **          [SQLITE_ERROR] and a UTF-16 native byte order error message
4818 **          copied from V up to the first zero terminator or until N bytes
4819 **          are read if N is positive.
4820 **
4821 ** {H16418} The [sqlite3_result_error_toobig(C)] interface changes the return
4822 **          value of the function C to be an exception with error code
4823 **          [SQLITE_TOOBIG] and an appropriate error message.
4824 **
4825 ** {H16421} The [sqlite3_result_error_nomem(C)] interface changes the return
4826 **          value of the function C to be an exception with error code
4827 **          [SQLITE_NOMEM] and an appropriate error message.
4828 **
4829 ** {H16424} The [sqlite3_result_error_code(C,E)] interface changes the return
4830 **          value of the function C to be an exception with error code E.
4831 **          The error message text is unchanged.
4832 **
4833 ** {H16427} The [sqlite3_result_int(C,V)] interface changes the
4834 **          return value of function C to be the 32-bit integer value V.
4835 **
4836 ** {H16430} The [sqlite3_result_int64(C,V)] interface changes the
4837 **          return value of function C to be the 64-bit integer value V.
4838 **
4839 ** {H16433} The [sqlite3_result_null(C)] interface changes the
4840 **          return value of function C to be NULL.
4841 **
4842 ** {H16436} The [sqlite3_result_text(C,V,N,D)] interface changes the
4843 **          return value of function C to be the UTF-8 string
4844 **          V up to the first zero if N is negative
4845 **          or the first N bytes of V if N is non-negative.
4846 **
4847 ** {H16439} The [sqlite3_result_text16(C,V,N,D)] interface changes the
4848 **          return value of function C to be the UTF-16 native byte order
4849 **          string V up to the first zero if N is negative
4850 **          or the first N bytes of V if N is non-negative.
4851 **
4852 ** {H16442} The [sqlite3_result_text16be(C,V,N,D)] interface changes the
4853 **          return value of function C to be the UTF-16 big-endian
4854 **          string V up to the first zero if N is negative
4855 **          or the first N bytes or V if N is non-negative.
4856 **
4857 ** {H16445} The [sqlite3_result_text16le(C,V,N,D)] interface changes the
4858 **          return value of function C to be the UTF-16 little-endian
4859 **          string V up to the first zero if N is negative
4860 **          or the first N bytes of V if N is non-negative.
4861 **
4862 ** {H16448} The [sqlite3_result_value(C,V)] interface changes the
4863 **          return value of function C to be the [unprotected sqlite3_value]
4864 **          object V.
4865 **
4866 ** {H16451} The [sqlite3_result_zeroblob(C,N)] interface changes the
4867 **          return value of function C to be an N-byte BLOB of all zeros.
4868 **
4869 ** {H16454} The [sqlite3_result_error()] and [sqlite3_result_error16()]
4870 **          interfaces make a copy of their error message strings before
4871 **          returning.
4872 **
4873 ** {H16457} If the D destructor parameter to [sqlite3_result_blob(C,V,N,D)],
4874 **          [sqlite3_result_text(C,V,N,D)], [sqlite3_result_text16(C,V,N,D)],
4875 **          [sqlite3_result_text16be(C,V,N,D)], or
4876 **          [sqlite3_result_text16le(C,V,N,D)] is the constant [SQLITE_STATIC]
4877 **          then no destructor is ever called on the pointer V and SQLite
4878 **          assumes that V is immutable.
4879 **
4880 ** {H16460} If the D destructor parameter to [sqlite3_result_blob(C,V,N,D)],
4881 **          [sqlite3_result_text(C,V,N,D)], [sqlite3_result_text16(C,V,N,D)],
4882 **          [sqlite3_result_text16be(C,V,N,D)], or
4883 **          [sqlite3_result_text16le(C,V,N,D)] is the constant
4884 **          [SQLITE_TRANSIENT] then the interfaces makes a copy of the
4885 **          content of V and retains the copy.
4886 **
4887 ** {H16463} If the D destructor parameter to [sqlite3_result_blob(C,V,N,D)],
4888 **          [sqlite3_result_text(C,V,N,D)], [sqlite3_result_text16(C,V,N,D)],
4889 **          [sqlite3_result_text16be(C,V,N,D)], or
4890 **          [sqlite3_result_text16le(C,V,N,D)] is some value other than
4891 **          the constants [SQLITE_STATIC] and [SQLITE_TRANSIENT] then
4892 **          SQLite will invoke the destructor D with V as its only argument
4893 **          when it has finished with the V value.
4894 */
4895 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4896 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4897 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4898 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4899 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4900 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4901 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4902 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4903 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4904 SQLITE_API void sqlite3_result_null(sqlite3_context*);
4905 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4906 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4907 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4908 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4909 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4910 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4911
4912 /*
4913 ** CAPI3REF: Define New Collating Sequences {H16600} <S20300>
4914 **
4915 ** These functions are used to add new collation sequences to the
4916 ** [database connection] specified as the first argument.
4917 **
4918 ** The name of the new collation sequence is specified as a UTF-8 string
4919 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4920 ** and a UTF-16 string for sqlite3_create_collation16(). In all cases
4921 ** the name is passed as the second function argument.
4922 **
4923 ** The third argument may be one of the constants [SQLITE_UTF8],
4924 ** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied
4925 ** routine expects to be passed pointers to strings encoded using UTF-8,
4926 ** UTF-16 little-endian, or UTF-16 big-endian, respectively. The
4927 ** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that
4928 ** the routine expects pointers to 16-bit word aligned strings
4929 ** of UTF-16 in the native byte order of the host computer.
4930 **
4931 ** A pointer to the user supplied routine must be passed as the fifth
4932 ** argument.  If it is NULL, this is the same as deleting the collation
4933 ** sequence (so that SQLite cannot call it anymore).
4934 ** Each time the application supplied function is invoked, it is passed
4935 ** as its first parameter a copy of the void* passed as the fourth argument
4936 ** to sqlite3_create_collation() or sqlite3_create_collation16().
4937 **
4938 ** The remaining arguments to the application-supplied routine are two strings,
4939 ** each represented by a (length, data) pair and encoded in the encoding
4940 ** that was passed as the third argument when the collation sequence was
4941 ** registered. {END}  The application defined collation routine should
4942 ** return negative, zero or positive if the first string is less than,
4943 ** equal to, or greater than the second string. i.e. (STRING1 - STRING2).
4944 **
4945 ** The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4946 ** except that it takes an extra argument which is a destructor for
4947 ** the collation.  The destructor is called when the collation is
4948 ** destroyed and is passed a copy of the fourth parameter void* pointer
4949 ** of the sqlite3_create_collation_v2().
4950 ** Collations are destroyed when they are overridden by later calls to the
4951 ** collation creation functions or when the [database connection] is closed
4952 ** using [sqlite3_close()].
4953 **
4954 ** INVARIANTS:
4955 **
4956 ** {H16603} A successful call to the
4957 **          [sqlite3_create_collation_v2(B,X,E,P,F,D)] interface
4958 **          registers function F as the comparison function used to
4959 **          implement collation X on the [database connection] B for
4960 **          databases having encoding E.
4961 **
4962 ** {H16604} SQLite understands the X parameter to
4963 **          [sqlite3_create_collation_v2(B,X,E,P,F,D)] as a zero-terminated
4964 **          UTF-8 string in which case is ignored for ASCII characters and
4965 **          is significant for non-ASCII characters.
4966 **
4967 ** {H16606} Successive calls to [sqlite3_create_collation_v2(B,X,E,P,F,D)]
4968 **          with the same values for B, X, and E, override prior values
4969 **          of P, F, and D.
4970 **
4971 ** {H16609} If the destructor D in [sqlite3_create_collation_v2(B,X,E,P,F,D)]
4972 **          is not NULL then it is called with argument P when the
4973 **          collating function is dropped by SQLite.
4974 **
4975 ** {H16612} A collating function is dropped when it is overloaded.
4976 **
4977 ** {H16615} A collating function is dropped when the database connection
4978 **          is closed using [sqlite3_close()].
4979 **
4980 ** {H16618} The pointer P in [sqlite3_create_collation_v2(B,X,E,P,F,D)]
4981 **          is passed through as the first parameter to the comparison
4982 **          function F for all subsequent invocations of F.
4983 **
4984 ** {H16621} A call to [sqlite3_create_collation(B,X,E,P,F)] is exactly
4985 **          the same as a call to [sqlite3_create_collation_v2()] with
4986 **          the same parameters and a NULL destructor.
4987 **
4988 ** {H16624} Following a [sqlite3_create_collation_v2(B,X,E,P,F,D)],
4989 **          SQLite uses the comparison function F for all text comparison
4990 **          operations on the [database connection] B on text values that
4991 **          use the collating sequence named X.
4992 **
4993 ** {H16627} The [sqlite3_create_collation16(B,X,E,P,F)] works the same
4994 **          as [sqlite3_create_collation(B,X,E,P,F)] except that the
4995 **          collation name X is understood as UTF-16 in native byte order
4996 **          instead of UTF-8.
4997 **
4998 ** {H16630} When multiple comparison functions are available for the same
4999 **          collating sequence, SQLite chooses the one whose text encoding
5000 **          requires the least amount of conversion from the default
5001 **          text encoding of the database.
5002 */
5003 SQLITE_API int sqlite3_create_collation(
5004   sqlite3*, 
5005   const char *zName, 
5006   int eTextRep, 
5007   void*,
5008   int(*xCompare)(void*,int,const void*,int,const void*)
5009 );
5010 SQLITE_API int sqlite3_create_collation_v2(
5011   sqlite3*, 
5012   const char *zName, 
5013   int eTextRep, 
5014   void*,
5015   int(*xCompare)(void*,int,const void*,int,const void*),
5016   void(*xDestroy)(void*)
5017 );
5018 SQLITE_API int sqlite3_create_collation16(
5019   sqlite3*, 
5020   const void *zName,
5021   int eTextRep, 
5022   void*,
5023   int(*xCompare)(void*,int,const void*,int,const void*)
5024 );
5025
5026 /*
5027 ** CAPI3REF: Collation Needed Callbacks {H16700} <S20300>
5028 **
5029 ** To avoid having to register all collation sequences before a database
5030 ** can be used, a single callback function may be registered with the
5031 ** [database connection] to be called whenever an undefined collation
5032 ** sequence is required.
5033 **
5034 ** If the function is registered using the sqlite3_collation_needed() API,
5035 ** then it is passed the names of undefined collation sequences as strings
5036 ** encoded in UTF-8. {H16703} If sqlite3_collation_needed16() is used,
5037 ** the names are passed as UTF-16 in machine native byte order.
5038 ** A call to either function replaces any existing callback.
5039 **
5040 ** When the callback is invoked, the first argument passed is a copy
5041 ** of the second argument to sqlite3_collation_needed() or
5042 ** sqlite3_collation_needed16().  The second argument is the database
5043 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
5044 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
5045 ** sequence function required.  The fourth parameter is the name of the
5046 ** required collation sequence.
5047 **
5048 ** The callback function should register the desired collation using
5049 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
5050 ** [sqlite3_create_collation_v2()].
5051 **
5052 ** INVARIANTS:
5053 **
5054 ** {H16702} A successful call to [sqlite3_collation_needed(D,P,F)]
5055 **          or [sqlite3_collation_needed16(D,P,F)] causes
5056 **          the [database connection] D to invoke callback F with first
5057 **          parameter P whenever it needs a comparison function for a
5058 **          collating sequence that it does not know about.
5059 **
5060 ** {H16704} Each successful call to [sqlite3_collation_needed()] or
5061 **          [sqlite3_collation_needed16()] overrides the callback registered
5062 **          on the same [database connection] by prior calls to either
5063 **          interface.
5064 **
5065 ** {H16706} The name of the requested collating function passed in the
5066 **          4th parameter to the callback is in UTF-8 if the callback
5067 **          was registered using [sqlite3_collation_needed()] and
5068 **          is in UTF-16 native byte order if the callback was
5069 **          registered using [sqlite3_collation_needed16()].
5070 */
5071 SQLITE_API int sqlite3_collation_needed(
5072   sqlite3*, 
5073   void*, 
5074   void(*)(void*,sqlite3*,int eTextRep,const char*)
5075 );
5076 SQLITE_API int sqlite3_collation_needed16(
5077   sqlite3*, 
5078   void*,
5079   void(*)(void*,sqlite3*,int eTextRep,const void*)
5080 );
5081
5082 /*
5083 ** Specify the key for an encrypted database.  This routine should be
5084 ** called right after sqlite3_open().
5085 **
5086 ** The code to implement this API is not available in the public release
5087 ** of SQLite.
5088 */
5089 SQLITE_API int sqlite3_key(
5090   sqlite3 *db,                   /* Database to be rekeyed */
5091   const void *pKey, int nKey     /* The key */
5092 );
5093
5094 /*
5095 ** Change the key on an open database.  If the current database is not
5096 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
5097 ** database is decrypted.
5098 **
5099 ** The code to implement this API is not available in the public release
5100 ** of SQLite.
5101 */
5102 SQLITE_API int sqlite3_rekey(
5103   sqlite3 *db,                   /* Database to be rekeyed */
5104   const void *pKey, int nKey     /* The new key */
5105 );
5106
5107 /*
5108 ** CAPI3REF: Suspend Execution For A Short Time {H10530} <S40410>
5109 **
5110 ** The sqlite3_sleep() function causes the current thread to suspend execution
5111 ** for at least a number of milliseconds specified in its parameter.
5112 **
5113 ** If the operating system does not support sleep requests with
5114 ** millisecond time resolution, then the time will be rounded up to
5115 ** the nearest second. The number of milliseconds of sleep actually
5116 ** requested from the operating system is returned.
5117 **
5118 ** SQLite implements this interface by calling the xSleep()
5119 ** method of the default [sqlite3_vfs] object.
5120 **
5121 ** INVARIANTS:
5122 **
5123 ** {H10533} The [sqlite3_sleep(M)] interface invokes the xSleep
5124 **          method of the default [sqlite3_vfs|VFS] in order to
5125 **          suspend execution of the current thread for at least
5126 **          M milliseconds.
5127 **
5128 ** {H10536} The [sqlite3_sleep(M)] interface returns the number of
5129 **          milliseconds of sleep actually requested of the operating
5130 **          system, which might be larger than the parameter M.
5131 */
5132 SQLITE_API int sqlite3_sleep(int);
5133
5134 /*
5135 ** CAPI3REF: Name Of The Folder Holding Temporary Files {H10310} <S20000>
5136 **
5137 ** If this global variable is made to point to a string which is
5138 ** the name of a folder (a.k.a. directory), then all temporary files
5139 ** created by SQLite will be placed in that directory.  If this variable
5140 ** is a NULL pointer, then SQLite performs a search for an appropriate
5141 ** temporary file directory.
5142 **
5143 ** It is not safe to modify this variable once a [database connection]
5144 ** has been opened.  It is intended that this variable be set once
5145 ** as part of process initialization and before any SQLite interface
5146 ** routines have been call and remain unchanged thereafter.
5147 */
5148 SQLITE_API char *sqlite3_temp_directory;
5149
5150 /*
5151 ** CAPI3REF: Test For Auto-Commit Mode {H12930} <S60200>
5152 ** KEYWORDS: {autocommit mode}
5153 **
5154 ** The sqlite3_get_autocommit() interface returns non-zero or
5155 ** zero if the given database connection is or is not in autocommit mode,
5156 ** respectively.  Autocommit mode is on by default.
5157 ** Autocommit mode is disabled by a [BEGIN] statement.
5158 ** Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
5159 **
5160 ** If certain kinds of errors occur on a statement within a multi-statement
5161 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
5162 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
5163 ** transaction might be rolled back automatically.  The only way to
5164 ** find out whether SQLite automatically rolled back the transaction after
5165 ** an error is to use this function.
5166 **
5167 ** INVARIANTS:
5168 **
5169 ** {H12931} The [sqlite3_get_autocommit(D)] interface returns non-zero or
5170 **          zero if the [database connection] D is or is not in autocommit
5171 **          mode, respectively.
5172 **
5173 ** {H12932} Autocommit mode is on by default.
5174 **
5175 ** {H12933} Autocommit mode is disabled by a successful [BEGIN] statement.
5176 **
5177 ** {H12934} Autocommit mode is enabled by a successful [COMMIT] or [ROLLBACK]
5178 **          statement.
5179 **
5180 ** ASSUMPTIONS:
5181 **
5182 ** {A12936} If another thread changes the autocommit status of the database
5183 **          connection while this routine is running, then the return value
5184 **          is undefined.
5185 */
5186 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
5187
5188 /*
5189 ** CAPI3REF: Find The Database Handle Of A Prepared Statement {H13120} <S60600>
5190 **
5191 ** The sqlite3_db_handle interface returns the [database connection] handle
5192 ** to which a [prepared statement] belongs.  The database handle returned by
5193 ** sqlite3_db_handle is the same database handle that was the first argument
5194 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
5195 ** create the statement in the first place.
5196 **
5197 ** INVARIANTS:
5198 **
5199 ** {H13123} The [sqlite3_db_handle(S)] interface returns a pointer
5200 **          to the [database connection] associated with the
5201 **          [prepared statement] S.
5202 */
5203 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
5204
5205 /*
5206 ** CAPI3REF: Find the next prepared statement {H13140} <S60600>
5207 **
5208 ** This interface returns a pointer to the next [prepared statement] after
5209 ** pStmt associated with the [database connection] pDb.  If pStmt is NULL
5210 ** then this interface returns a pointer to the first prepared statement
5211 ** associated with the database connection pDb.  If no prepared statement
5212 ** satisfies the conditions of this routine, it returns NULL.
5213 **
5214 ** INVARIANTS:
5215 **
5216 ** {H13143} If D is a [database connection] that holds one or more
5217 **          unfinalized [prepared statements] and S is a NULL pointer,
5218 **          then [sqlite3_next_stmt(D, S)] routine shall return a pointer
5219 **          to one of the prepared statements associated with D.
5220 **
5221 ** {H13146} If D is a [database connection] that holds no unfinalized
5222 **          [prepared statements] and S is a NULL pointer, then
5223 **          [sqlite3_next_stmt(D, S)] routine shall return a NULL pointer.
5224 **
5225 ** {H13149} If S is a [prepared statement] in the [database connection] D
5226 **          and S is not the last prepared statement in D, then
5227 **          [sqlite3_next_stmt(D, S)] routine shall return a pointer
5228 **          to the next prepared statement in D after S.
5229 **
5230 ** {H13152} If S is the last [prepared statement] in the
5231 **          [database connection] D then the [sqlite3_next_stmt(D, S)]
5232 **          routine shall return a NULL pointer.
5233 **
5234 ** ASSUMPTIONS:
5235 **
5236 ** {A13154} The [database connection] pointer D in a call to
5237 **          [sqlite3_next_stmt(D,S)] must refer to an open database
5238 **          connection and in particular must not be a NULL pointer.
5239 */
5240 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
5241
5242 /*
5243 ** CAPI3REF: Commit And Rollback Notification Callbacks {H12950} <S60400>
5244 **
5245 ** The sqlite3_commit_hook() interface registers a callback
5246 ** function to be invoked whenever a transaction is committed.
5247 ** Any callback set by a previous call to sqlite3_commit_hook()
5248 ** for the same database connection is overridden.
5249 ** The sqlite3_rollback_hook() interface registers a callback
5250 ** function to be invoked whenever a transaction is committed.
5251 ** Any callback set by a previous call to sqlite3_commit_hook()
5252 ** for the same database connection is overridden.
5253 ** The pArg argument is passed through to the callback.
5254 ** If the callback on a commit hook function returns non-zero,
5255 ** then the commit is converted into a rollback.
5256 **
5257 ** If another function was previously registered, its
5258 ** pArg value is returned.  Otherwise NULL is returned.
5259 **
5260 ** Registering a NULL function disables the callback.
5261 **
5262 ** For the purposes of this API, a transaction is said to have been
5263 ** rolled back if an explicit "ROLLBACK" statement is executed, or
5264 ** an error or constraint causes an implicit rollback to occur.
5265 ** The rollback callback is not invoked if a transaction is
5266 ** automatically rolled back because the database connection is closed.
5267 ** The rollback callback is not invoked if a transaction is
5268 ** rolled back because a commit callback returned non-zero.
5269 ** <todo> Check on this </todo>
5270 **
5271 ** INVARIANTS:
5272 **
5273 ** {H12951} The [sqlite3_commit_hook(D,F,P)] interface registers the
5274 **          callback function F to be invoked with argument P whenever
5275 **          a transaction commits on the [database connection] D.
5276 **
5277 ** {H12952} The [sqlite3_commit_hook(D,F,P)] interface returns the P argument
5278 **          from the previous call with the same [database connection] D,
5279 **          or NULL on the first call for a particular database connection D.
5280 **
5281 ** {H12953} Each call to [sqlite3_commit_hook()] overwrites the callback
5282 **          registered by prior calls.
5283 **
5284 ** {H12954} If the F argument to [sqlite3_commit_hook(D,F,P)] is NULL
5285 **          then the commit hook callback is canceled and no callback
5286 **          is invoked when a transaction commits.
5287 **
5288 ** {H12955} If the commit callback returns non-zero then the commit is
5289 **          converted into a rollback.
5290 **
5291 ** {H12961} The [sqlite3_rollback_hook(D,F,P)] interface registers the
5292 **          callback function F to be invoked with argument P whenever
5293 **          a transaction rolls back on the [database connection] D.
5294 **
5295 ** {H12962} The [sqlite3_rollback_hook(D,F,P)] interface returns the P
5296 **          argument from the previous call with the same
5297 **          [database connection] D, or NULL on the first call
5298 **          for a particular database connection D.
5299 **
5300 ** {H12963} Each call to [sqlite3_rollback_hook()] overwrites the callback
5301 **          registered by prior calls.
5302 **
5303 ** {H12964} If the F argument to [sqlite3_rollback_hook(D,F,P)] is NULL
5304 **          then the rollback hook callback is canceled and no callback
5305 **          is invoked when a transaction rolls back.
5306 */
5307 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
5308 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
5309
5310 /*
5311 ** CAPI3REF: Data Change Notification Callbacks {H12970} <S60400>
5312 **
5313 ** The sqlite3_update_hook() interface registers a callback function
5314 ** with the [database connection] identified by the first argument
5315 ** to be invoked whenever a row is updated, inserted or deleted.
5316 ** Any callback set by a previous call to this function
5317 ** for the same database connection is overridden.
5318 **
5319 ** The second argument is a pointer to the function to invoke when a
5320 ** row is updated, inserted or deleted.
5321 ** The first argument to the callback is a copy of the third argument
5322 ** to sqlite3_update_hook().
5323 ** The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
5324 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
5325 ** to be invoked.
5326 ** The third and fourth arguments to the callback contain pointers to the
5327 ** database and table name containing the affected row.
5328 ** The final callback parameter is the rowid of the row. In the case of
5329 ** an update, this is the rowid after the update takes place.
5330 **
5331 ** The update hook is not invoked when internal system tables are
5332 ** modified (i.e. sqlite_master and sqlite_sequence).
5333 **
5334 ** If another function was previously registered, its pArg value
5335 ** is returned.  Otherwise NULL is returned.
5336 **
5337 ** INVARIANTS:
5338 **
5339 ** {H12971} The [sqlite3_update_hook(D,F,P)] interface causes the callback
5340 **          function F to be invoked with first parameter P whenever
5341 **          a table row is modified, inserted, or deleted on
5342 **          the [database connection] D.
5343 **
5344 ** {H12973} The [sqlite3_update_hook(D,F,P)] interface returns the value
5345 **          of P for the previous call on the same [database connection] D,
5346 **          or NULL for the first call.
5347 **
5348 ** {H12975} If the update hook callback F in [sqlite3_update_hook(D,F,P)]
5349 **          is NULL then the no update callbacks are made.
5350 **
5351 ** {H12977} Each call to [sqlite3_update_hook(D,F,P)] overrides prior calls
5352 **          to the same interface on the same [database connection] D.
5353 **
5354 ** {H12979} The update hook callback is not invoked when internal system
5355 **          tables such as sqlite_master and sqlite_sequence are modified.
5356 **
5357 ** {H12981} The second parameter to the update callback
5358 **          is one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE],
5359 **          depending on the operation that caused the callback to be invoked.
5360 **
5361 ** {H12983} The third and fourth arguments to the callback contain pointers
5362 **          to zero-terminated UTF-8 strings which are the names of the
5363 **          database and table that is being updated.
5364
5365 ** {H12985} The final callback parameter is the rowid of the row after
5366 **          the change occurs.
5367 */
5368 SQLITE_API void *sqlite3_update_hook(
5369   sqlite3*, 
5370   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5371   void*
5372 );
5373
5374 /*
5375 ** CAPI3REF: Enable Or Disable Shared Pager Cache {H10330} <S30900>
5376 ** KEYWORDS: {shared cache} {shared cache mode}
5377 **
5378 ** This routine enables or disables the sharing of the database cache
5379 ** and schema data structures between [database connection | connections]
5380 ** to the same database. Sharing is enabled if the argument is true
5381 ** and disabled if the argument is false.
5382 **
5383 ** Cache sharing is enabled and disabled for an entire process. {END}
5384 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
5385 ** sharing was enabled or disabled for each thread separately.
5386 **
5387 ** The cache sharing mode set by this interface effects all subsequent
5388 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
5389 ** Existing database connections continue use the sharing mode
5390 ** that was in effect at the time they were opened.
5391 **
5392 ** Virtual tables cannot be used with a shared cache.  When shared
5393 ** cache is enabled, the [sqlite3_create_module()] API used to register
5394 ** virtual tables will always return an error.
5395 **
5396 ** This routine returns [SQLITE_OK] if shared cache was enabled or disabled
5397 ** successfully.  An [error code] is returned otherwise.
5398 **
5399 ** Shared cache is disabled by default. But this might change in
5400 ** future releases of SQLite.  Applications that care about shared
5401 ** cache setting should set it explicitly.
5402 **
5403 ** INVARIANTS:
5404 **
5405 ** {H10331} A successful invocation of [sqlite3_enable_shared_cache(B)]
5406 **          will enable or disable shared cache mode for any subsequently
5407 **          created [database connection] in the same process.
5408 **
5409 ** {H10336} When shared cache is enabled, the [sqlite3_create_module()]
5410 **          interface will always return an error.
5411 **
5412 ** {H10337} The [sqlite3_enable_shared_cache(B)] interface returns
5413 **          [SQLITE_OK] if shared cache was enabled or disabled successfully.
5414 **
5415 ** {H10339} Shared cache is disabled by default.
5416 */
5417 SQLITE_API int sqlite3_enable_shared_cache(int);
5418
5419 /*
5420 ** CAPI3REF: Attempt To Free Heap Memory {H17340} <S30220>
5421 **
5422 ** The sqlite3_release_memory() interface attempts to free N bytes
5423 ** of heap memory by deallocating non-essential memory allocations
5424 ** held by the database library. {END}  Memory used to cache database
5425 ** pages to improve performance is an example of non-essential memory.
5426 ** sqlite3_release_memory() returns the number of bytes actually freed,
5427 ** which might be more or less than the amount requested.
5428 **
5429 ** INVARIANTS:
5430 **
5431 ** {H17341} The [sqlite3_release_memory(N)] interface attempts to
5432 **          free N bytes of heap memory by deallocating non-essential
5433 **          memory allocations held by the database library.
5434 **
5435 ** {H16342} The [sqlite3_release_memory(N)] returns the number
5436 **          of bytes actually freed, which might be more or less
5437 **          than the amount requested.
5438 */
5439 SQLITE_API int sqlite3_release_memory(int);
5440
5441 /*
5442 ** CAPI3REF: Impose A Limit On Heap Size {H17350} <S30220>
5443 **
5444 ** The sqlite3_soft_heap_limit() interface places a "soft" limit
5445 ** on the amount of heap memory that may be allocated by SQLite.
5446 ** If an internal allocation is requested that would exceed the
5447 ** soft heap limit, [sqlite3_release_memory()] is invoked one or
5448 ** more times to free up some space before the allocation is performed.
5449 **
5450 ** The limit is called "soft", because if [sqlite3_release_memory()]
5451 ** cannot free sufficient memory to prevent the limit from being exceeded,
5452 ** the memory is allocated anyway and the current operation proceeds.
5453 **
5454 ** A negative or zero value for N means that there is no soft heap limit and
5455 ** [sqlite3_release_memory()] will only be called when memory is exhausted.
5456 ** The default value for the soft heap limit is zero.
5457 **
5458 ** SQLite makes a best effort to honor the soft heap limit.
5459 ** But if the soft heap limit cannot be honored, execution will
5460 ** continue without error or notification.  This is why the limit is
5461 ** called a "soft" limit.  It is advisory only.
5462 **
5463 ** Prior to SQLite version 3.5.0, this routine only constrained the memory
5464 ** allocated by a single thread - the same thread in which this routine
5465 ** runs.  Beginning with SQLite version 3.5.0, the soft heap limit is
5466 ** applied to all threads. The value specified for the soft heap limit
5467 ** is an upper bound on the total memory allocation for all threads. In
5468 ** version 3.5.0 there is no mechanism for limiting the heap usage for
5469 ** individual threads.
5470 **
5471 ** INVARIANTS:
5472 **
5473 ** {H16351} The [sqlite3_soft_heap_limit(N)] interface places a soft limit
5474 **          of N bytes on the amount of heap memory that may be allocated
5475 **          using [sqlite3_malloc()] or [sqlite3_realloc()] at any point
5476 **          in time.
5477 **
5478 ** {H16352} If a call to [sqlite3_malloc()] or [sqlite3_realloc()] would
5479 **          cause the total amount of allocated memory to exceed the
5480 **          soft heap limit, then [sqlite3_release_memory()] is invoked
5481 **          in an attempt to reduce the memory usage prior to proceeding
5482 **          with the memory allocation attempt.
5483 **
5484 ** {H16353} Calls to [sqlite3_malloc()] or [sqlite3_realloc()] that trigger
5485 **          attempts to reduce memory usage through the soft heap limit
5486 **          mechanism continue even if the attempt to reduce memory
5487 **          usage is unsuccessful.
5488 **
5489 ** {H16354} A negative or zero value for N in a call to
5490 **          [sqlite3_soft_heap_limit(N)] means that there is no soft
5491 **          heap limit and [sqlite3_release_memory()] will only be
5492 **          called when memory is completely exhausted.
5493 **
5494 ** {H16355} The default value for the soft heap limit is zero.
5495 **
5496 ** {H16358} Each call to [sqlite3_soft_heap_limit(N)] overrides the
5497 **          values set by all prior calls.
5498 */
5499 SQLITE_API void sqlite3_soft_heap_limit(int);
5500
5501 /*
5502 ** CAPI3REF: Extract Metadata About A Column Of A Table {H12850} <S60300>
5503 **
5504 ** This routine returns metadata about a specific column of a specific
5505 ** database table accessible using the [database connection] handle
5506 ** passed as the first function argument.
5507 **
5508 ** The column is identified by the second, third and fourth parameters to
5509 ** this function. The second parameter is either the name of the database
5510 ** (i.e. "main", "temp" or an attached database) containing the specified
5511 ** table or NULL. If it is NULL, then all attached databases are searched
5512 ** for the table using the same algorithm used by the database engine to
5513 ** resolve unqualified table references.
5514 **
5515 ** The third and fourth parameters to this function are the table and column
5516 ** name of the desired column, respectively. Neither of these parameters
5517 ** may be NULL.
5518 **
5519 ** Metadata is returned by writing to the memory locations passed as the 5th
5520 ** and subsequent parameters to this function. Any of these arguments may be
5521 ** NULL, in which case the corresponding element of metadata is omitted.
5522 **
5523 ** <blockquote>
5524 ** <table border="1">
5525 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
5526 **
5527 ** <tr><td> 5th <td> const char* <td> Data type
5528 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5529 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
5530 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
5531 ** <tr><td> 9th <td> int         <td> True if column is AUTOINCREMENT
5532 ** </table>
5533 ** </blockquote>
5534 **
5535 ** The memory pointed to by the character pointers returned for the
5536 ** declaration type and collation sequence is valid only until the next
5537 ** call to any SQLite API function.
5538 **
5539 ** If the specified table is actually a view, an [error code] is returned.
5540 **
5541 ** If the specified column is "rowid", "oid" or "_rowid_" and an
5542 ** INTEGER PRIMARY KEY column has been explicitly declared, then the output
5543 ** parameters are set for the explicitly declared column. If there is no
5544 ** explicitly declared INTEGER PRIMARY KEY column, then the output
5545 ** parameters are set as follows:
5546 **
5547 ** <pre>
5548 **     data type: "INTEGER"
5549 **     collation sequence: "BINARY"
5550 **     not null: 0
5551 **     primary key: 1
5552 **     auto increment: 0
5553 ** </pre>
5554 **
5555 ** This function may load one or more schemas from database files. If an
5556 ** error occurs during this process, or if the requested table or column
5557 ** cannot be found, an [error code] is returned and an error message left
5558 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).
5559 **
5560 ** This API is only available if the library was compiled with the
5561 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
5562 */
5563 SQLITE_API int sqlite3_table_column_metadata(
5564   sqlite3 *db,                /* Connection handle */
5565   const char *zDbName,        /* Database name or NULL */
5566   const char *zTableName,     /* Table name */
5567   const char *zColumnName,    /* Column name */
5568   char const **pzDataType,    /* OUTPUT: Declared data type */
5569   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
5570   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
5571   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
5572   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
5573 );
5574
5575 /*
5576 ** CAPI3REF: Load An Extension {H12600} <S20500>
5577 **
5578 ** This interface loads an SQLite extension library from the named file.
5579 **
5580 ** {H12601} The sqlite3_load_extension() interface attempts to load an
5581 **          SQLite extension library contained in the file zFile.
5582 **
5583 ** {H12602} The entry point is zProc.
5584 **
5585 ** {H12603} zProc may be 0, in which case the name of the entry point
5586 **          defaults to "sqlite3_extension_init".
5587 **
5588 ** {H12604} The sqlite3_load_extension() interface shall return
5589 **          [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5590 **
5591 ** {H12605} If an error occurs and pzErrMsg is not 0, then the
5592 **          [sqlite3_load_extension()] interface shall attempt to
5593 **          fill *pzErrMsg with error message text stored in memory
5594 **          obtained from [sqlite3_malloc()]. {END}  The calling function
5595 **          should free this memory by calling [sqlite3_free()].
5596 **
5597 ** {H12606} Extension loading must be enabled using
5598 **          [sqlite3_enable_load_extension()] prior to calling this API,
5599 **          otherwise an error will be returned.
5600 */
5601 SQLITE_API int sqlite3_load_extension(
5602   sqlite3 *db,          /* Load the extension into this database connection */
5603   const char *zFile,    /* Name of the shared library containing extension */
5604   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
5605   char **pzErrMsg       /* Put error message here if not 0 */
5606 );
5607
5608 /*
5609 ** CAPI3REF: Enable Or Disable Extension Loading {H12620} <S20500>
5610 **
5611 ** So as not to open security holes in older applications that are
5612 ** unprepared to deal with extension loading, and as a means of disabling
5613 ** extension loading while evaluating user-entered SQL, the following API
5614 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5615 **
5616 ** Extension loading is off by default. See ticket #1863.
5617 **
5618 ** {H12621} Call the sqlite3_enable_load_extension() routine with onoff==1
5619 **          to turn extension loading on and call it with onoff==0 to turn
5620 **          it back off again.
5621 **
5622 ** {H12622} Extension loading is off by default.
5623 */
5624 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5625
5626 /*
5627 ** CAPI3REF: Automatically Load An Extensions {H12640} <S20500>
5628 **
5629 ** This API can be invoked at program startup in order to register
5630 ** one or more statically linked extensions that will be available
5631 ** to all new [database connections]. {END}
5632 **
5633 ** This routine stores a pointer to the extension in an array that is
5634 ** obtained from [sqlite3_malloc()].  If you run a memory leak checker
5635 ** on your program and it reports a leak because of this array, invoke
5636 ** [sqlite3_reset_auto_extension()] prior to shutdown to free the memory.
5637 **
5638 ** {H12641} This function registers an extension entry point that is
5639 **          automatically invoked whenever a new [database connection]
5640 **          is opened using [sqlite3_open()], [sqlite3_open16()],
5641 **          or [sqlite3_open_v2()].
5642 **
5643 ** {H12642} Duplicate extensions are detected so calling this routine
5644 **          multiple times with the same extension is harmless.
5645 **
5646 ** {H12643} This routine stores a pointer to the extension in an array
5647 **          that is obtained from [sqlite3_malloc()].
5648 **
5649 ** {H12644} Automatic extensions apply across all threads.
5650 */
5651 SQLITE_API int sqlite3_auto_extension(void *xEntryPoint);
5652
5653 /*
5654 ** CAPI3REF: Reset Automatic Extension Loading {H12660} <S20500>
5655 **
5656 ** This function disables all previously registered automatic
5657 ** extensions. {END}  It undoes the effect of all prior
5658 ** [sqlite3_auto_extension()] calls.
5659 **
5660 ** {H12661} This function disables all previously registered
5661 **          automatic extensions.
5662 **
5663 ** {H12662} This function disables automatic extensions in all threads.
5664 */
5665 SQLITE_API void sqlite3_reset_auto_extension(void);
5666
5667 /*
5668 ****** EXPERIMENTAL - subject to change without notice **************
5669 **
5670 ** The interface to the virtual-table mechanism is currently considered
5671 ** to be experimental.  The interface might change in incompatible ways.
5672 ** If this is a problem for you, do not use the interface at this time.
5673 **
5674 ** When the virtual-table mechanism stabilizes, we will declare the
5675 ** interface fixed, support it indefinitely, and remove this comment.
5676 */
5677
5678 /*
5679 ** Structures used by the virtual table interface
5680 */
5681 typedef struct sqlite3_vtab sqlite3_vtab;
5682 typedef struct sqlite3_index_info sqlite3_index_info;
5683 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5684 typedef struct sqlite3_module sqlite3_module;
5685
5686 /*
5687 ** CAPI3REF: Virtual Table Object {H18000} <S20400>
5688 ** KEYWORDS: sqlite3_module
5689 ** EXPERIMENTAL
5690 **
5691 ** A module is a class of virtual tables.  Each module is defined
5692 ** by an instance of the following structure.  This structure consists
5693 ** mostly of methods for the module.
5694 **
5695 ** This interface is experimental and is subject to change or
5696 ** removal in future releases of SQLite.
5697 */
5698 struct sqlite3_module {
5699   int iVersion;
5700   int (*xCreate)(sqlite3*, void *pAux,
5701                int argc, const char *const*argv,
5702                sqlite3_vtab **ppVTab, char**);
5703   int (*xConnect)(sqlite3*, void *pAux,
5704                int argc, const char *const*argv,
5705                sqlite3_vtab **ppVTab, char**);
5706   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5707   int (*xDisconnect)(sqlite3_vtab *pVTab);
5708   int (*xDestroy)(sqlite3_vtab *pVTab);
5709   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5710   int (*xClose)(sqlite3_vtab_cursor*);
5711   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5712                 int argc, sqlite3_value **argv);
5713   int (*xNext)(sqlite3_vtab_cursor*);
5714   int (*xEof)(sqlite3_vtab_cursor*);
5715   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5716   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5717   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5718   int (*xBegin)(sqlite3_vtab *pVTab);
5719   int (*xSync)(sqlite3_vtab *pVTab);
5720   int (*xCommit)(sqlite3_vtab *pVTab);
5721   int (*xRollback)(sqlite3_vtab *pVTab);
5722   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5723                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5724                        void **ppArg);
5725   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5726 };
5727
5728 /*
5729 ** CAPI3REF: Virtual Table Indexing Information {H18100} <S20400>
5730 ** KEYWORDS: sqlite3_index_info
5731 ** EXPERIMENTAL
5732 **
5733 ** The sqlite3_index_info structure and its substructures is used to
5734 ** pass information into and receive the reply from the xBestIndex
5735 ** method of an sqlite3_module.  The fields under **Inputs** are the
5736 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
5737 ** results into the **Outputs** fields.
5738 **
5739 ** The aConstraint[] array records WHERE clause constraints of the form:
5740 **
5741 ** <pre>column OP expr</pre>
5742 **
5743 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.  The particular operator is
5744 ** stored in aConstraint[].op.  The index of the column is stored in
5745 ** aConstraint[].iColumn.  aConstraint[].usable is TRUE if the
5746 ** expr on the right-hand side can be evaluated (and thus the constraint
5747 ** is usable) and false if it cannot.
5748 **
5749 ** The optimizer automatically inverts terms of the form "expr OP column"
5750 ** and makes other simplifications to the WHERE clause in an attempt to
5751 ** get as many WHERE clause terms into the form shown above as possible.
5752 ** The aConstraint[] array only reports WHERE clause terms in the correct
5753 ** form that refer to the particular virtual table being queried.
5754 **
5755 ** Information about the ORDER BY clause is stored in aOrderBy[].
5756 ** Each term of aOrderBy records a column of the ORDER BY clause.
5757 **
5758 ** The xBestIndex method must fill aConstraintUsage[] with information
5759 ** about what parameters to pass to xFilter.  If argvIndex>0 then
5760 ** the right-hand side of the corresponding aConstraint[] is evaluated
5761 ** and becomes the argvIndex-th entry in argv.  If aConstraintUsage[].omit
5762 ** is true, then the constraint is assumed to be fully handled by the
5763 ** virtual table and is not checked again by SQLite.
5764 **
5765 ** The idxNum and idxPtr values are recorded and passed into xFilter.
5766 ** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true.
5767 **
5768 ** The orderByConsumed means that output from xFilter will occur in
5769 ** the correct order to satisfy the ORDER BY clause so that no separate
5770 ** sorting step is required.
5771 **
5772 ** The estimatedCost value is an estimate of the cost of doing the
5773 ** particular lookup.  A full scan of a table with N entries should have
5774 ** a cost of N.  A binary search of a table of N entries should have a
5775 ** cost of approximately log(N).
5776 **
5777 ** This interface is experimental and is subject to change or
5778 ** removal in future releases of SQLite.
5779 */
5780 struct sqlite3_index_info {
5781   /* Inputs */
5782   int nConstraint;           /* Number of entries in aConstraint */
5783   struct sqlite3_index_constraint {
5784      int iColumn;              /* Column on left-hand side of constraint */
5785      unsigned char op;         /* Constraint operator */
5786      unsigned char usable;     /* True if this constraint is usable */
5787      int iTermOffset;          /* Used internally - xBestIndex should ignore */
5788   } *aConstraint;            /* Table of WHERE clause constraints */
5789   int nOrderBy;              /* Number of terms in the ORDER BY clause */
5790   struct sqlite3_index_orderby {
5791      int iColumn;              /* Column number */
5792      unsigned char desc;       /* True for DESC.  False for ASC. */
5793   } *aOrderBy;               /* The ORDER BY clause */
5794   /* Outputs */
5795   struct sqlite3_index_constraint_usage {
5796     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
5797     unsigned char omit;      /* Do not code a test for this constraint */
5798   } *aConstraintUsage;
5799   int idxNum;                /* Number used to identify the index */
5800   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
5801   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
5802   int orderByConsumed;       /* True if output is already ordered */
5803   double estimatedCost;      /* Estimated cost of using this index */
5804 };
5805 #define SQLITE_INDEX_CONSTRAINT_EQ    2
5806 #define SQLITE_INDEX_CONSTRAINT_GT    4
5807 #define SQLITE_INDEX_CONSTRAINT_LE    8
5808 #define SQLITE_INDEX_CONSTRAINT_LT    16
5809 #define SQLITE_INDEX_CONSTRAINT_GE    32
5810 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
5811
5812 /*
5813 ** CAPI3REF: Register A Virtual Table Implementation {H18200} <S20400>
5814 ** EXPERIMENTAL
5815 **
5816 ** This routine is used to register a new module name with a
5817 ** [database connection].  Module names must be registered before
5818 ** creating new virtual tables on the module, or before using
5819 ** preexisting virtual tables of the module.
5820 **
5821 ** This interface is experimental and is subject to change or
5822 ** removal in future releases of SQLite.
5823 */
5824 SQLITE_API int sqlite3_create_module(
5825   sqlite3 *db,               /* SQLite connection to register module with */
5826   const char *zName,         /* Name of the module */
5827   const sqlite3_module *,    /* Methods for the module */
5828   void *                     /* Client data for xCreate/xConnect */
5829 );
5830
5831 /*
5832 ** CAPI3REF: Register A Virtual Table Implementation {H18210} <S20400>
5833 ** EXPERIMENTAL
5834 **
5835 ** This routine is identical to the [sqlite3_create_module()] method above,
5836 ** except that it allows a destructor function to be specified. It is
5837 ** even more experimental than the rest of the virtual tables API.
5838 */
5839 SQLITE_API int sqlite3_create_module_v2(
5840   sqlite3 *db,               /* SQLite connection to register module with */
5841   const char *zName,         /* Name of the module */
5842   const sqlite3_module *,    /* Methods for the module */
5843   void *,                    /* Client data for xCreate/xConnect */
5844   void(*xDestroy)(void*)     /* Module destructor function */
5845 );
5846
5847 /*
5848 ** CAPI3REF: Virtual Table Instance Object {H18010} <S20400>
5849 ** KEYWORDS: sqlite3_vtab
5850 ** EXPERIMENTAL
5851 **
5852 ** Every module implementation uses a subclass of the following structure
5853 ** to describe a particular instance of the module.  Each subclass will
5854 ** be tailored to the specific needs of the module implementation.
5855 ** The purpose of this superclass is to define certain fields that are
5856 ** common to all module implementations.
5857 **
5858 ** Virtual tables methods can set an error message by assigning a
5859 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
5860 ** take care that any prior string is freed by a call to [sqlite3_free()]
5861 ** prior to assigning a new string to zErrMsg.  After the error message
5862 ** is delivered up to the client application, the string will be automatically
5863 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.  Note
5864 ** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field
5865 ** since virtual tables are commonly implemented in loadable extensions which
5866 ** do not have access to sqlite3MPrintf() or sqlite3Free().
5867 **
5868 ** This interface is experimental and is subject to change or
5869 ** removal in future releases of SQLite.
5870 */
5871 struct sqlite3_vtab {
5872   const sqlite3_module *pModule;  /* The module for this virtual table */
5873   int nRef;                       /* Used internally */
5874   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
5875   /* Virtual table implementations will typically add additional fields */
5876 };
5877
5878 /*
5879 ** CAPI3REF: Virtual Table Cursor Object  {H18020} <S20400>
5880 ** KEYWORDS: sqlite3_vtab_cursor
5881 ** EXPERIMENTAL
5882 **
5883 ** Every module implementation uses a subclass of the following structure
5884 ** to describe cursors that point into the virtual table and are used
5885 ** to loop through the virtual table.  Cursors are created using the
5886 ** xOpen method of the module.  Each module implementation will define
5887 ** the content of a cursor structure to suit its own needs.
5888 **
5889 ** This superclass exists in order to define fields of the cursor that
5890 ** are common to all implementations.
5891 **
5892 ** This interface is experimental and is subject to change or
5893 ** removal in future releases of SQLite.
5894 */
5895 struct sqlite3_vtab_cursor {
5896   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
5897   /* Virtual table implementations will typically add additional fields */
5898 };
5899
5900 /*
5901 ** CAPI3REF: Declare The Schema Of A Virtual Table {H18280} <S20400>
5902 ** EXPERIMENTAL
5903 **
5904 ** The xCreate and xConnect methods of a module use the following API
5905 ** to declare the format (the names and datatypes of the columns) of
5906 ** the virtual tables they implement.
5907 **
5908 ** This interface is experimental and is subject to change or
5909 ** removal in future releases of SQLite.
5910 */
5911 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable);
5912
5913 /*
5914 ** CAPI3REF: Overload A Function For A Virtual Table {H18300} <S20400>
5915 ** EXPERIMENTAL
5916 **
5917 ** Virtual tables can provide alternative implementations of functions
5918 ** using the xFindFunction method.  But global versions of those functions
5919 ** must exist in order to be overloaded.
5920 **
5921 ** This API makes sure a global version of a function with a particular
5922 ** name and number of parameters exists.  If no such function exists
5923 ** before this API is called, a new function is created.  The implementation
5924 ** of the new function always causes an exception to be thrown.  So
5925 ** the new function is not good for anything by itself.  Its only
5926 ** purpose is to be a placeholder function that can be overloaded
5927 ** by virtual tables.
5928 **
5929 ** This API should be considered part of the virtual table interface,
5930 ** which is experimental and subject to change.
5931 */
5932 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5933
5934 /*
5935 ** The interface to the virtual-table mechanism defined above (back up
5936 ** to a comment remarkably similar to this one) is currently considered
5937 ** to be experimental.  The interface might change in incompatible ways.
5938 ** If this is a problem for you, do not use the interface at this time.
5939 **
5940 ** When the virtual-table mechanism stabilizes, we will declare the
5941 ** interface fixed, support it indefinitely, and remove this comment.
5942 **
5943 ****** EXPERIMENTAL - subject to change without notice **************
5944 */
5945
5946 /*
5947 ** CAPI3REF: A Handle To An Open BLOB {H17800} <S30230>
5948 ** KEYWORDS: {BLOB handle} {BLOB handles}
5949 **
5950 ** An instance of this object represents an open BLOB on which
5951 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
5952 ** Objects of this type are created by [sqlite3_blob_open()]
5953 ** and destroyed by [sqlite3_blob_close()].
5954 ** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5955 ** can be used to read or write small subsections of the BLOB.
5956 ** The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
5957 */
5958 typedef struct sqlite3_blob sqlite3_blob;
5959
5960 /*
5961 ** CAPI3REF: Open A BLOB For Incremental I/O {H17810} <S30230>
5962 **
5963 ** This interfaces opens a [BLOB handle | handle] to the BLOB located
5964 ** in row iRow, column zColumn, table zTable in database zDb;
5965 ** in other words, the same BLOB that would be selected by:
5966 **
5967 ** <pre>
5968 **     SELECT zColumn FROM zDb.zTable WHERE rowid = iRow;
5969 ** </pre> {END}
5970 **
5971 ** If the flags parameter is non-zero, the the BLOB is opened for read
5972 ** and write access. If it is zero, the BLOB is opened for read access.
5973 **
5974 ** Note that the database name is not the filename that contains
5975 ** the database but rather the symbolic name of the database that
5976 ** is assigned when the database is connected using [ATTACH].
5977 ** For the main database file, the database name is "main".
5978 ** For TEMP tables, the database name is "temp".
5979 **
5980 ** On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
5981 ** to *ppBlob. Otherwise an [error code] is returned and any value written
5982 ** to *ppBlob should not be used by the caller.
5983 ** This function sets the [database connection] error code and message
5984 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()].
5985 **
5986 ** If the row that a BLOB handle points to is modified by an
5987 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
5988 ** then the BLOB handle is marked as "expired".
5989 ** This is true if any column of the row is changed, even a column
5990 ** other than the one the BLOB handle is open on.
5991 ** Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
5992 ** a expired BLOB handle fail with an return code of [SQLITE_ABORT].
5993 ** Changes written into a BLOB prior to the BLOB expiring are not
5994 ** rollback by the expiration of the BLOB.  Such changes will eventually
5995 ** commit if the transaction continues to completion.
5996 **
5997 ** INVARIANTS:
5998 **
5999 ** {H17813} A successful invocation of the [sqlite3_blob_open(D,B,T,C,R,F,P)]
6000 **          interface shall open an [sqlite3_blob] object P on the BLOB
6001 **          in column C of the table T in the database B on
6002 **          the [database connection] D.
6003 **
6004 ** {H17814} A successful invocation of [sqlite3_blob_open(D,...)] shall start
6005 **          a new transaction on the [database connection] D if that
6006 **          connection is not already in a transaction.
6007 **
6008 ** {H17816} The [sqlite3_blob_open(D,B,T,C,R,F,P)] interface shall open
6009 **          the BLOB for read and write access if and only if the F
6010 **          parameter is non-zero.
6011 **
6012 ** {H17819} The [sqlite3_blob_open()] interface shall return [SQLITE_OK] on
6013 **          success and an appropriate [error code] on failure.
6014 **
6015 ** {H17821} If an error occurs during evaluation of [sqlite3_blob_open(D,...)]
6016 **          then subsequent calls to [sqlite3_errcode(D)],
6017 **          [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] shall return
6018 **          information appropriate for that error.
6019 **
6020 ** {H17824} If any column in the row that a [sqlite3_blob] has open is
6021 **          changed by a separate [UPDATE] or [DELETE] statement or by
6022 **          an [ON CONFLICT] side effect, then the [sqlite3_blob] shall
6023 **          be marked as invalid.
6024 */
6025 SQLITE_API int sqlite3_blob_open(
6026   sqlite3*,
6027   const char *zDb,
6028   const char *zTable,
6029   const char *zColumn,
6030   sqlite3_int64 iRow,
6031   int flags,
6032   sqlite3_blob **ppBlob
6033 );
6034
6035 /*
6036 ** CAPI3REF: Close A BLOB Handle {H17830} <S30230>
6037 **
6038 ** Closes an open [BLOB handle].
6039 **
6040 ** Closing a BLOB shall cause the current transaction to commit
6041 ** if there are no other BLOBs, no pending prepared statements, and the
6042 ** database connection is in [autocommit mode].
6043 ** If any writes were made to the BLOB, they might be held in cache
6044 ** until the close operation if they will fit. {END}
6045 **
6046 ** Closing the BLOB often forces the changes
6047 ** out to disk and so if any I/O errors occur, they will likely occur
6048 ** at the time when the BLOB is closed.  {H17833} Any errors that occur during
6049 ** closing are reported as a non-zero return value.
6050 **
6051 ** The BLOB is closed unconditionally.  Even if this routine returns
6052 ** an error code, the BLOB is still closed.
6053 **
6054 ** INVARIANTS:
6055 **
6056 ** {H17833} The [sqlite3_blob_close(P)] interface closes an [sqlite3_blob]
6057 **          object P previously opened using [sqlite3_blob_open()].
6058 **
6059 ** {H17836} Closing an [sqlite3_blob] object using
6060 **          [sqlite3_blob_close()] shall cause the current transaction to
6061 **          commit if there are no other open [sqlite3_blob] objects
6062 **          or [prepared statements] on the same [database connection] and
6063 **          the database connection is in [autocommit mode].
6064 **
6065 ** {H17839} The [sqlite3_blob_close(P)] interfaces shall close the
6066 **          [sqlite3_blob] object P unconditionally, even if
6067 **          [sqlite3_blob_close(P)] returns something other than [SQLITE_OK].
6068 */
6069 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
6070
6071 /*
6072 ** CAPI3REF: Return The Size Of An Open BLOB {H17840} <S30230>
6073 **
6074 ** Returns the size in bytes of the BLOB accessible via the open
6075 ** []BLOB handle] in its only argument.
6076 **
6077 ** INVARIANTS:
6078 **
6079 ** {H17843} The [sqlite3_blob_bytes(P)] interface returns the size
6080 **          in bytes of the BLOB that the [sqlite3_blob] object P
6081 **          refers to.
6082 */
6083 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
6084
6085 /*
6086 ** CAPI3REF: Read Data From A BLOB Incrementally {H17850} <S30230>
6087 **
6088 ** This function is used to read data from an open [BLOB handle] into a
6089 ** caller-supplied buffer. N bytes of data are copied into buffer Z
6090 ** from the open BLOB, starting at offset iOffset.
6091 **
6092 ** If offset iOffset is less than N bytes from the end of the BLOB,
6093 ** [SQLITE_ERROR] is returned and no data is read.  If N or iOffset is
6094 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
6095 **
6096 ** An attempt to read from an expired [BLOB handle] fails with an
6097 ** error code of [SQLITE_ABORT].
6098 **
6099 ** On success, SQLITE_OK is returned.
6100 ** Otherwise, an [error code] or an [extended error code] is returned.
6101 **
6102 ** INVARIANTS:
6103 **
6104 ** {H17853} A successful invocation of [sqlite3_blob_read(P,Z,N,X)] 
6105 **          shall reads N bytes of data out of the BLOB referenced by
6106 **          [BLOB handle] P beginning at offset X and store those bytes
6107 **          into buffer Z.
6108 **
6109 ** {H17856} In [sqlite3_blob_read(P,Z,N,X)] if the size of the BLOB
6110 **          is less than N+X bytes, then the function shall leave the
6111 **          Z buffer unchanged and return [SQLITE_ERROR].
6112 **
6113 ** {H17859} In [sqlite3_blob_read(P,Z,N,X)] if X or N is less than zero
6114 **          then the function shall leave the Z buffer unchanged
6115 **          and return [SQLITE_ERROR].
6116 **
6117 ** {H17862} The [sqlite3_blob_read(P,Z,N,X)] interface shall return [SQLITE_OK]
6118 **          if N bytes are successfully read into buffer Z.
6119 **
6120 ** {H17863} If the [BLOB handle] P is expired and X and N are within bounds
6121 **          then [sqlite3_blob_read(P,Z,N,X)] shall leave the Z buffer
6122 **          unchanged and return [SQLITE_ABORT].
6123 **
6124 ** {H17865} If the requested read could not be completed,
6125 **          the [sqlite3_blob_read(P,Z,N,X)] interface shall return an
6126 **          appropriate [error code] or [extended error code].
6127 **
6128 ** {H17868} If an error occurs during evaluation of [sqlite3_blob_read(P,...)]
6129 **          then subsequent calls to [sqlite3_errcode(D)],
6130 **          [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] shall return
6131 **          information appropriate for that error, where D is the
6132 **          [database connection] that was used to open the [BLOB handle] P.
6133 */
6134 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
6135
6136 /*
6137 ** CAPI3REF: Write Data Into A BLOB Incrementally {H17870} <S30230>
6138 **
6139 ** This function is used to write data into an open [BLOB handle] from a
6140 ** caller-supplied buffer. N bytes of data are copied from the buffer Z
6141 ** into the open BLOB, starting at offset iOffset.
6142 **
6143 ** If the [BLOB handle] passed as the first argument was not opened for
6144 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
6145 ** this function returns [SQLITE_READONLY].
6146 **
6147 ** This function may only modify the contents of the BLOB; it is
6148 ** not possible to increase the size of a BLOB using this API.
6149 ** If offset iOffset is less than N bytes from the end of the BLOB,
6150 ** [SQLITE_ERROR] is returned and no data is written.  If N is
6151 ** less than zero [SQLITE_ERROR] is returned and no data is written.
6152 **
6153 ** An attempt to write to an expired [BLOB handle] fails with an
6154 ** error code of [SQLITE_ABORT].  Writes to the BLOB that occurred
6155 ** before the [BLOB handle] expired are not rolled back by the
6156 ** expiration of the handle, though of course those changes might
6157 ** have been overwritten by the statement that expired the BLOB handle
6158 ** or by other independent statements.
6159 **
6160 ** On success, SQLITE_OK is returned.
6161 ** Otherwise, an  [error code] or an [extended error code] is returned.
6162 **
6163 ** INVARIANTS:
6164 **
6165 ** {H17873} A successful invocation of [sqlite3_blob_write(P,Z,N,X)]
6166 **          shall write N bytes of data from buffer Z into the BLOB 
6167 **          referenced by [BLOB handle] P beginning at offset X into
6168 **          the BLOB.
6169 **
6170 ** {H17874} In the absence of other overridding changes, the changes
6171 **          written to a BLOB by [sqlite3_blob_write()] shall
6172 **          remain in effect after the associated [BLOB handle] expires.
6173 **
6174 ** {H17875} If the [BLOB handle] P was opened for reading only then
6175 **          an invocation of [sqlite3_blob_write(P,Z,N,X)] shall leave
6176 **          the referenced BLOB unchanged and return [SQLITE_READONLY].
6177 **
6178 ** {H17876} If the size of the BLOB referenced by [BLOB handle] P is
6179 **          less than N+X bytes then [sqlite3_blob_write(P,Z,N,X)] shall
6180 **          leave the BLOB unchanged and return [SQLITE_ERROR].
6181 **
6182 ** {H17877} If the [BLOB handle] P is expired and X and N are within bounds
6183 **          then [sqlite3_blob_read(P,Z,N,X)] shall leave the BLOB
6184 **          unchanged and return [SQLITE_ABORT].
6185 **
6186 ** {H17879} If X or N are less than zero then [sqlite3_blob_write(P,Z,N,X)]
6187 **          shall leave the BLOB referenced by [BLOB handle] P unchanged
6188 **          and return [SQLITE_ERROR].
6189 **
6190 ** {H17882} The [sqlite3_blob_write(P,Z,N,X)] interface shall return
6191 **          [SQLITE_OK] if N bytes where successfully written into the BLOB.
6192 **
6193 ** {H17885} If the requested write could not be completed,
6194 **          the [sqlite3_blob_write(P,Z,N,X)] interface shall return an
6195 **          appropriate [error code] or [extended error code].
6196 **
6197 ** {H17888} If an error occurs during evaluation of [sqlite3_blob_write(D,...)]
6198 **          then subsequent calls to [sqlite3_errcode(D)],
6199 **          [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] shall return
6200 **          information appropriate for that error.
6201 */
6202 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
6203
6204 /*
6205 ** CAPI3REF: Virtual File System Objects {H11200} <S20100>
6206 **
6207 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
6208 ** that SQLite uses to interact
6209 ** with the underlying operating system.  Most SQLite builds come with a
6210 ** single default VFS that is appropriate for the host computer.
6211 ** New VFSes can be registered and existing VFSes can be unregistered.
6212 ** The following interfaces are provided.
6213 **
6214 ** The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
6215 ** Names are case sensitive.
6216 ** Names are zero-terminated UTF-8 strings.
6217 ** If there is no match, a NULL pointer is returned.
6218 ** If zVfsName is NULL then the default VFS is returned.
6219 **
6220 ** New VFSes are registered with sqlite3_vfs_register().
6221 ** Each new VFS becomes the default VFS if the makeDflt flag is set.
6222 ** The same VFS can be registered multiple times without injury.
6223 ** To make an existing VFS into the default VFS, register it again
6224 ** with the makeDflt flag set.  If two different VFSes with the
6225 ** same name are registered, the behavior is undefined.  If a
6226 ** VFS is registered with a name that is NULL or an empty string,
6227 ** then the behavior is undefined.
6228 **
6229 ** Unregister a VFS with the sqlite3_vfs_unregister() interface.
6230 ** If the default VFS is unregistered, another VFS is chosen as
6231 ** the default.  The choice for the new VFS is arbitrary.
6232 **
6233 ** INVARIANTS:
6234 **
6235 ** {H11203} The [sqlite3_vfs_find(N)] interface returns a pointer to the
6236 **          registered [sqlite3_vfs] object whose name exactly matches
6237 **          the zero-terminated UTF-8 string N, or it returns NULL if
6238 **          there is no match.
6239 **
6240 ** {H11206} If the N parameter to [sqlite3_vfs_find(N)] is NULL then
6241 **          the function returns a pointer to the default [sqlite3_vfs]
6242 **          object if there is one, or NULL if there is no default
6243 **          [sqlite3_vfs] object.
6244 **
6245 ** {H11209} The [sqlite3_vfs_register(P,F)] interface registers the
6246 **          well-formed [sqlite3_vfs] object P using the name given
6247 **          by the zName field of the object.
6248 **
6249 ** {H11212} Using the [sqlite3_vfs_register(P,F)] interface to register
6250 **          the same [sqlite3_vfs] object multiple times is a harmless no-op.
6251 **
6252 ** {H11215} The [sqlite3_vfs_register(P,F)] interface makes the [sqlite3_vfs]
6253 **          object P the default [sqlite3_vfs] object if F is non-zero.
6254 **
6255 ** {H11218} The [sqlite3_vfs_unregister(P)] interface unregisters the
6256 **          [sqlite3_vfs] object P so that it is no longer returned by
6257 **          subsequent calls to [sqlite3_vfs_find()].
6258 */
6259 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
6260 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
6261 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
6262
6263 /*
6264 ** CAPI3REF: Mutexes {H17000} <S20000>
6265 **
6266 ** The SQLite core uses these routines for thread
6267 ** synchronization. Though they are intended for internal
6268 ** use by SQLite, code that links against SQLite is
6269 ** permitted to use any of these routines.
6270 **
6271 ** The SQLite source code contains multiple implementations
6272 ** of these mutex routines.  An appropriate implementation
6273 ** is selected automatically at compile-time.  The following
6274 ** implementations are available in the SQLite core:
6275 **
6276 ** <ul>
6277 ** <li>   SQLITE_MUTEX_OS2
6278 ** <li>   SQLITE_MUTEX_PTHREAD
6279 ** <li>   SQLITE_MUTEX_W32
6280 ** <li>   SQLITE_MUTEX_NOOP
6281 ** </ul>
6282 **
6283 ** The SQLITE_MUTEX_NOOP implementation is a set of routines
6284 ** that does no real locking and is appropriate for use in
6285 ** a single-threaded application.  The SQLITE_MUTEX_OS2,
6286 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
6287 ** are appropriate for use on OS/2, Unix, and Windows.
6288 **
6289 ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
6290 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
6291 ** implementation is included with the library. In this case the
6292 ** application must supply a custom mutex implementation using the
6293 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
6294 ** before calling sqlite3_initialize() or any other public sqlite3_
6295 ** function that calls sqlite3_initialize().
6296 **
6297 ** {H17011} The sqlite3_mutex_alloc() routine allocates a new
6298 ** mutex and returns a pointer to it. {H17012} If it returns NULL
6299 ** that means that a mutex could not be allocated. {H17013} SQLite
6300 ** will unwind its stack and return an error. {H17014} The argument
6301 ** to sqlite3_mutex_alloc() is one of these integer constants:
6302 **
6303 ** <ul>
6304 ** <li>  SQLITE_MUTEX_FAST
6305 ** <li>  SQLITE_MUTEX_RECURSIVE
6306 ** <li>  SQLITE_MUTEX_STATIC_MASTER
6307 ** <li>  SQLITE_MUTEX_STATIC_MEM
6308 ** <li>  SQLITE_MUTEX_STATIC_MEM2
6309 ** <li>  SQLITE_MUTEX_STATIC_PRNG
6310 ** <li>  SQLITE_MUTEX_STATIC_LRU
6311 ** <li>  SQLITE_MUTEX_STATIC_LRU2
6312 ** </ul>
6313 **
6314 ** {H17015} The first two constants cause sqlite3_mutex_alloc() to create
6315 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
6316 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. {END}
6317 ** The mutex implementation does not need to make a distinction
6318 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
6319 ** not want to.  {H17016} But SQLite will only request a recursive mutex in
6320 ** cases where it really needs one.  {END} If a faster non-recursive mutex
6321 ** implementation is available on the host platform, the mutex subsystem
6322 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
6323 **
6324 ** {H17017} The other allowed parameters to sqlite3_mutex_alloc() each return
6325 ** a pointer to a static preexisting mutex. {END}  Four static mutexes are
6326 ** used by the current version of SQLite.  Future versions of SQLite
6327 ** may add additional static mutexes.  Static mutexes are for internal
6328 ** use by SQLite only.  Applications that use SQLite mutexes should
6329 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
6330 ** SQLITE_MUTEX_RECURSIVE.
6331 **
6332 ** {H17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
6333 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
6334 ** returns a different mutex on every call.  {H17034} But for the static
6335 ** mutex types, the same mutex is returned on every call that has
6336 ** the same type number.
6337 **
6338 ** {H17019} The sqlite3_mutex_free() routine deallocates a previously
6339 ** allocated dynamic mutex. {H17020} SQLite is careful to deallocate every
6340 ** dynamic mutex that it allocates. {A17021} The dynamic mutexes must not be in
6341 ** use when they are deallocated. {A17022} Attempting to deallocate a static
6342 ** mutex results in undefined behavior. {H17023} SQLite never deallocates
6343 ** a static mutex. {END}
6344 **
6345 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
6346 ** to enter a mutex. {H17024} If another thread is already within the mutex,
6347 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
6348 ** SQLITE_BUSY. {H17025}  The sqlite3_mutex_try() interface returns [SQLITE_OK]
6349 ** upon successful entry.  {H17026} Mutexes created using
6350 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
6351 ** {H17027} In such cases the,
6352 ** mutex must be exited an equal number of times before another thread
6353 ** can enter.  {A17028} If the same thread tries to enter any other
6354 ** kind of mutex more than once, the behavior is undefined.
6355 ** {H17029} SQLite will never exhibit
6356 ** such behavior in its own use of mutexes.
6357 **
6358 ** Some systems (for example, Windows 95) do not support the operation
6359 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
6360 ** will always return SQLITE_BUSY.  {H17030} The SQLite core only ever uses
6361 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.
6362 **
6363 ** {H17031} The sqlite3_mutex_leave() routine exits a mutex that was
6364 ** previously entered by the same thread.  {A17032} The behavior
6365 ** is undefined if the mutex is not currently entered by the
6366 ** calling thread or is not currently allocated.  {H17033} SQLite will
6367 ** never do either. {END}
6368 **
6369 ** If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
6370 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
6371 ** behave as no-ops.
6372 **
6373 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
6374 */
6375 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
6376 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
6377 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
6378 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
6379 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
6380
6381 /*
6382 ** CAPI3REF: Mutex Methods Object {H17120} <S20130>
6383 ** EXPERIMENTAL
6384 **
6385 ** An instance of this structure defines the low-level routines
6386 ** used to allocate and use mutexes.
6387 **
6388 ** Usually, the default mutex implementations provided by SQLite are
6389 ** sufficient, however the user has the option of substituting a custom
6390 ** implementation for specialized deployments or systems for which SQLite
6391 ** does not provide a suitable implementation. In this case, the user
6392 ** creates and populates an instance of this structure to pass
6393 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
6394 ** Additionally, an instance of this structure can be used as an
6395 ** output variable when querying the system for the current mutex
6396 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
6397 **
6398 ** The xMutexInit method defined by this structure is invoked as
6399 ** part of system initialization by the sqlite3_initialize() function.
6400 ** {H17001} The xMutexInit routine shall be called by SQLite once for each
6401 ** effective call to [sqlite3_initialize()].
6402 **
6403 ** The xMutexEnd method defined by this structure is invoked as
6404 ** part of system shutdown by the sqlite3_shutdown() function. The
6405 ** implementation of this method is expected to release all outstanding
6406 ** resources obtained by the mutex methods implementation, especially
6407 ** those obtained by the xMutexInit method. {H17003} The xMutexEnd()
6408 ** interface shall be invoked once for each call to [sqlite3_shutdown()].
6409 **
6410 ** The remaining seven methods defined by this structure (xMutexAlloc,
6411 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
6412 ** xMutexNotheld) implement the following interfaces (respectively):
6413 **
6414 ** <ul>
6415 **   <li>  [sqlite3_mutex_alloc()] </li>
6416 **   <li>  [sqlite3_mutex_free()] </li>
6417 **   <li>  [sqlite3_mutex_enter()] </li>
6418 **   <li>  [sqlite3_mutex_try()] </li>
6419 **   <li>  [sqlite3_mutex_leave()] </li>
6420 **   <li>  [sqlite3_mutex_held()] </li>
6421 **   <li>  [sqlite3_mutex_notheld()] </li>
6422 ** </ul>
6423 **
6424 ** The only difference is that the public sqlite3_XXX functions enumerated
6425 ** above silently ignore any invocations that pass a NULL pointer instead
6426 ** of a valid mutex handle. The implementations of the methods defined
6427 ** by this structure are not required to handle this case, the results
6428 ** of passing a NULL pointer instead of a valid mutex handle are undefined
6429 ** (i.e. it is acceptable to provide an implementation that segfaults if
6430 ** it is passed a NULL pointer).
6431 */
6432 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
6433 struct sqlite3_mutex_methods {
6434   int (*xMutexInit)(void);
6435   int (*xMutexEnd)(void);
6436   sqlite3_mutex *(*xMutexAlloc)(int);
6437   void (*xMutexFree)(sqlite3_mutex *);
6438   void (*xMutexEnter)(sqlite3_mutex *);
6439   int (*xMutexTry)(sqlite3_mutex *);
6440   void (*xMutexLeave)(sqlite3_mutex *);
6441   int (*xMutexHeld)(sqlite3_mutex *);
6442   int (*xMutexNotheld)(sqlite3_mutex *);
6443 };
6444
6445 /*
6446 ** CAPI3REF: Mutex Verification Routines {H17080} <S20130> <S30800>
6447 **
6448 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
6449 ** are intended for use inside assert() statements. {H17081} The SQLite core
6450 ** never uses these routines except inside an assert() and applications
6451 ** are advised to follow the lead of the core.  {H17082} The core only
6452 ** provides implementations for these routines when it is compiled
6453 ** with the SQLITE_DEBUG flag.  {A17087} External mutex implementations
6454 ** are only required to provide these routines if SQLITE_DEBUG is
6455 ** defined and if NDEBUG is not defined.
6456 **
6457 ** {H17083} These routines should return true if the mutex in their argument
6458 ** is held or not held, respectively, by the calling thread.
6459 **
6460 ** {X17084} The implementation is not required to provided versions of these
6461 ** routines that actually work. If the implementation does not provide working
6462 ** versions of these routines, it should at least provide stubs that always
6463 ** return true so that one does not get spurious assertion failures.
6464 **
6465 ** {H17085} If the argument to sqlite3_mutex_held() is a NULL pointer then
6466 ** the routine should return 1.  {END} This seems counter-intuitive since
6467 ** clearly the mutex cannot be held if it does not exist.  But the
6468 ** the reason the mutex does not exist is because the build is not
6469 ** using mutexes.  And we do not want the assert() containing the
6470 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
6471 ** the appropriate thing to do.  {H17086} The sqlite3_mutex_notheld()
6472 ** interface should also return 1 when given a NULL pointer.
6473 */
6474 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
6475 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
6476
6477 /*
6478 ** CAPI3REF: Mutex Types {H17001} <H17000>
6479 **
6480 ** The [sqlite3_mutex_alloc()] interface takes a single argument
6481 ** which is one of these integer constants.
6482 **
6483 ** The set of static mutexes may change from one SQLite release to the
6484 ** next.  Applications that override the built-in mutex logic must be
6485 ** prepared to accommodate additional static mutexes.
6486 */
6487 #define SQLITE_MUTEX_FAST             0
6488 #define SQLITE_MUTEX_RECURSIVE        1
6489 #define SQLITE_MUTEX_STATIC_MASTER    2
6490 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
6491 #define SQLITE_MUTEX_STATIC_MEM2      4  /* sqlite3_release_memory() */
6492 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
6493 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
6494 #define SQLITE_MUTEX_STATIC_LRU2      7  /* lru page list */
6495
6496 /*
6497 ** CAPI3REF: Low-Level Control Of Database Files {H11300} <S30800>
6498 **
6499 ** {H11301} The [sqlite3_file_control()] interface makes a direct call to the
6500 ** xFileControl method for the [sqlite3_io_methods] object associated
6501 ** with a particular database identified by the second argument. {H11302} The
6502 ** name of the database is the name assigned to the database by the
6503 ** <a href="lang_attach.html">ATTACH</a> SQL command that opened the
6504 ** database. {H11303} To control the main database file, use the name "main"
6505 ** or a NULL pointer. {H11304} The third and fourth parameters to this routine
6506 ** are passed directly through to the second and third parameters of
6507 ** the xFileControl method.  {H11305} The return value of the xFileControl
6508 ** method becomes the return value of this routine.
6509 **
6510 ** {H11306} If the second parameter (zDbName) does not match the name of any
6511 ** open database file, then SQLITE_ERROR is returned. {H11307} This error
6512 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
6513 ** or [sqlite3_errmsg()]. {A11308} The underlying xFileControl method might
6514 ** also return SQLITE_ERROR.  {A11309} There is no way to distinguish between
6515 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
6516 ** xFileControl method. {END}
6517 **
6518 ** See also: [SQLITE_FCNTL_LOCKSTATE]
6519 */
6520 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
6521
6522 /*
6523 ** CAPI3REF: Testing Interface {H11400} <S30800>
6524 **
6525 ** The sqlite3_test_control() interface is used to read out internal
6526 ** state of SQLite and to inject faults into SQLite for testing
6527 ** purposes.  The first parameter is an operation code that determines
6528 ** the number, meaning, and operation of all subsequent parameters.
6529 **
6530 ** This interface is not for use by applications.  It exists solely
6531 ** for verifying the correct operation of the SQLite library.  Depending
6532 ** on how the SQLite library is compiled, this interface might not exist.
6533 **
6534 ** The details of the operation codes, their meanings, the parameters
6535 ** they take, and what they do are all subject to change without notice.
6536 ** Unlike most of the SQLite API, this function is not guaranteed to
6537 ** operate consistently from one release to the next.
6538 */
6539 SQLITE_API int sqlite3_test_control(int op, ...);
6540
6541 /*
6542 ** CAPI3REF: Testing Interface Operation Codes {H11410} <H11400>
6543 **
6544 ** These constants are the valid operation code parameters used
6545 ** as the first argument to [sqlite3_test_control()].
6546 **
6547 ** These parameters and their meanings are subject to change
6548 ** without notice.  These values are for testing purposes only.
6549 ** Applications should not use any of these parameters or the
6550 ** [sqlite3_test_control()] interface.
6551 */
6552 #define SQLITE_TESTCTRL_PRNG_SAVE                5
6553 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
6554 #define SQLITE_TESTCTRL_PRNG_RESET               7
6555 #define SQLITE_TESTCTRL_BITVEC_TEST              8
6556 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
6557 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
6558
6559 /*
6560 ** CAPI3REF: SQLite Runtime Status {H17200} <S60200>
6561 ** EXPERIMENTAL
6562 **
6563 ** This interface is used to retrieve runtime status information
6564 ** about the preformance of SQLite, and optionally to reset various
6565 ** highwater marks.  The first argument is an integer code for
6566 ** the specific parameter to measure.  Recognized integer codes
6567 ** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].
6568 ** The current value of the parameter is returned into *pCurrent.
6569 ** The highest recorded value is returned in *pHighwater.  If the
6570 ** resetFlag is true, then the highest record value is reset after
6571 ** *pHighwater is written. Some parameters do not record the highest
6572 ** value.  For those parameters
6573 ** nothing is written into *pHighwater and the resetFlag is ignored.
6574 ** Other parameters record only the highwater mark and not the current
6575 ** value.  For these latter parameters nothing is written into *pCurrent.
6576 **
6577 ** This routine returns SQLITE_OK on success and a non-zero
6578 ** [error code] on failure.
6579 **
6580 ** This routine is threadsafe but is not atomic.  This routine can
6581 ** called while other threads are running the same or different SQLite
6582 ** interfaces.  However the values returned in *pCurrent and
6583 ** *pHighwater reflect the status of SQLite at different points in time
6584 ** and it is possible that another thread might change the parameter
6585 ** in between the times when *pCurrent and *pHighwater are written.
6586 **
6587 ** See also: [sqlite3_db_status()]
6588 */
6589 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
6590
6591 /*
6592 ** CAPI3REF: Database Connection Status {H17201} <S60200>
6593 ** EXPERIMENTAL
6594 **
6595 ** This interface is used to retrieve runtime status information 
6596 ** about a single [database connection].  The first argument is the
6597 ** database connection object to be interrogated.  The second argument
6598 ** is the parameter to interrogate.  Currently, the only allowed value
6599 ** for the second parameter is [SQLITE_DBSTATUS_LOOKASIDE_USED].
6600 ** Additional options will likely appear in future releases of SQLite.
6601 **
6602 ** The current value of the request parameter is written into *pCur
6603 ** and the highest instantaneous value is written into *pHiwtr.  If
6604 ** the resetFlg is true, then the highest instantaneous value is
6605 ** reset back down to the current value.
6606 **
6607 ** See also: [sqlite3_status()].
6608 */
6609 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6610
6611 /*
6612 ** CAPI3REF: Status Parameters {H17250} <H17200>
6613 ** EXPERIMENTAL
6614 **
6615 ** These integer constants designate various run-time status parameters
6616 ** that can be returned by [sqlite3_status()].
6617 **
6618 ** <dl>
6619 ** <dt>SQLITE_STATUS_MEMORY_USED</dt>
6620 ** <dd>This parameter is the current amount of memory checked out
6621 ** using [sqlite3_malloc()], either directly or indirectly.  The
6622 ** figure includes calls made to [sqlite3_malloc()] by the application
6623 ** and internal memory usage by the SQLite library.  Scratch memory
6624 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
6625 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
6626 ** this parameter.  The amount returned is the sum of the allocation
6627 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>
6628 **
6629 ** <dt>SQLITE_STATUS_MALLOC_SIZE</dt>
6630 ** <dd>This parameter records the largest memory allocation request
6631 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
6632 ** internal equivalents).  Only the value returned in the
6633 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6634 ** The value written into the *pCurrent parameter is undefined.</dd>
6635 **
6636 ** <dt>SQLITE_STATUS_PAGECACHE_USED</dt>
6637 ** <dd>This parameter returns the number of pages used out of the
6638 ** [pagecache memory allocator] that was configured using 
6639 ** [SQLITE_CONFIG_PAGECACHE].  The
6640 ** value returned is in pages, not in bytes.</dd>
6641 **
6642 ** <dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
6643 ** <dd>This parameter returns the number of bytes of page cache
6644 ** allocation which could not be statisfied by the [SQLITE_CONFIG_PAGECACHE]
6645 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
6646 ** returned value includes allocations that overflowed because they
6647 ** where too large (they were larger than the "sz" parameter to
6648 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
6649 ** no space was left in the page cache.</dd>
6650 **
6651 ** <dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
6652 ** <dd>This parameter records the largest memory allocation request
6653 ** handed to [pagecache memory allocator].  Only the value returned in the
6654 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6655 ** The value written into the *pCurrent parameter is undefined.</dd>
6656 **
6657 ** <dt>SQLITE_STATUS_SCRATCH_USED</dt>
6658 ** <dd>This parameter returns the number of allocations used out of the
6659 ** [scratch memory allocator] configured using
6660 ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
6661 ** in bytes.  Since a single thread may only have one scratch allocation
6662 ** outstanding at time, this parameter also reports the number of threads
6663 ** using scratch memory at the same time.</dd>
6664 **
6665 ** <dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6666 ** <dd>This parameter returns the number of bytes of scratch memory
6667 ** allocation which could not be statisfied by the [SQLITE_CONFIG_SCRATCH]
6668 ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
6669 ** returned include overflows because the requested allocation was too
6670 ** larger (that is, because the requested allocation was larger than the
6671 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6672 ** slots were available.
6673 ** </dd>
6674 **
6675 ** <dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6676 ** <dd>This parameter records the largest memory allocation request
6677 ** handed to [scratch memory allocator].  Only the value returned in the
6678 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6679 ** The value written into the *pCurrent parameter is undefined.</dd>
6680 **
6681 ** <dt>SQLITE_STATUS_PARSER_STACK</dt>
6682 ** <dd>This parameter records the deepest parser stack.  It is only
6683 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>
6684 ** </dl>
6685 **
6686 ** New status parameters may be added from time to time.
6687 */
6688 #define SQLITE_STATUS_MEMORY_USED          0
6689 #define SQLITE_STATUS_PAGECACHE_USED       1
6690 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
6691 #define SQLITE_STATUS_SCRATCH_USED         3
6692 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
6693 #define SQLITE_STATUS_MALLOC_SIZE          5
6694 #define SQLITE_STATUS_PARSER_STACK         6
6695 #define SQLITE_STATUS_PAGECACHE_SIZE       7
6696 #define SQLITE_STATUS_SCRATCH_SIZE         8
6697
6698 /*
6699 ** CAPI3REF: Status Parameters for database connections {H17275} <H17200>
6700 ** EXPERIMENTAL
6701 **
6702 ** Status verbs for [sqlite3_db_status()].
6703 **
6704 ** <dl>
6705 ** <dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6706 ** <dd>This parameter returns the number of lookaside memory slots currently
6707 ** checked out.</dd>
6708 ** </dl>
6709 */
6710 #define SQLITE_DBSTATUS_LOOKASIDE_USED     0
6711
6712 /*
6713 ** Undo the hack that converts floating point types to integer for
6714 ** builds on processors without floating point support.
6715 */
6716 #ifdef SQLITE_OMIT_FLOATING_POINT
6717 # undef double
6718 #endif
6719
6720 #if 0
6721 }  /* End of the 'extern "C"' block */
6722 #endif
6723 #endif
6724
6725 /************** End of sqlite3.h *********************************************/
6726 /************** Continuing where we left off in sqliteInt.h ******************/
6727 /************** Include hash.h in the middle of sqliteInt.h ******************/
6728 /************** Begin file hash.h ********************************************/
6729 /*
6730 ** 2001 September 22
6731 **
6732 ** The author disclaims copyright to this source code.  In place of
6733 ** a legal notice, here is a blessing:
6734 **
6735 **    May you do good and not evil.
6736 **    May you find forgiveness for yourself and forgive others.
6737 **    May you share freely, never taking more than you give.
6738 **
6739 *************************************************************************
6740 ** This is the header file for the generic hash-table implemenation
6741 ** used in SQLite.
6742 **
6743 ** $Id: hash.h,v 1.11 2007/09/04 14:31:47 danielk1977 Exp $
6744 */
6745 #ifndef _SQLITE_HASH_H_
6746 #define _SQLITE_HASH_H_
6747
6748 /* Forward declarations of structures. */
6749 typedef struct Hash Hash;
6750 typedef struct HashElem HashElem;
6751
6752 /* A complete hash table is an instance of the following structure.
6753 ** The internals of this structure are intended to be opaque -- client
6754 ** code should not attempt to access or modify the fields of this structure
6755 ** directly.  Change this structure only by using the routines below.
6756 ** However, many of the "procedures" and "functions" for modifying and
6757 ** accessing this structure are really macros, so we can't really make
6758 ** this structure opaque.
6759 */
6760 struct Hash {
6761   char keyClass;          /* SQLITE_HASH_INT, _POINTER, _STRING, _BINARY */
6762   char copyKey;           /* True if copy of key made on insert */
6763   int count;              /* Number of entries in this table */
6764   int htsize;             /* Number of buckets in the hash table */
6765   HashElem *first;        /* The first element of the array */
6766   struct _ht {            /* the hash table */
6767     int count;               /* Number of entries with this hash */
6768     HashElem *chain;         /* Pointer to first entry with this hash */
6769   } *ht;
6770 };
6771
6772 /* Each element in the hash table is an instance of the following 
6773 ** structure.  All elements are stored on a single doubly-linked list.
6774 **
6775 ** Again, this structure is intended to be opaque, but it can't really
6776 ** be opaque because it is used by macros.
6777 */
6778 struct HashElem {
6779   HashElem *next, *prev;   /* Next and previous elements in the table */
6780   void *data;              /* Data associated with this element */
6781   void *pKey; int nKey;    /* Key associated with this element */
6782 };
6783
6784 /*
6785 ** There are 4 different modes of operation for a hash table:
6786 **
6787 **   SQLITE_HASH_INT         nKey is used as the key and pKey is ignored.
6788 **
6789 **   SQLITE_HASH_POINTER     pKey is used as the key and nKey is ignored.
6790 **
6791 **   SQLITE_HASH_STRING      pKey points to a string that is nKey bytes long
6792 **                           (including the null-terminator, if any).  Case
6793 **                           is ignored in comparisons.
6794 **
6795 **   SQLITE_HASH_BINARY      pKey points to binary data nKey bytes long. 
6796 **                           memcmp() is used to compare keys.
6797 **
6798 ** A copy of the key is made for SQLITE_HASH_STRING and SQLITE_HASH_BINARY
6799 ** if the copyKey parameter to HashInit is 1.  
6800 */
6801 /* #define SQLITE_HASH_INT       1 // NOT USED */
6802 /* #define SQLITE_HASH_POINTER   2 // NOT USED */
6803 #define SQLITE_HASH_STRING    3
6804 #define SQLITE_HASH_BINARY    4
6805
6806 /*
6807 ** Access routines.  To delete, insert a NULL pointer.
6808 */
6809 SQLITE_PRIVATE void sqlite3HashInit(Hash*, int keytype, int copyKey);
6810 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const void *pKey, int nKey, void *pData);
6811 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const void *pKey, int nKey);
6812 SQLITE_PRIVATE HashElem *sqlite3HashFindElem(const Hash*, const void *pKey, int nKey);
6813 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
6814
6815 /*
6816 ** Macros for looping over all elements of a hash table.  The idiom is
6817 ** like this:
6818 **
6819 **   Hash h;
6820 **   HashElem *p;
6821 **   ...
6822 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
6823 **     SomeStructure *pData = sqliteHashData(p);
6824 **     // do something with pData
6825 **   }
6826 */
6827 #define sqliteHashFirst(H)  ((H)->first)
6828 #define sqliteHashNext(E)   ((E)->next)
6829 #define sqliteHashData(E)   ((E)->data)
6830 #define sqliteHashKey(E)    ((E)->pKey)
6831 #define sqliteHashKeysize(E) ((E)->nKey)
6832
6833 /*
6834 ** Number of entries in a hash table
6835 */
6836 #define sqliteHashCount(H)  ((H)->count)
6837
6838 #endif /* _SQLITE_HASH_H_ */
6839
6840 /************** End of hash.h ************************************************/
6841 /************** Continuing where we left off in sqliteInt.h ******************/
6842 /************** Include parse.h in the middle of sqliteInt.h *****************/
6843 /************** Begin file parse.h *******************************************/
6844 #define TK_SEMI                            1
6845 #define TK_EXPLAIN                         2
6846 #define TK_QUERY                           3
6847 #define TK_PLAN                            4
6848 #define TK_BEGIN                           5
6849 #define TK_TRANSACTION                     6
6850 #define TK_DEFERRED                        7
6851 #define TK_IMMEDIATE                       8
6852 #define TK_EXCLUSIVE                       9
6853 #define TK_COMMIT                         10
6854 #define TK_END                            11
6855 #define TK_ROLLBACK                       12
6856 #define TK_CREATE                         13
6857 #define TK_TABLE                          14
6858 #define TK_IF                             15
6859 #define TK_NOT                            16
6860 #define TK_EXISTS                         17
6861 #define TK_TEMP                           18
6862 #define TK_LP                             19
6863 #define TK_RP                             20
6864 #define TK_AS                             21
6865 #define TK_COMMA                          22
6866 #define TK_ID                             23
6867 #define TK_ABORT                          24
6868 #define TK_AFTER                          25
6869 #define TK_ANALYZE                        26
6870 #define TK_ASC                            27
6871 #define TK_ATTACH                         28
6872 #define TK_BEFORE                         29
6873 #define TK_CASCADE                        30
6874 #define TK_CAST                           31
6875 #define TK_CONFLICT                       32
6876 #define TK_DATABASE                       33
6877 #define TK_DESC                           34
6878 #define TK_DETACH                         35
6879 #define TK_EACH                           36
6880 #define TK_FAIL                           37
6881 #define TK_FOR                            38
6882 #define TK_IGNORE                         39
6883 #define TK_INITIALLY                      40
6884 #define TK_INSTEAD                        41
6885 #define TK_LIKE_KW                        42
6886 #define TK_MATCH                          43
6887 #define TK_KEY                            44
6888 #define TK_OF                             45
6889 #define TK_OFFSET                         46
6890 #define TK_PRAGMA                         47
6891 #define TK_RAISE                          48
6892 #define TK_REPLACE                        49
6893 #define TK_RESTRICT                       50
6894 #define TK_ROW                            51
6895 #define TK_TRIGGER                        52
6896 #define TK_VACUUM                         53
6897 #define TK_VIEW                           54
6898 #define TK_VIRTUAL                        55
6899 #define TK_REINDEX                        56
6900 #define TK_RENAME                         57
6901 #define TK_CTIME_KW                       58
6902 #define TK_ANY                            59
6903 #define TK_OR                             60
6904 #define TK_AND                            61
6905 #define TK_IS                             62
6906 #define TK_BETWEEN                        63
6907 #define TK_IN                             64
6908 #define TK_ISNULL                         65
6909 #define TK_NOTNULL                        66
6910 #define TK_NE                             67
6911 #define TK_EQ                             68
6912 #define TK_GT                             69
6913 #define TK_LE                             70
6914 #define TK_LT                             71
6915 #define TK_GE                             72
6916 #define TK_ESCAPE                         73
6917 #define TK_BITAND                         74
6918 #define TK_BITOR                          75
6919 #define TK_LSHIFT                         76
6920 #define TK_RSHIFT                         77
6921 #define TK_PLUS                           78
6922 #define TK_MINUS                          79
6923 #define TK_STAR                           80
6924 #define TK_SLASH                          81
6925 #define TK_REM                            82
6926 #define TK_CONCAT                         83
6927 #define TK_COLLATE                        84
6928 #define TK_UMINUS                         85
6929 #define TK_UPLUS                          86
6930 #define TK_BITNOT                         87
6931 #define TK_STRING                         88
6932 #define TK_JOIN_KW                        89
6933 #define TK_CONSTRAINT                     90
6934 #define TK_DEFAULT                        91
6935 #define TK_NULL                           92
6936 #define TK_PRIMARY                        93
6937 #define TK_UNIQUE                         94
6938 #define TK_CHECK                          95
6939 #define TK_REFERENCES                     96
6940 #define TK_AUTOINCR                       97
6941 #define TK_ON                             98
6942 #define TK_DELETE                         99
6943 #define TK_UPDATE                         100
6944 #define TK_INSERT                         101
6945 #define TK_SET                            102
6946 #define TK_DEFERRABLE                     103
6947 #define TK_FOREIGN                        104
6948 #define TK_DROP                           105
6949 #define TK_UNION                          106
6950 #define TK_ALL                            107
6951 #define TK_EXCEPT                         108
6952 #define TK_INTERSECT                      109
6953 #define TK_SELECT                         110
6954 #define TK_DISTINCT                       111
6955 #define TK_DOT                            112
6956 #define TK_FROM                           113
6957 #define TK_JOIN                           114
6958 #define TK_USING                          115
6959 #define TK_ORDER                          116
6960 #define TK_BY                             117
6961 #define TK_GROUP                          118
6962 #define TK_HAVING                         119
6963 #define TK_LIMIT                          120
6964 #define TK_WHERE                          121
6965 #define TK_INTO                           122
6966 #define TK_VALUES                         123
6967 #define TK_INTEGER                        124
6968 #define TK_FLOAT                          125
6969 #define TK_BLOB                           126
6970 #define TK_REGISTER                       127
6971 #define TK_VARIABLE                       128
6972 #define TK_CASE                           129
6973 #define TK_WHEN                           130
6974 #define TK_THEN                           131
6975 #define TK_ELSE                           132
6976 #define TK_INDEX                          133
6977 #define TK_ALTER                          134
6978 #define TK_TO                             135
6979 #define TK_ADD                            136
6980 #define TK_COLUMNKW                       137
6981 #define TK_TO_TEXT                        138
6982 #define TK_TO_BLOB                        139
6983 #define TK_TO_NUMERIC                     140
6984 #define TK_TO_INT                         141
6985 #define TK_TO_REAL                        142
6986 #define TK_END_OF_FILE                    143
6987 #define TK_ILLEGAL                        144
6988 #define TK_SPACE                          145
6989 #define TK_UNCLOSED_STRING                146
6990 #define TK_COMMENT                        147
6991 #define TK_FUNCTION                       148
6992 #define TK_COLUMN                         149
6993 #define TK_AGG_FUNCTION                   150
6994 #define TK_AGG_COLUMN                     151
6995 #define TK_CONST_FUNC                     152
6996
6997 /************** End of parse.h ***********************************************/
6998 /************** Continuing where we left off in sqliteInt.h ******************/
6999 #include <stdio.h>
7000 #include <stdlib.h>
7001 #include <string.h>
7002 #include <assert.h>
7003 #include <stddef.h>
7004
7005 /*
7006 ** If compiling for a processor that lacks floating point support,
7007 ** substitute integer for floating-point
7008 */
7009 #ifdef SQLITE_OMIT_FLOATING_POINT
7010 # define double sqlite_int64
7011 # define LONGDOUBLE_TYPE sqlite_int64
7012 # ifndef SQLITE_BIG_DBL
7013 #   define SQLITE_BIG_DBL (0x7fffffffffffffff)
7014 # endif
7015 # define SQLITE_OMIT_DATETIME_FUNCS 1
7016 # define SQLITE_OMIT_TRACE 1
7017 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
7018 #endif
7019 #ifndef SQLITE_BIG_DBL
7020 # define SQLITE_BIG_DBL (1e99)
7021 #endif
7022
7023 /*
7024 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
7025 ** afterward. Having this macro allows us to cause the C compiler 
7026 ** to omit code used by TEMP tables without messy #ifndef statements.
7027 */
7028 #ifdef SQLITE_OMIT_TEMPDB
7029 #define OMIT_TEMPDB 1
7030 #else
7031 #define OMIT_TEMPDB 0
7032 #endif
7033
7034 /*
7035 ** If the following macro is set to 1, then NULL values are considered
7036 ** distinct when determining whether or not two entries are the same
7037 ** in a UNIQUE index.  This is the way PostgreSQL, Oracle, DB2, MySQL,
7038 ** OCELOT, and Firebird all work.  The SQL92 spec explicitly says this
7039 ** is the way things are suppose to work.
7040 **
7041 ** If the following macro is set to 0, the NULLs are indistinct for
7042 ** a UNIQUE index.  In this mode, you can only have a single NULL entry
7043 ** for a column declared UNIQUE.  This is the way Informix and SQL Server
7044 ** work.
7045 */
7046 #define NULL_DISTINCT_FOR_UNIQUE 1
7047
7048 /*
7049 ** The "file format" number is an integer that is incremented whenever
7050 ** the VDBE-level file format changes.  The following macros define the
7051 ** the default file format for new databases and the maximum file format
7052 ** that the library can read.
7053 */
7054 #define SQLITE_MAX_FILE_FORMAT 4
7055 #ifndef SQLITE_DEFAULT_FILE_FORMAT
7056 # define SQLITE_DEFAULT_FILE_FORMAT 1
7057 #endif
7058
7059 /*
7060 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
7061 ** on the command-line
7062 */
7063 #ifndef SQLITE_TEMP_STORE
7064 # define SQLITE_TEMP_STORE 1
7065 #endif
7066
7067 /*
7068 ** GCC does not define the offsetof() macro so we'll have to do it
7069 ** ourselves.
7070 */
7071 #ifndef offsetof
7072 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
7073 #endif
7074
7075 /*
7076 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
7077 ** not, there are still machines out there that use EBCDIC.)
7078 */
7079 #if 'A' == '\301'
7080 # define SQLITE_EBCDIC 1
7081 #else
7082 # define SQLITE_ASCII 1
7083 #endif
7084
7085 /*
7086 ** Integers of known sizes.  These typedefs might change for architectures
7087 ** where the sizes very.  Preprocessor macros are available so that the
7088 ** types can be conveniently redefined at compile-type.  Like this:
7089 **
7090 **         cc '-DUINTPTR_TYPE=long long int' ...
7091 */
7092 #ifndef UINT32_TYPE
7093 # ifdef HAVE_UINT32_T
7094 #  define UINT32_TYPE uint32_t
7095 # else
7096 #  define UINT32_TYPE unsigned int
7097 # endif
7098 #endif
7099 #ifndef UINT16_TYPE
7100 # ifdef HAVE_UINT16_T
7101 #  define UINT16_TYPE uint16_t
7102 # else
7103 #  define UINT16_TYPE unsigned short int
7104 # endif
7105 #endif
7106 #ifndef INT16_TYPE
7107 # ifdef HAVE_INT16_T
7108 #  define INT16_TYPE int16_t
7109 # else
7110 #  define INT16_TYPE short int
7111 # endif
7112 #endif
7113 #ifndef UINT8_TYPE
7114 # ifdef HAVE_UINT8_T
7115 #  define UINT8_TYPE uint8_t
7116 # else
7117 #  define UINT8_TYPE unsigned char
7118 # endif
7119 #endif
7120 #ifndef INT8_TYPE
7121 # ifdef HAVE_INT8_T
7122 #  define INT8_TYPE int8_t
7123 # else
7124 #  define INT8_TYPE signed char
7125 # endif
7126 #endif
7127 #ifndef LONGDOUBLE_TYPE
7128 # define LONGDOUBLE_TYPE long double
7129 #endif
7130 typedef sqlite_int64 i64;          /* 8-byte signed integer */
7131 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
7132 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
7133 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
7134 typedef INT16_TYPE i16;            /* 2-byte signed integer */
7135 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
7136 typedef UINT8_TYPE i8;             /* 1-byte signed integer */
7137
7138 /*
7139 ** Macros to determine whether the machine is big or little endian,
7140 ** evaluated at runtime.
7141 */
7142 #ifdef SQLITE_AMALGAMATION
7143 SQLITE_PRIVATE const int sqlite3one;
7144 #else
7145 SQLITE_PRIVATE const int sqlite3one;
7146 #endif
7147 #if defined(i386) || defined(__i386__) || defined(_M_IX86)
7148 # define SQLITE_BIGENDIAN    0
7149 # define SQLITE_LITTLEENDIAN 1
7150 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
7151 #else
7152 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
7153 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
7154 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
7155 #endif
7156
7157 /*
7158 ** Constants for the largest and smallest possible 64-bit signed integers.
7159 ** These macros are designed to work correctly on both 32-bit and 64-bit
7160 ** compilers.
7161 */
7162 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
7163 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
7164
7165 /*
7166 ** An instance of the following structure is used to store the busy-handler
7167 ** callback for a given sqlite handle. 
7168 **
7169 ** The sqlite.busyHandler member of the sqlite struct contains the busy
7170 ** callback for the database handle. Each pager opened via the sqlite
7171 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
7172 ** callback is currently invoked only from within pager.c.
7173 */
7174 typedef struct BusyHandler BusyHandler;
7175 struct BusyHandler {
7176   int (*xFunc)(void *,int);  /* The busy callback */
7177   void *pArg;                /* First arg to busy callback */
7178   int nBusy;                 /* Incremented with each busy call */
7179 };
7180
7181 /*
7182 ** Name of the master database table.  The master database table
7183 ** is a special table that holds the names and attributes of all
7184 ** user tables and indices.
7185 */
7186 #define MASTER_NAME       "sqlite_master"
7187 #define TEMP_MASTER_NAME  "sqlite_temp_master"
7188
7189 /*
7190 ** The root-page of the master database table.
7191 */
7192 #define MASTER_ROOT       1
7193
7194 /*
7195 ** The name of the schema table.
7196 */
7197 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
7198
7199 /*
7200 ** A convenience macro that returns the number of elements in
7201 ** an array.
7202 */
7203 #define ArraySize(X)    (sizeof(X)/sizeof(X[0]))
7204
7205 /*
7206 ** The following value as a destructor means to use sqlite3DbFree().
7207 ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
7208 */
7209 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3DbFree)
7210
7211 /*
7212 ** Forward references to structures
7213 */
7214 typedef struct AggInfo AggInfo;
7215 typedef struct AuthContext AuthContext;
7216 typedef struct Bitvec Bitvec;
7217 typedef struct CollSeq CollSeq;
7218 typedef struct Column Column;
7219 typedef struct Db Db;
7220 typedef struct Schema Schema;
7221 typedef struct Expr Expr;
7222 typedef struct ExprList ExprList;
7223 typedef struct FKey FKey;
7224 typedef struct FuncDef FuncDef;
7225 typedef struct IdList IdList;
7226 typedef struct Index Index;
7227 typedef struct KeyClass KeyClass;
7228 typedef struct KeyInfo KeyInfo;
7229 typedef struct Lookaside Lookaside;
7230 typedef struct LookasideSlot LookasideSlot;
7231 typedef struct Module Module;
7232 typedef struct NameContext NameContext;
7233 typedef struct Parse Parse;
7234 typedef struct Select Select;
7235 typedef struct SrcList SrcList;
7236 typedef struct StrAccum StrAccum;
7237 typedef struct Table Table;
7238 typedef struct TableLock TableLock;
7239 typedef struct Token Token;
7240 typedef struct TriggerStack TriggerStack;
7241 typedef struct TriggerStep TriggerStep;
7242 typedef struct Trigger Trigger;
7243 typedef struct WhereInfo WhereInfo;
7244 typedef struct WhereLevel WhereLevel;
7245
7246 /*
7247 ** Defer sourcing vdbe.h and btree.h until after the "u8" and 
7248 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
7249 ** pointer types (i.e. FuncDef) defined above.
7250 */
7251 /************** Include btree.h in the middle of sqliteInt.h *****************/
7252 /************** Begin file btree.h *******************************************/
7253 /*
7254 ** 2001 September 15
7255 **
7256 ** The author disclaims copyright to this source code.  In place of
7257 ** a legal notice, here is a blessing:
7258 **
7259 **    May you do good and not evil.
7260 **    May you find forgiveness for yourself and forgive others.
7261 **    May you share freely, never taking more than you give.
7262 **
7263 *************************************************************************
7264 ** This header file defines the interface that the sqlite B-Tree file
7265 ** subsystem.  See comments in the source code for a detailed description
7266 ** of what each interface routine does.
7267 **
7268 ** @(#) $Id: btree.h,v 1.102 2008/07/11 21:02:54 drh Exp $
7269 */
7270 #ifndef _BTREE_H_
7271 #define _BTREE_H_
7272
7273 /* TODO: This definition is just included so other modules compile. It
7274 ** needs to be revisited.
7275 */
7276 #define SQLITE_N_BTREE_META 10
7277
7278 /*
7279 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
7280 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
7281 */
7282 #ifndef SQLITE_DEFAULT_AUTOVACUUM
7283   #define SQLITE_DEFAULT_AUTOVACUUM 0
7284 #endif
7285
7286 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
7287 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
7288 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
7289
7290 /*
7291 ** Forward declarations of structure
7292 */
7293 typedef struct Btree Btree;
7294 typedef struct BtCursor BtCursor;
7295 typedef struct BtShared BtShared;
7296 typedef struct BtreeMutexArray BtreeMutexArray;
7297
7298 /*
7299 ** This structure records all of the Btrees that need to hold
7300 ** a mutex before we enter sqlite3VdbeExec().  The Btrees are
7301 ** are placed in aBtree[] in order of aBtree[]->pBt.  That way,
7302 ** we can always lock and unlock them all quickly.
7303 */
7304 struct BtreeMutexArray {
7305   int nMutex;
7306   Btree *aBtree[SQLITE_MAX_ATTACHED+1];
7307 };
7308
7309
7310 SQLITE_PRIVATE int sqlite3BtreeOpen(
7311   const char *zFilename,   /* Name of database file to open */
7312   sqlite3 *db,             /* Associated database connection */
7313   Btree **,                /* Return open Btree* here */
7314   int flags,               /* Flags */
7315   int vfsFlags             /* Flags passed through to VFS open */
7316 );
7317
7318 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
7319 ** following values.
7320 **
7321 ** NOTE:  These values must match the corresponding PAGER_ values in
7322 ** pager.h.
7323 */
7324 #define BTREE_OMIT_JOURNAL  1  /* Do not use journal.  No argument */
7325 #define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
7326 #define BTREE_MEMORY        4  /* In-memory DB.  No argument */
7327 #define BTREE_READONLY      8  /* Open the database in read-only mode */
7328 #define BTREE_READWRITE    16  /* Open for both reading and writing */
7329 #define BTREE_CREATE       32  /* Create the database if it does not exist */
7330
7331 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
7332 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
7333 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
7334 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
7335 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree*,int,int);
7336 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
7337 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
7338 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
7339 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
7340 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
7341 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
7342 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
7343 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*);
7344 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
7345 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
7346 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*);
7347 SQLITE_PRIVATE int sqlite3BtreeCommitStmt(Btree*);
7348 SQLITE_PRIVATE int sqlite3BtreeRollbackStmt(Btree*);
7349 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
7350 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
7351 SQLITE_PRIVATE int sqlite3BtreeIsInStmt(Btree*);
7352 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
7353 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
7354 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *);
7355 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *, int, u8);
7356
7357 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
7358 SQLITE_PRIVATE const char *sqlite3BtreeGetDirname(Btree *);
7359 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
7360 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
7361
7362 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
7363
7364 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
7365 ** of the following flags:
7366 */
7367 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
7368 #define BTREE_ZERODATA   2    /* Table has keys only - no data */
7369 #define BTREE_LEAFDATA   4    /* Data stored in leaves only.  Implies INTKEY */
7370
7371 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
7372 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int);
7373 SQLITE_PRIVATE int sqlite3BtreeGetMeta(Btree*, int idx, u32 *pValue);
7374 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
7375 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
7376
7377 struct UnpackedRecord;  /* Forward declaration.  Definition in vdbeaux.c. */
7378
7379 SQLITE_PRIVATE int sqlite3BtreeCursor(
7380   Btree*,                              /* BTree containing table to open */
7381   int iTable,                          /* Index of root page */
7382   int wrFlag,                          /* 1 for writing.  0 for read-only */
7383   struct KeyInfo*,                     /* First argument to compare function */
7384   BtCursor *pCursor                    /* Space to write cursor structure */
7385 );
7386 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
7387
7388 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
7389 SQLITE_PRIVATE int sqlite3BtreeMoveto(
7390   BtCursor*,
7391   const void *pKey,
7392   struct UnpackedRecord *pUnKey,
7393   i64 nKey,
7394   int bias,
7395   int *pRes
7396 );
7397 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
7398 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
7399 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
7400                                   const void *pData, int nData,
7401                                   int nZero, int bias);
7402 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
7403 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
7404 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
7405 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
7406 SQLITE_PRIVATE int sqlite3BtreeFlags(BtCursor*);
7407 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
7408 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
7409 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
7410 SQLITE_PRIVATE sqlite3 *sqlite3BtreeCursorDb(const BtCursor*);
7411 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
7412 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
7413 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
7414 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
7415
7416 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
7417 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
7418
7419 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
7420 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
7421
7422 #ifdef SQLITE_TEST
7423 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
7424 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
7425 #endif
7426
7427 /*
7428 ** If we are not using shared cache, then there is no need to
7429 ** use mutexes to access the BtShared structures.  So make the
7430 ** Enter and Leave procedures no-ops.
7431 */
7432 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
7433 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
7434 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
7435 #ifndef NDEBUG
7436   /* This routine is used inside assert() statements only. */
7437 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
7438 #endif
7439 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
7440 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
7441 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
7442 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
7443 #ifndef NDEBUG
7444   /* This routine is used inside assert() statements only. */
7445 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
7446 #endif
7447 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*);
7448 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*);
7449 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*);
7450 #else
7451 # define sqlite3BtreeEnter(X)
7452 # define sqlite3BtreeLeave(X)
7453 #ifndef NDEBUG
7454   /* This routine is used inside assert() statements only. */
7455 # define sqlite3BtreeHoldsMutex(X) 1
7456 #endif
7457 # define sqlite3BtreeEnterCursor(X)
7458 # define sqlite3BtreeLeaveCursor(X)
7459 # define sqlite3BtreeEnterAll(X)
7460 # define sqlite3BtreeLeaveAll(X)
7461 #ifndef NDEBUG
7462   /* This routine is used inside assert() statements only. */
7463 # define sqlite3BtreeHoldsAllMutexes(X) 1
7464 #endif
7465 # define sqlite3BtreeMutexArrayEnter(X)
7466 # define sqlite3BtreeMutexArrayLeave(X)
7467 # define sqlite3BtreeMutexArrayInsert(X,Y)
7468 #endif
7469
7470
7471 #endif /* _BTREE_H_ */
7472
7473 /************** End of btree.h ***********************************************/
7474 /************** Continuing where we left off in sqliteInt.h ******************/
7475 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
7476 /************** Begin file vdbe.h ********************************************/
7477 /*
7478 ** 2001 September 15
7479 **
7480 ** The author disclaims copyright to this source code.  In place of
7481 ** a legal notice, here is a blessing:
7482 **
7483 **    May you do good and not evil.
7484 **    May you find forgiveness for yourself and forgive others.
7485 **    May you share freely, never taking more than you give.
7486 **
7487 *************************************************************************
7488 ** Header file for the Virtual DataBase Engine (VDBE)
7489 **
7490 ** This header defines the interface to the virtual database engine
7491 ** or VDBE.  The VDBE implements an abstract machine that runs a
7492 ** simple program to access and modify the underlying database.
7493 **
7494 ** $Id: vdbe.h,v 1.135 2008/08/01 20:10:08 drh Exp $
7495 */
7496 #ifndef _SQLITE_VDBE_H_
7497 #define _SQLITE_VDBE_H_
7498
7499 /*
7500 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
7501 ** in the source file sqliteVdbe.c are allowed to see the insides
7502 ** of this structure.
7503 */
7504 typedef struct Vdbe Vdbe;
7505
7506 /*
7507 ** The names of the following types declared in vdbeInt.h are required
7508 ** for the VdbeOp definition.
7509 */
7510 typedef struct VdbeFunc VdbeFunc;
7511 typedef struct Mem Mem;
7512 typedef struct UnpackedRecord UnpackedRecord;
7513
7514 /*
7515 ** A single instruction of the virtual machine has an opcode
7516 ** and as many as three operands.  The instruction is recorded
7517 ** as an instance of the following structure:
7518 */
7519 struct VdbeOp {
7520   u8 opcode;          /* What operation to perform */
7521   signed char p4type; /* One of the P4_xxx constants for p4 */
7522   u8 opflags;         /* Not currently used */
7523   u8 p5;              /* Fifth parameter is an unsigned character */
7524   int p1;             /* First operand */
7525   int p2;             /* Second parameter (often the jump destination) */
7526   int p3;             /* The third parameter */
7527   union {             /* forth parameter */
7528     int i;                 /* Integer value if p4type==P4_INT32 */
7529     void *p;               /* Generic pointer */
7530     char *z;               /* Pointer to data for string (char array) types */
7531     i64 *pI64;             /* Used when p4type is P4_INT64 */
7532     double *pReal;         /* Used when p4type is P4_REAL */
7533     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
7534     VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
7535     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
7536     Mem *pMem;             /* Used when p4type is P4_MEM */
7537     sqlite3_vtab *pVtab;   /* Used when p4type is P4_VTAB */
7538     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
7539     int *ai;               /* Used when p4type is P4_INTARRAY */
7540   } p4;
7541 #ifdef SQLITE_DEBUG
7542   char *zComment;          /* Comment to improve readability */
7543 #endif
7544 #ifdef VDBE_PROFILE
7545   int cnt;                 /* Number of times this instruction was executed */
7546   u64 cycles;              /* Total time spent executing this instruction */
7547 #endif
7548 };
7549 typedef struct VdbeOp VdbeOp;
7550
7551 /*
7552 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
7553 ** it takes up less space.
7554 */
7555 struct VdbeOpList {
7556   u8 opcode;          /* What operation to perform */
7557   signed char p1;     /* First operand */
7558   signed char p2;     /* Second parameter (often the jump destination) */
7559   signed char p3;     /* Third parameter */
7560 };
7561 typedef struct VdbeOpList VdbeOpList;
7562
7563 /*
7564 ** Allowed values of VdbeOp.p3type
7565 */
7566 #define P4_NOTUSED    0   /* The P4 parameter is not used */
7567 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
7568 #define P4_STATIC   (-2)  /* Pointer to a static string */
7569 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
7570 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
7571 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
7572 #define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
7573 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
7574 #define P4_TRANSIENT (-9) /* P4 is a pointer to a transient string */
7575 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
7576 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
7577 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
7578 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
7579 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
7580 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
7581
7582 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
7583 ** is made.  That copy is freed when the Vdbe is finalized.  But if the
7584 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
7585 ** gets freed when the Vdbe is finalized so it still should be obtained
7586 ** from a single sqliteMalloc().  But no copy is made and the calling
7587 ** function should *not* try to free the KeyInfo.
7588 */
7589 #define P4_KEYINFO_HANDOFF (-16)
7590 #define P4_KEYINFO_STATIC  (-17)
7591
7592 /*
7593 ** The Vdbe.aColName array contains 5n Mem structures, where n is the 
7594 ** number of columns of data returned by the statement.
7595 */
7596 #define COLNAME_NAME     0
7597 #define COLNAME_DECLTYPE 1
7598 #define COLNAME_DATABASE 2
7599 #define COLNAME_TABLE    3
7600 #define COLNAME_COLUMN   4
7601 #ifdef SQLITE_ENABLE_COLUMN_METADATA
7602 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
7603 #else
7604 # ifdef SQLITE_OMIT_DECLTYPE
7605 #   define COLNAME_N      1      /* Store only the name */
7606 # else
7607 #   define COLNAME_N      2      /* Store the name and decltype */
7608 # endif
7609 #endif
7610
7611 /*
7612 ** The following macro converts a relative address in the p2 field
7613 ** of a VdbeOp structure into a negative number so that 
7614 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
7615 ** the macro again restores the address.
7616 */
7617 #define ADDR(X)  (-1-(X))
7618
7619 /*
7620 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
7621 ** header file that defines a number for each opcode used by the VDBE.
7622 */
7623 /************** Include opcodes.h in the middle of vdbe.h ********************/
7624 /************** Begin file opcodes.h *****************************************/
7625 /* Automatically generated.  Do not edit */
7626 /* See the mkopcodeh.awk script for details */
7627 #define OP_VNext                                1
7628 #define OP_Affinity                             2
7629 #define OP_Column                               3
7630 #define OP_SetCookie                            4
7631 #define OP_Real                               125   /* same as TK_FLOAT    */
7632 #define OP_Sequence                             5
7633 #define OP_MoveGt                               6
7634 #define OP_Ge                                  72   /* same as TK_GE       */
7635 #define OP_RowKey                               7
7636 #define OP_SCopy                                8
7637 #define OP_Eq                                  68   /* same as TK_EQ       */
7638 #define OP_OpenWrite                            9
7639 #define OP_NotNull                             66   /* same as TK_NOTNULL  */
7640 #define OP_If                                  10
7641 #define OP_ToInt                              141   /* same as TK_TO_INT   */
7642 #define OP_String8                             88   /* same as TK_STRING   */
7643 #define OP_VRowid                              11
7644 #define OP_CollSeq                             12
7645 #define OP_OpenRead                            13
7646 #define OP_Expire                              14
7647 #define OP_AutoCommit                          15
7648 #define OP_Gt                                  69   /* same as TK_GT       */
7649 #define OP_Pagecount                           17
7650 #define OP_IntegrityCk                         18
7651 #define OP_Sort                                19
7652 #define OP_Copy                                20
7653 #define OP_Trace                               21
7654 #define OP_Function                            22
7655 #define OP_IfNeg                               23
7656 #define OP_And                                 61   /* same as TK_AND      */
7657 #define OP_Subtract                            79   /* same as TK_MINUS    */
7658 #define OP_Noop                                24
7659 #define OP_Return                              25
7660 #define OP_Remainder                           82   /* same as TK_REM      */
7661 #define OP_NewRowid                            26
7662 #define OP_Multiply                            80   /* same as TK_STAR     */
7663 #define OP_Variable                            27
7664 #define OP_String                              28
7665 #define OP_RealAffinity                        29
7666 #define OP_VRename                             30
7667 #define OP_ParseSchema                         31
7668 #define OP_VOpen                               32
7669 #define OP_Close                               33
7670 #define OP_CreateIndex                         34
7671 #define OP_IsUnique                            35
7672 #define OP_NotFound                            36
7673 #define OP_Int64                               37
7674 #define OP_MustBeInt                           38
7675 #define OP_Halt                                39
7676 #define OP_Rowid                               40
7677 #define OP_IdxLT                               41
7678 #define OP_AddImm                              42
7679 #define OP_Statement                           43
7680 #define OP_RowData                             44
7681 #define OP_MemMax                              45
7682 #define OP_Or                                  60   /* same as TK_OR       */
7683 #define OP_NotExists                           46
7684 #define OP_Gosub                               47
7685 #define OP_Divide                              81   /* same as TK_SLASH    */
7686 #define OP_Integer                             48
7687 #define OP_ToNumeric                          140   /* same as TK_TO_NUMERIC*/
7688 #define OP_Prev                                49
7689 #define OP_Concat                              83   /* same as TK_CONCAT   */
7690 #define OP_BitAnd                              74   /* same as TK_BITAND   */
7691 #define OP_VColumn                             50
7692 #define OP_CreateTable                         51
7693 #define OP_Last                                52
7694 #define OP_IsNull                              65   /* same as TK_ISNULL   */
7695 #define OP_IncrVacuum                          53
7696 #define OP_IdxRowid                            54
7697 #define OP_ShiftRight                          77   /* same as TK_RSHIFT   */
7698 #define OP_ResetCount                          55
7699 #define OP_FifoWrite                           56
7700 #define OP_ContextPush                         57
7701 #define OP_Yield                               58
7702 #define OP_DropTrigger                         59
7703 #define OP_DropIndex                           62
7704 #define OP_IdxGE                               63
7705 #define OP_IdxDelete                           64
7706 #define OP_Vacuum                              73
7707 #define OP_MoveLe                              84
7708 #define OP_IfNot                               85
7709 #define OP_DropTable                           86
7710 #define OP_MakeRecord                          89
7711 #define OP_ToBlob                             139   /* same as TK_TO_BLOB  */
7712 #define OP_ResultRow                           90
7713 #define OP_Delete                              91
7714 #define OP_AggFinal                            92
7715 #define OP_Compare                             93
7716 #define OP_ShiftLeft                           76   /* same as TK_LSHIFT   */
7717 #define OP_Goto                                94
7718 #define OP_TableLock                           95
7719 #define OP_FifoRead                            96
7720 #define OP_Clear                               97
7721 #define OP_MoveLt                              98
7722 #define OP_Le                                  70   /* same as TK_LE       */
7723 #define OP_VerifyCookie                        99
7724 #define OP_AggStep                            100
7725 #define OP_ToText                             138   /* same as TK_TO_TEXT  */
7726 #define OP_Not                                 16   /* same as TK_NOT      */
7727 #define OP_ToReal                             142   /* same as TK_TO_REAL  */
7728 #define OP_SetNumColumns                      101
7729 #define OP_Transaction                        102
7730 #define OP_VFilter                            103
7731 #define OP_Ne                                  67   /* same as TK_NE       */
7732 #define OP_VDestroy                           104
7733 #define OP_ContextPop                         105
7734 #define OP_BitOr                               75   /* same as TK_BITOR    */
7735 #define OP_Next                               106
7736 #define OP_IdxInsert                          107
7737 #define OP_Lt                                  71   /* same as TK_LT       */
7738 #define OP_Insert                             108
7739 #define OP_Destroy                            109
7740 #define OP_ReadCookie                         110
7741 #define OP_ForceInt                           111
7742 #define OP_LoadAnalysis                       112
7743 #define OP_Explain                            113
7744 #define OP_OpenPseudo                         114
7745 #define OP_OpenEphemeral                      115
7746 #define OP_Null                               116
7747 #define OP_Move                               117
7748 #define OP_Blob                               118
7749 #define OP_Add                                 78   /* same as TK_PLUS     */
7750 #define OP_Rewind                             119
7751 #define OP_MoveGe                             120
7752 #define OP_VBegin                             121
7753 #define OP_VUpdate                            122
7754 #define OP_IfZero                             123
7755 #define OP_BitNot                              87   /* same as TK_BITNOT   */
7756 #define OP_VCreate                            124
7757 #define OP_Found                              126
7758 #define OP_IfPos                              127
7759 #define OP_NullRow                            128
7760 #define OP_Jump                               129
7761 #define OP_Permutation                        130
7762
7763 /* The following opcode values are never used */
7764 #define OP_NotUsed_131                        131
7765 #define OP_NotUsed_132                        132
7766 #define OP_NotUsed_133                        133
7767 #define OP_NotUsed_134                        134
7768 #define OP_NotUsed_135                        135
7769 #define OP_NotUsed_136                        136
7770 #define OP_NotUsed_137                        137
7771
7772
7773 /* Properties such as "out2" or "jump" that are specified in
7774 ** comments following the "case" for each opcode in the vdbe.c
7775 ** are encoded into bitvectors as follows:
7776 */
7777 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
7778 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
7779 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
7780 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
7781 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
7782 #define OPFLG_OUT3            0x0020  /* out3:  P3 is an output */
7783 #define OPFLG_INITIALIZER {\
7784 /*   0 */ 0x00, 0x01, 0x00, 0x00, 0x10, 0x02, 0x11, 0x00,\
7785 /*   8 */ 0x00, 0x00, 0x05, 0x02, 0x00, 0x00, 0x00, 0x00,\
7786 /*  16 */ 0x04, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x05,\
7787 /*  24 */ 0x00, 0x04, 0x02, 0x02, 0x02, 0x04, 0x00, 0x00,\
7788 /*  32 */ 0x00, 0x00, 0x02, 0x11, 0x11, 0x02, 0x05, 0x00,\
7789 /*  40 */ 0x02, 0x11, 0x04, 0x00, 0x00, 0x0c, 0x11, 0x01,\
7790 /*  48 */ 0x02, 0x01, 0x00, 0x02, 0x01, 0x01, 0x02, 0x00,\
7791 /*  56 */ 0x04, 0x00, 0x00, 0x00, 0x2c, 0x2c, 0x00, 0x11,\
7792 /*  64 */ 0x00, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
7793 /*  72 */ 0x15, 0x00, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c,\
7794 /*  80 */ 0x2c, 0x2c, 0x2c, 0x2c, 0x11, 0x05, 0x00, 0x04,\
7795 /*  88 */ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00,\
7796 /*  96 */ 0x01, 0x00, 0x11, 0x00, 0x00, 0x00, 0x00, 0x01,\
7797 /* 104 */ 0x00, 0x00, 0x01, 0x08, 0x00, 0x02, 0x02, 0x05,\
7798 /* 112 */ 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x02, 0x01,\
7799 /* 120 */ 0x11, 0x00, 0x00, 0x05, 0x00, 0x02, 0x11, 0x05,\
7800 /* 128 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
7801 /* 136 */ 0x00, 0x00, 0x04, 0x04, 0x04, 0x04, 0x04,}
7802
7803 /************** End of opcodes.h *********************************************/
7804 /************** Continuing where we left off in vdbe.h ***********************/
7805
7806 /*
7807 ** Prototypes for the VDBE interface.  See comments on the implementation
7808 ** for a description of what each of these routines does.
7809 */
7810 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
7811 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
7812 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
7813 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
7814 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
7815 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
7816 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
7817 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
7818 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
7819 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
7820 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
7821 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
7822 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
7823 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
7824 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
7825 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
7826 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
7827 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
7828 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int);
7829 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
7830 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
7831 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
7832 #ifdef SQLITE_DEBUG
7833 SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
7834 #endif
7835 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
7836 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
7837 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
7838 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, int);
7839 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
7840 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
7841 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n);
7842 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
7843
7844 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
7845 SQLITE_PRIVATE int sqlite3VdbeReleaseMemory(int);
7846 #endif
7847 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,void*,int);
7848 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
7849 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
7850
7851
7852 #ifndef NDEBUG
7853 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
7854 # define VdbeComment(X)  sqlite3VdbeComment X
7855 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
7856 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
7857 #else
7858 # define VdbeComment(X)
7859 # define VdbeNoopComment(X)
7860 #endif
7861
7862 #endif
7863
7864 /************** End of vdbe.h ************************************************/
7865 /************** Continuing where we left off in sqliteInt.h ******************/
7866 /************** Include pager.h in the middle of sqliteInt.h *****************/
7867 /************** Begin file pager.h *******************************************/
7868 /*
7869 ** 2001 September 15
7870 **
7871 ** The author disclaims copyright to this source code.  In place of
7872 ** a legal notice, here is a blessing:
7873 **
7874 **    May you do good and not evil.
7875 **    May you find forgiveness for yourself and forgive others.
7876 **    May you share freely, never taking more than you give.
7877 **
7878 *************************************************************************
7879 ** This header file defines the interface that the sqlite page cache
7880 ** subsystem.  The page cache subsystem reads and writes a file a page
7881 ** at a time and provides a journal for rollback.
7882 **
7883 ** @(#) $Id: pager.h,v 1.77 2008/07/16 18:17:56 danielk1977 Exp $
7884 */
7885
7886 #ifndef _PAGER_H_
7887 #define _PAGER_H_
7888
7889 /*
7890 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
7891 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
7892 */
7893 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
7894   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
7895 #endif
7896
7897 /*
7898 ** The type used to represent a page number.  The first page in a file
7899 ** is called page 1.  0 is used to represent "not a page".
7900 */
7901 typedef u32 Pgno;
7902
7903 /*
7904 ** Each open file is managed by a separate instance of the "Pager" structure.
7905 */
7906 typedef struct Pager Pager;
7907
7908 /*
7909 ** Handle type for pages.
7910 */
7911 typedef struct PgHdr DbPage;
7912
7913 /*
7914 ** Allowed values for the flags parameter to sqlite3PagerOpen().
7915 **
7916 ** NOTE: This values must match the corresponding BTREE_ values in btree.h.
7917 */
7918 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
7919 #define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */
7920
7921 /*
7922 ** Valid values for the second argument to sqlite3PagerLockingMode().
7923 */
7924 #define PAGER_LOCKINGMODE_QUERY      -1
7925 #define PAGER_LOCKINGMODE_NORMAL      0
7926 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
7927
7928 /*
7929 ** Valid values for the second argument to sqlite3PagerJournalMode().
7930 */
7931 #define PAGER_JOURNALMODE_QUERY      -1
7932 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
7933 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
7934 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
7935
7936 /*
7937 ** See source code comments for a detailed description of the following
7938 ** routines:
7939 */
7940 SQLITE_PRIVATE int sqlite3PagerOpen(sqlite3_vfs *, Pager **ppPager, const char*, int,int,int);
7941 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, BusyHandler *pBusyHandler);
7942 SQLITE_PRIVATE void sqlite3PagerSetDestructor(Pager*, void(*)(DbPage*,int));
7943 SQLITE_PRIVATE void sqlite3PagerSetReiniter(Pager*, void(*)(DbPage*,int));
7944 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u16*);
7945 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
7946 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
7947 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
7948 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
7949 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
7950 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
7951 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
7952 SQLITE_PRIVATE int sqlite3PagerRef(DbPage*);
7953 SQLITE_PRIVATE int sqlite3PagerUnref(DbPage*);
7954 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
7955 SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*, int*);
7956 SQLITE_PRIVATE int sqlite3PagerTruncate(Pager*,Pgno);
7957 SQLITE_PRIVATE int sqlite3PagerBegin(DbPage*, int exFlag);
7958 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, Pgno, int);
7959 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
7960 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
7961 SQLITE_PRIVATE int sqlite3PagerIsreadonly(Pager*);
7962 SQLITE_PRIVATE int sqlite3PagerStmtBegin(Pager*);
7963 SQLITE_PRIVATE int sqlite3PagerStmtCommit(Pager*);
7964 SQLITE_PRIVATE int sqlite3PagerStmtRollback(Pager*);
7965 SQLITE_PRIVATE void sqlite3PagerDontRollback(DbPage*);
7966 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
7967 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
7968 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int);
7969 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
7970 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
7971 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
7972 SQLITE_PRIVATE const char *sqlite3PagerDirname(Pager*);
7973 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
7974 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
7975 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
7976 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
7977 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
7978 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
7979 SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *, int);
7980 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
7981 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
7982 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
7983
7984 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) && !defined(SQLITE_OMIT_DISKIO)
7985 SQLITE_PRIVATE   int sqlite3PagerReleaseMemory(int);
7986 #endif
7987
7988 #ifdef SQLITE_HAS_CODEC
7989 SQLITE_PRIVATE   void sqlite3PagerSetCodec(Pager*,void*(*)(void*,void*,Pgno,int),void*);
7990 #endif
7991
7992 #if !defined(NDEBUG) || defined(SQLITE_TEST)
7993 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
7994 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
7995 #endif
7996
7997 #ifdef SQLITE_TEST
7998 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
7999 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
8000 SQLITE_PRIVATE   int sqlite3PagerIsMemdb(Pager*);
8001 #endif
8002
8003 #ifdef SQLITE_TEST
8004 void disable_simulated_io_errors(void);
8005 void enable_simulated_io_errors(void);
8006 #else
8007 # define disable_simulated_io_errors()
8008 # define enable_simulated_io_errors()
8009 #endif
8010
8011 #endif /* _PAGER_H_ */
8012
8013 /************** End of pager.h ***********************************************/
8014 /************** Continuing where we left off in sqliteInt.h ******************/
8015
8016 /************** Include os.h in the middle of sqliteInt.h ********************/
8017 /************** Begin file os.h **********************************************/
8018 /*
8019 ** 2001 September 16
8020 **
8021 ** The author disclaims copyright to this source code.  In place of
8022 ** a legal notice, here is a blessing:
8023 **
8024 **    May you do good and not evil.
8025 **    May you find forgiveness for yourself and forgive others.
8026 **    May you share freely, never taking more than you give.
8027 **
8028 ******************************************************************************
8029 **
8030 ** This header file (together with is companion C source-code file
8031 ** "os.c") attempt to abstract the underlying operating system so that
8032 ** the SQLite library will work on both POSIX and windows systems.
8033 **
8034 ** This header file is #include-ed by sqliteInt.h and thus ends up
8035 ** being included by every source file.
8036 **
8037 ** $Id: os.h,v 1.105 2008/06/26 10:41:19 danielk1977 Exp $
8038 */
8039 #ifndef _SQLITE_OS_H_
8040 #define _SQLITE_OS_H_
8041
8042 /*
8043 ** Figure out if we are dealing with Unix, Windows, or some other
8044 ** operating system.  After the following block of preprocess macros,
8045 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER 
8046 ** will defined to either 1 or 0.  One of the four will be 1.  The other 
8047 ** three will be 0.
8048 */
8049 #if defined(SQLITE_OS_OTHER)
8050 # if SQLITE_OS_OTHER==1
8051 #   undef SQLITE_OS_UNIX
8052 #   define SQLITE_OS_UNIX 0
8053 #   undef SQLITE_OS_WIN
8054 #   define SQLITE_OS_WIN 0
8055 #   undef SQLITE_OS_OS2
8056 #   define SQLITE_OS_OS2 0
8057 # else
8058 #   undef SQLITE_OS_OTHER
8059 # endif
8060 #endif
8061 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
8062 # define SQLITE_OS_OTHER 0
8063 # ifndef SQLITE_OS_WIN
8064 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
8065 #     define SQLITE_OS_WIN 1
8066 #     define SQLITE_OS_UNIX 0
8067 #     define SQLITE_OS_OS2 0
8068 #   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
8069 #     define SQLITE_OS_WIN 0
8070 #     define SQLITE_OS_UNIX 0
8071 #     define SQLITE_OS_OS2 1
8072 #   else
8073 #     define SQLITE_OS_WIN 0
8074 #     define SQLITE_OS_UNIX 1
8075 #     define SQLITE_OS_OS2 0
8076 #  endif
8077 # else
8078 #  define SQLITE_OS_UNIX 0
8079 #  define SQLITE_OS_OS2 0
8080 # endif
8081 #else
8082 # ifndef SQLITE_OS_WIN
8083 #  define SQLITE_OS_WIN 0
8084 # endif
8085 #endif
8086
8087 /*
8088 ** Determine if we are dealing with WindowsCE - which has a much
8089 ** reduced API.
8090 */
8091 #if defined(_WIN32_WCE)
8092 # define SQLITE_OS_WINCE 1
8093 #else
8094 # define SQLITE_OS_WINCE 0
8095 #endif
8096
8097
8098 /*
8099 ** Define the maximum size of a temporary filename
8100 */
8101 #if SQLITE_OS_WIN
8102 # include <windows.h>
8103 # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
8104 #elif SQLITE_OS_OS2
8105 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
8106 #  include <os2safe.h> /* has to be included before os2.h for linking to work */
8107 # endif
8108 # define INCL_DOSDATETIME
8109 # define INCL_DOSFILEMGR
8110 # define INCL_DOSERRORS
8111 # define INCL_DOSMISC
8112 # define INCL_DOSPROCESS
8113 # define INCL_DOSMODULEMGR
8114 # define INCL_DOSSEMAPHORES
8115 # include <os2.h>
8116 # include <uconv.h>
8117 # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
8118 #else
8119 # define SQLITE_TEMPNAME_SIZE 200
8120 #endif
8121
8122 /* If the SET_FULLSYNC macro is not defined above, then make it
8123 ** a no-op
8124 */
8125 #ifndef SET_FULLSYNC
8126 # define SET_FULLSYNC(x,y)
8127 #endif
8128
8129 /*
8130 ** The default size of a disk sector
8131 */
8132 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
8133 # define SQLITE_DEFAULT_SECTOR_SIZE 512
8134 #endif
8135
8136 /*
8137 ** Temporary files are named starting with this prefix followed by 16 random
8138 ** alphanumeric characters, and no file extension. They are stored in the
8139 ** OS's standard temporary file directory, and are deleted prior to exit.
8140 ** If sqlite is being embedded in another program, you may wish to change the
8141 ** prefix to reflect your program's name, so that if your program exits
8142 ** prematurely, old temporary files can be easily identified. This can be done
8143 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
8144 **
8145 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
8146 ** Mcafee started using SQLite in their anti-virus product and it
8147 ** started putting files with the "sqlite" name in the c:/temp folder.
8148 ** This annoyed many windows users.  Those users would then do a 
8149 ** Google search for "sqlite", find the telephone numbers of the
8150 ** developers and call to wake them up at night and complain.
8151 ** For this reason, the default name prefix is changed to be "sqlite" 
8152 ** spelled backwards.  So the temp files are still identified, but
8153 ** anybody smart enough to figure out the code is also likely smart
8154 ** enough to know that calling the developer will not help get rid
8155 ** of the file.
8156 */
8157 #ifndef SQLITE_TEMP_FILE_PREFIX
8158 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
8159 #endif
8160
8161 /*
8162 ** The following values may be passed as the second argument to
8163 ** sqlite3OsLock(). The various locks exhibit the following semantics:
8164 **
8165 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
8166 ** RESERVED:  A single process may hold a RESERVED lock on a file at
8167 **            any time. Other processes may hold and obtain new SHARED locks.
8168 ** PENDING:   A single process may hold a PENDING lock on a file at
8169 **            any one time. Existing SHARED locks may persist, but no new
8170 **            SHARED locks may be obtained by other processes.
8171 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
8172 **
8173 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
8174 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
8175 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
8176 ** sqlite3OsLock().
8177 */
8178 #define NO_LOCK         0
8179 #define SHARED_LOCK     1
8180 #define RESERVED_LOCK   2
8181 #define PENDING_LOCK    3
8182 #define EXCLUSIVE_LOCK  4
8183
8184 /*
8185 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
8186 **
8187 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
8188 ** those functions are not available.  So we use only LockFile() and
8189 ** UnlockFile().
8190 **
8191 ** LockFile() prevents not just writing but also reading by other processes.
8192 ** A SHARED_LOCK is obtained by locking a single randomly-chosen 
8193 ** byte out of a specific range of bytes. The lock byte is obtained at 
8194 ** random so two separate readers can probably access the file at the 
8195 ** same time, unless they are unlucky and choose the same lock byte.
8196 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
8197 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
8198 ** a single byte of the file that is designated as the reserved lock byte.
8199 ** A PENDING_LOCK is obtained by locking a designated byte different from
8200 ** the RESERVED_LOCK byte.
8201 **
8202 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
8203 ** which means we can use reader/writer locks.  When reader/writer locks
8204 ** are used, the lock is placed on the same range of bytes that is used
8205 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
8206 ** will support two or more Win95 readers or two or more WinNT readers.
8207 ** But a single Win95 reader will lock out all WinNT readers and a single
8208 ** WinNT reader will lock out all other Win95 readers.
8209 **
8210 ** The following #defines specify the range of bytes used for locking.
8211 ** SHARED_SIZE is the number of bytes available in the pool from which
8212 ** a random byte is selected for a shared lock.  The pool of bytes for
8213 ** shared locks begins at SHARED_FIRST. 
8214 **
8215 ** These #defines are available in sqlite_aux.h so that adaptors for
8216 ** connecting SQLite to other operating systems can use the same byte
8217 ** ranges for locking.  In particular, the same locking strategy and
8218 ** byte ranges are used for Unix.  This leaves open the possiblity of having
8219 ** clients on win95, winNT, and unix all talking to the same shared file
8220 ** and all locking correctly.  To do so would require that samba (or whatever
8221 ** tool is being used for file sharing) implements locks correctly between
8222 ** windows and unix.  I'm guessing that isn't likely to happen, but by
8223 ** using the same locking range we are at least open to the possibility.
8224 **
8225 ** Locking in windows is manditory.  For this reason, we cannot store
8226 ** actual data in the bytes used for locking.  The pager never allocates
8227 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
8228 ** that all locks will fit on a single page even at the minimum page size.
8229 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
8230 ** is set high so that we don't have to allocate an unused page except
8231 ** for very large databases.  But one should test the page skipping logic 
8232 ** by setting PENDING_BYTE low and running the entire regression suite.
8233 **
8234 ** Changing the value of PENDING_BYTE results in a subtly incompatible
8235 ** file format.  Depending on how it is changed, you might not notice
8236 ** the incompatibility right away, even running a full regression test.
8237 ** The default location of PENDING_BYTE is the first byte past the
8238 ** 1GB boundary.
8239 **
8240 */
8241 #ifndef SQLITE_TEST
8242 #define PENDING_BYTE      0x40000000  /* First byte past the 1GB boundary */
8243 #else
8244 SQLITE_API extern unsigned int sqlite3_pending_byte;
8245 #define PENDING_BYTE sqlite3_pending_byte
8246 #endif
8247
8248 #define RESERVED_BYTE     (PENDING_BYTE+1)
8249 #define SHARED_FIRST      (PENDING_BYTE+2)
8250 #define SHARED_SIZE       510
8251
8252 /* 
8253 ** Functions for accessing sqlite3_file methods 
8254 */
8255 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
8256 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
8257 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
8258 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
8259 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
8260 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
8261 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
8262 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
8263 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
8264 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
8265 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
8266 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
8267
8268 /* 
8269 ** Functions for accessing sqlite3_vfs methods 
8270 */
8271 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
8272 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
8273 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
8274 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
8275 #ifndef SQLITE_OMIT_LOAD_EXTENSION
8276 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
8277 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
8278 SQLITE_PRIVATE void *sqlite3OsDlSym(sqlite3_vfs *, void *, const char *);
8279 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
8280 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
8281 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
8282 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
8283 SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *, double*);
8284
8285 /*
8286 ** Convenience functions for opening and closing files using 
8287 ** sqlite3_malloc() to obtain space for the file-handle structure.
8288 */
8289 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
8290 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
8291
8292 #endif /* _SQLITE_OS_H_ */
8293
8294 /************** End of os.h **************************************************/
8295 /************** Continuing where we left off in sqliteInt.h ******************/
8296 /************** Include mutex.h in the middle of sqliteInt.h *****************/
8297 /************** Begin file mutex.h *******************************************/
8298 /*
8299 ** 2007 August 28
8300 **
8301 ** The author disclaims copyright to this source code.  In place of
8302 ** a legal notice, here is a blessing:
8303 **
8304 **    May you do good and not evil.
8305 **    May you find forgiveness for yourself and forgive others.
8306 **    May you share freely, never taking more than you give.
8307 **
8308 *************************************************************************
8309 **
8310 ** This file contains the common header for all mutex implementations.
8311 ** The sqliteInt.h header #includes this file so that it is available
8312 ** to all source files.  We break it out in an effort to keep the code
8313 ** better organized.
8314 **
8315 ** NOTE:  source files should *not* #include this header file directly.
8316 ** Source files should #include the sqliteInt.h file and let that file
8317 ** include this one indirectly.
8318 **
8319 ** $Id: mutex.h,v 1.8 2008/06/26 10:41:19 danielk1977 Exp $
8320 */
8321
8322
8323 #ifdef SQLITE_MUTEX_APPDEF
8324 /*
8325 ** If SQLITE_MUTEX_APPDEF is defined, then this whole module is
8326 ** omitted and equivalent functionality must be provided by the
8327 ** application that links against the SQLite library.
8328 */
8329 #else
8330 /*
8331 ** Figure out what version of the code to use.  The choices are
8332 **
8333 **   SQLITE_MUTEX_NOOP         For single-threaded applications that
8334 **                             do not desire error checking.
8335 **
8336 **   SQLITE_MUTEX_NOOP_DEBUG   For single-threaded applications with
8337 **                             error checking to help verify that mutexes
8338 **                             are being used correctly even though they
8339 **                             are not needed.  Used when SQLITE_DEBUG is
8340 **                             defined on single-threaded builds.
8341 **
8342 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
8343 **
8344 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
8345 **
8346 **   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
8347 */
8348 #define SQLITE_MUTEX_NOOP 1   /* The default */
8349 #if defined(SQLITE_DEBUG) && !SQLITE_THREADSAFE
8350 # undef SQLITE_MUTEX_NOOP
8351 # define SQLITE_MUTEX_NOOP_DEBUG
8352 #endif
8353 #if defined(SQLITE_MUTEX_NOOP) && SQLITE_THREADSAFE && SQLITE_OS_UNIX
8354 # undef SQLITE_MUTEX_NOOP
8355 # define SQLITE_MUTEX_PTHREADS
8356 #endif
8357 #if defined(SQLITE_MUTEX_NOOP) && SQLITE_THREADSAFE && SQLITE_OS_WIN
8358 # undef SQLITE_MUTEX_NOOP
8359 # define SQLITE_MUTEX_W32
8360 #endif
8361 #if defined(SQLITE_MUTEX_NOOP) && SQLITE_THREADSAFE && SQLITE_OS_OS2
8362 # undef SQLITE_MUTEX_NOOP
8363 # define SQLITE_MUTEX_OS2
8364 #endif
8365
8366 #ifdef SQLITE_MUTEX_NOOP
8367 /*
8368 ** If this is a no-op implementation, implement everything as macros.
8369 */
8370 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
8371 #define sqlite3_mutex_free(X)
8372 #define sqlite3_mutex_enter(X)
8373 #define sqlite3_mutex_try(X)      SQLITE_OK
8374 #define sqlite3_mutex_leave(X)
8375 #define sqlite3_mutex_held(X)     1
8376 #define sqlite3_mutex_notheld(X)  1
8377 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
8378 #define sqlite3MutexInit()        SQLITE_OK
8379 #define sqlite3MutexEnd()
8380 #endif
8381
8382 #endif /* SQLITE_MUTEX_APPDEF */
8383
8384 /************** End of mutex.h ***********************************************/
8385 /************** Continuing where we left off in sqliteInt.h ******************/
8386
8387
8388 /*
8389 ** Each database file to be accessed by the system is an instance
8390 ** of the following structure.  There are normally two of these structures
8391 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
8392 ** aDb[1] is the database file used to hold temporary tables.  Additional
8393 ** databases may be attached.
8394 */
8395 struct Db {
8396   char *zName;         /* Name of this database */
8397   Btree *pBt;          /* The B*Tree structure for this database file */
8398   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
8399   u8 safety_level;     /* How aggressive at synching data to disk */
8400   void *pAux;               /* Auxiliary data.  Usually NULL */
8401   void (*xFreeAux)(void*);  /* Routine to free pAux */
8402   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
8403 };
8404
8405 /*
8406 ** An instance of the following structure stores a database schema.
8407 **
8408 ** If there are no virtual tables configured in this schema, the
8409 ** Schema.db variable is set to NULL. After the first virtual table
8410 ** has been added, it is set to point to the database connection 
8411 ** used to create the connection. Once a virtual table has been
8412 ** added to the Schema structure and the Schema.db variable populated, 
8413 ** only that database connection may use the Schema to prepare 
8414 ** statements.
8415 */
8416 struct Schema {
8417   int schema_cookie;   /* Database schema version number for this file */
8418   Hash tblHash;        /* All tables indexed by name */
8419   Hash idxHash;        /* All (named) indices indexed by name */
8420   Hash trigHash;       /* All triggers indexed by name */
8421   Hash aFKey;          /* Foreign keys indexed by to-table */
8422   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
8423   u8 file_format;      /* Schema format version for this file */
8424   u8 enc;              /* Text encoding used by this database */
8425   u16 flags;           /* Flags associated with this schema */
8426   int cache_size;      /* Number of pages to use in the cache */
8427 #ifndef SQLITE_OMIT_VIRTUALTABLE
8428   sqlite3 *db;         /* "Owner" connection. See comment above */
8429 #endif
8430 };
8431
8432 /*
8433 ** These macros can be used to test, set, or clear bits in the 
8434 ** Db.flags field.
8435 */
8436 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
8437 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
8438 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
8439 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
8440
8441 /*
8442 ** Allowed values for the DB.flags field.
8443 **
8444 ** The DB_SchemaLoaded flag is set after the database schema has been
8445 ** read into internal hash tables.
8446 **
8447 ** DB_UnresetViews means that one or more views have column names that
8448 ** have been filled out.  If the schema changes, these column names might
8449 ** changes and so the view will need to be reset.
8450 */
8451 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
8452 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
8453 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
8454
8455 /*
8456 ** The number of different kinds of things that can be limited
8457 ** using the sqlite3_limit() interface.
8458 */
8459 #define SQLITE_N_LIMIT (SQLITE_LIMIT_VARIABLE_NUMBER+1)
8460
8461 /*
8462 ** Lookaside malloc is a set of fixed-size buffers that can be used
8463 ** to satisify small transient memory allocation requests for objects
8464 ** associated with a particular database connection.  The use of
8465 ** lookaside malloc provides a significant performance enhancement
8466 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
8467 ** SQL statements.
8468 **
8469 ** The Lookaside structure holds configuration information about the
8470 ** lookaside malloc subsystem.  Each available memory allocation in
8471 ** the lookaside subsystem is stored on a linked list of LookasideSlot
8472 ** objects.
8473 */
8474 struct Lookaside {
8475   u16 sz;                 /* Size of each buffer in bytes */
8476   u8 bEnabled;            /* True if use lookaside.  False to ignore it */
8477   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
8478   int nOut;               /* Number of buffers currently checked out */
8479   int mxOut;              /* Highwater mark for nOut */
8480   LookasideSlot *pFree;   /* List if available buffers */
8481   void *pStart;           /* First byte of available memory space */
8482   void *pEnd;             /* First byte past end of available space */
8483 };
8484 struct LookasideSlot {
8485   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
8486 };
8487
8488 /*
8489 ** Each database is an instance of the following structure.
8490 **
8491 ** The sqlite.lastRowid records the last insert rowid generated by an
8492 ** insert statement.  Inserts on views do not affect its value.  Each
8493 ** trigger has its own context, so that lastRowid can be updated inside
8494 ** triggers as usual.  The previous value will be restored once the trigger
8495 ** exits.  Upon entering a before or instead of trigger, lastRowid is no
8496 ** longer (since after version 2.8.12) reset to -1.
8497 **
8498 ** The sqlite.nChange does not count changes within triggers and keeps no
8499 ** context.  It is reset at start of sqlite3_exec.
8500 ** The sqlite.lsChange represents the number of changes made by the last
8501 ** insert, update, or delete statement.  It remains constant throughout the
8502 ** length of a statement and is then updated by OP_SetCounts.  It keeps a
8503 ** context stack just like lastRowid so that the count of changes
8504 ** within a trigger is not seen outside the trigger.  Changes to views do not
8505 ** affect the value of lsChange.
8506 ** The sqlite.csChange keeps track of the number of current changes (since
8507 ** the last statement) and is used to update sqlite_lsChange.
8508 **
8509 ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
8510 ** store the most recent error code and, if applicable, string. The
8511 ** internal function sqlite3Error() is used to set these variables
8512 ** consistently.
8513 */
8514 struct sqlite3 {
8515   sqlite3_vfs *pVfs;            /* OS Interface */
8516   int nDb;                      /* Number of backends currently in use */
8517   Db *aDb;                      /* All backends */
8518   int flags;                    /* Miscellanous flags. See below */
8519   int openFlags;                /* Flags passed to sqlite3_vfs.xOpen() */
8520   int errCode;                  /* Most recent error code (SQLITE_*) */
8521   int errMask;                  /* & result codes with this before returning */
8522   u8 autoCommit;                /* The auto-commit flag. */
8523   u8 temp_store;                /* 1: file 2: memory 0: default */
8524   u8 mallocFailed;              /* True if we have seen a malloc failure */
8525   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
8526   u8 dfltJournalMode;           /* Default journal mode for attached dbs */
8527   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
8528   int nextPagesize;             /* Pagesize after VACUUM if >0 */
8529   int nTable;                   /* Number of tables in the database */
8530   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
8531   i64 lastRowid;                /* ROWID of most recent insert (see above) */
8532   i64 priorNewRowid;            /* Last randomly generated ROWID */
8533   int magic;                    /* Magic number for detect library misuse */
8534   int nChange;                  /* Value returned by sqlite3_changes() */
8535   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
8536   sqlite3_mutex *mutex;         /* Connection mutex */
8537   int aLimit[SQLITE_N_LIMIT];   /* Limits */
8538   struct sqlite3InitInfo {      /* Information used during initialization */
8539     int iDb;                    /* When back is being initialized */
8540     int newTnum;                /* Rootpage of table being initialized */
8541     u8 busy;                    /* TRUE if currently initializing */
8542   } init;
8543   int nExtension;               /* Number of loaded extensions */
8544   void **aExtension;            /* Array of shared libraray handles */
8545   struct Vdbe *pVdbe;           /* List of active virtual machines */
8546   int activeVdbeCnt;            /* Number of vdbes currently executing */
8547   void (*xTrace)(void*,const char*);        /* Trace function */
8548   void *pTraceArg;                          /* Argument to the trace function */
8549   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
8550   void *pProfileArg;                        /* Argument to profile function */
8551   void *pCommitArg;                 /* Argument to xCommitCallback() */   
8552   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
8553   void *pRollbackArg;               /* Argument to xRollbackCallback() */   
8554   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
8555   void *pUpdateArg;
8556   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
8557   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
8558   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
8559   void *pCollNeededArg;
8560   sqlite3_value *pErr;          /* Most recent error message */
8561   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
8562   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
8563   union {
8564     int isInterrupted;          /* True if sqlite3_interrupt has been called */
8565     double notUsed1;            /* Spacer */
8566   } u1;
8567   Lookaside lookaside;          /* Lookaside malloc configuration */
8568 #ifndef SQLITE_OMIT_AUTHORIZATION
8569   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
8570                                 /* Access authorization function */
8571   void *pAuthArg;               /* 1st argument to the access auth function */
8572 #endif
8573 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
8574   int (*xProgress)(void *);     /* The progress callback */
8575   void *pProgressArg;           /* Argument to the progress callback */
8576   int nProgressOps;             /* Number of opcodes for progress callback */
8577 #endif
8578 #ifndef SQLITE_OMIT_VIRTUALTABLE
8579   Hash aModule;                 /* populated by sqlite3_create_module() */
8580   Table *pVTab;                 /* vtab with active Connect/Create method */
8581   sqlite3_vtab **aVTrans;       /* Virtual tables with open transactions */
8582   int nVTrans;                  /* Allocated size of aVTrans */
8583 #endif
8584   Hash aFunc;                   /* All functions that can be in SQL exprs */
8585   Hash aCollSeq;                /* All collating sequences */
8586   BusyHandler busyHandler;      /* Busy callback */
8587   int busyTimeout;              /* Busy handler timeout, in msec */
8588   Db aDbStatic[2];              /* Static space for the 2 default backends */
8589 #ifdef SQLITE_SSE
8590   sqlite3_stmt *pFetch;         /* Used by SSE to fetch stored statements */
8591 #endif
8592 };
8593
8594 /*
8595 ** A macro to discover the encoding of a database.
8596 */
8597 #define ENC(db) ((db)->aDb[0].pSchema->enc)
8598
8599 /*
8600 ** Possible values for the sqlite.flags and or Db.flags fields.
8601 **
8602 ** On sqlite.flags, the SQLITE_InTrans value means that we have
8603 ** executed a BEGIN.  On Db.flags, SQLITE_InTrans means a statement
8604 ** transaction is active on that particular database file.
8605 */
8606 #define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
8607 #define SQLITE_InTrans        0x00000008  /* True if in a transaction */
8608 #define SQLITE_InternChanges  0x00000010  /* Uncommitted Hash table changes */
8609 #define SQLITE_FullColNames   0x00000020  /* Show full column names on SELECT */
8610 #define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
8611 #define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
8612                                           /*   DELETE, or UPDATE and return */
8613                                           /*   the count using a callback. */
8614 #define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
8615                                           /*   result set is empty */
8616 #define SQLITE_SqlTrace       0x00000200  /* Debug print SQL as it executes */
8617 #define SQLITE_VdbeListing    0x00000400  /* Debug listings of VDBE programs */
8618 #define SQLITE_WriteSchema    0x00000800  /* OK to update SQLITE_MASTER */
8619 #define SQLITE_NoReadlock     0x00001000  /* Readlocks are omitted when 
8620                                           ** accessing read-only databases */
8621 #define SQLITE_IgnoreChecks   0x00002000  /* Do not enforce check constraints */
8622 #define SQLITE_ReadUncommitted 0x00004000 /* For shared-cache mode */
8623 #define SQLITE_LegacyFileFmt  0x00008000  /* Create new databases in format 1 */
8624 #define SQLITE_FullFSync      0x00010000  /* Use full fsync on the backend */
8625 #define SQLITE_LoadExtension  0x00020000  /* Enable load_extension */
8626
8627 #define SQLITE_RecoveryMode   0x00040000  /* Ignore schema errors */
8628 #define SQLITE_SharedCache    0x00080000  /* Cache sharing is enabled */
8629 #define SQLITE_Vtab           0x00100000  /* There exists a virtual table */
8630
8631 /*
8632 ** Possible values for the sqlite.magic field.
8633 ** The numbers are obtained at random and have no special meaning, other
8634 ** than being distinct from one another.
8635 */
8636 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
8637 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
8638 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
8639 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
8640 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
8641
8642 /*
8643 ** Each SQL function is defined by an instance of the following
8644 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
8645 ** hash table.  When multiple functions have the same name, the hash table
8646 ** points to a linked list of these structures.
8647 */
8648 struct FuncDef {
8649   i16 nArg;            /* Number of arguments.  -1 means unlimited */
8650   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
8651   u8 needCollSeq;      /* True if sqlite3GetFuncCollSeq() might be called */
8652   u8 flags;            /* Some combination of SQLITE_FUNC_* */
8653   void *pUserData;     /* User data parameter */
8654   FuncDef *pNext;      /* Next function with same name */
8655   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
8656   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
8657   void (*xFinalize)(sqlite3_context*);                /* Aggregate finializer */
8658   char zName[1];       /* SQL name of the function.  MUST BE LAST */
8659 };
8660
8661 /*
8662 ** Each SQLite module (virtual table definition) is defined by an
8663 ** instance of the following structure, stored in the sqlite3.aModule
8664 ** hash table.
8665 */
8666 struct Module {
8667   const sqlite3_module *pModule;       /* Callback pointers */
8668   const char *zName;                   /* Name passed to create_module() */
8669   void *pAux;                          /* pAux passed to create_module() */
8670   void (*xDestroy)(void *);            /* Module destructor function */
8671 };
8672
8673 /*
8674 ** Possible values for FuncDef.flags
8675 */
8676 #define SQLITE_FUNC_LIKE   0x01  /* Candidate for the LIKE optimization */
8677 #define SQLITE_FUNC_CASE   0x02  /* Case-sensitive LIKE-type function */
8678 #define SQLITE_FUNC_EPHEM  0x04  /* Ephermeral.  Delete with VDBE */
8679
8680 /*
8681 ** information about each column of an SQL table is held in an instance
8682 ** of this structure.
8683 */
8684 struct Column {
8685   char *zName;     /* Name of this column */
8686   Expr *pDflt;     /* Default value of this column */
8687   char *zType;     /* Data type for this column */
8688   char *zColl;     /* Collating sequence.  If NULL, use the default */
8689   u8 notNull;      /* True if there is a NOT NULL constraint */
8690   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
8691   char affinity;   /* One of the SQLITE_AFF_... values */
8692 #ifndef SQLITE_OMIT_VIRTUALTABLE
8693   u8 isHidden;     /* True if this column is 'hidden' */
8694 #endif
8695 };
8696
8697 /*
8698 ** A "Collating Sequence" is defined by an instance of the following
8699 ** structure. Conceptually, a collating sequence consists of a name and
8700 ** a comparison routine that defines the order of that sequence.
8701 **
8702 ** There may two seperate implementations of the collation function, one
8703 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
8704 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
8705 ** native byte order. When a collation sequence is invoked, SQLite selects
8706 ** the version that will require the least expensive encoding
8707 ** translations, if any.
8708 **
8709 ** The CollSeq.pUser member variable is an extra parameter that passed in
8710 ** as the first argument to the UTF-8 comparison function, xCmp.
8711 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
8712 ** xCmp16.
8713 **
8714 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
8715 ** collating sequence is undefined.  Indices built on an undefined
8716 ** collating sequence may not be read or written.
8717 */
8718 struct CollSeq {
8719   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
8720   u8 enc;               /* Text encoding handled by xCmp() */
8721   u8 type;              /* One of the SQLITE_COLL_... values below */
8722   void *pUser;          /* First argument to xCmp() */
8723   int (*xCmp)(void*,int, const void*, int, const void*);
8724   void (*xDel)(void*);  /* Destructor for pUser */
8725 };
8726
8727 /*
8728 ** Allowed values of CollSeq flags:
8729 */
8730 #define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
8731 #define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
8732 #define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
8733 #define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
8734
8735 /*
8736 ** A sort order can be either ASC or DESC.
8737 */
8738 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
8739 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
8740
8741 /*
8742 ** Column affinity types.
8743 **
8744 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
8745 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
8746 ** the speed a little by number the values consecutively.  
8747 **
8748 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
8749 ** when multiple affinity types are concatenated into a string and
8750 ** used as the P4 operand, they will be more readable.
8751 **
8752 ** Note also that the numeric types are grouped together so that testing
8753 ** for a numeric type is a single comparison.
8754 */
8755 #define SQLITE_AFF_TEXT     'a'
8756 #define SQLITE_AFF_NONE     'b'
8757 #define SQLITE_AFF_NUMERIC  'c'
8758 #define SQLITE_AFF_INTEGER  'd'
8759 #define SQLITE_AFF_REAL     'e'
8760
8761 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
8762
8763 /*
8764 ** The SQLITE_AFF_MASK values masks off the significant bits of an
8765 ** affinity value. 
8766 */
8767 #define SQLITE_AFF_MASK     0x67
8768
8769 /*
8770 ** Additional bit values that can be ORed with an affinity without
8771 ** changing the affinity.
8772 */
8773 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
8774 #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
8775
8776 /*
8777 ** Each SQL table is represented in memory by an instance of the
8778 ** following structure.
8779 **
8780 ** Table.zName is the name of the table.  The case of the original
8781 ** CREATE TABLE statement is stored, but case is not significant for
8782 ** comparisons.
8783 **
8784 ** Table.nCol is the number of columns in this table.  Table.aCol is a
8785 ** pointer to an array of Column structures, one for each column.
8786 **
8787 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
8788 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
8789 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
8790 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
8791 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
8792 ** is generated for each row of the table.  Table.hasPrimKey is true if
8793 ** the table has any PRIMARY KEY, INTEGER or otherwise.
8794 **
8795 ** Table.tnum is the page number for the root BTree page of the table in the
8796 ** database file.  If Table.iDb is the index of the database table backend
8797 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
8798 ** holds temporary tables and indices.  If Table.isEphem
8799 ** is true, then the table is stored in a file that is automatically deleted
8800 ** when the VDBE cursor to the table is closed.  In this case Table.tnum 
8801 ** refers VDBE cursor number that holds the table open, not to the root
8802 ** page number.  Transient tables are used to hold the results of a
8803 ** sub-query that appears instead of a real table name in the FROM clause 
8804 ** of a SELECT statement.
8805 */
8806 struct Table {
8807   sqlite3 *db;     /* Associated database connection.  Might be NULL. */
8808   char *zName;     /* Name of the table */
8809   int nCol;        /* Number of columns in this table */
8810   Column *aCol;    /* Information about each column */
8811   int iPKey;       /* If not less then 0, use aCol[iPKey] as the primary key */
8812   Index *pIndex;   /* List of SQL indexes on this table. */
8813   int tnum;        /* Root BTree node for this table (see note above) */
8814   Select *pSelect; /* NULL for tables.  Points to definition if a view. */
8815   int nRef;          /* Number of pointers to this Table */
8816   Trigger *pTrigger; /* List of SQL triggers on this table */
8817   FKey *pFKey;       /* Linked list of all foreign keys in this table */
8818   char *zColAff;     /* String defining the affinity of each column */
8819 #ifndef SQLITE_OMIT_CHECK
8820   Expr *pCheck;      /* The AND of all CHECK constraints */
8821 #endif
8822 #ifndef SQLITE_OMIT_ALTERTABLE
8823   int addColOffset;  /* Offset in CREATE TABLE statement to add a new column */
8824 #endif
8825   u8 readOnly;     /* True if this table should not be written by the user */
8826   u8 isEphem;      /* True if created using OP_OpenEphermeral */
8827   u8 hasPrimKey;   /* True if there exists a primary key */
8828   u8 keyConf;      /* What to do in case of uniqueness conflict on iPKey */
8829   u8 autoInc;      /* True if the integer primary key is autoincrement */
8830 #ifndef SQLITE_OMIT_VIRTUALTABLE
8831   u8 isVirtual;             /* True if this is a virtual table */
8832   u8 isCommit;              /* True once the CREATE TABLE has been committed */
8833   Module *pMod;             /* Pointer to the implementation of the module */
8834   sqlite3_vtab *pVtab;      /* Pointer to the module instance */
8835   int nModuleArg;           /* Number of arguments to the module */
8836   char **azModuleArg;       /* Text of all module args. [0] is module name */
8837 #endif
8838   Schema *pSchema;          /* Schema that contains this table */
8839 };
8840
8841 /*
8842 ** Test to see whether or not a table is a virtual table.  This is
8843 ** done as a macro so that it will be optimized out when virtual
8844 ** table support is omitted from the build.
8845 */
8846 #ifndef SQLITE_OMIT_VIRTUALTABLE
8847 #  define IsVirtual(X)      ((X)->isVirtual)
8848 #  define IsHiddenColumn(X) ((X)->isHidden)
8849 #else
8850 #  define IsVirtual(X)      0
8851 #  define IsHiddenColumn(X) 0
8852 #endif
8853
8854 /*
8855 ** Each foreign key constraint is an instance of the following structure.
8856 **
8857 ** A foreign key is associated with two tables.  The "from" table is
8858 ** the table that contains the REFERENCES clause that creates the foreign
8859 ** key.  The "to" table is the table that is named in the REFERENCES clause.
8860 ** Consider this example:
8861 **
8862 **     CREATE TABLE ex1(
8863 **       a INTEGER PRIMARY KEY,
8864 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
8865 **     );
8866 **
8867 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
8868 **
8869 ** Each REFERENCES clause generates an instance of the following structure
8870 ** which is attached to the from-table.  The to-table need not exist when
8871 ** the from-table is created.  The existance of the to-table is not checked
8872 ** until an attempt is made to insert data into the from-table.
8873 **
8874 ** The sqlite.aFKey hash table stores pointers to this structure
8875 ** given the name of a to-table.  For each to-table, all foreign keys
8876 ** associated with that table are on a linked list using the FKey.pNextTo
8877 ** field.
8878 */
8879 struct FKey {
8880   Table *pFrom;     /* The table that constains the REFERENCES clause */
8881   FKey *pNextFrom;  /* Next foreign key in pFrom */
8882   char *zTo;        /* Name of table that the key points to */
8883   FKey *pNextTo;    /* Next foreign key that points to zTo */
8884   int nCol;         /* Number of columns in this key */
8885   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
8886     int iFrom;         /* Index of column in pFrom */
8887     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
8888   } *aCol;          /* One entry for each of nCol column s */
8889   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
8890   u8 updateConf;    /* How to resolve conflicts that occur on UPDATE */
8891   u8 deleteConf;    /* How to resolve conflicts that occur on DELETE */
8892   u8 insertConf;    /* How to resolve conflicts that occur on INSERT */
8893 };
8894
8895 /*
8896 ** SQLite supports many different ways to resolve a constraint
8897 ** error.  ROLLBACK processing means that a constraint violation
8898 ** causes the operation in process to fail and for the current transaction
8899 ** to be rolled back.  ABORT processing means the operation in process
8900 ** fails and any prior changes from that one operation are backed out,
8901 ** but the transaction is not rolled back.  FAIL processing means that
8902 ** the operation in progress stops and returns an error code.  But prior
8903 ** changes due to the same operation are not backed out and no rollback
8904 ** occurs.  IGNORE means that the particular row that caused the constraint
8905 ** error is not inserted or updated.  Processing continues and no error
8906 ** is returned.  REPLACE means that preexisting database rows that caused
8907 ** a UNIQUE constraint violation are removed so that the new insert or
8908 ** update can proceed.  Processing continues and no error is reported.
8909 **
8910 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
8911 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
8912 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
8913 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
8914 ** referenced table row is propagated into the row that holds the
8915 ** foreign key.
8916 ** 
8917 ** The following symbolic values are used to record which type
8918 ** of action to take.
8919 */
8920 #define OE_None     0   /* There is no constraint to check */
8921 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
8922 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
8923 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
8924 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
8925 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
8926
8927 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
8928 #define OE_SetNull  7   /* Set the foreign key value to NULL */
8929 #define OE_SetDflt  8   /* Set the foreign key value to its default */
8930 #define OE_Cascade  9   /* Cascade the changes */
8931
8932 #define OE_Default  99  /* Do whatever the default action is */
8933
8934
8935 /*
8936 ** An instance of the following structure is passed as the first
8937 ** argument to sqlite3VdbeKeyCompare and is used to control the 
8938 ** comparison of the two index keys.
8939 **
8940 ** If the KeyInfo.incrKey value is true and the comparison would
8941 ** otherwise be equal, then return a result as if the second key
8942 ** were larger.
8943 */
8944 struct KeyInfo {
8945   sqlite3 *db;        /* The database connection */
8946   u8 enc;             /* Text encoding - one of the TEXT_Utf* values */
8947   u8 incrKey;         /* Increase 2nd key by epsilon before comparison */
8948   u8 prefixIsEqual;   /* Treat a prefix as equal */
8949   int nField;         /* Number of entries in aColl[] */
8950   u8 *aSortOrder;     /* If defined an aSortOrder[i] is true, sort DESC */
8951   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
8952 };
8953
8954 /*
8955 ** Each SQL index is represented in memory by an
8956 ** instance of the following structure.
8957 **
8958 ** The columns of the table that are to be indexed are described
8959 ** by the aiColumn[] field of this structure.  For example, suppose
8960 ** we have the following table and index:
8961 **
8962 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
8963 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
8964 **
8965 ** In the Table structure describing Ex1, nCol==3 because there are
8966 ** three columns in the table.  In the Index structure describing
8967 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
8968 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
8969 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
8970 ** The second column to be indexed (c1) has an index of 0 in
8971 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
8972 **
8973 ** The Index.onError field determines whether or not the indexed columns
8974 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
8975 ** it means this is not a unique index.  Otherwise it is a unique index
8976 ** and the value of Index.onError indicate the which conflict resolution 
8977 ** algorithm to employ whenever an attempt is made to insert a non-unique
8978 ** element.
8979 */
8980 struct Index {
8981   char *zName;     /* Name of this index */
8982   int nColumn;     /* Number of columns in the table used by this index */
8983   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
8984   unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
8985   Table *pTable;   /* The SQL table being indexed */
8986   int tnum;        /* Page containing root of this index in database file */
8987   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
8988   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
8989   char *zColAff;   /* String defining the affinity of each column */
8990   Index *pNext;    /* The next index associated with the same table */
8991   Schema *pSchema; /* Schema containing this index */
8992   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
8993   char **azColl;   /* Array of collation sequence names for index */
8994 };
8995
8996 /*
8997 ** Each token coming out of the lexer is an instance of
8998 ** this structure.  Tokens are also used as part of an expression.
8999 **
9000 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
9001 ** may contain random values.  Do not make any assuptions about Token.dyn
9002 ** and Token.n when Token.z==0.
9003 */
9004 struct Token {
9005   const unsigned char *z; /* Text of the token.  Not NULL-terminated! */
9006   unsigned dyn  : 1;      /* True for malloced memory, false for static */
9007   unsigned n    : 31;     /* Number of characters in this token */
9008 };
9009
9010 /*
9011 ** An instance of this structure contains information needed to generate
9012 ** code for a SELECT that contains aggregate functions.
9013 **
9014 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
9015 ** pointer to this structure.  The Expr.iColumn field is the index in
9016 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
9017 ** code for that node.
9018 **
9019 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
9020 ** original Select structure that describes the SELECT statement.  These
9021 ** fields do not need to be freed when deallocating the AggInfo structure.
9022 */
9023 struct AggInfo {
9024   u8 directMode;          /* Direct rendering mode means take data directly
9025                           ** from source tables rather than from accumulators */
9026   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
9027                           ** than the source table */
9028   int sortingIdx;         /* Cursor number of the sorting index */
9029   ExprList *pGroupBy;     /* The group by clause */
9030   int nSortingColumn;     /* Number of columns in the sorting index */
9031   struct AggInfo_col {    /* For each column used in source tables */
9032     Table *pTab;             /* Source table */
9033     int iTable;              /* Cursor number of the source table */
9034     int iColumn;             /* Column number within the source table */
9035     int iSorterColumn;       /* Column number in the sorting index */
9036     int iMem;                /* Memory location that acts as accumulator */
9037     Expr *pExpr;             /* The original expression */
9038   } *aCol;
9039   int nColumn;            /* Number of used entries in aCol[] */
9040   int nColumnAlloc;       /* Number of slots allocated for aCol[] */
9041   int nAccumulator;       /* Number of columns that show through to the output.
9042                           ** Additional columns are used only as parameters to
9043                           ** aggregate functions */
9044   struct AggInfo_func {   /* For each aggregate function */
9045     Expr *pExpr;             /* Expression encoding the function */
9046     FuncDef *pFunc;          /* The aggregate function implementation */
9047     int iMem;                /* Memory location that acts as accumulator */
9048     int iDistinct;           /* Ephermeral table used to enforce DISTINCT */
9049   } *aFunc;
9050   int nFunc;              /* Number of entries in aFunc[] */
9051   int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
9052 };
9053
9054 /*
9055 ** Each node of an expression in the parse tree is an instance
9056 ** of this structure.
9057 **
9058 ** Expr.op is the opcode.  The integer parser token codes are reused
9059 ** as opcodes here.  For example, the parser defines TK_GE to be an integer
9060 ** code representing the ">=" operator.  This same integer code is reused
9061 ** to represent the greater-than-or-equal-to operator in the expression
9062 ** tree.
9063 **
9064 ** Expr.pRight and Expr.pLeft are subexpressions.  Expr.pList is a list
9065 ** of argument if the expression is a function.
9066 **
9067 ** Expr.token is the operator token for this node.  For some expressions
9068 ** that have subexpressions, Expr.token can be the complete text that gave
9069 ** rise to the Expr.  In the latter case, the token is marked as being
9070 ** a compound token.
9071 **
9072 ** An expression of the form ID or ID.ID refers to a column in a table.
9073 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
9074 ** the integer cursor number of a VDBE cursor pointing to that table and
9075 ** Expr.iColumn is the column number for the specific column.  If the
9076 ** expression is used as a result in an aggregate SELECT, then the
9077 ** value is also stored in the Expr.iAgg column in the aggregate so that
9078 ** it can be accessed after all aggregates are computed.
9079 **
9080 ** If the expression is a function, the Expr.iTable is an integer code
9081 ** representing which function.  If the expression is an unbound variable
9082 ** marker (a question mark character '?' in the original SQL) then the
9083 ** Expr.iTable holds the index number for that variable.
9084 **
9085 ** If the expression is a subquery then Expr.iColumn holds an integer
9086 ** register number containing the result of the subquery.  If the
9087 ** subquery gives a constant result, then iTable is -1.  If the subquery
9088 ** gives a different answer at different times during statement processing
9089 ** then iTable is the address of a subroutine that computes the subquery.
9090 **
9091 ** The Expr.pSelect field points to a SELECT statement.  The SELECT might
9092 ** be the right operand of an IN operator.  Or, if a scalar SELECT appears
9093 ** in an expression the opcode is TK_SELECT and Expr.pSelect is the only
9094 ** operand.
9095 **
9096 ** If the Expr is of type OP_Column, and the table it is selecting from
9097 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
9098 ** corresponding table definition.
9099 */
9100 struct Expr {
9101   u8 op;                 /* Operation performed by this node */
9102   char affinity;         /* The affinity of the column or 0 if not a column */
9103   u16 flags;             /* Various flags.  See below */
9104   CollSeq *pColl;        /* The collation type of the column or 0 */
9105   Expr *pLeft, *pRight;  /* Left and right subnodes */
9106   ExprList *pList;       /* A list of expressions used as function arguments
9107                          ** or in "<expr> IN (<expr-list)" */
9108   Token token;           /* An operand token */
9109   Token span;            /* Complete text of the expression */
9110   int iTable, iColumn;   /* When op==TK_COLUMN, then this expr node means the
9111                          ** iColumn-th field of the iTable-th table. */
9112   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
9113   int iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
9114   int iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
9115   Select *pSelect;       /* When the expression is a sub-select.  Also the
9116                          ** right side of "<expr> IN (<select>)" */
9117   Table *pTab;           /* Table for OP_Column expressions. */
9118 #if SQLITE_MAX_EXPR_DEPTH>0
9119   int nHeight;           /* Height of the tree headed by this node */
9120 #endif
9121 };
9122
9123 /*
9124 ** The following are the meanings of bits in the Expr.flags field.
9125 */
9126 #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
9127 #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
9128 #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
9129 #define EP_Error      0x0008  /* Expression contains one or more errors */
9130 #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
9131 #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
9132 #define EP_Dequoted   0x0040  /* True if the string has been dequoted */
9133 #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
9134 #define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
9135 #define EP_AnyAff     0x0200  /* Can take a cached column of any affinity */
9136 #define EP_FixedDest  0x0400  /* Result needed in a specific register */
9137 #define EP_IntValue   0x0800  /* Integer value contained in iTable */
9138 /*
9139 ** These macros can be used to test, set, or clear bits in the 
9140 ** Expr.flags field.
9141 */
9142 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
9143 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
9144 #define ExprSetProperty(E,P)     (E)->flags|=(P)
9145 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
9146
9147 /*
9148 ** A list of expressions.  Each expression may optionally have a
9149 ** name.  An expr/name combination can be used in several ways, such
9150 ** as the list of "expr AS ID" fields following a "SELECT" or in the
9151 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
9152 ** also be used as the argument to a function, in which case the a.zName
9153 ** field is not used.
9154 */
9155 struct ExprList {
9156   int nExpr;             /* Number of expressions on the list */
9157   int nAlloc;            /* Number of entries allocated below */
9158   int iECursor;          /* VDBE Cursor associated with this ExprList */
9159   struct ExprList_item {
9160     Expr *pExpr;           /* The list of expressions */
9161     char *zName;           /* Token associated with this expression */
9162     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
9163     u8 isAgg;              /* True if this is an aggregate like count(*) */
9164     u8 done;               /* A flag to indicate when processing is finished */
9165   } *a;                  /* One entry for each expression */
9166 };
9167
9168 /*
9169 ** An instance of this structure can hold a simple list of identifiers,
9170 ** such as the list "a,b,c" in the following statements:
9171 **
9172 **      INSERT INTO t(a,b,c) VALUES ...;
9173 **      CREATE INDEX idx ON t(a,b,c);
9174 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
9175 **
9176 ** The IdList.a.idx field is used when the IdList represents the list of
9177 ** column names after a table name in an INSERT statement.  In the statement
9178 **
9179 **     INSERT INTO t(a,b,c) ...
9180 **
9181 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
9182 */
9183 struct IdList {
9184   struct IdList_item {
9185     char *zName;      /* Name of the identifier */
9186     int idx;          /* Index in some Table.aCol[] of a column named zName */
9187   } *a;
9188   int nId;         /* Number of identifiers on the list */
9189   int nAlloc;      /* Number of entries allocated for a[] below */
9190 };
9191
9192 /*
9193 ** The bitmask datatype defined below is used for various optimizations.
9194 **
9195 ** Changing this from a 64-bit to a 32-bit type limits the number of
9196 ** tables in a join to 32 instead of 64.  But it also reduces the size
9197 ** of the library by 738 bytes on ix86.
9198 */
9199 typedef u64 Bitmask;
9200
9201 /*
9202 ** The following structure describes the FROM clause of a SELECT statement.
9203 ** Each table or subquery in the FROM clause is a separate element of
9204 ** the SrcList.a[] array.
9205 **
9206 ** With the addition of multiple database support, the following structure
9207 ** can also be used to describe a particular table such as the table that
9208 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
9209 ** such a table must be a simple name: ID.  But in SQLite, the table can
9210 ** now be identified by a database name, a dot, then the table name: ID.ID.
9211 **
9212 ** The jointype starts out showing the join type between the current table
9213 ** and the next table on the list.  The parser builds the list this way.
9214 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
9215 ** jointype expresses the join between the table and the previous table.
9216 */
9217 struct SrcList {
9218   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
9219   i16 nAlloc;      /* Number of entries allocated in a[] below */
9220   struct SrcList_item {
9221     char *zDatabase;  /* Name of database holding this table */
9222     char *zName;      /* Name of the table */
9223     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
9224     Table *pTab;      /* An SQL table corresponding to zName */
9225     Select *pSelect;  /* A SELECT statement used in place of a table name */
9226     u8 isPopulated;   /* Temporary table associated with SELECT is populated */
9227     u8 jointype;      /* Type of join between this able and the previous */
9228     int iCursor;      /* The VDBE cursor number used to access this table */
9229     Expr *pOn;        /* The ON clause of a join */
9230     IdList *pUsing;   /* The USING clause of a join */
9231     Bitmask colUsed;  /* Bit N (1<<N) set if column N or pTab is used */
9232   } a[1];             /* One entry for each identifier on the list */
9233 };
9234
9235 /*
9236 ** Permitted values of the SrcList.a.jointype field
9237 */
9238 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
9239 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
9240 #define JT_NATURAL   0x0004    /* True for a "natural" join */
9241 #define JT_LEFT      0x0008    /* Left outer join */
9242 #define JT_RIGHT     0x0010    /* Right outer join */
9243 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
9244 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
9245
9246 /*
9247 ** For each nested loop in a WHERE clause implementation, the WhereInfo
9248 ** structure contains a single instance of this structure.  This structure
9249 ** is intended to be private the the where.c module and should not be
9250 ** access or modified by other modules.
9251 **
9252 ** The pIdxInfo and pBestIdx fields are used to help pick the best
9253 ** index on a virtual table.  The pIdxInfo pointer contains indexing
9254 ** information for the i-th table in the FROM clause before reordering.
9255 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
9256 ** The pBestIdx pointer is a copy of pIdxInfo for the i-th table after
9257 ** FROM clause ordering.  This is a little confusing so I will repeat
9258 ** it in different words.  WhereInfo.a[i].pIdxInfo is index information 
9259 ** for WhereInfo.pTabList.a[i].  WhereInfo.a[i].pBestInfo is the
9260 ** index information for the i-th loop of the join.  pBestInfo is always
9261 ** either NULL or a copy of some pIdxInfo.  So for cleanup it is 
9262 ** sufficient to free all of the pIdxInfo pointers.
9263 ** 
9264 */
9265 struct WhereLevel {
9266   int iFrom;            /* Which entry in the FROM clause */
9267   int flags;            /* Flags associated with this level */
9268   int iMem;             /* First memory cell used by this level */
9269   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
9270   Index *pIdx;          /* Index used.  NULL if no index */
9271   int iTabCur;          /* The VDBE cursor used to access the table */
9272   int iIdxCur;          /* The VDBE cursor used to acesss pIdx */
9273   int brk;              /* Jump here to break out of the loop */
9274   int nxt;              /* Jump here to start the next IN combination */
9275   int cont;             /* Jump here to continue with the next loop cycle */
9276   int top;              /* First instruction of interior of the loop */
9277   int op, p1, p2;       /* Opcode used to terminate the loop */
9278   int nEq;              /* Number of == or IN constraints on this loop */
9279   int nIn;              /* Number of IN operators constraining this loop */
9280   struct InLoop {
9281     int iCur;              /* The VDBE cursor used by this IN operator */
9282     int topAddr;           /* Top of the IN loop */
9283   } *aInLoop;           /* Information about each nested IN operator */
9284   sqlite3_index_info *pBestIdx;  /* Index information for this level */
9285
9286   /* The following field is really not part of the current level.  But
9287   ** we need a place to cache index information for each table in the
9288   ** FROM clause and the WhereLevel structure is a convenient place.
9289   */
9290   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
9291 };
9292
9293 /*
9294 ** Flags appropriate for the wflags parameter of sqlite3WhereBegin().
9295 */
9296 #define WHERE_ORDERBY_NORMAL     0   /* No-op */
9297 #define WHERE_ORDERBY_MIN        1   /* ORDER BY processing for min() func */
9298 #define WHERE_ORDERBY_MAX        2   /* ORDER BY processing for max() func */
9299 #define WHERE_ONEPASS_DESIRED    4   /* Want to do one-pass UPDATE/DELETE */
9300
9301 /*
9302 ** The WHERE clause processing routine has two halves.  The
9303 ** first part does the start of the WHERE loop and the second
9304 ** half does the tail of the WHERE loop.  An instance of
9305 ** this structure is returned by the first half and passed
9306 ** into the second half to give some continuity.
9307 */
9308 struct WhereInfo {
9309   Parse *pParse;       /* Parsing and code generating context */
9310   u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
9311   SrcList *pTabList;   /* List of tables in the join */
9312   int iTop;            /* The very beginning of the WHERE loop */
9313   int iContinue;       /* Jump here to continue with next record */
9314   int iBreak;          /* Jump here to break out of the loop */
9315   int nLevel;          /* Number of nested loop */
9316   sqlite3_index_info **apInfo;  /* Array of pointers to index info structures */
9317   WhereLevel a[1];     /* Information about each nest loop in the WHERE */
9318 };
9319
9320 /*
9321 ** A NameContext defines a context in which to resolve table and column
9322 ** names.  The context consists of a list of tables (the pSrcList) field and
9323 ** a list of named expression (pEList).  The named expression list may
9324 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
9325 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
9326 ** pEList corresponds to the result set of a SELECT and is NULL for
9327 ** other statements.
9328 **
9329 ** NameContexts can be nested.  When resolving names, the inner-most 
9330 ** context is searched first.  If no match is found, the next outer
9331 ** context is checked.  If there is still no match, the next context
9332 ** is checked.  This process continues until either a match is found
9333 ** or all contexts are check.  When a match is found, the nRef member of
9334 ** the context containing the match is incremented. 
9335 **
9336 ** Each subquery gets a new NameContext.  The pNext field points to the
9337 ** NameContext in the parent query.  Thus the process of scanning the
9338 ** NameContext list corresponds to searching through successively outer
9339 ** subqueries looking for a match.
9340 */
9341 struct NameContext {
9342   Parse *pParse;       /* The parser */
9343   SrcList *pSrcList;   /* One or more tables used to resolve names */
9344   ExprList *pEList;    /* Optional list of named expressions */
9345   int nRef;            /* Number of names resolved by this context */
9346   int nErr;            /* Number of errors encountered while resolving names */
9347   u8 allowAgg;         /* Aggregate functions allowed here */
9348   u8 hasAgg;           /* True if aggregates are seen */
9349   u8 isCheck;          /* True if resolving names in a CHECK constraint */
9350   int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
9351   AggInfo *pAggInfo;   /* Information about aggregates at this level */
9352   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
9353 };
9354
9355 /*
9356 ** An instance of the following structure contains all information
9357 ** needed to generate code for a single SELECT statement.
9358 **
9359 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
9360 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
9361 ** limit and nOffset to the value of the offset (or 0 if there is not
9362 ** offset).  But later on, nLimit and nOffset become the memory locations
9363 ** in the VDBE that record the limit and offset counters.
9364 **
9365 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
9366 ** These addresses must be stored so that we can go back and fill in
9367 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
9368 ** the number of columns in P2 can be computed at the same time
9369 ** as the OP_OpenEphm instruction is coded because not
9370 ** enough information about the compound query is known at that point.
9371 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
9372 ** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
9373 ** sequences for the ORDER BY clause.
9374 */
9375 struct Select {
9376   ExprList *pEList;      /* The fields of the result */
9377   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
9378   u8 isDistinct;         /* True if the DISTINCT keyword is present */
9379   u8 isResolved;         /* True once sqlite3SelectResolve() has run. */
9380   u8 isAgg;              /* True if this is an aggregate query */
9381   u8 usesEphm;           /* True if uses an OpenEphemeral opcode */
9382   u8 disallowOrderBy;    /* Do not allow an ORDER BY to be attached if TRUE */
9383   char affinity;         /* MakeRecord with this affinity for SRT_Set */
9384   SrcList *pSrc;         /* The FROM clause */
9385   Expr *pWhere;          /* The WHERE clause */
9386   ExprList *pGroupBy;    /* The GROUP BY clause */
9387   Expr *pHaving;         /* The HAVING clause */
9388   ExprList *pOrderBy;    /* The ORDER BY clause */
9389   Select *pPrior;        /* Prior select in a compound select statement */
9390   Select *pNext;         /* Next select to the left in a compound */
9391   Select *pRightmost;    /* Right-most select in a compound select statement */
9392   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
9393   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
9394   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
9395   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
9396 };
9397
9398 /*
9399 ** The results of a select can be distributed in several ways.
9400 */
9401 #define SRT_Union        1  /* Store result as keys in an index */
9402 #define SRT_Except       2  /* Remove result from a UNION index */
9403 #define SRT_Exists       3  /* Store 1 if the result is not empty */
9404 #define SRT_Discard      4  /* Do not save the results anywhere */
9405
9406 /* The ORDER BY clause is ignored for all of the above */
9407 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
9408
9409 #define SRT_Callback     5  /* Invoke a callback with each row of result */
9410 #define SRT_Mem          6  /* Store result in a memory cell */
9411 #define SRT_Set          7  /* Store results as keys in an index */
9412 #define SRT_Table        8  /* Store result as data with an automatic rowid */
9413 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
9414 #define SRT_Coroutine   10  /* Generate a single row of result */
9415
9416 /*
9417 ** A structure used to customize the behaviour of sqlite3Select(). See
9418 ** comments above sqlite3Select() for details.
9419 */
9420 typedef struct SelectDest SelectDest;
9421 struct SelectDest {
9422   u8 eDest;         /* How to dispose of the results */
9423   u8 affinity;      /* Affinity used when eDest==SRT_Set */
9424   int iParm;        /* A parameter used by the eDest disposal method */
9425   int iMem;         /* Base register where results are written */
9426   int nMem;         /* Number of registers allocated */
9427 };
9428
9429 /*
9430 ** An SQL parser context.  A copy of this structure is passed through
9431 ** the parser and down into all the parser action routine in order to
9432 ** carry around information that is global to the entire parse.
9433 **
9434 ** The structure is divided into two parts.  When the parser and code
9435 ** generate call themselves recursively, the first part of the structure
9436 ** is constant but the second part is reset at the beginning and end of
9437 ** each recursion.
9438 **
9439 ** The nTableLock and aTableLock variables are only used if the shared-cache 
9440 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
9441 ** used to store the set of table-locks required by the statement being
9442 ** compiled. Function sqlite3TableLock() is used to add entries to the
9443 ** list.
9444 */
9445 struct Parse {
9446   sqlite3 *db;         /* The main database structure */
9447   int rc;              /* Return code from execution */
9448   char *zErrMsg;       /* An error message */
9449   Vdbe *pVdbe;         /* An engine for executing database bytecode */
9450   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
9451   u8 nameClash;        /* A permanent table name clashes with temp table name */
9452   u8 checkSchema;      /* Causes schema cookie check after an error */
9453   u8 nested;           /* Number of nested calls to the parser/code generator */
9454   u8 parseError;       /* True after a parsing error.  Ticket #1794 */
9455   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
9456   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
9457   int aTempReg[8];     /* Holding area for temporary registers */
9458   int nRangeReg;       /* Size of the temporary register block */
9459   int iRangeReg;       /* First register in temporary register block */
9460   int nErr;            /* Number of errors seen */
9461   int nTab;            /* Number of previously allocated VDBE cursors */
9462   int nMem;            /* Number of memory cells used so far */
9463   int nSet;            /* Number of sets used so far */
9464   int ckBase;          /* Base register of data during check constraints */
9465   int disableColCache; /* True to disable adding to column cache */
9466   int nColCache;       /* Number of entries in the column cache */
9467   int iColCache;       /* Next entry of the cache to replace */
9468   struct yColCache {
9469     int iTable;           /* Table cursor number */
9470     int iColumn;          /* Table column number */
9471     char affChange;       /* True if this register has had an affinity change */
9472     int iReg;             /* Register holding value of this column */
9473   } aColCache[10];     /* One for each valid column cache entry */
9474   u32 writeMask;       /* Start a write transaction on these databases */
9475   u32 cookieMask;      /* Bitmask of schema verified databases */
9476   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
9477   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
9478 #ifndef SQLITE_OMIT_SHARED_CACHE
9479   int nTableLock;        /* Number of locks in aTableLock */
9480   TableLock *aTableLock; /* Required table locks for shared-cache mode */
9481 #endif
9482   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
9483   int regRoot;         /* Register holding root page number for new objects */
9484
9485   /* Above is constant between recursions.  Below is reset before and after
9486   ** each recursion */
9487
9488   int nVar;            /* Number of '?' variables seen in the SQL so far */
9489   int nVarExpr;        /* Number of used slots in apVarExpr[] */
9490   int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
9491   Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
9492   u8 explain;          /* True if the EXPLAIN flag is found on the query */
9493   Token sErrToken;     /* The token at which the error occurred */
9494   Token sNameToken;    /* Token with unqualified schema object name */
9495   Token sLastToken;    /* The last token parsed */
9496   const char *zSql;    /* All SQL text */
9497   const char *zTail;   /* All SQL text past the last semicolon parsed */
9498   Table *pNewTable;    /* A table being constructed by CREATE TABLE */
9499   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
9500   TriggerStack *trigStack;  /* Trigger actions being coded */
9501   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
9502 #ifndef SQLITE_OMIT_VIRTUALTABLE
9503   Token sArg;                /* Complete text of a module argument */
9504   u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
9505   int nVtabLock;             /* Number of virtual tables to lock */
9506   Table **apVtabLock;        /* Pointer to virtual tables needing locking */
9507 #endif
9508   int nHeight;            /* Expression tree height of current sub-select */
9509 };
9510
9511 #ifdef SQLITE_OMIT_VIRTUALTABLE
9512   #define IN_DECLARE_VTAB 0
9513 #else
9514   #define IN_DECLARE_VTAB (pParse->declareVtab)
9515 #endif
9516
9517 /*
9518 ** An instance of the following structure can be declared on a stack and used
9519 ** to save the Parse.zAuthContext value so that it can be restored later.
9520 */
9521 struct AuthContext {
9522   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
9523   Parse *pParse;              /* The Parse structure */
9524 };
9525
9526 /*
9527 ** Bitfield flags for P2 value in OP_Insert and OP_Delete
9528 */
9529 #define OPFLAG_NCHANGE   1    /* Set to update db->nChange */
9530 #define OPFLAG_LASTROWID 2    /* Set to update db->lastRowid */
9531 #define OPFLAG_ISUPDATE  4    /* This OP_Insert is an sql UPDATE */
9532 #define OPFLAG_APPEND    8    /* This is likely to be an append */
9533
9534 /*
9535  * Each trigger present in the database schema is stored as an instance of
9536  * struct Trigger. 
9537  *
9538  * Pointers to instances of struct Trigger are stored in two ways.
9539  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the 
9540  *    database). This allows Trigger structures to be retrieved by name.
9541  * 2. All triggers associated with a single table form a linked list, using the
9542  *    pNext member of struct Trigger. A pointer to the first element of the
9543  *    linked list is stored as the "pTrigger" member of the associated
9544  *    struct Table.
9545  *
9546  * The "step_list" member points to the first element of a linked list
9547  * containing the SQL statements specified as the trigger program.
9548  */
9549 struct Trigger {
9550   char *name;             /* The name of the trigger                        */
9551   char *table;            /* The table or view to which the trigger applies */
9552   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
9553   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
9554   Expr *pWhen;            /* The WHEN clause of the expresion (may be NULL) */
9555   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
9556                              the <column-list> is stored here */
9557   Token nameToken;        /* Token containing zName. Use during parsing only */
9558   Schema *pSchema;        /* Schema containing the trigger */
9559   Schema *pTabSchema;     /* Schema containing the table */
9560   TriggerStep *step_list; /* Link list of trigger program steps             */
9561   Trigger *pNext;         /* Next trigger associated with the table */
9562 };
9563
9564 /*
9565 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
9566 ** determine which. 
9567 **
9568 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
9569 ** In that cases, the constants below can be ORed together.
9570 */
9571 #define TRIGGER_BEFORE  1
9572 #define TRIGGER_AFTER   2
9573
9574 /*
9575  * An instance of struct TriggerStep is used to store a single SQL statement
9576  * that is a part of a trigger-program. 
9577  *
9578  * Instances of struct TriggerStep are stored in a singly linked list (linked
9579  * using the "pNext" member) referenced by the "step_list" member of the 
9580  * associated struct Trigger instance. The first element of the linked list is
9581  * the first step of the trigger-program.
9582  * 
9583  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
9584  * "SELECT" statement. The meanings of the other members is determined by the 
9585  * value of "op" as follows:
9586  *
9587  * (op == TK_INSERT)
9588  * orconf    -> stores the ON CONFLICT algorithm
9589  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
9590  *              this stores a pointer to the SELECT statement. Otherwise NULL.
9591  * target    -> A token holding the name of the table to insert into.
9592  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
9593  *              this stores values to be inserted. Otherwise NULL.
9594  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
9595  *              statement, then this stores the column-names to be
9596  *              inserted into.
9597  *
9598  * (op == TK_DELETE)
9599  * target    -> A token holding the name of the table to delete from.
9600  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
9601  *              Otherwise NULL.
9602  * 
9603  * (op == TK_UPDATE)
9604  * target    -> A token holding the name of the table to update rows of.
9605  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
9606  *              Otherwise NULL.
9607  * pExprList -> A list of the columns to update and the expressions to update
9608  *              them to. See sqlite3Update() documentation of "pChanges"
9609  *              argument.
9610  * 
9611  */
9612 struct TriggerStep {
9613   int op;              /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
9614   int orconf;          /* OE_Rollback etc. */
9615   Trigger *pTrig;      /* The trigger that this step is a part of */
9616
9617   Select *pSelect;     /* Valid for SELECT and sometimes 
9618                           INSERT steps (when pExprList == 0) */
9619   Token target;        /* Valid for DELETE, UPDATE, INSERT steps */
9620   Expr *pWhere;        /* Valid for DELETE, UPDATE steps */
9621   ExprList *pExprList; /* Valid for UPDATE statements and sometimes 
9622                            INSERT steps (when pSelect == 0)         */
9623   IdList *pIdList;     /* Valid for INSERT statements only */
9624   TriggerStep *pNext;  /* Next in the link-list */
9625   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
9626 };
9627
9628 /*
9629  * An instance of struct TriggerStack stores information required during code
9630  * generation of a single trigger program. While the trigger program is being
9631  * coded, its associated TriggerStack instance is pointed to by the
9632  * "pTriggerStack" member of the Parse structure.
9633  *
9634  * The pTab member points to the table that triggers are being coded on. The 
9635  * newIdx member contains the index of the vdbe cursor that points at the temp
9636  * table that stores the new.* references. If new.* references are not valid
9637  * for the trigger being coded (for example an ON DELETE trigger), then newIdx
9638  * is set to -1. The oldIdx member is analogous to newIdx, for old.* references.
9639  *
9640  * The ON CONFLICT policy to be used for the trigger program steps is stored 
9641  * as the orconf member. If this is OE_Default, then the ON CONFLICT clause 
9642  * specified for individual triggers steps is used.
9643  *
9644  * struct TriggerStack has a "pNext" member, to allow linked lists to be
9645  * constructed. When coding nested triggers (triggers fired by other triggers)
9646  * each nested trigger stores its parent trigger's TriggerStack as the "pNext" 
9647  * pointer. Once the nested trigger has been coded, the pNext value is restored
9648  * to the pTriggerStack member of the Parse stucture and coding of the parent
9649  * trigger continues.
9650  *
9651  * Before a nested trigger is coded, the linked list pointed to by the 
9652  * pTriggerStack is scanned to ensure that the trigger is not about to be coded
9653  * recursively. If this condition is detected, the nested trigger is not coded.
9654  */
9655 struct TriggerStack {
9656   Table *pTab;         /* Table that triggers are currently being coded on */
9657   int newIdx;          /* Index of vdbe cursor to "new" temp table */
9658   int oldIdx;          /* Index of vdbe cursor to "old" temp table */
9659   u32 newColMask;
9660   u32 oldColMask;
9661   int orconf;          /* Current orconf policy */
9662   int ignoreJump;      /* where to jump to for a RAISE(IGNORE) */
9663   Trigger *pTrigger;   /* The trigger currently being coded */
9664   TriggerStack *pNext; /* Next trigger down on the trigger stack */
9665 };
9666
9667 /*
9668 ** The following structure contains information used by the sqliteFix...
9669 ** routines as they walk the parse tree to make database references
9670 ** explicit.  
9671 */
9672 typedef struct DbFixer DbFixer;
9673 struct DbFixer {
9674   Parse *pParse;      /* The parsing context.  Error messages written here */
9675   const char *zDb;    /* Make sure all objects are contained in this database */
9676   const char *zType;  /* Type of the container - used for error messages */
9677   const Token *pName; /* Name of the container - used for error messages */
9678 };
9679
9680 /*
9681 ** An objected used to accumulate the text of a string where we
9682 ** do not necessarily know how big the string will be in the end.
9683 */
9684 struct StrAccum {
9685   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
9686   char *zBase;         /* A base allocation.  Not from malloc. */
9687   char *zText;         /* The string collected so far */
9688   int  nChar;          /* Length of the string so far */
9689   int  nAlloc;         /* Amount of space allocated in zText */
9690   int  mxAlloc;        /* Maximum allowed string length */
9691   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
9692   u8   useMalloc;      /* True if zText is enlargable using realloc */
9693   u8   tooBig;         /* Becomes true if string size exceeds limits */
9694 };
9695
9696 /*
9697 ** A pointer to this structure is used to communicate information
9698 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
9699 */
9700 typedef struct {
9701   sqlite3 *db;        /* The database being initialized */
9702   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
9703   char **pzErrMsg;    /* Error message stored here */
9704   int rc;             /* Result code stored here */
9705 } InitData;
9706
9707 /*
9708 ** Structure containing global configuration data for the SQLite library.
9709 **
9710 ** This structure also contains some state information.
9711 */
9712 struct Sqlite3Config {
9713   int bMemstat;                     /* True to enable memory status */
9714   int bCoreMutex;                   /* True to enable core mutexing */
9715   int bFullMutex;                   /* True to enable full mutexing */
9716   int mxStrlen;                     /* Maximum string length */
9717   int szLookaside;                  /* Default lookaside buffer size */
9718   int nLookaside;                   /* Default lookaside buffer count */
9719   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
9720   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
9721   void *pHeap;                      /* Heap storage space */
9722   int nHeap;                        /* Size of pHeap[] */
9723   int mnReq, mxReq;                 /* Min and max heap requests sizes */
9724   void *pScratch;                   /* Scratch memory */
9725   int szScratch;                    /* Size of each scratch buffer */
9726   int nScratch;                     /* Number of scratch buffers */
9727   void *pPage;                      /* Page cache memory */
9728   int szPage;                       /* Size of each page in pPage[] */
9729   int nPage;                        /* Number of pages in pPage[] */
9730   int isInit;                       /* True after initialization has finished */
9731   int isMallocInit;                 /* True after malloc is initialized */
9732   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
9733   int nSmall;                       /* alloc size threshold used by mem6.c */
9734   int mxParserStack;                /* maximum depth of the parser stack */
9735 };
9736
9737 /*
9738 ** Assuming zIn points to the first byte of a UTF-8 character,
9739 ** advance zIn to point to the first byte of the next UTF-8 character.
9740 */
9741 #define SQLITE_SKIP_UTF8(zIn) {                        \
9742   if( (*(zIn++))>=0xc0 ){                              \
9743     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
9744   }                                                    \
9745 }
9746
9747 /*
9748 ** The SQLITE_CORRUPT_BKPT macro can be either a constant (for production
9749 ** builds) or a function call (for debugging).  If it is a function call,
9750 ** it allows the operator to set a breakpoint at the spot where database
9751 ** corruption is first detected.
9752 */
9753 #ifdef SQLITE_DEBUG
9754 SQLITE_PRIVATE   int sqlite3Corrupt(void);
9755 # define SQLITE_CORRUPT_BKPT sqlite3Corrupt()
9756 #else
9757 # define SQLITE_CORRUPT_BKPT SQLITE_CORRUPT
9758 #endif
9759
9760 /*
9761 ** Internal function prototypes
9762 */
9763 SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
9764 SQLITE_PRIVATE int sqlite3StrNICmp(const char *, const char *, int);
9765 SQLITE_PRIVATE int sqlite3IsNumber(const char*, int*, u8);
9766 SQLITE_PRIVATE int sqlite3Strlen(sqlite3*, const char*);
9767
9768 SQLITE_PRIVATE int sqlite3MallocInit(void);
9769 SQLITE_PRIVATE void sqlite3MallocEnd(void);
9770 SQLITE_PRIVATE void *sqlite3Malloc(int);
9771 SQLITE_PRIVATE void *sqlite3MallocZero(int);
9772 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
9773 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
9774 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
9775 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
9776 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
9777 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
9778 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
9779 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
9780 SQLITE_PRIVATE int sqlite3MallocSize(void*);
9781 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
9782 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
9783 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
9784 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
9785 SQLITE_PRIVATE void sqlite3PageFree(void*);
9786 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
9787 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetDefault(void);
9788 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
9789 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
9790 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys6(void);
9791 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
9792
9793 #ifndef SQLITE_MUTEX_NOOP
9794 SQLITE_PRIVATE   sqlite3_mutex_methods *sqlite3DefaultMutex(void);
9795 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
9796 SQLITE_PRIVATE   int sqlite3MutexInit(void);
9797 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
9798 #endif
9799
9800 SQLITE_PRIVATE void sqlite3StatusReset(void);
9801 SQLITE_PRIVATE int sqlite3StatusValue(int);
9802 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
9803 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
9804
9805 SQLITE_PRIVATE int sqlite3IsNaN(double);
9806
9807 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
9808 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
9809 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
9810 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
9811 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
9812 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
9813 #endif
9814 #if defined(SQLITE_TEST)
9815 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
9816 #endif
9817 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
9818 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
9819 SQLITE_PRIVATE void sqlite3ErrorClear(Parse*);
9820 SQLITE_PRIVATE void sqlite3Dequote(char*);
9821 SQLITE_PRIVATE void sqlite3DequoteExpr(sqlite3*, Expr*);
9822 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
9823 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
9824 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
9825 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
9826 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
9827 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
9828 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
9829 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*, int, Expr*, Expr*, const Token*);
9830 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
9831 SQLITE_PRIVATE Expr *sqlite3RegisterExpr(Parse*,Token*);
9832 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
9833 SQLITE_PRIVATE void sqlite3ExprSpan(Expr*,Token*,Token*);
9834 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
9835 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
9836 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
9837 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*,Token*);
9838 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
9839 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
9840 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
9841 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
9842 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
9843 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
9844 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
9845 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,char*,Select*);
9846 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
9847 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
9848 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
9849 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
9850 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
9851 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
9852 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
9853 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,Expr*);
9854 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
9855 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
9856
9857 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
9858 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
9859 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
9860 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32);
9861 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
9862 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
9863
9864 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
9865
9866 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
9867 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
9868 #else
9869 # define sqlite3ViewGetColumnNames(A,B) 0
9870 #endif
9871
9872 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
9873 SQLITE_PRIVATE void sqlite3DeleteTable(Table*);
9874 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
9875 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
9876 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
9877 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
9878 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
9879 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*, Token*,
9880                                       Select*, Expr*, IdList*);
9881 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
9882 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
9883 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
9884 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
9885 SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
9886                         Token*, int, int);
9887 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
9888 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*, Select*, int, int*);
9889 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
9890                          Expr*,ExprList*,int,Expr*,Expr*);
9891 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
9892 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
9893 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
9894 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
9895 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
9896 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
9897 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u8);
9898 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
9899 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, int);
9900 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
9901 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
9902 SQLITE_PRIVATE void sqlite3ExprClearColumnCache(Parse*, int);
9903 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
9904 SQLITE_PRIVATE int sqlite3ExprWritableRegister(Parse*,int,int);
9905 SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse*,int,int);
9906 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
9907 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
9908 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
9909 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
9910 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
9911 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
9912 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
9913 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
9914 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
9915 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
9916 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
9917 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
9918 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
9919 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
9920 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
9921 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
9922 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
9923 SQLITE_PRIVATE int sqlite3ExprResolveNames(NameContext *, Expr *);
9924 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
9925 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
9926 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
9927 SQLITE_PRIVATE Expr *sqlite3CreateIdExpr(Parse *, const char*);
9928 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
9929 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
9930 SQLITE_PRIVATE void sqlite3PrngResetState(void);
9931 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
9932 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
9933 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
9934 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
9935 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
9936 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
9937 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
9938 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
9939 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
9940 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
9941 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int);
9942 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
9943 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
9944 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
9945                                      int*,int,int,int,int);
9946 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*,int,int,int,int);
9947 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
9948 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
9949 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*);
9950 SQLITE_PRIVATE void sqlite3TokenCopy(sqlite3*,Token*, Token*);
9951 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*);
9952 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*);
9953 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
9954 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*);
9955 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
9956 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
9957 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(sqlite3*);
9958 #ifdef SQLITE_DEBUG
9959 SQLITE_PRIVATE   int sqlite3SafetyOn(sqlite3*);
9960 SQLITE_PRIVATE   int sqlite3SafetyOff(sqlite3*);
9961 #else
9962 # define sqlite3SafetyOn(A) 0
9963 # define sqlite3SafetyOff(A) 0
9964 #endif
9965 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
9966 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
9967 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
9968 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Select*, Expr*, int);
9969
9970 #ifndef SQLITE_OMIT_TRIGGER
9971 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
9972                            Expr*,int, int);
9973 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
9974 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
9975 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
9976 SQLITE_PRIVATE   int sqlite3TriggersExist(Parse*, Table*, int, ExprList*);
9977 SQLITE_PRIVATE   int sqlite3CodeRowTrigger(Parse*, int, ExprList*, int, Table *, int, int, 
9978                            int, int, u32*, u32*);
9979   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
9980 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
9981 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
9982 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
9983                                         ExprList*,Select*,int);
9984 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, int);
9985 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
9986 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
9987 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
9988 #else
9989 # define sqlite3TriggersExist(A,B,C,D,E,F) 0
9990 # define sqlite3DeleteTrigger(A,B)
9991 # define sqlite3DropTriggerPtr(A,B)
9992 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
9993 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I,J,K) 0
9994 #endif
9995
9996 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
9997 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
9998 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
9999 #ifndef SQLITE_OMIT_AUTHORIZATION
10000 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
10001 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
10002 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
10003 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
10004 #else
10005 # define sqlite3AuthRead(a,b,c,d)
10006 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
10007 # define sqlite3AuthContextPush(a,b,c)
10008 # define sqlite3AuthContextPop(a)  ((void)(a))
10009 #endif
10010 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
10011 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
10012 SQLITE_PRIVATE int sqlite3BtreeFactory(const sqlite3 *db, const char *zFilename,
10013                        int omitJournal, int nCache, int flags, Btree **ppBtree);
10014 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
10015 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
10016 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
10017 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
10018 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
10019 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
10020 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*);
10021 SQLITE_API char *sqlite3_snprintf(int,char*,const char*,...);
10022 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
10023 SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *, int);
10024 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
10025 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
10026 SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8*, const u8**);
10027
10028 /*
10029 ** Routines to read and write variable-length integers.  These used to
10030 ** be defined locally, but now we use the varint routines in the util.c
10031 ** file.  Code should use the MACRO forms below, as the Varint32 versions
10032 ** are coded to assume the single byte case is already handled (which 
10033 ** the MACRO form does).
10034 */
10035 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
10036 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
10037 SQLITE_PRIVATE int sqlite3GetVarint(const unsigned char *, u64 *);
10038 SQLITE_PRIVATE int sqlite3GetVarint32(const unsigned char *, u32 *);
10039 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
10040
10041 /*
10042 ** The header of a record consists of a sequence variable-length integers.
10043 ** These integers are almost always small and are encoded as a single byte.
10044 ** The following macros take advantage this fact to provide a fast encode
10045 ** and decode of the integers in a record header.  It is faster for the common
10046 ** case where the integer is a single byte.  It is a little slower when the
10047 ** integer is two or more bytes.  But overall it is faster.
10048 **
10049 ** The following expressions are equivalent:
10050 **
10051 **     x = sqlite3GetVarint32( A, &B );
10052 **     x = sqlite3PutVarint32( A, B );
10053 **
10054 **     x = getVarint32( A, B );
10055 **     x = putVarint32( A, B );
10056 **
10057 */
10058 #define getVarint32(A,B)  ((*(A)<(unsigned char)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), &(B)))
10059 #define putVarint32(A,B)  (((B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
10060 #define getVarint    sqlite3GetVarint
10061 #define putVarint    sqlite3PutVarint
10062
10063
10064 SQLITE_PRIVATE void sqlite3IndexAffinityStr(Vdbe *, Index *);
10065 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
10066 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
10067 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
10068 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
10069 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*);
10070 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
10071 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
10072 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
10073 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
10074 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
10075 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char *,int,int);
10076 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName);
10077 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
10078 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *, Token *);
10079 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
10080 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
10081 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
10082
10083 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
10084 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
10085 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, 
10086                         void(*)(void*));
10087 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
10088 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
10089 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int);
10090 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
10091 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
10092 #ifndef SQLITE_AMALGAMATION
10093 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
10094 SQLITE_PRIVATE struct Sqlite3Config sqlite3Config;
10095 #endif
10096 SQLITE_PRIVATE void sqlite3RootPageMoved(Db*, int, int);
10097 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
10098 SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3*);
10099 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
10100 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
10101 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
10102 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
10103 SQLITE_PRIVATE void sqlite3CodeSubselect(Parse *, Expr *, int);
10104 SQLITE_PRIVATE int sqlite3SelectResolve(Parse *, Select *, NameContext *);
10105 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int);
10106 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
10107 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
10108 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, CollSeq *, const char *, int);
10109 SQLITE_PRIVATE char sqlite3AffinityType(const Token*);
10110 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
10111 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
10112 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
10113 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
10114 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
10115 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
10116 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
10117 SQLITE_PRIVATE void sqlite3AttachFunctions(sqlite3 *);
10118 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
10119 SQLITE_PRIVATE void sqlite3SchemaFree(void *);
10120 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
10121 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
10122 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
10123 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
10124   void (*)(sqlite3_context*,int,sqlite3_value **),
10125   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
10126 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
10127 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
10128
10129 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
10130 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
10131 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
10132 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
10133 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
10134
10135 /*
10136 ** The interface to the LEMON-generated parser
10137 */
10138 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
10139 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
10140 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
10141 #ifdef YYTRACKMAXSTACKDEPTH
10142 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
10143 #endif
10144
10145 SQLITE_PRIVATE int sqlite3AutoLoadExtensions(sqlite3*);
10146 #ifndef SQLITE_OMIT_LOAD_EXTENSION
10147 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
10148 #else
10149 # define sqlite3CloseExtensions(X)
10150 #endif
10151
10152 #ifndef SQLITE_OMIT_SHARED_CACHE
10153 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
10154 #else
10155   #define sqlite3TableLock(v,w,x,y,z)
10156 #endif
10157
10158 #ifdef SQLITE_TEST
10159 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
10160 #endif
10161
10162 #ifdef SQLITE_OMIT_VIRTUALTABLE
10163 #  define sqlite3VtabClear(X)
10164 #  define sqlite3VtabSync(X,Y) SQLITE_OK
10165 #  define sqlite3VtabRollback(X)
10166 #  define sqlite3VtabCommit(X)
10167 #else
10168 SQLITE_PRIVATE    void sqlite3VtabClear(Table*);
10169 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
10170 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
10171 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
10172 #endif
10173 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
10174 SQLITE_PRIVATE void sqlite3VtabLock(sqlite3_vtab*);
10175 SQLITE_PRIVATE void sqlite3VtabUnlock(sqlite3*, sqlite3_vtab*);
10176 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
10177 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
10178 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
10179 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
10180 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
10181 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
10182 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
10183 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, sqlite3_vtab *);
10184 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
10185 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
10186 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
10187 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
10188 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
10189
10190
10191 /*
10192 ** Available fault injectors.  Should be numbered beginning with 0.
10193 */
10194 #define SQLITE_FAULTINJECTOR_MALLOC     0
10195 #define SQLITE_FAULTINJECTOR_COUNT      1
10196
10197 /*
10198 ** The interface to the code in fault.c used for identifying "benign"
10199 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
10200 ** is not defined.
10201 */
10202 #ifndef SQLITE_OMIT_BUILTIN_TEST
10203 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
10204 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
10205 #else
10206   #define sqlite3BeginBenignMalloc()
10207   #define sqlite3EndBenignMalloc()
10208 #endif
10209
10210 #define IN_INDEX_ROWID           1
10211 #define IN_INDEX_EPH             2
10212 #define IN_INDEX_INDEX           3
10213 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
10214
10215 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
10216 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
10217 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
10218 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
10219 #else
10220   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
10221 #endif
10222
10223 #if SQLITE_MAX_EXPR_DEPTH>0
10224 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
10225 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
10226 #else
10227   #define sqlite3ExprSetHeight(x,y)
10228   #define sqlite3SelectExprHeight(x) 0
10229 #endif
10230
10231 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
10232 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
10233
10234 #ifdef SQLITE_SSE
10235 #include "sseInt.h"
10236 #endif
10237
10238 #ifdef SQLITE_DEBUG
10239 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
10240 #endif
10241
10242 /*
10243 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
10244 ** sqlite3IoTrace is a pointer to a printf-like routine used to
10245 ** print I/O tracing messages. 
10246 */
10247 #ifdef SQLITE_ENABLE_IOTRACE
10248 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
10249 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
10250 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
10251 #else
10252 # define IOTRACE(A)
10253 # define sqlite3VdbeIOTraceSql(X)
10254 #endif
10255
10256 #endif
10257
10258 /************** End of sqliteInt.h *******************************************/
10259 /************** Begin file global.c ******************************************/
10260 /*
10261 ** 2008 June 13
10262 **
10263 ** The author disclaims copyright to this source code.  In place of
10264 ** a legal notice, here is a blessing:
10265 **
10266 **    May you do good and not evil.
10267 **    May you find forgiveness for yourself and forgive others.
10268 **    May you share freely, never taking more than you give.
10269 **
10270 *************************************************************************
10271 **
10272 ** This file contains definitions of global variables and contants.
10273 **
10274 ** $Id: global.c,v 1.4 2008/07/28 19:34:53 drh Exp $
10275 */
10276
10277
10278 /* An array to map all upper-case characters into their corresponding
10279 ** lower-case character. 
10280 **
10281 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
10282 ** handle case conversions for the UTF character set since the tables
10283 ** involved are nearly as big or bigger than SQLite itself.
10284 */
10285 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
10286 #ifdef SQLITE_ASCII
10287       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
10288      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
10289      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
10290      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
10291     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
10292     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
10293     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
10294     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
10295     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
10296     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
10297     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
10298     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
10299     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
10300     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
10301     252,253,254,255
10302 #endif
10303 #ifdef SQLITE_EBCDIC
10304       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
10305      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
10306      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
10307      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
10308      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
10309      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
10310      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
10311     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
10312     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
10313     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
10314     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
10315     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
10316     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
10317     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
10318     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
10319     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
10320 #endif
10321 };
10322
10323 /*
10324 ** The following singleton contains the global configuration for
10325 ** the SQLite library.
10326 */
10327 SQLITE_PRIVATE struct Sqlite3Config sqlite3Config = {
10328    1,                /* bMemstat */
10329    1,                /* bCoreMutex */
10330    1,                /* bFullMutex */
10331    0x7ffffffe,       /* mxStrlen */
10332    100,              /* szLookaside */
10333    500,              /* nLookaside */
10334    /* Other fields all default to zero */
10335 };
10336
10337 /************** End of global.c **********************************************/
10338 /************** Begin file status.c ******************************************/
10339 /*
10340 ** 2008 June 18
10341 **
10342 ** The author disclaims copyright to this source code.  In place of
10343 ** a legal notice, here is a blessing:
10344 **
10345 **    May you do good and not evil.
10346 **    May you find forgiveness for yourself and forgive others.
10347 **    May you share freely, never taking more than you give.
10348 **
10349 *************************************************************************
10350 **
10351 ** This module implements the sqlite3_status() interface and related
10352 ** functionality.
10353 **
10354 ** $Id: status.c,v 1.7 2008/08/05 17:53:23 drh Exp $
10355 */
10356
10357 /*
10358 ** Variables in which to record status information.
10359 */
10360 static struct {
10361   int nowValue[9];         /* Current value */
10362   int mxValue[9];          /* Maximum value */
10363 } sqlite3Stat;
10364
10365
10366 /*
10367 ** Reset the status records.  This routine is called by
10368 ** sqlite3_initialize().
10369 */
10370 SQLITE_PRIVATE void sqlite3StatusReset(void){
10371   memset(&sqlite3Stat, 0, sizeof(sqlite3Stat));
10372 }
10373
10374 /*
10375 ** Return the current value of a status parameter.
10376 */
10377 SQLITE_PRIVATE int sqlite3StatusValue(int op){
10378   assert( op>=0 && op<ArraySize(sqlite3Stat.nowValue) );
10379   return sqlite3Stat.nowValue[op];
10380 }
10381
10382 /*
10383 ** Add N to the value of a status record.  It is assumed that the
10384 ** caller holds appropriate locks.
10385 */
10386 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
10387   assert( op>=0 && op<ArraySize(sqlite3Stat.nowValue) );
10388   sqlite3Stat.nowValue[op] += N;
10389   if( sqlite3Stat.nowValue[op]>sqlite3Stat.mxValue[op] ){
10390     sqlite3Stat.mxValue[op] = sqlite3Stat.nowValue[op];
10391   }
10392 }
10393
10394 /*
10395 ** Set the value of a status to X.
10396 */
10397 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
10398   assert( op>=0 && op<ArraySize(sqlite3Stat.nowValue) );
10399   sqlite3Stat.nowValue[op] = X;
10400   if( sqlite3Stat.nowValue[op]>sqlite3Stat.mxValue[op] ){
10401     sqlite3Stat.mxValue[op] = sqlite3Stat.nowValue[op];
10402   }
10403 }
10404
10405 /*
10406 ** Query status information.
10407 **
10408 ** This implementation assumes that reading or writing an aligned
10409 ** 32-bit integer is an atomic operation.  If that assumption is not true,
10410 ** then this routine is not threadsafe.
10411 */
10412 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
10413   if( op<0 || op>=ArraySize(sqlite3Stat.nowValue) ){
10414     return SQLITE_MISUSE;
10415   }
10416   *pCurrent = sqlite3Stat.nowValue[op];
10417   *pHighwater = sqlite3Stat.mxValue[op];
10418   if( resetFlag ){
10419     sqlite3Stat.mxValue[op] = sqlite3Stat.nowValue[op];
10420   }
10421   return SQLITE_OK;
10422 }
10423
10424 /*
10425 ** Query status information for a single database connection
10426 */
10427 SQLITE_API int sqlite3_db_status(
10428   sqlite3 *db,          /* The database connection whose status is desired */
10429   int op,               /* Status verb */
10430   int *pCurrent,        /* Write current value here */
10431   int *pHighwater,      /* Write high-water mark here */
10432   int resetFlag         /* Reset high-water mark if true */
10433 ){
10434   switch( op ){
10435     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
10436       *pCurrent = db->lookaside.nOut;
10437       *pHighwater = db->lookaside.mxOut;
10438       if( resetFlag ){
10439         db->lookaside.mxOut = db->lookaside.nOut;
10440       }
10441       break;
10442     }
10443     default: {
10444       return SQLITE_ERROR;
10445     }
10446   }
10447   return SQLITE_OK;
10448 }
10449
10450 /************** End of status.c **********************************************/
10451 /************** Begin file date.c ********************************************/
10452 /*
10453 ** 2003 October 31
10454 **
10455 ** The author disclaims copyright to this source code.  In place of
10456 ** a legal notice, here is a blessing:
10457 **
10458 **    May you do good and not evil.
10459 **    May you find forgiveness for yourself and forgive others.
10460 **    May you share freely, never taking more than you give.
10461 **
10462 *************************************************************************
10463 ** This file contains the C functions that implement date and time
10464 ** functions for SQLite.  
10465 **
10466 ** There is only one exported symbol in this file - the function
10467 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
10468 ** All other code has file scope.
10469 **
10470 ** $Id: date.c,v 1.87 2008/07/28 19:34:53 drh Exp $
10471 **
10472 ** SQLite processes all times and dates as Julian Day numbers.  The
10473 ** dates and times are stored as the number of days since noon
10474 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
10475 ** calendar system. 
10476 **
10477 ** 1970-01-01 00:00:00 is JD 2440587.5
10478 ** 2000-01-01 00:00:00 is JD 2451544.5
10479 **
10480 ** This implemention requires years to be expressed as a 4-digit number
10481 ** which means that only dates between 0000-01-01 and 9999-12-31 can
10482 ** be represented, even though julian day numbers allow a much wider
10483 ** range of dates.
10484 **
10485 ** The Gregorian calendar system is used for all dates and times,
10486 ** even those that predate the Gregorian calendar.  Historians usually
10487 ** use the Julian calendar for dates prior to 1582-10-15 and for some
10488 ** dates afterwards, depending on locale.  Beware of this difference.
10489 **
10490 ** The conversion algorithms are implemented based on descriptions
10491 ** in the following text:
10492 **
10493 **      Jean Meeus
10494 **      Astronomical Algorithms, 2nd Edition, 1998
10495 **      ISBM 0-943396-61-1
10496 **      Willmann-Bell, Inc
10497 **      Richmond, Virginia (USA)
10498 */
10499 #include <ctype.h>
10500 #include <time.h>
10501
10502 #ifndef SQLITE_OMIT_DATETIME_FUNCS
10503
10504 /*
10505 ** On recent Windows platforms, the localtime_s() function is available
10506 ** as part of the "Secure CRT". It is essentially equivalent to 
10507 ** localtime_r() available under most POSIX platforms, except that the 
10508 ** order of the parameters is reversed.
10509 **
10510 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
10511 **
10512 ** If the user has not indicated to use localtime_r() or localtime_s()
10513 ** already, check for an MSVC build environment that provides 
10514 ** localtime_s().
10515 */
10516 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
10517      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
10518 #define HAVE_LOCALTIME_S 1
10519 #endif
10520
10521 /*
10522 ** A structure for holding a single date and time.
10523 */
10524 typedef struct DateTime DateTime;
10525 struct DateTime {
10526   sqlite3_int64 iJD; /* The julian day number times 86400000 */
10527   int Y, M, D;       /* Year, month, and day */
10528   int h, m;          /* Hour and minutes */
10529   int tz;            /* Timezone offset in minutes */
10530   double s;          /* Seconds */
10531   char validYMD;     /* True if Y,M,D are valid */
10532   char validHMS;     /* True if h,m,s are valid */
10533   char validJD;      /* True if iJD is valid */
10534   char validTZ;      /* True if tz is valid */
10535 };
10536
10537
10538 /*
10539 ** Convert zDate into one or more integers.  Additional arguments
10540 ** come in groups of 5 as follows:
10541 **
10542 **       N       number of digits in the integer
10543 **       min     minimum allowed value of the integer
10544 **       max     maximum allowed value of the integer
10545 **       nextC   first character after the integer
10546 **       pVal    where to write the integers value.
10547 **
10548 ** Conversions continue until one with nextC==0 is encountered.
10549 ** The function returns the number of successful conversions.
10550 */
10551 static int getDigits(const char *zDate, ...){
10552   va_list ap;
10553   int val;
10554   int N;
10555   int min;
10556   int max;
10557   int nextC;
10558   int *pVal;
10559   int cnt = 0;
10560   va_start(ap, zDate);
10561   do{
10562     N = va_arg(ap, int);
10563     min = va_arg(ap, int);
10564     max = va_arg(ap, int);
10565     nextC = va_arg(ap, int);
10566     pVal = va_arg(ap, int*);
10567     val = 0;
10568     while( N-- ){
10569       if( !isdigit(*(u8*)zDate) ){
10570         goto end_getDigits;
10571       }
10572       val = val*10 + *zDate - '0';
10573       zDate++;
10574     }
10575     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
10576       goto end_getDigits;
10577     }
10578     *pVal = val;
10579     zDate++;
10580     cnt++;
10581   }while( nextC );
10582 end_getDigits:
10583   va_end(ap);
10584   return cnt;
10585 }
10586
10587 /*
10588 ** Read text from z[] and convert into a floating point number.  Return
10589 ** the number of digits converted.
10590 */
10591 #define getValue sqlite3AtoF
10592
10593 /*
10594 ** Parse a timezone extension on the end of a date-time.
10595 ** The extension is of the form:
10596 **
10597 **        (+/-)HH:MM
10598 **
10599 ** Or the "zulu" notation:
10600 **
10601 **        Z
10602 **
10603 ** If the parse is successful, write the number of minutes
10604 ** of change in p->tz and return 0.  If a parser error occurs,
10605 ** return non-zero.
10606 **
10607 ** A missing specifier is not considered an error.
10608 */
10609 static int parseTimezone(const char *zDate, DateTime *p){
10610   int sgn = 0;
10611   int nHr, nMn;
10612   int c;
10613   while( isspace(*(u8*)zDate) ){ zDate++; }
10614   p->tz = 0;
10615   c = *zDate;
10616   if( c=='-' ){
10617     sgn = -1;
10618   }else if( c=='+' ){
10619     sgn = +1;
10620   }else if( c=='Z' || c=='z' ){
10621     zDate++;
10622     goto zulu_time;
10623   }else{
10624     return c!=0;
10625   }
10626   zDate++;
10627   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
10628     return 1;
10629   }
10630   zDate += 5;
10631   p->tz = sgn*(nMn + nHr*60);
10632 zulu_time:
10633   while( isspace(*(u8*)zDate) ){ zDate++; }
10634   return *zDate!=0;
10635 }
10636
10637 /*
10638 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
10639 ** The HH, MM, and SS must each be exactly 2 digits.  The
10640 ** fractional seconds FFFF can be one or more digits.
10641 **
10642 ** Return 1 if there is a parsing error and 0 on success.
10643 */
10644 static int parseHhMmSs(const char *zDate, DateTime *p){
10645   int h, m, s;
10646   double ms = 0.0;
10647   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
10648     return 1;
10649   }
10650   zDate += 5;
10651   if( *zDate==':' ){
10652     zDate++;
10653     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
10654       return 1;
10655     }
10656     zDate += 2;
10657     if( *zDate=='.' && isdigit((u8)zDate[1]) ){
10658       double rScale = 1.0;
10659       zDate++;
10660       while( isdigit(*(u8*)zDate) ){
10661         ms = ms*10.0 + *zDate - '0';
10662         rScale *= 10.0;
10663         zDate++;
10664       }
10665       ms /= rScale;
10666     }
10667   }else{
10668     s = 0;
10669   }
10670   p->validJD = 0;
10671   p->validHMS = 1;
10672   p->h = h;
10673   p->m = m;
10674   p->s = s + ms;
10675   if( parseTimezone(zDate, p) ) return 1;
10676   p->validTZ = p->tz!=0;
10677   return 0;
10678 }
10679
10680 /*
10681 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
10682 ** that the YYYY-MM-DD is according to the Gregorian calendar.
10683 **
10684 ** Reference:  Meeus page 61
10685 */
10686 static void computeJD(DateTime *p){
10687   int Y, M, D, A, B, X1, X2;
10688
10689   if( p->validJD ) return;
10690   if( p->validYMD ){
10691     Y = p->Y;
10692     M = p->M;
10693     D = p->D;
10694   }else{
10695     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
10696     M = 1;
10697     D = 1;
10698   }
10699   if( M<=2 ){
10700     Y--;
10701     M += 12;
10702   }
10703   A = Y/100;
10704   B = 2 - A + (A/4);
10705   X1 = 365.25*(Y+4716);
10706   X2 = 30.6001*(M+1);
10707   p->iJD = (X1 + X2 + D + B - 1524.5)*86400000;
10708   p->validJD = 1;
10709   if( p->validHMS ){
10710     p->iJD += p->h*3600000 + p->m*60000 + p->s*1000;
10711     if( p->validTZ ){
10712       p->iJD -= p->tz*60000;
10713       p->validYMD = 0;
10714       p->validHMS = 0;
10715       p->validTZ = 0;
10716     }
10717   }
10718 }
10719
10720 /*
10721 ** Parse dates of the form
10722 **
10723 **     YYYY-MM-DD HH:MM:SS.FFF
10724 **     YYYY-MM-DD HH:MM:SS
10725 **     YYYY-MM-DD HH:MM
10726 **     YYYY-MM-DD
10727 **
10728 ** Write the result into the DateTime structure and return 0
10729 ** on success and 1 if the input string is not a well-formed
10730 ** date.
10731 */
10732 static int parseYyyyMmDd(const char *zDate, DateTime *p){
10733   int Y, M, D, neg;
10734
10735   if( zDate[0]=='-' ){
10736     zDate++;
10737     neg = 1;
10738   }else{
10739     neg = 0;
10740   }
10741   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
10742     return 1;
10743   }
10744   zDate += 10;
10745   while( isspace(*(u8*)zDate) || 'T'==*(u8*)zDate ){ zDate++; }
10746   if( parseHhMmSs(zDate, p)==0 ){
10747     /* We got the time */
10748   }else if( *zDate==0 ){
10749     p->validHMS = 0;
10750   }else{
10751     return 1;
10752   }
10753   p->validJD = 0;
10754   p->validYMD = 1;
10755   p->Y = neg ? -Y : Y;
10756   p->M = M;
10757   p->D = D;
10758   if( p->validTZ ){
10759     computeJD(p);
10760   }
10761   return 0;
10762 }
10763
10764 /*
10765 ** Set the time to the current time reported by the VFS
10766 */
10767 static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
10768   double r;
10769   sqlite3 *db = sqlite3_context_db_handle(context);
10770   sqlite3OsCurrentTime(db->pVfs, &r);
10771   p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
10772   p->validJD = 1;
10773 }
10774
10775 /*
10776 ** Attempt to parse the given string into a Julian Day Number.  Return
10777 ** the number of errors.
10778 **
10779 ** The following are acceptable forms for the input string:
10780 **
10781 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
10782 **      DDDD.DD 
10783 **      now
10784 **
10785 ** In the first form, the +/-HH:MM is always optional.  The fractional
10786 ** seconds extension (the ".FFF") is optional.  The seconds portion
10787 ** (":SS.FFF") is option.  The year and date can be omitted as long
10788 ** as there is a time string.  The time string can be omitted as long
10789 ** as there is a year and date.
10790 */
10791 static int parseDateOrTime(
10792   sqlite3_context *context, 
10793   const char *zDate, 
10794   DateTime *p
10795 ){
10796   if( parseYyyyMmDd(zDate,p)==0 ){
10797     return 0;
10798   }else if( parseHhMmSs(zDate, p)==0 ){
10799     return 0;
10800   }else if( sqlite3StrICmp(zDate,"now")==0){
10801     setDateTimeToCurrent(context, p);
10802     return 0;
10803   }else if( sqlite3IsNumber(zDate, 0, SQLITE_UTF8) ){
10804     double r;
10805     getValue(zDate, &r);
10806     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
10807     p->validJD = 1;
10808     return 0;
10809   }
10810   return 1;
10811 }
10812
10813 /*
10814 ** Compute the Year, Month, and Day from the julian day number.
10815 */
10816 static void computeYMD(DateTime *p){
10817   int Z, A, B, C, D, E, X1;
10818   if( p->validYMD ) return;
10819   if( !p->validJD ){
10820     p->Y = 2000;
10821     p->M = 1;
10822     p->D = 1;
10823   }else{
10824     Z = (p->iJD + 43200000)/86400000;
10825     A = (Z - 1867216.25)/36524.25;
10826     A = Z + 1 + A - (A/4);
10827     B = A + 1524;
10828     C = (B - 122.1)/365.25;
10829     D = 365.25*C;
10830     E = (B-D)/30.6001;
10831     X1 = 30.6001*E;
10832     p->D = B - D - X1;
10833     p->M = E<14 ? E-1 : E-13;
10834     p->Y = p->M>2 ? C - 4716 : C - 4715;
10835   }
10836   p->validYMD = 1;
10837 }
10838
10839 /*
10840 ** Compute the Hour, Minute, and Seconds from the julian day number.
10841 */
10842 static void computeHMS(DateTime *p){
10843   int s;
10844   if( p->validHMS ) return;
10845   computeJD(p);
10846   s = (p->iJD + 43200000) % 86400000;
10847   p->s = s/1000.0;
10848   s = p->s;
10849   p->s -= s;
10850   p->h = s/3600;
10851   s -= p->h*3600;
10852   p->m = s/60;
10853   p->s += s - p->m*60;
10854   p->validHMS = 1;
10855 }
10856
10857 /*
10858 ** Compute both YMD and HMS
10859 */
10860 static void computeYMD_HMS(DateTime *p){
10861   computeYMD(p);
10862   computeHMS(p);
10863 }
10864
10865 /*
10866 ** Clear the YMD and HMS and the TZ
10867 */
10868 static void clearYMD_HMS_TZ(DateTime *p){
10869   p->validYMD = 0;
10870   p->validHMS = 0;
10871   p->validTZ = 0;
10872 }
10873
10874 #ifndef SQLITE_OMIT_LOCALTIME
10875 /*
10876 ** Compute the difference (in milliseconds)
10877 ** between localtime and UTC (a.k.a. GMT)
10878 ** for the time value p where p is in UTC.
10879 */
10880 static int localtimeOffset(DateTime *p){
10881   DateTime x, y;
10882   time_t t;
10883   x = *p;
10884   computeYMD_HMS(&x);
10885   if( x.Y<1971 || x.Y>=2038 ){
10886     x.Y = 2000;
10887     x.M = 1;
10888     x.D = 1;
10889     x.h = 0;
10890     x.m = 0;
10891     x.s = 0.0;
10892   } else {
10893     int s = x.s + 0.5;
10894     x.s = s;
10895   }
10896   x.tz = 0;
10897   x.validJD = 0;
10898   computeJD(&x);
10899   t = x.iJD/1000 - 2440587.5*86400.0;
10900 #ifdef HAVE_LOCALTIME_R
10901   {
10902     struct tm sLocal;
10903     localtime_r(&t, &sLocal);
10904     y.Y = sLocal.tm_year + 1900;
10905     y.M = sLocal.tm_mon + 1;
10906     y.D = sLocal.tm_mday;
10907     y.h = sLocal.tm_hour;
10908     y.m = sLocal.tm_min;
10909     y.s = sLocal.tm_sec;
10910   }
10911 #elif defined(HAVE_LOCALTIME_S)
10912   {
10913     struct tm sLocal;
10914     localtime_s(&sLocal, &t);
10915     y.Y = sLocal.tm_year + 1900;
10916     y.M = sLocal.tm_mon + 1;
10917     y.D = sLocal.tm_mday;
10918     y.h = sLocal.tm_hour;
10919     y.m = sLocal.tm_min;
10920     y.s = sLocal.tm_sec;
10921   }
10922 #else
10923   {
10924     struct tm *pTm;
10925     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
10926     pTm = localtime(&t);
10927     y.Y = pTm->tm_year + 1900;
10928     y.M = pTm->tm_mon + 1;
10929     y.D = pTm->tm_mday;
10930     y.h = pTm->tm_hour;
10931     y.m = pTm->tm_min;
10932     y.s = pTm->tm_sec;
10933     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
10934   }
10935 #endif
10936   y.validYMD = 1;
10937   y.validHMS = 1;
10938   y.validJD = 0;
10939   y.validTZ = 0;
10940   computeJD(&y);
10941   return y.iJD - x.iJD;
10942 }
10943 #endif /* SQLITE_OMIT_LOCALTIME */
10944
10945 /*
10946 ** Process a modifier to a date-time stamp.  The modifiers are
10947 ** as follows:
10948 **
10949 **     NNN days
10950 **     NNN hours
10951 **     NNN minutes
10952 **     NNN.NNNN seconds
10953 **     NNN months
10954 **     NNN years
10955 **     start of month
10956 **     start of year
10957 **     start of week
10958 **     start of day
10959 **     weekday N
10960 **     unixepoch
10961 **     localtime
10962 **     utc
10963 **
10964 ** Return 0 on success and 1 if there is any kind of error.
10965 */
10966 static int parseModifier(const char *zMod, DateTime *p){
10967   int rc = 1;
10968   int n;
10969   double r;
10970   char *z, zBuf[30];
10971   z = zBuf;
10972   for(n=0; n<sizeof(zBuf)-1 && zMod[n]; n++){
10973     z[n] = tolower(zMod[n]);
10974   }
10975   z[n] = 0;
10976   switch( z[0] ){
10977 #ifndef SQLITE_OMIT_LOCALTIME
10978     case 'l': {
10979       /*    localtime
10980       **
10981       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
10982       ** show local time.
10983       */
10984       if( strcmp(z, "localtime")==0 ){
10985         computeJD(p);
10986         p->iJD += localtimeOffset(p);
10987         clearYMD_HMS_TZ(p);
10988         rc = 0;
10989       }
10990       break;
10991     }
10992 #endif
10993     case 'u': {
10994       /*
10995       **    unixepoch
10996       **
10997       ** Treat the current value of p->iJD as the number of
10998       ** seconds since 1970.  Convert to a real julian day number.
10999       */
11000       if( strcmp(z, "unixepoch")==0 && p->validJD ){
11001         p->iJD = p->iJD/86400.0 + 2440587.5*86400000.0;
11002         clearYMD_HMS_TZ(p);
11003         rc = 0;
11004       }
11005 #ifndef SQLITE_OMIT_LOCALTIME
11006       else if( strcmp(z, "utc")==0 ){
11007         double c1;
11008         computeJD(p);
11009         c1 = localtimeOffset(p);
11010         p->iJD -= c1;
11011         clearYMD_HMS_TZ(p);
11012         p->iJD += c1 - localtimeOffset(p);
11013         rc = 0;
11014       }
11015 #endif
11016       break;
11017     }
11018     case 'w': {
11019       /*
11020       **    weekday N
11021       **
11022       ** Move the date to the same time on the next occurrence of
11023       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
11024       ** date is already on the appropriate weekday, this is a no-op.
11025       */
11026       if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
11027                  && (n=r)==r && n>=0 && r<7 ){
11028         sqlite3_int64 Z;
11029         computeYMD_HMS(p);
11030         p->validTZ = 0;
11031         p->validJD = 0;
11032         computeJD(p);
11033         Z = ((p->iJD + 129600000)/86400000) % 7;
11034         if( Z>n ) Z -= 7;
11035         p->iJD += (n - Z)*86400000;
11036         clearYMD_HMS_TZ(p);
11037         rc = 0;
11038       }
11039       break;
11040     }
11041     case 's': {
11042       /*
11043       **    start of TTTTT
11044       **
11045       ** Move the date backwards to the beginning of the current day,
11046       ** or month or year.
11047       */
11048       if( strncmp(z, "start of ", 9)!=0 ) break;
11049       z += 9;
11050       computeYMD(p);
11051       p->validHMS = 1;
11052       p->h = p->m = 0;
11053       p->s = 0.0;
11054       p->validTZ = 0;
11055       p->validJD = 0;
11056       if( strcmp(z,"month")==0 ){
11057         p->D = 1;
11058         rc = 0;
11059       }else if( strcmp(z,"year")==0 ){
11060         computeYMD(p);
11061         p->M = 1;
11062         p->D = 1;
11063         rc = 0;
11064       }else if( strcmp(z,"day")==0 ){
11065         rc = 0;
11066       }
11067       break;
11068     }
11069     case '+':
11070     case '-':
11071     case '0':
11072     case '1':
11073     case '2':
11074     case '3':
11075     case '4':
11076     case '5':
11077     case '6':
11078     case '7':
11079     case '8':
11080     case '9': {
11081       n = getValue(z, &r);
11082       assert( n>=1 );
11083       if( z[n]==':' ){
11084         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
11085         ** specified number of hours, minutes, seconds, and fractional seconds
11086         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
11087         ** omitted.
11088         */
11089         const char *z2 = z;
11090         DateTime tx;
11091         sqlite3_int64 day;
11092         if( !isdigit(*(u8*)z2) ) z2++;
11093         memset(&tx, 0, sizeof(tx));
11094         if( parseHhMmSs(z2, &tx) ) break;
11095         computeJD(&tx);
11096         tx.iJD -= 43200000;
11097         day = tx.iJD/86400000;
11098         tx.iJD -= day*86400000;
11099         if( z[0]=='-' ) tx.iJD = -tx.iJD;
11100         computeJD(p);
11101         clearYMD_HMS_TZ(p);
11102         p->iJD += tx.iJD;
11103         rc = 0;
11104         break;
11105       }
11106       z += n;
11107       while( isspace(*(u8*)z) ) z++;
11108       n = strlen(z);
11109       if( n>10 || n<3 ) break;
11110       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
11111       computeJD(p);
11112       rc = 0;
11113       if( n==3 && strcmp(z,"day")==0 ){
11114         p->iJD += r*86400000.0 + 0.5;
11115       }else if( n==4 && strcmp(z,"hour")==0 ){
11116         p->iJD += r*(86400000.0/24.0) + 0.5;
11117       }else if( n==6 && strcmp(z,"minute")==0 ){
11118         p->iJD += r*(86400000.0/(24.0*60.0)) + 0.5;
11119       }else if( n==6 && strcmp(z,"second")==0 ){
11120         p->iJD += r*(86400000.0/(24.0*60.0*60.0)) + 0.5;
11121       }else if( n==5 && strcmp(z,"month")==0 ){
11122         int x, y;
11123         computeYMD_HMS(p);
11124         p->M += r;
11125         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
11126         p->Y += x;
11127         p->M -= x*12;
11128         p->validJD = 0;
11129         computeJD(p);
11130         y = r;
11131         if( y!=r ){
11132           p->iJD += (r - y)*30.0*86400000.0 + 0.5;
11133         }
11134       }else if( n==4 && strcmp(z,"year")==0 ){
11135         computeYMD_HMS(p);
11136         p->Y += r;
11137         p->validJD = 0;
11138         computeJD(p);
11139       }else{
11140         rc = 1;
11141       }
11142       clearYMD_HMS_TZ(p);
11143       break;
11144     }
11145     default: {
11146       break;
11147     }
11148   }
11149   return rc;
11150 }
11151
11152 /*
11153 ** Process time function arguments.  argv[0] is a date-time stamp.
11154 ** argv[1] and following are modifiers.  Parse them all and write
11155 ** the resulting time into the DateTime structure p.  Return 0
11156 ** on success and 1 if there are any errors.
11157 **
11158 ** If there are zero parameters (if even argv[0] is undefined)
11159 ** then assume a default value of "now" for argv[0].
11160 */
11161 static int isDate(
11162   sqlite3_context *context, 
11163   int argc, 
11164   sqlite3_value **argv, 
11165   DateTime *p
11166 ){
11167   int i;
11168   const unsigned char *z;
11169   int eType;
11170   memset(p, 0, sizeof(*p));
11171   if( argc==0 ){
11172     setDateTimeToCurrent(context, p);
11173   }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
11174                    || eType==SQLITE_INTEGER ){
11175     p->iJD = sqlite3_value_double(argv[0])*86400000.0 + 0.5;
11176     p->validJD = 1;
11177   }else{
11178     z = sqlite3_value_text(argv[0]);
11179     if( !z || parseDateOrTime(context, (char*)z, p) ){
11180       return 1;
11181     }
11182   }
11183   for(i=1; i<argc; i++){
11184     if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
11185       return 1;
11186     }
11187   }
11188   return 0;
11189 }
11190
11191
11192 /*
11193 ** The following routines implement the various date and time functions
11194 ** of SQLite.
11195 */
11196
11197 /*
11198 **    julianday( TIMESTRING, MOD, MOD, ...)
11199 **
11200 ** Return the julian day number of the date specified in the arguments
11201 */
11202 static void juliandayFunc(
11203   sqlite3_context *context,
11204   int argc,
11205   sqlite3_value **argv
11206 ){
11207   DateTime x;
11208   if( isDate(context, argc, argv, &x)==0 ){
11209     computeJD(&x);
11210     sqlite3_result_double(context, x.iJD/86400000.0);
11211   }
11212 }
11213
11214 /*
11215 **    datetime( TIMESTRING, MOD, MOD, ...)
11216 **
11217 ** Return YYYY-MM-DD HH:MM:SS
11218 */
11219 static void datetimeFunc(
11220   sqlite3_context *context,
11221   int argc,
11222   sqlite3_value **argv
11223 ){
11224   DateTime x;
11225   if( isDate(context, argc, argv, &x)==0 ){
11226     char zBuf[100];
11227     computeYMD_HMS(&x);
11228     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
11229                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
11230     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
11231   }
11232 }
11233
11234 /*
11235 **    time( TIMESTRING, MOD, MOD, ...)
11236 **
11237 ** Return HH:MM:SS
11238 */
11239 static void timeFunc(
11240   sqlite3_context *context,
11241   int argc,
11242   sqlite3_value **argv
11243 ){
11244   DateTime x;
11245   if( isDate(context, argc, argv, &x)==0 ){
11246     char zBuf[100];
11247     computeHMS(&x);
11248     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
11249     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
11250   }
11251 }
11252
11253 /*
11254 **    date( TIMESTRING, MOD, MOD, ...)
11255 **
11256 ** Return YYYY-MM-DD
11257 */
11258 static void dateFunc(
11259   sqlite3_context *context,
11260   int argc,
11261   sqlite3_value **argv
11262 ){
11263   DateTime x;
11264   if( isDate(context, argc, argv, &x)==0 ){
11265     char zBuf[100];
11266     computeYMD(&x);
11267     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
11268     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
11269   }
11270 }
11271
11272 /*
11273 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
11274 **
11275 ** Return a string described by FORMAT.  Conversions as follows:
11276 **
11277 **   %d  day of month
11278 **   %f  ** fractional seconds  SS.SSS
11279 **   %H  hour 00-24
11280 **   %j  day of year 000-366
11281 **   %J  ** Julian day number
11282 **   %m  month 01-12
11283 **   %M  minute 00-59
11284 **   %s  seconds since 1970-01-01
11285 **   %S  seconds 00-59
11286 **   %w  day of week 0-6  sunday==0
11287 **   %W  week of year 00-53
11288 **   %Y  year 0000-9999
11289 **   %%  %
11290 */
11291 static void strftimeFunc(
11292   sqlite3_context *context,
11293   int argc,
11294   sqlite3_value **argv
11295 ){
11296   DateTime x;
11297   u64 n;
11298   int i, j;
11299   char *z;
11300   sqlite3 *db;
11301   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
11302   char zBuf[100];
11303   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
11304   db = sqlite3_context_db_handle(context);
11305   for(i=0, n=1; zFmt[i]; i++, n++){
11306     if( zFmt[i]=='%' ){
11307       switch( zFmt[i+1] ){
11308         case 'd':
11309         case 'H':
11310         case 'm':
11311         case 'M':
11312         case 'S':
11313         case 'W':
11314           n++;
11315           /* fall thru */
11316         case 'w':
11317         case '%':
11318           break;
11319         case 'f':
11320           n += 8;
11321           break;
11322         case 'j':
11323           n += 3;
11324           break;
11325         case 'Y':
11326           n += 8;
11327           break;
11328         case 's':
11329         case 'J':
11330           n += 50;
11331           break;
11332         default:
11333           return;  /* ERROR.  return a NULL */
11334       }
11335       i++;
11336     }
11337   }
11338   if( n<sizeof(zBuf) ){
11339     z = zBuf;
11340   }else if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
11341     sqlite3_result_error_toobig(context);
11342     return;
11343   }else{
11344     z = sqlite3DbMallocRaw(db, n);
11345     if( z==0 ){
11346       sqlite3_result_error_nomem(context);
11347       return;
11348     }
11349   }
11350   computeJD(&x);
11351   computeYMD_HMS(&x);
11352   for(i=j=0; zFmt[i]; i++){
11353     if( zFmt[i]!='%' ){
11354       z[j++] = zFmt[i];
11355     }else{
11356       i++;
11357       switch( zFmt[i] ){
11358         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
11359         case 'f': {
11360           double s = x.s;
11361           if( s>59.999 ) s = 59.999;
11362           sqlite3_snprintf(7, &z[j],"%06.3f", s);
11363           j += strlen(&z[j]);
11364           break;
11365         }
11366         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
11367         case 'W': /* Fall thru */
11368         case 'j': {
11369           int nDay;             /* Number of days since 1st day of year */
11370           DateTime y = x;
11371           y.validJD = 0;
11372           y.M = 1;
11373           y.D = 1;
11374           computeJD(&y);
11375           nDay = (x.iJD - y.iJD)/86400000.0 + 0.5;
11376           if( zFmt[i]=='W' ){
11377             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
11378             wd = ((x.iJD+43200000)/86400000) % 7;
11379             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
11380             j += 2;
11381           }else{
11382             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
11383             j += 3;
11384           }
11385           break;
11386         }
11387         case 'J': {
11388           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
11389           j+=strlen(&z[j]);
11390           break;
11391         }
11392         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
11393         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
11394         case 's': {
11395           sqlite3_snprintf(30,&z[j],"%d",
11396                            (int)(x.iJD/1000.0 - 210866760000.0));
11397           j += strlen(&z[j]);
11398           break;
11399         }
11400         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
11401         case 'w':  z[j++] = (((x.iJD+129600000)/86400000) % 7) + '0'; break;
11402         case 'Y':  sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=strlen(&z[j]);break;
11403         default:   z[j++] = '%'; break;
11404       }
11405     }
11406   }
11407   z[j] = 0;
11408   sqlite3_result_text(context, z, -1,
11409                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
11410 }
11411
11412 /*
11413 ** current_time()
11414 **
11415 ** This function returns the same value as time('now').
11416 */
11417 static void ctimeFunc(
11418   sqlite3_context *context,
11419   int argc,
11420   sqlite3_value **argv
11421 ){
11422   timeFunc(context, 0, 0);
11423 }
11424
11425 /*
11426 ** current_date()
11427 **
11428 ** This function returns the same value as date('now').
11429 */
11430 static void cdateFunc(
11431   sqlite3_context *context,
11432   int argc,
11433   sqlite3_value **argv
11434 ){
11435   dateFunc(context, 0, 0);
11436 }
11437
11438 /*
11439 ** current_timestamp()
11440 **
11441 ** This function returns the same value as datetime('now').
11442 */
11443 static void ctimestampFunc(
11444   sqlite3_context *context,
11445   int argc,
11446   sqlite3_value **argv
11447 ){
11448   datetimeFunc(context, 0, 0);
11449 }
11450 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
11451
11452 #ifdef SQLITE_OMIT_DATETIME_FUNCS
11453 /*
11454 ** If the library is compiled to omit the full-scale date and time
11455 ** handling (to get a smaller binary), the following minimal version
11456 ** of the functions current_time(), current_date() and current_timestamp()
11457 ** are included instead. This is to support column declarations that
11458 ** include "DEFAULT CURRENT_TIME" etc.
11459 **
11460 ** This function uses the C-library functions time(), gmtime()
11461 ** and strftime(). The format string to pass to strftime() is supplied
11462 ** as the user-data for the function.
11463 */
11464 static void currentTimeFunc(
11465   sqlite3_context *context,
11466   int argc,
11467   sqlite3_value **argv
11468 ){
11469   time_t t;
11470   char *zFormat = (char *)sqlite3_user_data(context);
11471   sqlite3 *db;
11472   double rT;
11473   char zBuf[20];
11474
11475   db = sqlite3_context_db_handle(context);
11476   sqlite3OsCurrentTime(db->pVfs, &rT);
11477   t = 86400.0*(rT - 2440587.5) + 0.5;
11478 #ifdef HAVE_GMTIME_R
11479   {
11480     struct tm sNow;
11481     gmtime_r(&t, &sNow);
11482     strftime(zBuf, 20, zFormat, &sNow);
11483   }
11484 #else
11485   {
11486     struct tm *pTm;
11487     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
11488     pTm = gmtime(&t);
11489     strftime(zBuf, 20, zFormat, pTm);
11490     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
11491   }
11492 #endif
11493
11494   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
11495 }
11496 #endif
11497
11498 /*
11499 ** This function registered all of the above C functions as SQL
11500 ** functions.  This should be the only routine in this file with
11501 ** external linkage.
11502 */
11503 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(sqlite3 *db){
11504 #ifndef SQLITE_OMIT_DATETIME_FUNCS
11505   static const struct {
11506      char *zName;
11507      int nArg;
11508      void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
11509   } aFuncs[] = {
11510     { "julianday", -1, juliandayFunc   },
11511     { "date",      -1, dateFunc        },
11512     { "time",      -1, timeFunc        },
11513     { "datetime",  -1, datetimeFunc    },
11514     { "strftime",  -1, strftimeFunc    },
11515     { "current_time",       0, ctimeFunc      },
11516     { "current_timestamp",  0, ctimestampFunc },
11517     { "current_date",       0, cdateFunc      },
11518   };
11519   int i;
11520
11521   for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
11522     sqlite3CreateFunc(db, aFuncs[i].zName, aFuncs[i].nArg,
11523         SQLITE_UTF8, 0, aFuncs[i].xFunc, 0, 0);
11524   }
11525 #else
11526   static const struct {
11527      char *zName;
11528      char *zFormat;
11529   } aFuncs[] = {
11530     { "current_time", "%H:%M:%S" },
11531     { "current_date", "%Y-%m-%d" },
11532     { "current_timestamp", "%Y-%m-%d %H:%M:%S" }
11533   };
11534   int i;
11535
11536   for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
11537     sqlite3CreateFunc(db, aFuncs[i].zName, 0, SQLITE_UTF8, 
11538         aFuncs[i].zFormat, currentTimeFunc, 0, 0);
11539   }
11540 #endif
11541 }
11542
11543 /************** End of date.c ************************************************/
11544 /************** Begin file os.c **********************************************/
11545 /*
11546 ** 2005 November 29
11547 **
11548 ** The author disclaims copyright to this source code.  In place of
11549 ** a legal notice, here is a blessing:
11550 **
11551 **    May you do good and not evil.
11552 **    May you find forgiveness for yourself and forgive others.
11553 **    May you share freely, never taking more than you give.
11554 **
11555 ******************************************************************************
11556 **
11557 ** This file contains OS interface code that is common to all
11558 ** architectures.
11559 **
11560 ** $Id: os.c,v 1.120 2008/07/28 19:34:53 drh Exp $
11561 */
11562 #define _SQLITE_OS_C_ 1
11563 #undef _SQLITE_OS_C_
11564
11565 /*
11566 ** The default SQLite sqlite3_vfs implementations do not allocate
11567 ** memory (actually, os_unix.c allocates a small amount of memory
11568 ** from within OsOpen()), but some third-party implementations may.
11569 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
11570 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
11571 **
11572 ** The following functions are instrumented for malloc() failure 
11573 ** testing:
11574 **
11575 **     sqlite3OsOpen()
11576 **     sqlite3OsRead()
11577 **     sqlite3OsWrite()
11578 **     sqlite3OsSync()
11579 **     sqlite3OsLock()
11580 **
11581 */
11582 #if defined(SQLITE_TEST) && (SQLITE_OS_WIN==0) && 0
11583   #define DO_OS_MALLOC_TEST if (1) {            \
11584     void *pTstAlloc = sqlite3Malloc(10);       \
11585     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;  \
11586     sqlite3_free(pTstAlloc);                    \
11587   }
11588 #else
11589   #define DO_OS_MALLOC_TEST
11590 #endif
11591
11592 /*
11593 ** The following routines are convenience wrappers around methods
11594 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
11595 ** of this would be completely automatic if SQLite were coded using
11596 ** C++ instead of plain old C.
11597 */
11598 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
11599   int rc = SQLITE_OK;
11600   if( pId->pMethods ){
11601     rc = pId->pMethods->xClose(pId);
11602     pId->pMethods = 0;
11603   }
11604   return rc;
11605 }
11606 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
11607   DO_OS_MALLOC_TEST;
11608   return id->pMethods->xRead(id, pBuf, amt, offset);
11609 }
11610 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
11611   DO_OS_MALLOC_TEST;
11612   return id->pMethods->xWrite(id, pBuf, amt, offset);
11613 }
11614 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
11615   return id->pMethods->xTruncate(id, size);
11616 }
11617 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
11618   DO_OS_MALLOC_TEST;
11619   return id->pMethods->xSync(id, flags);
11620 }
11621 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
11622   DO_OS_MALLOC_TEST;
11623   return id->pMethods->xFileSize(id, pSize);
11624 }
11625 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
11626   DO_OS_MALLOC_TEST;
11627   return id->pMethods->xLock(id, lockType);
11628 }
11629 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
11630   return id->pMethods->xUnlock(id, lockType);
11631 }
11632 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
11633   DO_OS_MALLOC_TEST;
11634   return id->pMethods->xCheckReservedLock(id, pResOut);
11635 }
11636 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
11637   return id->pMethods->xFileControl(id, op, pArg);
11638 }
11639 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
11640   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
11641   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
11642 }
11643 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
11644   return id->pMethods->xDeviceCharacteristics(id);
11645 }
11646
11647 /*
11648 ** The next group of routines are convenience wrappers around the
11649 ** VFS methods.
11650 */
11651 SQLITE_PRIVATE int sqlite3OsOpen(
11652   sqlite3_vfs *pVfs, 
11653   const char *zPath, 
11654   sqlite3_file *pFile, 
11655   int flags, 
11656   int *pFlagsOut
11657 ){
11658   DO_OS_MALLOC_TEST;
11659   return pVfs->xOpen(pVfs, zPath, pFile, flags, pFlagsOut);
11660 }
11661 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
11662   return pVfs->xDelete(pVfs, zPath, dirSync);
11663 }
11664 SQLITE_PRIVATE int sqlite3OsAccess(
11665   sqlite3_vfs *pVfs, 
11666   const char *zPath, 
11667   int flags, 
11668   int *pResOut
11669 ){
11670   DO_OS_MALLOC_TEST;
11671   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
11672 }
11673 SQLITE_PRIVATE int sqlite3OsFullPathname(
11674   sqlite3_vfs *pVfs, 
11675   const char *zPath, 
11676   int nPathOut, 
11677   char *zPathOut
11678 ){
11679   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
11680 }
11681 #ifndef SQLITE_OMIT_LOAD_EXTENSION
11682 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
11683   return pVfs->xDlOpen(pVfs, zPath);
11684 }
11685 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
11686   pVfs->xDlError(pVfs, nByte, zBufOut);
11687 }
11688 SQLITE_PRIVATE void *sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
11689   return pVfs->xDlSym(pVfs, pHandle, zSymbol);
11690 }
11691 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
11692   pVfs->xDlClose(pVfs, pHandle);
11693 }
11694 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
11695 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
11696   return pVfs->xRandomness(pVfs, nByte, zBufOut);
11697 }
11698 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
11699   return pVfs->xSleep(pVfs, nMicro);
11700 }
11701 SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
11702   return pVfs->xCurrentTime(pVfs, pTimeOut);
11703 }
11704
11705 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
11706   sqlite3_vfs *pVfs, 
11707   const char *zFile, 
11708   sqlite3_file **ppFile, 
11709   int flags,
11710   int *pOutFlags
11711 ){
11712   int rc = SQLITE_NOMEM;
11713   sqlite3_file *pFile;
11714   pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
11715   if( pFile ){
11716     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
11717     if( rc!=SQLITE_OK ){
11718       sqlite3_free(pFile);
11719     }else{
11720       *ppFile = pFile;
11721     }
11722   }
11723   return rc;
11724 }
11725 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
11726   int rc = SQLITE_OK;
11727   assert( pFile );
11728   rc = sqlite3OsClose(pFile);
11729   sqlite3_free(pFile);
11730   return rc;
11731 }
11732
11733 /*
11734 ** The list of all registered VFS implementations.
11735 */
11736 static sqlite3_vfs *vfsList = 0;
11737
11738 /*
11739 ** Locate a VFS by name.  If no name is given, simply return the
11740 ** first VFS on the list.
11741 */
11742 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
11743   sqlite3_vfs *pVfs = 0;
11744 #ifndef SQLITE_MUTEX_NOOP
11745   sqlite3_mutex *mutex;
11746 #endif
11747 #ifndef SQLITE_OMIT_AUTOINIT
11748   int rc = sqlite3_initialize();
11749   if( rc ) return 0;
11750 #endif
11751 #ifndef SQLITE_MUTEX_NOOP
11752   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
11753 #endif
11754   sqlite3_mutex_enter(mutex);
11755   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
11756     if( zVfs==0 ) break;
11757     if( strcmp(zVfs, pVfs->zName)==0 ) break;
11758   }
11759   sqlite3_mutex_leave(mutex);
11760   return pVfs;
11761 }
11762
11763 /*
11764 ** Unlink a VFS from the linked list
11765 */
11766 static void vfsUnlink(sqlite3_vfs *pVfs){
11767   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
11768   if( pVfs==0 ){
11769     /* No-op */
11770   }else if( vfsList==pVfs ){
11771     vfsList = pVfs->pNext;
11772   }else if( vfsList ){
11773     sqlite3_vfs *p = vfsList;
11774     while( p->pNext && p->pNext!=pVfs ){
11775       p = p->pNext;
11776     }
11777     if( p->pNext==pVfs ){
11778       p->pNext = pVfs->pNext;
11779     }
11780   }
11781 }
11782
11783 /*
11784 ** Register a VFS with the system.  It is harmless to register the same
11785 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
11786 ** true.
11787 */
11788 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
11789   sqlite3_mutex *mutex = 0;
11790 #ifndef SQLITE_OMIT_AUTOINIT
11791   int rc = sqlite3_initialize();
11792   if( rc ) return rc;
11793 #endif
11794   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
11795   sqlite3_mutex_enter(mutex);
11796   vfsUnlink(pVfs);
11797   if( makeDflt || vfsList==0 ){
11798     pVfs->pNext = vfsList;
11799     vfsList = pVfs;
11800   }else{
11801     pVfs->pNext = vfsList->pNext;
11802     vfsList->pNext = pVfs;
11803   }
11804   assert(vfsList);
11805   sqlite3_mutex_leave(mutex);
11806   return SQLITE_OK;
11807 }
11808
11809 /*
11810 ** Unregister a VFS so that it is no longer accessible.
11811 */
11812 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
11813 #ifndef SQLITE_MUTEX_NOOP
11814   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
11815 #endif
11816   sqlite3_mutex_enter(mutex);
11817   vfsUnlink(pVfs);
11818   sqlite3_mutex_leave(mutex);
11819   return SQLITE_OK;
11820 }
11821
11822 /************** End of os.c **************************************************/
11823 /************** Begin file fault.c *******************************************/
11824 /*
11825 ** 2008 Jan 22
11826 **
11827 ** The author disclaims copyright to this source code.  In place of
11828 ** a legal notice, here is a blessing:
11829 **
11830 **    May you do good and not evil.
11831 **    May you find forgiveness for yourself and forgive others.
11832 **    May you share freely, never taking more than you give.
11833 **
11834 *************************************************************************
11835 **
11836 ** $Id: fault.c,v 1.10 2008/06/22 12:37:58 drh Exp $
11837 */
11838
11839 /*
11840 ** This file contains code to support the concept of "benign" 
11841 ** malloc failures (when the xMalloc() or xRealloc() method of the
11842 ** sqlite3_mem_methods structure fails to allocate a block of memory
11843 ** and returns 0). 
11844 **
11845 ** Most malloc failures are non-benign. After they occur, SQLite
11846 ** abandons the current operation and returns an error code (usually
11847 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
11848 ** fatal. For example, if a malloc fails while resizing a hash table, this 
11849 ** is completely recoverable simply by not carrying out the resize. The 
11850 ** hash table will continue to function normally.  So a malloc failure 
11851 ** during a hash table resize is a benign fault.
11852 */
11853
11854
11855 #ifndef SQLITE_OMIT_BUILTIN_TEST
11856
11857 /*
11858 ** Global variables.
11859 */
11860 static struct BenignMallocHooks {
11861   void (*xBenignBegin)(void);
11862   void (*xBenignEnd)(void);
11863 } hooks;
11864
11865 /*
11866 ** Register hooks to call when sqlite3BeginBenignMalloc() and
11867 ** sqlite3EndBenignMalloc() are called, respectively.
11868 */
11869 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
11870   void (*xBenignBegin)(void),
11871   void (*xBenignEnd)(void)
11872 ){
11873   hooks.xBenignBegin = xBenignBegin;
11874   hooks.xBenignEnd = xBenignEnd;
11875 }
11876
11877 /*
11878 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
11879 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
11880 ** indicates that subsequent malloc failures are non-benign.
11881 */
11882 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
11883   if( hooks.xBenignBegin ){
11884     hooks.xBenignBegin();
11885   }
11886 }
11887 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
11888   if( hooks.xBenignEnd ){
11889     hooks.xBenignEnd();
11890   }
11891 }
11892
11893 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
11894
11895 /************** End of fault.c ***********************************************/
11896 /************** Begin file mem1.c ********************************************/
11897 /*
11898 ** 2007 August 14
11899 **
11900 ** The author disclaims copyright to this source code.  In place of
11901 ** a legal notice, here is a blessing:
11902 **
11903 **    May you do good and not evil.
11904 **    May you find forgiveness for yourself and forgive others.
11905 **    May you share freely, never taking more than you give.
11906 **
11907 *************************************************************************
11908 **
11909 ** This file contains low-level memory allocation drivers for when
11910 ** SQLite will use the standard C-library malloc/realloc/free interface
11911 ** to obtain the memory it needs.
11912 **
11913 ** This file contains implementations of the low-level memory allocation
11914 ** routines specified in the sqlite3_mem_methods object.
11915 **
11916 ** $Id: mem1.c,v 1.25 2008/07/25 08:49:00 danielk1977 Exp $
11917 */
11918
11919 /*
11920 ** This version of the memory allocator is the default.  It is
11921 ** used when no other memory allocator is specified using compile-time
11922 ** macros.
11923 */
11924 #ifdef SQLITE_SYSTEM_MALLOC
11925
11926 /*
11927 ** Like malloc(), but remember the size of the allocation
11928 ** so that we can find it later using sqlite3MemSize().
11929 **
11930 ** For this low-level routine, we are guaranteed that nByte>0 because
11931 ** cases of nByte<=0 will be intercepted and dealt with by higher level
11932 ** routines.
11933 */
11934 static void *sqlite3MemMalloc(int nByte){
11935   sqlite3_int64 *p;
11936   assert( nByte>0 );
11937   nByte = (nByte+7)&~7;
11938   p = malloc( nByte+8 );
11939   if( p ){
11940     p[0] = nByte;
11941     p++;
11942   }
11943   return (void *)p;
11944 }
11945
11946 /*
11947 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
11948 ** or sqlite3MemRealloc().
11949 **
11950 ** For this low-level routine, we already know that pPrior!=0 since
11951 ** cases where pPrior==0 will have been intecepted and dealt with
11952 ** by higher-level routines.
11953 */
11954 static void sqlite3MemFree(void *pPrior){
11955   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
11956   assert( pPrior!=0 );
11957   p--;
11958   free(p);
11959 }
11960
11961 /*
11962 ** Like realloc().  Resize an allocation previously obtained from
11963 ** sqlite3MemMalloc().
11964 **
11965 ** For this low-level interface, we know that pPrior!=0.  Cases where
11966 ** pPrior==0 while have been intercepted by higher-level routine and
11967 ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
11968 ** cases where nByte<=0 will have been intercepted by higher-level
11969 ** routines and redirected to xFree.
11970 */
11971 static void *sqlite3MemRealloc(void *pPrior, int nByte){
11972   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
11973   assert( pPrior!=0 && nByte>0 );
11974   nByte = (nByte+7)&~7;
11975   p = (sqlite3_int64*)pPrior;
11976   p--;
11977   p = realloc(p, nByte+8 );
11978   if( p ){
11979     p[0] = nByte;
11980     p++;
11981   }
11982   return (void*)p;
11983 }
11984
11985 /*
11986 ** Report the allocated size of a prior return from xMalloc()
11987 ** or xRealloc().
11988 */
11989 static int sqlite3MemSize(void *pPrior){
11990   sqlite3_int64 *p;
11991   if( pPrior==0 ) return 0;
11992   p = (sqlite3_int64*)pPrior;
11993   p--;
11994   return p[0];
11995 }
11996
11997 /*
11998 ** Round up a request size to the next valid allocation size.
11999 */
12000 static int sqlite3MemRoundup(int n){
12001   return (n+7) & ~7;
12002 }
12003
12004 /*
12005 ** Initialize this module.
12006 */
12007 static int sqlite3MemInit(void *NotUsed){
12008   return SQLITE_OK;
12009 }
12010
12011 /*
12012 ** Deinitialize this module.
12013 */
12014 static void sqlite3MemShutdown(void *NotUsed){
12015   return;
12016 }
12017
12018 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetDefault(void){
12019   static const sqlite3_mem_methods defaultMethods = {
12020      sqlite3MemMalloc,
12021      sqlite3MemFree,
12022      sqlite3MemRealloc,
12023      sqlite3MemSize,
12024      sqlite3MemRoundup,
12025      sqlite3MemInit,
12026      sqlite3MemShutdown,
12027      0
12028   };
12029   return &defaultMethods;
12030 }
12031
12032 /*
12033 ** This routine is the only routine in this file with external linkage.
12034 **
12035 ** Populate the low-level memory allocation function pointers in
12036 ** sqlite3Config.m with pointers to the routines in this file.
12037 */
12038 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
12039   sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetDefault());
12040 }
12041
12042 #endif /* SQLITE_SYSTEM_MALLOC */
12043
12044 /************** End of mem1.c ************************************************/
12045 /************** Begin file mem2.c ********************************************/
12046 /*
12047 ** 2007 August 15
12048 **
12049 ** The author disclaims copyright to this source code.  In place of
12050 ** a legal notice, here is a blessing:
12051 **
12052 **    May you do good and not evil.
12053 **    May you find forgiveness for yourself and forgive others.
12054 **    May you share freely, never taking more than you give.
12055 **
12056 *************************************************************************
12057 **
12058 ** This file contains low-level memory allocation drivers for when
12059 ** SQLite will use the standard C-library malloc/realloc/free interface
12060 ** to obtain the memory it needs while adding lots of additional debugging
12061 ** information to each allocation in order to help detect and fix memory
12062 ** leaks and memory usage errors.
12063 **
12064 ** This file contains implementations of the low-level memory allocation
12065 ** routines specified in the sqlite3_mem_methods object.
12066 **
12067 ** $Id: mem2.c,v 1.37 2008/07/25 08:49:00 danielk1977 Exp $
12068 */
12069
12070 /*
12071 ** This version of the memory allocator is used only if the
12072 ** SQLITE_MEMDEBUG macro is defined
12073 */
12074 #ifdef SQLITE_MEMDEBUG
12075
12076 /*
12077 ** The backtrace functionality is only available with GLIBC
12078 */
12079 #ifdef __GLIBC__
12080   extern int backtrace(void**,int);
12081   extern void backtrace_symbols_fd(void*const*,int,int);
12082 #else
12083 # define backtrace(A,B) 0
12084 # define backtrace_symbols_fd(A,B,C)
12085 #endif
12086
12087 /*
12088 ** Each memory allocation looks like this:
12089 **
12090 **  ------------------------------------------------------------------------
12091 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
12092 **  ------------------------------------------------------------------------
12093 **
12094 ** The application code sees only a pointer to the allocation.  We have
12095 ** to back up from the allocation pointer to find the MemBlockHdr.  The
12096 ** MemBlockHdr tells us the size of the allocation and the number of
12097 ** backtrace pointers.  There is also a guard word at the end of the
12098 ** MemBlockHdr.
12099 */
12100 struct MemBlockHdr {
12101   i64 iSize;                          /* Size of this allocation */
12102   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
12103   char nBacktrace;                    /* Number of backtraces on this alloc */
12104   char nBacktraceSlots;               /* Available backtrace slots */
12105   short nTitle;                       /* Bytes of title; includes '\0' */
12106   int iForeGuard;                     /* Guard word for sanity */
12107 };
12108
12109 /*
12110 ** Guard words
12111 */
12112 #define FOREGUARD 0x80F5E153
12113 #define REARGUARD 0xE4676B53
12114
12115 /*
12116 ** Number of malloc size increments to track.
12117 */
12118 #define NCSIZE  1000
12119
12120 /*
12121 ** All of the static variables used by this module are collected
12122 ** into a single structure named "mem".  This is to keep the
12123 ** static variables organized and to reduce namespace pollution
12124 ** when this module is combined with other in the amalgamation.
12125 */
12126 static struct {
12127   
12128   /*
12129   ** Mutex to control access to the memory allocation subsystem.
12130   */
12131   sqlite3_mutex *mutex;
12132
12133   /*
12134   ** Head and tail of a linked list of all outstanding allocations
12135   */
12136   struct MemBlockHdr *pFirst;
12137   struct MemBlockHdr *pLast;
12138   
12139   /*
12140   ** The number of levels of backtrace to save in new allocations.
12141   */
12142   int nBacktrace;
12143   void (*xBacktrace)(int, int, void **);
12144
12145   /*
12146   ** Title text to insert in front of each block
12147   */
12148   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
12149   char zTitle[100];  /* The title text */
12150
12151   /* 
12152   ** sqlite3MallocDisallow() increments the following counter.
12153   ** sqlite3MallocAllow() decrements it.
12154   */
12155   int disallow; /* Do not allow memory allocation */
12156
12157   /*
12158   ** Gather statistics on the sizes of memory allocations.
12159   ** nAlloc[i] is the number of allocation attempts of i*8
12160   ** bytes.  i==NCSIZE is the number of allocation attempts for
12161   ** sizes more than NCSIZE*8 bytes.
12162   */
12163   int nAlloc[NCSIZE];      /* Total number of allocations */
12164   int nCurrent[NCSIZE];    /* Current number of allocations */
12165   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
12166
12167 } mem;
12168
12169
12170 /*
12171 ** Adjust memory usage statistics
12172 */
12173 static void adjustStats(int iSize, int increment){
12174   int i = ((iSize+7)&~7)/8;
12175   if( i>NCSIZE-1 ){
12176     i = NCSIZE - 1;
12177   }
12178   if( increment>0 ){
12179     mem.nAlloc[i]++;
12180     mem.nCurrent[i]++;
12181     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
12182       mem.mxCurrent[i] = mem.nCurrent[i];
12183     }
12184   }else{
12185     mem.nCurrent[i]--;
12186     assert( mem.nCurrent[i]>=0 );
12187   }
12188 }
12189
12190 /*
12191 ** Given an allocation, find the MemBlockHdr for that allocation.
12192 **
12193 ** This routine checks the guards at either end of the allocation and
12194 ** if they are incorrect it asserts.
12195 */
12196 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
12197   struct MemBlockHdr *p;
12198   int *pInt;
12199   u8 *pU8;
12200   int nReserve;
12201
12202   p = (struct MemBlockHdr*)pAllocation;
12203   p--;
12204   assert( p->iForeGuard==FOREGUARD );
12205   nReserve = (p->iSize+7)&~7;
12206   pInt = (int*)pAllocation;
12207   pU8 = (u8*)pAllocation;
12208   assert( pInt[nReserve/sizeof(int)]==REARGUARD );
12209   assert( (nReserve-0)<=p->iSize || pU8[nReserve-1]==0x65 );
12210   assert( (nReserve-1)<=p->iSize || pU8[nReserve-2]==0x65 );
12211   assert( (nReserve-2)<=p->iSize || pU8[nReserve-3]==0x65 );
12212   return p;
12213 }
12214
12215 /*
12216 ** Return the number of bytes currently allocated at address p.
12217 */
12218 static int sqlite3MemSize(void *p){
12219   struct MemBlockHdr *pHdr;
12220   if( !p ){
12221     return 0;
12222   }
12223   pHdr = sqlite3MemsysGetHeader(p);
12224   return pHdr->iSize;
12225 }
12226
12227 /*
12228 ** Initialize the memory allocation subsystem.
12229 */
12230 static int sqlite3MemInit(void *NotUsed){
12231   if( !sqlite3Config.bMemstat ){
12232     /* If memory status is enabled, then the malloc.c wrapper will already
12233     ** hold the STATIC_MEM mutex when the routines here are invoked. */
12234     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
12235   }
12236   return SQLITE_OK;
12237 }
12238
12239 /*
12240 ** Deinitialize the memory allocation subsystem.
12241 */
12242 static void sqlite3MemShutdown(void *NotUsed){
12243   mem.mutex = 0;
12244 }
12245
12246 /*
12247 ** Round up a request size to the next valid allocation size.
12248 */
12249 static int sqlite3MemRoundup(int n){
12250   return (n+7) & ~7;
12251 }
12252
12253 /*
12254 ** Allocate nByte bytes of memory.
12255 */
12256 static void *sqlite3MemMalloc(int nByte){
12257   struct MemBlockHdr *pHdr;
12258   void **pBt;
12259   char *z;
12260   int *pInt;
12261   void *p = 0;
12262   int totalSize;
12263   int nReserve;
12264   sqlite3_mutex_enter(mem.mutex);
12265   assert( mem.disallow==0 );
12266   nReserve = (nByte+7)&~7;
12267   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
12268                mem.nBacktrace*sizeof(void*) + mem.nTitle;
12269   p = malloc(totalSize);
12270   if( p ){
12271     z = p;
12272     pBt = (void**)&z[mem.nTitle];
12273     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
12274     pHdr->pNext = 0;
12275     pHdr->pPrev = mem.pLast;
12276     if( mem.pLast ){
12277       mem.pLast->pNext = pHdr;
12278     }else{
12279       mem.pFirst = pHdr;
12280     }
12281     mem.pLast = pHdr;
12282     pHdr->iForeGuard = FOREGUARD;
12283     pHdr->nBacktraceSlots = mem.nBacktrace;
12284     pHdr->nTitle = mem.nTitle;
12285     if( mem.nBacktrace ){
12286       void *aAddr[40];
12287       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
12288       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
12289       if( mem.xBacktrace ){
12290         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
12291       }
12292     }else{
12293       pHdr->nBacktrace = 0;
12294     }
12295     if( mem.nTitle ){
12296       memcpy(z, mem.zTitle, mem.nTitle);
12297     }
12298     pHdr->iSize = nByte;
12299     adjustStats(nByte, +1);
12300     pInt = (int*)&pHdr[1];
12301     pInt[nReserve/sizeof(int)] = REARGUARD;
12302     memset(pInt, 0x65, nReserve);
12303     p = (void*)pInt;
12304   }
12305   sqlite3_mutex_leave(mem.mutex);
12306   return p; 
12307 }
12308
12309 /*
12310 ** Free memory.
12311 */
12312 static void sqlite3MemFree(void *pPrior){
12313   struct MemBlockHdr *pHdr;
12314   void **pBt;
12315   char *z;
12316   assert( sqlite3Config.bMemstat || mem.mutex!=0 );
12317   pHdr = sqlite3MemsysGetHeader(pPrior);
12318   pBt = (void**)pHdr;
12319   pBt -= pHdr->nBacktraceSlots;
12320   sqlite3_mutex_enter(mem.mutex);
12321   if( pHdr->pPrev ){
12322     assert( pHdr->pPrev->pNext==pHdr );
12323     pHdr->pPrev->pNext = pHdr->pNext;
12324   }else{
12325     assert( mem.pFirst==pHdr );
12326     mem.pFirst = pHdr->pNext;
12327   }
12328   if( pHdr->pNext ){
12329     assert( pHdr->pNext->pPrev==pHdr );
12330     pHdr->pNext->pPrev = pHdr->pPrev;
12331   }else{
12332     assert( mem.pLast==pHdr );
12333     mem.pLast = pHdr->pPrev;
12334   }
12335   z = (char*)pBt;
12336   z -= pHdr->nTitle;
12337   adjustStats(pHdr->iSize, -1);
12338   memset(z, 0x2b, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
12339                   pHdr->iSize + sizeof(int) + pHdr->nTitle);
12340   free(z);
12341   sqlite3_mutex_leave(mem.mutex);  
12342 }
12343
12344 /*
12345 ** Change the size of an existing memory allocation.
12346 **
12347 ** For this debugging implementation, we *always* make a copy of the
12348 ** allocation into a new place in memory.  In this way, if the 
12349 ** higher level code is using pointer to the old allocation, it is 
12350 ** much more likely to break and we are much more liking to find
12351 ** the error.
12352 */
12353 static void *sqlite3MemRealloc(void *pPrior, int nByte){
12354   struct MemBlockHdr *pOldHdr;
12355   void *pNew;
12356   assert( mem.disallow==0 );
12357   pOldHdr = sqlite3MemsysGetHeader(pPrior);
12358   pNew = sqlite3MemMalloc(nByte);
12359   if( pNew ){
12360     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
12361     if( nByte>pOldHdr->iSize ){
12362       memset(&((char*)pNew)[pOldHdr->iSize], 0x2b, nByte - pOldHdr->iSize);
12363     }
12364     sqlite3MemFree(pPrior);
12365   }
12366   return pNew;
12367 }
12368
12369
12370 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetDefault(void){
12371   static const sqlite3_mem_methods defaultMethods = {
12372      sqlite3MemMalloc,
12373      sqlite3MemFree,
12374      sqlite3MemRealloc,
12375      sqlite3MemSize,
12376      sqlite3MemRoundup,
12377      sqlite3MemInit,
12378      sqlite3MemShutdown,
12379      0
12380   };
12381   return &defaultMethods;
12382 }
12383
12384 /*
12385 ** Populate the low-level memory allocation function pointers in
12386 ** sqlite3Config.m with pointers to the routines in this file.
12387 */
12388 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
12389   sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetDefault());
12390 }
12391
12392 /*
12393 ** Set the number of backtrace levels kept for each allocation.
12394 ** A value of zero turns off backtracing.  The number is always rounded
12395 ** up to a multiple of 2.
12396 */
12397 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
12398   if( depth<0 ){ depth = 0; }
12399   if( depth>20 ){ depth = 20; }
12400   depth = (depth+1)&0xfe;
12401   mem.nBacktrace = depth;
12402 }
12403
12404 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
12405   mem.xBacktrace = xBacktrace;
12406 }
12407
12408 /*
12409 ** Set the title string for subsequent allocations.
12410 */
12411 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
12412   int n = strlen(zTitle) + 1;
12413   sqlite3_mutex_enter(mem.mutex);
12414   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
12415   memcpy(mem.zTitle, zTitle, n);
12416   mem.zTitle[n] = 0;
12417   mem.nTitle = (n+7)&~7;
12418   sqlite3_mutex_leave(mem.mutex);
12419 }
12420
12421 SQLITE_PRIVATE void sqlite3MemdebugSync(){
12422   struct MemBlockHdr *pHdr;
12423   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
12424     void **pBt = (void**)pHdr;
12425     pBt -= pHdr->nBacktraceSlots;
12426     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
12427   }
12428 }
12429
12430 /*
12431 ** Open the file indicated and write a log of all unfreed memory 
12432 ** allocations into that log.
12433 */
12434 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
12435   FILE *out;
12436   struct MemBlockHdr *pHdr;
12437   void **pBt;
12438   int i;
12439   out = fopen(zFilename, "w");
12440   if( out==0 ){
12441     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
12442                     zFilename);
12443     return;
12444   }
12445   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
12446     char *z = (char*)pHdr;
12447     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
12448     fprintf(out, "**** %lld bytes at %p from %s ****\n", 
12449             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
12450     if( pHdr->nBacktrace ){
12451       fflush(out);
12452       pBt = (void**)pHdr;
12453       pBt -= pHdr->nBacktraceSlots;
12454       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
12455       fprintf(out, "\n");
12456     }
12457   }
12458   fprintf(out, "COUNTS:\n");
12459   for(i=0; i<NCSIZE-1; i++){
12460     if( mem.nAlloc[i] ){
12461       fprintf(out, "   %5d: %10d %10d %10d\n", 
12462             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
12463     }
12464   }
12465   if( mem.nAlloc[NCSIZE-1] ){
12466     fprintf(out, "   %5d: %10d %10d %10d\n",
12467              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
12468              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
12469   }
12470   fclose(out);
12471 }
12472
12473 /*
12474 ** Return the number of times sqlite3MemMalloc() has been called.
12475 */
12476 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
12477   int i;
12478   int nTotal = 0;
12479   for(i=0; i<NCSIZE; i++){
12480     nTotal += mem.nAlloc[i];
12481   }
12482   return nTotal;
12483 }
12484
12485
12486 #endif /* SQLITE_MEMDEBUG */
12487
12488 /************** End of mem2.c ************************************************/
12489 /************** Begin file mem3.c ********************************************/
12490 /*
12491 ** 2007 October 14
12492 **
12493 ** The author disclaims copyright to this source code.  In place of
12494 ** a legal notice, here is a blessing:
12495 **
12496 **    May you do good and not evil.
12497 **    May you find forgiveness for yourself and forgive others.
12498 **    May you share freely, never taking more than you give.
12499 **
12500 *************************************************************************
12501 ** This file contains the C functions that implement a memory
12502 ** allocation subsystem for use by SQLite. 
12503 **
12504 ** This version of the memory allocation subsystem omits all
12505 ** use of malloc(). The SQLite user supplies a block of memory
12506 ** before calling sqlite3_initialize() from which allocations
12507 ** are made and returned by the xMalloc() and xRealloc() 
12508 ** implementations. Once sqlite3_initialize() has been called,
12509 ** the amount of memory available to SQLite is fixed and cannot
12510 ** be changed.
12511 **
12512 ** This version of the memory allocation subsystem is included
12513 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
12514 **
12515 ** $Id: mem3.c,v 1.20 2008/07/18 18:56:17 drh Exp $
12516 */
12517
12518 /*
12519 ** This version of the memory allocator is only built into the library
12520 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
12521 ** mean that the library will use a memory-pool by default, just that
12522 ** it is available. The mempool allocator is activated by calling
12523 ** sqlite3_config().
12524 */
12525 #ifdef SQLITE_ENABLE_MEMSYS3
12526
12527 /*
12528 ** Maximum size (in Mem3Blocks) of a "small" chunk.
12529 */
12530 #define MX_SMALL 10
12531
12532
12533 /*
12534 ** Number of freelist hash slots
12535 */
12536 #define N_HASH  61
12537
12538 /*
12539 ** A memory allocation (also called a "chunk") consists of two or 
12540 ** more blocks where each block is 8 bytes.  The first 8 bytes are 
12541 ** a header that is not returned to the user.
12542 **
12543 ** A chunk is two or more blocks that is either checked out or
12544 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
12545 ** size of the allocation in blocks if the allocation is free.
12546 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
12547 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
12548 ** is true if the previous chunk is checked out and false if the
12549 ** previous chunk is free.  The u.hdr.prevSize field is the size of
12550 ** the previous chunk in blocks if the previous chunk is on the
12551 ** freelist. If the previous chunk is checked out, then
12552 ** u.hdr.prevSize can be part of the data for that chunk and should
12553 ** not be read or written.
12554 **
12555 ** We often identify a chunk by its index in mem3.aPool[].  When
12556 ** this is done, the chunk index refers to the second block of
12557 ** the chunk.  In this way, the first chunk has an index of 1.
12558 ** A chunk index of 0 means "no such chunk" and is the equivalent
12559 ** of a NULL pointer.
12560 **
12561 ** The second block of free chunks is of the form u.list.  The
12562 ** two fields form a double-linked list of chunks of related sizes.
12563 ** Pointers to the head of the list are stored in mem3.aiSmall[] 
12564 ** for smaller chunks and mem3.aiHash[] for larger chunks.
12565 **
12566 ** The second block of a chunk is user data if the chunk is checked 
12567 ** out.  If a chunk is checked out, the user data may extend into
12568 ** the u.hdr.prevSize value of the following chunk.
12569 */
12570 typedef struct Mem3Block Mem3Block;
12571 struct Mem3Block {
12572   union {
12573     struct {
12574       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
12575       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
12576     } hdr;
12577     struct {
12578       u32 next;       /* Index in mem3.aPool[] of next free chunk */
12579       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
12580     } list;
12581   } u;
12582 };
12583
12584 /*
12585 ** All of the static variables used by this module are collected
12586 ** into a single structure named "mem3".  This is to keep the
12587 ** static variables organized and to reduce namespace pollution
12588 ** when this module is combined with other in the amalgamation.
12589 */
12590 static struct {
12591   /*
12592   ** True if we are evaluating an out-of-memory callback.
12593   */
12594   int alarmBusy;
12595   
12596   /*
12597   ** Mutex to control access to the memory allocation subsystem.
12598   */
12599   sqlite3_mutex *mutex;
12600   
12601   /*
12602   ** The minimum amount of free space that we have seen.
12603   */
12604   u32 mnMaster;
12605
12606   /*
12607   ** iMaster is the index of the master chunk.  Most new allocations
12608   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
12609   ** of the current master.  iMaster is 0 if there is not master chunk.
12610   ** The master chunk is not in either the aiHash[] or aiSmall[].
12611   */
12612   u32 iMaster;
12613   u32 szMaster;
12614
12615   /*
12616   ** Array of lists of free blocks according to the block size 
12617   ** for smaller chunks, or a hash on the block size for larger
12618   ** chunks.
12619   */
12620   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
12621   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
12622
12623   /*
12624   ** Memory available for allocation. nPool is the size of the array
12625   ** (in Mem3Blocks) pointed to by aPool less 2.
12626   */
12627   u32 nPool;
12628   Mem3Block *aPool;
12629 } mem3;
12630
12631 /*
12632 ** Unlink the chunk at mem3.aPool[i] from list it is currently
12633 ** on.  *pRoot is the list that i is a member of.
12634 */
12635 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
12636   u32 next = mem3.aPool[i].u.list.next;
12637   u32 prev = mem3.aPool[i].u.list.prev;
12638   assert( sqlite3_mutex_held(mem3.mutex) );
12639   if( prev==0 ){
12640     *pRoot = next;
12641   }else{
12642     mem3.aPool[prev].u.list.next = next;
12643   }
12644   if( next ){
12645     mem3.aPool[next].u.list.prev = prev;
12646   }
12647   mem3.aPool[i].u.list.next = 0;
12648   mem3.aPool[i].u.list.prev = 0;
12649 }
12650
12651 /*
12652 ** Unlink the chunk at index i from 
12653 ** whatever list is currently a member of.
12654 */
12655 static void memsys3Unlink(u32 i){
12656   u32 size, hash;
12657   assert( sqlite3_mutex_held(mem3.mutex) );
12658   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
12659   assert( i>=1 );
12660   size = mem3.aPool[i-1].u.hdr.size4x/4;
12661   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
12662   assert( size>=2 );
12663   if( size <= MX_SMALL ){
12664     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
12665   }else{
12666     hash = size % N_HASH;
12667     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
12668   }
12669 }
12670
12671 /*
12672 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
12673 ** at *pRoot.
12674 */
12675 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
12676   assert( sqlite3_mutex_held(mem3.mutex) );
12677   mem3.aPool[i].u.list.next = *pRoot;
12678   mem3.aPool[i].u.list.prev = 0;
12679   if( *pRoot ){
12680     mem3.aPool[*pRoot].u.list.prev = i;
12681   }
12682   *pRoot = i;
12683 }
12684
12685 /*
12686 ** Link the chunk at index i into either the appropriate
12687 ** small chunk list, or into the large chunk hash table.
12688 */
12689 static void memsys3Link(u32 i){
12690   u32 size, hash;
12691   assert( sqlite3_mutex_held(mem3.mutex) );
12692   assert( i>=1 );
12693   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
12694   size = mem3.aPool[i-1].u.hdr.size4x/4;
12695   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
12696   assert( size>=2 );
12697   if( size <= MX_SMALL ){
12698     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
12699   }else{
12700     hash = size % N_HASH;
12701     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
12702   }
12703 }
12704
12705 /*
12706 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
12707 ** will already be held (obtained by code in malloc.c) if
12708 ** sqlite3Config.bMemStat is true.
12709 */
12710 static void memsys3Enter(void){
12711   if( sqlite3Config.bMemstat==0 && mem3.mutex==0 ){
12712     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
12713   }
12714   sqlite3_mutex_enter(mem3.mutex);
12715 }
12716 static void memsys3Leave(void){
12717   sqlite3_mutex_leave(mem3.mutex);
12718 }
12719
12720 /*
12721 ** Called when we are unable to satisfy an allocation of nBytes.
12722 */
12723 static void memsys3OutOfMemory(int nByte){
12724   if( !mem3.alarmBusy ){
12725     mem3.alarmBusy = 1;
12726     assert( sqlite3_mutex_held(mem3.mutex) );
12727     sqlite3_mutex_leave(mem3.mutex);
12728     sqlite3_release_memory(nByte);
12729     sqlite3_mutex_enter(mem3.mutex);
12730     mem3.alarmBusy = 0;
12731   }
12732 }
12733
12734
12735 /*
12736 ** Chunk i is a free chunk that has been unlinked.  Adjust its 
12737 ** size parameters for check-out and return a pointer to the 
12738 ** user portion of the chunk.
12739 */
12740 static void *memsys3Checkout(u32 i, int nBlock){
12741   u32 x;
12742   assert( sqlite3_mutex_held(mem3.mutex) );
12743   assert( i>=1 );
12744   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
12745   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
12746   x = mem3.aPool[i-1].u.hdr.size4x;
12747   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
12748   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
12749   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
12750   return &mem3.aPool[i];
12751 }
12752
12753 /*
12754 ** Carve a piece off of the end of the mem3.iMaster free chunk.
12755 ** Return a pointer to the new allocation.  Or, if the master chunk
12756 ** is not large enough, return 0.
12757 */
12758 static void *memsys3FromMaster(int nBlock){
12759   assert( sqlite3_mutex_held(mem3.mutex) );
12760   assert( mem3.szMaster>=nBlock );
12761   if( nBlock>=mem3.szMaster-1 ){
12762     /* Use the entire master */
12763     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
12764     mem3.iMaster = 0;
12765     mem3.szMaster = 0;
12766     mem3.mnMaster = 0;
12767     return p;
12768   }else{
12769     /* Split the master block.  Return the tail. */
12770     u32 newi, x;
12771     newi = mem3.iMaster + mem3.szMaster - nBlock;
12772     assert( newi > mem3.iMaster+1 );
12773     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
12774     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
12775     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
12776     mem3.szMaster -= nBlock;
12777     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
12778     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
12779     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
12780     if( mem3.szMaster < mem3.mnMaster ){
12781       mem3.mnMaster = mem3.szMaster;
12782     }
12783     return (void*)&mem3.aPool[newi];
12784   }
12785 }
12786
12787 /*
12788 ** *pRoot is the head of a list of free chunks of the same size
12789 ** or same size hash.  In other words, *pRoot is an entry in either
12790 ** mem3.aiSmall[] or mem3.aiHash[].  
12791 **
12792 ** This routine examines all entries on the given list and tries
12793 ** to coalesce each entries with adjacent free chunks.  
12794 **
12795 ** If it sees a chunk that is larger than mem3.iMaster, it replaces 
12796 ** the current mem3.iMaster with the new larger chunk.  In order for
12797 ** this mem3.iMaster replacement to work, the master chunk must be
12798 ** linked into the hash tables.  That is not the normal state of
12799 ** affairs, of course.  The calling routine must link the master
12800 ** chunk before invoking this routine, then must unlink the (possibly
12801 ** changed) master chunk once this routine has finished.
12802 */
12803 static void memsys3Merge(u32 *pRoot){
12804   u32 iNext, prev, size, i, x;
12805
12806   assert( sqlite3_mutex_held(mem3.mutex) );
12807   for(i=*pRoot; i>0; i=iNext){
12808     iNext = mem3.aPool[i].u.list.next;
12809     size = mem3.aPool[i-1].u.hdr.size4x;
12810     assert( (size&1)==0 );
12811     if( (size&2)==0 ){
12812       memsys3UnlinkFromList(i, pRoot);
12813       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
12814       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
12815       if( prev==iNext ){
12816         iNext = mem3.aPool[prev].u.list.next;
12817       }
12818       memsys3Unlink(prev);
12819       size = i + size/4 - prev;
12820       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
12821       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
12822       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
12823       memsys3Link(prev);
12824       i = prev;
12825     }else{
12826       size /= 4;
12827     }
12828     if( size>mem3.szMaster ){
12829       mem3.iMaster = i;
12830       mem3.szMaster = size;
12831     }
12832   }
12833 }
12834
12835 /*
12836 ** Return a block of memory of at least nBytes in size.
12837 ** Return NULL if unable.
12838 **
12839 ** This function assumes that the necessary mutexes, if any, are
12840 ** already held by the caller. Hence "Unsafe".
12841 */
12842 static void *memsys3MallocUnsafe(int nByte){
12843   u32 i;
12844   int nBlock;
12845   int toFree;
12846
12847   assert( sqlite3_mutex_held(mem3.mutex) );
12848   assert( sizeof(Mem3Block)==8 );
12849   if( nByte<=12 ){
12850     nBlock = 2;
12851   }else{
12852     nBlock = (nByte + 11)/8;
12853   }
12854   assert( nBlock>=2 );
12855
12856   /* STEP 1:
12857   ** Look for an entry of the correct size in either the small
12858   ** chunk table or in the large chunk hash table.  This is
12859   ** successful most of the time (about 9 times out of 10).
12860   */
12861   if( nBlock <= MX_SMALL ){
12862     i = mem3.aiSmall[nBlock-2];
12863     if( i>0 ){
12864       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
12865       return memsys3Checkout(i, nBlock);
12866     }
12867   }else{
12868     int hash = nBlock % N_HASH;
12869     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
12870       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
12871         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
12872         return memsys3Checkout(i, nBlock);
12873       }
12874     }
12875   }
12876
12877   /* STEP 2:
12878   ** Try to satisfy the allocation by carving a piece off of the end
12879   ** of the master chunk.  This step usually works if step 1 fails.
12880   */
12881   if( mem3.szMaster>=nBlock ){
12882     return memsys3FromMaster(nBlock);
12883   }
12884
12885
12886   /* STEP 3:  
12887   ** Loop through the entire memory pool.  Coalesce adjacent free
12888   ** chunks.  Recompute the master chunk as the largest free chunk.
12889   ** Then try again to satisfy the allocation by carving a piece off
12890   ** of the end of the master chunk.  This step happens very
12891   ** rarely (we hope!)
12892   */
12893   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
12894     memsys3OutOfMemory(toFree);
12895     if( mem3.iMaster ){
12896       memsys3Link(mem3.iMaster);
12897       mem3.iMaster = 0;
12898       mem3.szMaster = 0;
12899     }
12900     for(i=0; i<N_HASH; i++){
12901       memsys3Merge(&mem3.aiHash[i]);
12902     }
12903     for(i=0; i<MX_SMALL-1; i++){
12904       memsys3Merge(&mem3.aiSmall[i]);
12905     }
12906     if( mem3.szMaster ){
12907       memsys3Unlink(mem3.iMaster);
12908       if( mem3.szMaster>=nBlock ){
12909         return memsys3FromMaster(nBlock);
12910       }
12911     }
12912   }
12913
12914   /* If none of the above worked, then we fail. */
12915   return 0;
12916 }
12917
12918 /*
12919 ** Free an outstanding memory allocation.
12920 **
12921 ** This function assumes that the necessary mutexes, if any, are
12922 ** already held by the caller. Hence "Unsafe".
12923 */
12924 void memsys3FreeUnsafe(void *pOld){
12925   Mem3Block *p = (Mem3Block*)pOld;
12926   int i;
12927   u32 size, x;
12928   assert( sqlite3_mutex_held(mem3.mutex) );
12929   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
12930   i = p - mem3.aPool;
12931   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
12932   size = mem3.aPool[i-1].u.hdr.size4x/4;
12933   assert( i+size<=mem3.nPool+1 );
12934   mem3.aPool[i-1].u.hdr.size4x &= ~1;
12935   mem3.aPool[i+size-1].u.hdr.prevSize = size;
12936   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
12937   memsys3Link(i);
12938
12939   /* Try to expand the master using the newly freed chunk */
12940   if( mem3.iMaster ){
12941     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
12942       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
12943       mem3.iMaster -= size;
12944       mem3.szMaster += size;
12945       memsys3Unlink(mem3.iMaster);
12946       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
12947       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
12948       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
12949     }
12950     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
12951     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
12952       memsys3Unlink(mem3.iMaster+mem3.szMaster);
12953       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
12954       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
12955       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
12956     }
12957   }
12958 }
12959
12960 /*
12961 ** Return the size of an outstanding allocation, in bytes.  The
12962 ** size returned omits the 8-byte header overhead.  This only
12963 ** works for chunks that are currently checked out.
12964 */
12965 static int memsys3Size(void *p){
12966   Mem3Block *pBlock;
12967   if( p==0 ) return 0;
12968   pBlock = (Mem3Block*)p;
12969   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
12970   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
12971 }
12972
12973 /*
12974 ** Round up a request size to the next valid allocation size.
12975 */
12976 static int memsys3Roundup(int n){
12977   if( n<=12 ){
12978     return 12;
12979   }else{
12980     return ((n+11)&~7) - 4;
12981   }
12982 }
12983
12984 /*
12985 ** Allocate nBytes of memory.
12986 */
12987 static void *memsys3Malloc(int nBytes){
12988   sqlite3_int64 *p;
12989   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
12990   memsys3Enter();
12991   p = memsys3MallocUnsafe(nBytes);
12992   memsys3Leave();
12993   return (void*)p; 
12994 }
12995
12996 /*
12997 ** Free memory.
12998 */
12999 void memsys3Free(void *pPrior){
13000   assert( pPrior );
13001   memsys3Enter();
13002   memsys3FreeUnsafe(pPrior);
13003   memsys3Leave();
13004 }
13005
13006 /*
13007 ** Change the size of an existing memory allocation
13008 */
13009 void *memsys3Realloc(void *pPrior, int nBytes){
13010   int nOld;
13011   void *p;
13012   if( pPrior==0 ){
13013     return sqlite3_malloc(nBytes);
13014   }
13015   if( nBytes<=0 ){
13016     sqlite3_free(pPrior);
13017     return 0;
13018   }
13019   nOld = memsys3Size(pPrior);
13020   if( nBytes<=nOld && nBytes>=nOld-128 ){
13021     return pPrior;
13022   }
13023   memsys3Enter();
13024   p = memsys3MallocUnsafe(nBytes);
13025   if( p ){
13026     if( nOld<nBytes ){
13027       memcpy(p, pPrior, nOld);
13028     }else{
13029       memcpy(p, pPrior, nBytes);
13030     }
13031     memsys3FreeUnsafe(pPrior);
13032   }
13033   memsys3Leave();
13034   return p;
13035 }
13036
13037 /*
13038 ** Initialize this module.
13039 */
13040 static int memsys3Init(void *NotUsed){
13041   if( !sqlite3Config.pHeap ){
13042     return SQLITE_ERROR;
13043   }
13044
13045   /* Store a pointer to the memory block in global structure mem3. */
13046   assert( sizeof(Mem3Block)==8 );
13047   mem3.aPool = (Mem3Block *)sqlite3Config.pHeap;
13048   mem3.nPool = (sqlite3Config.nHeap / sizeof(Mem3Block)) - 2;
13049
13050   /* Initialize the master block. */
13051   mem3.szMaster = mem3.nPool;
13052   mem3.mnMaster = mem3.szMaster;
13053   mem3.iMaster = 1;
13054   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
13055   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
13056   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
13057
13058   return SQLITE_OK;
13059 }
13060
13061 /*
13062 ** Deinitialize this module.
13063 */
13064 static void memsys3Shutdown(void *NotUsed){
13065   return;
13066 }
13067
13068
13069
13070 /*
13071 ** Open the file indicated and write a log of all unfreed memory 
13072 ** allocations into that log.
13073 */
13074 #ifdef SQLITE_DEBUG
13075 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
13076   FILE *out;
13077   int i, j;
13078   u32 size;
13079   if( zFilename==0 || zFilename[0]==0 ){
13080     out = stdout;
13081   }else{
13082     out = fopen(zFilename, "w");
13083     if( out==0 ){
13084       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
13085                       zFilename);
13086       return;
13087     }
13088   }
13089   memsys3Enter();
13090   fprintf(out, "CHUNKS:\n");
13091   for(i=1; i<=mem3.nPool; i+=size/4){
13092     size = mem3.aPool[i-1].u.hdr.size4x;
13093     if( size/4<=1 ){
13094       fprintf(out, "%p size error\n", &mem3.aPool[i]);
13095       assert( 0 );
13096       break;
13097     }
13098     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
13099       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
13100       assert( 0 );
13101       break;
13102     }
13103     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
13104       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
13105       assert( 0 );
13106       break;
13107     }
13108     if( size&1 ){
13109       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
13110     }else{
13111       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
13112                   i==mem3.iMaster ? " **master**" : "");
13113     }
13114   }
13115   for(i=0; i<MX_SMALL-1; i++){
13116     if( mem3.aiSmall[i]==0 ) continue;
13117     fprintf(out, "small(%2d):", i);
13118     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
13119       fprintf(out, " %p(%d)", &mem3.aPool[j],
13120               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
13121     }
13122     fprintf(out, "\n"); 
13123   }
13124   for(i=0; i<N_HASH; i++){
13125     if( mem3.aiHash[i]==0 ) continue;
13126     fprintf(out, "hash(%2d):", i);
13127     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
13128       fprintf(out, " %p(%d)", &mem3.aPool[j],
13129               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
13130     }
13131     fprintf(out, "\n"); 
13132   }
13133   fprintf(out, "master=%d\n", mem3.iMaster);
13134   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
13135   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
13136   sqlite3_mutex_leave(mem3.mutex);
13137   if( out==stdout ){
13138     fflush(stdout);
13139   }else{
13140     fclose(out);
13141   }
13142 }
13143 #endif
13144
13145 /*
13146 ** This routine is the only routine in this file with external 
13147 ** linkage.
13148 **
13149 ** Populate the low-level memory allocation function pointers in
13150 ** sqlite3Config.m with pointers to the routines in this file. The
13151 ** arguments specify the block of memory to manage.
13152 **
13153 ** This routine is only called by sqlite3_config(), and therefore
13154 ** is not required to be threadsafe (it is not).
13155 */
13156 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
13157   static const sqlite3_mem_methods mempoolMethods = {
13158      memsys3Malloc,
13159      memsys3Free,
13160      memsys3Realloc,
13161      memsys3Size,
13162      memsys3Roundup,
13163      memsys3Init,
13164      memsys3Shutdown,
13165      0
13166   };
13167   return &mempoolMethods;
13168 }
13169
13170 #endif /* SQLITE_ENABLE_MEMSYS3 */
13171
13172 /************** End of mem3.c ************************************************/
13173 /************** Begin file mem5.c ********************************************/
13174 /*
13175 ** 2007 October 14
13176 **
13177 ** The author disclaims copyright to this source code.  In place of
13178 ** a legal notice, here is a blessing:
13179 **
13180 **    May you do good and not evil.
13181 **    May you find forgiveness for yourself and forgive others.
13182 **    May you share freely, never taking more than you give.
13183 **
13184 *************************************************************************
13185 ** This file contains the C functions that implement a memory
13186 ** allocation subsystem for use by SQLite. 
13187 **
13188 ** This version of the memory allocation subsystem omits all
13189 ** use of malloc(). The SQLite user supplies a block of memory
13190 ** before calling sqlite3_initialize() from which allocations
13191 ** are made and returned by the xMalloc() and xRealloc() 
13192 ** implementations. Once sqlite3_initialize() has been called,
13193 ** the amount of memory available to SQLite is fixed and cannot
13194 ** be changed.
13195 **
13196 ** This version of the memory allocation subsystem is included
13197 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
13198 **
13199 ** $Id: mem5.c,v 1.11 2008/07/16 12:25:32 drh Exp $
13200 */
13201
13202 /*
13203 ** This version of the memory allocator is used only when 
13204 ** SQLITE_POW2_MEMORY_SIZE is defined.
13205 */
13206 #ifdef SQLITE_ENABLE_MEMSYS5
13207
13208 /*
13209 ** Log2 of the minimum size of an allocation.  For example, if
13210 ** 4 then all allocations will be rounded up to at least 16 bytes.
13211 ** If 5 then all allocations will be rounded up to at least 32 bytes.
13212 */
13213 #ifndef SQLITE_POW2_LOGMIN
13214 # define SQLITE_POW2_LOGMIN 6
13215 #endif
13216
13217 /*
13218 ** Log2 of the maximum size of an allocation.
13219 */
13220 #ifndef SQLITE_POW2_LOGMAX
13221 # define SQLITE_POW2_LOGMAX 20
13222 #endif
13223 #define POW2_MAX (((unsigned int)1)<<SQLITE_POW2_LOGMAX)
13224
13225 /*
13226 ** Number of distinct allocation sizes.
13227 */
13228 #define NSIZE (SQLITE_POW2_LOGMAX - SQLITE_POW2_LOGMIN + 1)
13229
13230 /*
13231 ** A minimum allocation is an instance of the following structure.
13232 ** Larger allocations are an array of these structures where the
13233 ** size of the array is a power of 2.
13234 */
13235 typedef struct Mem5Link Mem5Link;
13236 struct Mem5Link {
13237   int next;       /* Index of next free chunk */
13238   int prev;       /* Index of previous free chunk */
13239 };
13240
13241 /*
13242 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.nAtom). Since
13243 ** mem5.nAtom is always at least 8, this is not really a practical
13244 ** limitation.
13245 */
13246 #define LOGMAX 30
13247
13248 /*
13249 ** Masks used for mem5.aCtrl[] elements.
13250 */
13251 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block relative to POW2_MIN */
13252 #define CTRL_FREE     0x20    /* True if not checked out */
13253
13254 /*
13255 ** All of the static variables used by this module are collected
13256 ** into a single structure named "mem5".  This is to keep the
13257 ** static variables organized and to reduce namespace pollution
13258 ** when this module is combined with other in the amalgamation.
13259 */
13260 static struct {
13261   /*
13262   ** The alarm callback and its arguments.  The mem5.mutex lock will
13263   ** be held while the callback is running.  Recursive calls into
13264   ** the memory subsystem are allowed, but no new callbacks will be
13265   ** issued.  The alarmBusy variable is set to prevent recursive
13266   ** callbacks.
13267   */
13268   sqlite3_int64 alarmThreshold;
13269   void (*alarmCallback)(void*, sqlite3_int64,int);
13270   void *alarmArg;
13271   int alarmBusy;
13272   
13273   /*
13274   ** Mutex to control access to the memory allocation subsystem.
13275   */
13276   sqlite3_mutex *mutex;
13277
13278   /*
13279   ** Performance statistics
13280   */
13281   u64 nAlloc;         /* Total number of calls to malloc */
13282   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
13283   u64 totalExcess;    /* Total internal fragmentation */
13284   u32 currentOut;     /* Current checkout, including internal fragmentation */
13285   u32 currentCount;   /* Current number of distinct checkouts */
13286   u32 maxOut;         /* Maximum instantaneous currentOut */
13287   u32 maxCount;       /* Maximum instantaneous currentCount */
13288   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
13289   
13290   /*
13291   ** Lists of free blocks of various sizes.
13292   */
13293   int aiFreelist[LOGMAX+1];
13294
13295   /*
13296   ** Space for tracking which blocks are checked out and the size
13297   ** of each block.  One byte per block.
13298   */
13299   u8 *aCtrl;
13300
13301   /*
13302   ** Memory available for allocation
13303   */
13304   int nAtom;       /* Smallest possible allocation in bytes */
13305   int nBlock;      /* Number of nAtom sized blocks in zPool */
13306   u8 *zPool;
13307 } mem5;
13308
13309 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.nAtom]))
13310
13311 /*
13312 ** Unlink the chunk at mem5.aPool[i] from list it is currently
13313 ** on.  It should be found on mem5.aiFreelist[iLogsize].
13314 */
13315 static void memsys5Unlink(int i, int iLogsize){
13316   int next, prev;
13317   assert( i>=0 && i<mem5.nBlock );
13318   assert( iLogsize>=0 && iLogsize<=LOGMAX );
13319   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
13320
13321   next = MEM5LINK(i)->next;
13322   prev = MEM5LINK(i)->prev;
13323   if( prev<0 ){
13324     mem5.aiFreelist[iLogsize] = next;
13325   }else{
13326     MEM5LINK(prev)->next = next;
13327   }
13328   if( next>=0 ){
13329     MEM5LINK(next)->prev = prev;
13330   }
13331 }
13332
13333 /*
13334 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
13335 ** free list.
13336 */
13337 static void memsys5Link(int i, int iLogsize){
13338   int x;
13339   assert( sqlite3_mutex_held(mem5.mutex) );
13340   assert( i>=0 && i<mem5.nBlock );
13341   assert( iLogsize>=0 && iLogsize<=LOGMAX );
13342   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
13343
13344   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
13345   MEM5LINK(i)->prev = -1;
13346   if( x>=0 ){
13347     assert( x<mem5.nBlock );
13348     MEM5LINK(x)->prev = i;
13349   }
13350   mem5.aiFreelist[iLogsize] = i;
13351 }
13352
13353 /*
13354 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
13355 ** will already be held (obtained by code in malloc.c) if
13356 ** sqlite3Config.bMemStat is true.
13357 */
13358 static void memsys5Enter(void){
13359   if( sqlite3Config.bMemstat==0 && mem5.mutex==0 ){
13360     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
13361   }
13362   sqlite3_mutex_enter(mem5.mutex);
13363 }
13364 static void memsys5Leave(void){
13365   sqlite3_mutex_leave(mem5.mutex);
13366 }
13367
13368 /*
13369 ** Return the size of an outstanding allocation, in bytes.  The
13370 ** size returned omits the 8-byte header overhead.  This only
13371 ** works for chunks that are currently checked out.
13372 */
13373 static int memsys5Size(void *p){
13374   int iSize = 0;
13375   if( p ){
13376     int i = ((u8 *)p-mem5.zPool)/mem5.nAtom;
13377     assert( i>=0 && i<mem5.nBlock );
13378     iSize = mem5.nAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
13379   }
13380   return iSize;
13381 }
13382
13383 /*
13384 ** Find the first entry on the freelist iLogsize.  Unlink that
13385 ** entry and return its index. 
13386 */
13387 static int memsys5UnlinkFirst(int iLogsize){
13388   int i;
13389   int iFirst;
13390
13391   assert( iLogsize>=0 && iLogsize<=LOGMAX );
13392   i = iFirst = mem5.aiFreelist[iLogsize];
13393   assert( iFirst>=0 );
13394   while( i>0 ){
13395     if( i<iFirst ) iFirst = i;
13396     i = MEM5LINK(i)->next;
13397   }
13398   memsys5Unlink(iFirst, iLogsize);
13399   return iFirst;
13400 }
13401
13402 /*
13403 ** Return a block of memory of at least nBytes in size.
13404 ** Return NULL if unable.
13405 */
13406 static void *memsys5MallocUnsafe(int nByte){
13407   int i;           /* Index of a mem5.aPool[] slot */
13408   int iBin;        /* Index into mem5.aiFreelist[] */
13409   int iFullSz;     /* Size of allocation rounded up to power of 2 */
13410   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
13411
13412   /* Keep track of the maximum allocation request.  Even unfulfilled
13413   ** requests are counted */
13414   if( nByte>mem5.maxRequest ){
13415     mem5.maxRequest = nByte;
13416   }
13417
13418   /* Round nByte up to the next valid power of two */
13419   if( nByte>POW2_MAX ) return 0;
13420   for(iFullSz=mem5.nAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
13421
13422   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
13423   ** block.  If not, then split a block of the next larger power of
13424   ** two in order to create a new free block of size iLogsize.
13425   */
13426   for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
13427   if( iBin>LOGMAX ) return 0;
13428   i = memsys5UnlinkFirst(iBin);
13429   while( iBin>iLogsize ){
13430     int newSize;
13431
13432     iBin--;
13433     newSize = 1 << iBin;
13434     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
13435     memsys5Link(i+newSize, iBin);
13436   }
13437   mem5.aCtrl[i] = iLogsize;
13438
13439   /* Update allocator performance statistics. */
13440   mem5.nAlloc++;
13441   mem5.totalAlloc += iFullSz;
13442   mem5.totalExcess += iFullSz - nByte;
13443   mem5.currentCount++;
13444   mem5.currentOut += iFullSz;
13445   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
13446   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
13447
13448   /* Return a pointer to the allocated memory. */
13449   return (void*)&mem5.zPool[i*mem5.nAtom];
13450 }
13451
13452 /*
13453 ** Free an outstanding memory allocation.
13454 */
13455 static void memsys5FreeUnsafe(void *pOld){
13456   u32 size, iLogsize;
13457   int iBlock;             
13458
13459   /* Set iBlock to the index of the block pointed to by pOld in 
13460   ** the array of mem5.nAtom byte blocks pointed to by mem5.zPool.
13461   */
13462   iBlock = ((u8 *)pOld-mem5.zPool)/mem5.nAtom;
13463
13464   /* Check that the pointer pOld points to a valid, non-free block. */
13465   assert( iBlock>=0 && iBlock<mem5.nBlock );
13466   assert( ((u8 *)pOld-mem5.zPool)%mem5.nAtom==0 );
13467   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
13468
13469   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
13470   size = 1<<iLogsize;
13471   assert( iBlock+size-1<mem5.nBlock );
13472
13473   mem5.aCtrl[iBlock] |= CTRL_FREE;
13474   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
13475   assert( mem5.currentCount>0 );
13476   assert( mem5.currentOut>=0 );
13477   mem5.currentCount--;
13478   mem5.currentOut -= size*mem5.nAtom;
13479   assert( mem5.currentOut>0 || mem5.currentCount==0 );
13480   assert( mem5.currentCount>0 || mem5.currentOut==0 );
13481
13482   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
13483   while( iLogsize<LOGMAX ){
13484     int iBuddy;
13485     if( (iBlock>>iLogsize) & 1 ){
13486       iBuddy = iBlock - size;
13487     }else{
13488       iBuddy = iBlock + size;
13489     }
13490     assert( iBuddy>=0 );
13491     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
13492     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
13493     memsys5Unlink(iBuddy, iLogsize);
13494     iLogsize++;
13495     if( iBuddy<iBlock ){
13496       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
13497       mem5.aCtrl[iBlock] = 0;
13498       iBlock = iBuddy;
13499     }else{
13500       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
13501       mem5.aCtrl[iBuddy] = 0;
13502     }
13503     size *= 2;
13504   }
13505   memsys5Link(iBlock, iLogsize);
13506 }
13507
13508 /*
13509 ** Allocate nBytes of memory
13510 */
13511 static void *memsys5Malloc(int nBytes){
13512   sqlite3_int64 *p = 0;
13513   if( nBytes>0 ){
13514     memsys5Enter();
13515     p = memsys5MallocUnsafe(nBytes);
13516     memsys5Leave();
13517   }
13518   return (void*)p; 
13519 }
13520
13521 /*
13522 ** Free memory.
13523 */
13524 static void memsys5Free(void *pPrior){
13525   if( pPrior==0 ){
13526 assert(0);
13527     return;
13528   }
13529   memsys5Enter();
13530   memsys5FreeUnsafe(pPrior);
13531   memsys5Leave();  
13532 }
13533
13534 /*
13535 ** Change the size of an existing memory allocation
13536 */
13537 static void *memsys5Realloc(void *pPrior, int nBytes){
13538   int nOld;
13539   void *p;
13540   if( pPrior==0 ){
13541     return memsys5Malloc(nBytes);
13542   }
13543   if( nBytes<=0 ){
13544     memsys5Free(pPrior);
13545     return 0;
13546   }
13547   nOld = memsys5Size(pPrior);
13548   if( nBytes<=nOld ){
13549     return pPrior;
13550   }
13551   memsys5Enter();
13552   p = memsys5MallocUnsafe(nBytes);
13553   if( p ){
13554     memcpy(p, pPrior, nOld);
13555     memsys5FreeUnsafe(pPrior);
13556   }
13557   memsys5Leave();
13558   return p;
13559 }
13560
13561 /*
13562 ** Round up a request size to the next valid allocation size.
13563 */
13564 static int memsys5Roundup(int n){
13565   int iFullSz;
13566   for(iFullSz=mem5.nAtom; iFullSz<n; iFullSz *= 2);
13567   return iFullSz;
13568 }
13569
13570 static int memsys5Log(int iValue){
13571   int iLog;
13572   for(iLog=0; (1<<iLog)<iValue; iLog++);
13573   return iLog;
13574 }
13575
13576 /*
13577 ** Initialize this module.
13578 */
13579 static int memsys5Init(void *NotUsed){
13580   int ii;
13581   int nByte = sqlite3Config.nHeap;
13582   u8 *zByte = (u8 *)sqlite3Config.pHeap;
13583   int nMinLog;                 /* Log of minimum allocation size in bytes*/
13584   int iOffset;
13585
13586   if( !zByte ){
13587     return SQLITE_ERROR;
13588   }
13589
13590   nMinLog = memsys5Log(sqlite3Config.mnReq);
13591   mem5.nAtom = (1<<nMinLog);
13592   while( sizeof(Mem5Link)>mem5.nAtom ){
13593     mem5.nAtom = mem5.nAtom << 1;
13594   }
13595
13596   mem5.nBlock = (nByte / (mem5.nAtom+sizeof(u8)));
13597   mem5.zPool = zByte;
13598   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.nAtom];
13599
13600   for(ii=0; ii<=LOGMAX; ii++){
13601     mem5.aiFreelist[ii] = -1;
13602   }
13603
13604   iOffset = 0;
13605   for(ii=LOGMAX; ii>=0; ii--){
13606     int nAlloc = (1<<ii);
13607     if( (iOffset+nAlloc)<=mem5.nBlock ){
13608       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
13609       memsys5Link(iOffset, ii);
13610       iOffset += nAlloc;
13611     }
13612     assert((iOffset+nAlloc)>mem5.nBlock);
13613   }
13614
13615   return SQLITE_OK;
13616 }
13617
13618 /*
13619 ** Deinitialize this module.
13620 */
13621 static void memsys5Shutdown(void *NotUsed){
13622   return;
13623 }
13624
13625 /*
13626 ** Open the file indicated and write a log of all unfreed memory 
13627 ** allocations into that log.
13628 */
13629 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
13630 #ifdef SQLITE_DEBUG
13631   FILE *out;
13632   int i, j, n;
13633   int nMinLog;
13634
13635   if( zFilename==0 || zFilename[0]==0 ){
13636     out = stdout;
13637   }else{
13638     out = fopen(zFilename, "w");
13639     if( out==0 ){
13640       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
13641                       zFilename);
13642       return;
13643     }
13644   }
13645   memsys5Enter();
13646   nMinLog = memsys5Log(mem5.nAtom);
13647   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
13648     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
13649     fprintf(out, "freelist items of size %d: %d\n", mem5.nAtom << i, n);
13650   }
13651   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
13652   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
13653   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
13654   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
13655   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
13656   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
13657   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
13658   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
13659   memsys5Leave();
13660   if( out==stdout ){
13661     fflush(stdout);
13662   }else{
13663     fclose(out);
13664   }
13665 #endif
13666 }
13667
13668 /*
13669 ** This routine is the only routine in this file with external 
13670 ** linkage. It returns a pointer to a static sqlite3_mem_methods
13671 ** struct populated with the memsys5 methods.
13672 */
13673 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
13674   static const sqlite3_mem_methods memsys5Methods = {
13675      memsys5Malloc,
13676      memsys5Free,
13677      memsys5Realloc,
13678      memsys5Size,
13679      memsys5Roundup,
13680      memsys5Init,
13681      memsys5Shutdown,
13682      0
13683   };
13684   return &memsys5Methods;
13685 }
13686
13687 #endif /* SQLITE_ENABLE_MEMSYS5 */
13688
13689 /************** End of mem5.c ************************************************/
13690 /************** Begin file mem6.c ********************************************/
13691 /*
13692 ** 2008 July 24
13693 **
13694 ** The author disclaims copyright to this source code.  In place of
13695 ** a legal notice, here is a blessing:
13696 **
13697 **    May you do good and not evil.
13698 **    May you find forgiveness for yourself and forgive others.
13699 **    May you share freely, never taking more than you give.
13700 **
13701 *************************************************************************
13702 **
13703 ** This file contains an alternative memory allocation system for SQLite.
13704 ** This system is implemented as a wrapper around the system provided
13705 ** by the operating system - vanilla malloc(), realloc() and free().
13706 **
13707 ** This system differentiates between requests for "small" allocations 
13708 ** (by default those of 128 bytes or less) and "large" allocations (all
13709 ** others). The 256 byte threshhold is configurable at runtime.
13710 **
13711 ** All requests for large allocations are passed through to the 
13712 ** default system.
13713 **
13714 ** Requests for small allocations are met by allocating space within
13715 ** one or more larger "chunks" of memory obtained from the default
13716 ** memory allocation system. Chunks of memory are usually 64KB or 
13717 ** larger. The algorithm used to manage space within each chunk is
13718 ** the same as that used by mem5.c. 
13719 **
13720 ** This strategy is designed to prevent the default memory allocation
13721 ** system (usually the system malloc) from suffering from heap 
13722 ** fragmentation. On some systems, heap fragmentation can cause a 
13723 ** significant real-time slowdown.
13724 **
13725 ** $Id: mem6.c,v 1.7 2008/07/28 19:34:53 drh Exp $
13726 */
13727
13728 #ifdef SQLITE_ENABLE_MEMSYS6
13729
13730
13731 /*
13732 ** Maximum size of any "small" allocation is ((1<<LOGMAX)*Mem6Chunk.nAtom).
13733 ** Mem6Chunk.nAtom is always at least 8, so this is not a practical
13734 ** limitation
13735 */
13736 #define LOGMAX 30
13737
13738 /*
13739 ** Default value for the "small" allocation size threshold.
13740 */
13741 #define SMALL_MALLOC_DEFAULT_THRESHOLD 256
13742
13743 /*
13744 ** Minimum size for a memory chunk.
13745 */
13746 #define MIN_CHUNKSIZE (1<<16)
13747
13748 #define LOG2_MINALLOC 4
13749
13750
13751 typedef struct Mem6Chunk Mem6Chunk;
13752 typedef struct Mem6Link Mem6Link;
13753
13754 /*
13755 ** A minimum allocation is an instance of the following structure.
13756 ** Larger allocations are an array of these structures where the
13757 ** size of the array is a power of 2.
13758 */
13759 struct Mem6Link {
13760   int next;       /* Index of next free chunk */
13761   int prev;       /* Index of previous free chunk */
13762 };
13763
13764 /*
13765 ** Masks used for mem5.aCtrl[] elements.
13766 */
13767 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block relative to POW2_MIN */
13768 #define CTRL_FREE     0x20    /* True if not checked out */
13769
13770 struct Mem6Chunk {
13771   Mem6Chunk *pNext;
13772
13773   /*
13774   ** Lists of free blocks of various sizes.
13775   */
13776   int aiFreelist[LOGMAX+1];
13777
13778   int nCheckedOut; /* Number of currently outstanding allocations */
13779
13780   /*
13781   ** Space for tracking which blocks are checked out and the size
13782   ** of each block. One byte per block.
13783   */
13784   u8 *aCtrl;
13785
13786   /*
13787   ** Memory available for allocation
13788   */
13789   int nAtom;       /* Smallest possible allocation in bytes */
13790   int nBlock;      /* Number of nAtom sized blocks in zPool */
13791   u8 *zPool;       /* Pointer to memory chunk from which allocations are made */
13792 };
13793
13794 #define MEM6LINK(idx) ((Mem6Link *)(&pChunk->zPool[(idx)*pChunk->nAtom]))
13795
13796 struct Mem6Global {
13797   int nMinAlloc;                  /* Minimum allowed allocation size */
13798   int nThreshold;                 /* Allocs larger than this go to malloc() */
13799   int nLogThreshold;              /* log2 of (nThreshold/nMinAlloc) */
13800   sqlite3_mutex *mutex;
13801   Mem6Chunk *pChunk;              /* Singly linked list of all memory chunks */
13802 } mem6;
13803
13804 /*
13805 ** Unlink the chunk at pChunk->aPool[i] from list it is currently
13806 ** on.  It should be found on pChunk->aiFreelist[iLogsize].
13807 */
13808 static void memsys6Unlink(Mem6Chunk *pChunk, int i, int iLogsize){
13809   int next, prev;
13810   assert( i>=0 && i<pChunk->nBlock );
13811   assert( iLogsize>=0 && iLogsize<=mem6.nLogThreshold );
13812   assert( (pChunk->aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
13813
13814   next = MEM6LINK(i)->next;
13815   prev = MEM6LINK(i)->prev;
13816   if( prev<0 ){
13817     pChunk->aiFreelist[iLogsize] = next;
13818   }else{
13819     MEM6LINK(prev)->next = next;
13820   }
13821   if( next>=0 ){
13822     MEM6LINK(next)->prev = prev;
13823   }
13824 }
13825
13826 /*
13827 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
13828 ** free list.
13829 */
13830 static void memsys6Link(Mem6Chunk *pChunk, int i, int iLogsize){
13831   int x;
13832   assert( i>=0 && i<pChunk->nBlock );
13833   assert( iLogsize>=0 && iLogsize<=mem6.nLogThreshold );
13834   assert( (pChunk->aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
13835
13836   x = MEM6LINK(i)->next = pChunk->aiFreelist[iLogsize];
13837   MEM6LINK(i)->prev = -1;
13838   if( x>=0 ){
13839     assert( x<pChunk->nBlock );
13840     MEM6LINK(x)->prev = i;
13841   }
13842   pChunk->aiFreelist[iLogsize] = i;
13843 }
13844
13845
13846 /*
13847 ** Find the first entry on the freelist iLogsize.  Unlink that
13848 ** entry and return its index. 
13849 */
13850 static int memsys6UnlinkFirst(Mem6Chunk *pChunk, int iLogsize){
13851   int i;
13852   int iFirst;
13853
13854   assert( iLogsize>=0 && iLogsize<=mem6.nLogThreshold );
13855   i = iFirst = pChunk->aiFreelist[iLogsize];
13856   assert( iFirst>=0 );
13857   memsys6Unlink(pChunk, iFirst, iLogsize);
13858   return iFirst;
13859 }
13860
13861 static int roundupLog2(int n){
13862   static const char LogTable256[256] = {
13863     0,                                                    /* 1 */
13864     1,                                                    /* 2 */
13865     2, 2,                                                 /* 3..4 */
13866     3, 3, 3, 3,                                           /* 5..8 */
13867     4, 4, 4, 4, 4, 4, 4, 4,                               /* 9..16 */
13868     5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,       /* 17..32 */
13869     6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
13870     6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,       /* 33..64 */
13871     7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
13872     7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
13873     7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
13874     7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,       /* 65..128 */
13875     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
13876     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
13877     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
13878     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
13879     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
13880     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
13881     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
13882     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,       /* 129..256 */
13883   };
13884
13885   assert(n<=(1<<16) && n>0);
13886   if( n<=256 ) return LogTable256[n-1];
13887   return LogTable256[(n>>8) - ((n&0xFF)?0:1)] + 8;
13888 }
13889
13890 /*
13891 ** Allocate and return a block of (pChunk->nAtom << iLogsize) bytes from chunk
13892 ** pChunk. If the allocation request cannot be satisfied, return 0.
13893 */
13894 static void *chunkMalloc(Mem6Chunk *pChunk, int iLogsize){
13895   int i;           /* Index of a mem5.aPool[] slot */
13896   int iBin;        /* Index into mem5.aiFreelist[] */
13897
13898   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
13899   ** block.  If not, then split a block of the next larger power of
13900   ** two in order to create a new free block of size iLogsize.
13901   */
13902   for(iBin=iLogsize; pChunk->aiFreelist[iBin]<0 && iBin<=mem6.nLogThreshold; iBin++){}
13903   if( iBin>mem6.nLogThreshold ) return 0;
13904   i = memsys6UnlinkFirst(pChunk, iBin);
13905   while( iBin>iLogsize ){
13906     int newSize;
13907     iBin--;
13908     newSize = 1 << iBin;
13909     pChunk->aCtrl[i+newSize] = CTRL_FREE | iBin;
13910     memsys6Link(pChunk, i+newSize, iBin);
13911   }
13912   pChunk->aCtrl[i] = iLogsize;
13913
13914   /* Return a pointer to the allocated memory. */
13915   pChunk->nCheckedOut++;
13916   return (void*)&pChunk->zPool[i*pChunk->nAtom];
13917 }
13918
13919 /*
13920 ** Free the allocation pointed to by p, which is guaranteed to be non-zero
13921 ** and a part of chunk object pChunk.
13922 */
13923 static void chunkFree(Mem6Chunk *pChunk, void *pOld){
13924   u32 size, iLogsize;
13925   int iBlock;             
13926
13927   /* Set iBlock to the index of the block pointed to by pOld in 
13928   ** the array of pChunk->nAtom byte blocks pointed to by pChunk->zPool.
13929   */
13930   iBlock = ((u8 *)pOld-pChunk->zPool)/pChunk->nAtom;
13931
13932   /* Check that the pointer pOld points to a valid, non-free block. */
13933   assert( iBlock>=0 && iBlock<pChunk->nBlock );
13934   assert( ((u8 *)pOld-pChunk->zPool)%pChunk->nAtom==0 );
13935   assert( (pChunk->aCtrl[iBlock] & CTRL_FREE)==0 );
13936
13937   iLogsize = pChunk->aCtrl[iBlock] & CTRL_LOGSIZE;
13938   size = 1<<iLogsize;
13939   assert( iBlock+size-1<pChunk->nBlock );
13940
13941   pChunk->aCtrl[iBlock] |= CTRL_FREE;
13942   pChunk->aCtrl[iBlock+size-1] |= CTRL_FREE;
13943
13944   pChunk->aCtrl[iBlock] = CTRL_FREE | iLogsize;
13945   while( iLogsize<mem6.nLogThreshold ){
13946     int iBuddy;
13947     if( (iBlock>>iLogsize) & 1 ){
13948       iBuddy = iBlock - size;
13949     }else{
13950       iBuddy = iBlock + size;
13951     }
13952     assert( iBuddy>=0 );
13953     if( (iBuddy+(1<<iLogsize))>pChunk->nBlock ) break;
13954     if( pChunk->aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
13955     memsys6Unlink(pChunk, iBuddy, iLogsize);
13956     iLogsize++;
13957     if( iBuddy<iBlock ){
13958       pChunk->aCtrl[iBuddy] = CTRL_FREE | iLogsize;
13959       pChunk->aCtrl[iBlock] = 0;
13960       iBlock = iBuddy;
13961     }else{
13962       pChunk->aCtrl[iBlock] = CTRL_FREE | iLogsize;
13963       pChunk->aCtrl[iBuddy] = 0;
13964     }
13965     size *= 2;
13966   }
13967   pChunk->nCheckedOut--;
13968   memsys6Link(pChunk, iBlock, iLogsize);
13969 }
13970
13971 /*
13972 ** Return the actual size of the block pointed to by p, which is guaranteed
13973 ** to have been allocated from chunk pChunk.
13974 */
13975 static int chunkSize(Mem6Chunk *pChunk, void *p){
13976   int iSize = 0;
13977   if( p ){
13978     int i = ((u8 *)p-pChunk->zPool)/pChunk->nAtom;
13979     assert( i>=0 && i<pChunk->nBlock );
13980     iSize = pChunk->nAtom * (1 << (pChunk->aCtrl[i]&CTRL_LOGSIZE));
13981   }
13982   return iSize;
13983 }
13984
13985 /*
13986 ** Return true if there are currently no outstanding allocations.
13987 */
13988 static int chunkIsEmpty(Mem6Chunk *pChunk){
13989   return (pChunk->nCheckedOut==0);
13990 }
13991
13992 /*
13993 ** Initialize the buffer zChunk, which is nChunk bytes in size, as
13994 ** an Mem6Chunk object. Return a copy of the zChunk pointer.
13995 */
13996 static Mem6Chunk *chunkInit(u8 *zChunk, int nChunk, int nMinAlloc){
13997   int ii;
13998   int iOffset;
13999   Mem6Chunk *pChunk = (Mem6Chunk *)zChunk;
14000
14001   assert( nChunk>sizeof(Mem6Chunk) );
14002   assert( nMinAlloc>sizeof(Mem6Link) );
14003
14004   memset(pChunk, 0, sizeof(Mem6Chunk));
14005   pChunk->nAtom = nMinAlloc;
14006   pChunk->nBlock = ((nChunk-sizeof(Mem6Chunk)) / (pChunk->nAtom+sizeof(u8)));
14007
14008   pChunk->zPool = (u8 *)&pChunk[1];
14009   pChunk->aCtrl = &pChunk->zPool[pChunk->nBlock*pChunk->nAtom];
14010
14011   for(ii=0; ii<=mem6.nLogThreshold; ii++){
14012     pChunk->aiFreelist[ii] = -1;
14013   }
14014
14015   iOffset = 0;
14016   for(ii=mem6.nLogThreshold; ii>=0; ii--){
14017     int nAlloc = (1<<ii);
14018     while( (iOffset+nAlloc)<=pChunk->nBlock ){
14019       pChunk->aCtrl[iOffset] = ii | CTRL_FREE;
14020       memsys6Link(pChunk, iOffset, ii);
14021       iOffset += nAlloc;
14022     }
14023   }
14024
14025   return pChunk;
14026 }
14027
14028
14029 static void mem6Enter(void){
14030   sqlite3_mutex_enter(mem6.mutex);
14031 }
14032
14033 static void mem6Leave(void){
14034   sqlite3_mutex_leave(mem6.mutex);
14035 }
14036
14037 /*
14038 ** Based on the number and size of the currently allocated chunks, return
14039 ** the size of the next chunk to allocate, in bytes.
14040 */
14041 static int nextChunkSize(void){
14042   int iTotal = MIN_CHUNKSIZE;
14043   Mem6Chunk *p;
14044   for(p=mem6.pChunk; p; p=p->pNext){
14045     iTotal = iTotal*2;
14046   }
14047   return iTotal;
14048 }
14049
14050 static void freeChunk(Mem6Chunk *pChunk){
14051   Mem6Chunk **pp = &mem6.pChunk;
14052   for( pp=&mem6.pChunk; *pp!=pChunk; pp = &(*pp)->pNext );
14053   *pp = (*pp)->pNext;
14054   free(pChunk);
14055 }
14056
14057 static void *memsys6Malloc(int nByte){
14058   Mem6Chunk *pChunk;
14059   void *p = 0;
14060   int nTotal = nByte+8;
14061   int iOffset = 0;
14062
14063   if( nTotal>mem6.nThreshold ){
14064     p = malloc(nTotal);
14065   }else{
14066     int iLogsize = 0;
14067     if( nTotal>(1<<LOG2_MINALLOC) ){
14068       iLogsize = roundupLog2(nTotal) - LOG2_MINALLOC;
14069     }
14070     mem6Enter();
14071     for(pChunk=mem6.pChunk; pChunk; pChunk=pChunk->pNext){
14072       p = chunkMalloc(pChunk, iLogsize);
14073       if( p ){
14074         break;
14075       }
14076     }
14077     if( !p ){
14078       int iSize = nextChunkSize();
14079       p = malloc(iSize);
14080       if( p ){
14081         pChunk = chunkInit((u8 *)p, iSize, mem6.nMinAlloc);
14082         pChunk->pNext = mem6.pChunk;
14083         mem6.pChunk = pChunk;
14084         p = chunkMalloc(pChunk, iLogsize);
14085         assert(p);
14086       }
14087     }
14088     iOffset = ((u8*)p - (u8*)pChunk);
14089     mem6Leave();
14090   }
14091
14092   if( !p ){
14093     return 0;
14094   }
14095   ((u32 *)p)[0] = iOffset;
14096   ((u32 *)p)[1] = nByte;
14097   return &((u32 *)p)[2];
14098 }
14099
14100 static int memsys6Size(void *pPrior){
14101   if( pPrior==0 ) return 0;
14102   return ((u32*)pPrior)[-1];
14103 }
14104
14105 static void memsys6Free(void *pPrior){
14106   int iSlot;
14107   void *p = &((u32 *)pPrior)[-2];
14108   iSlot = ((u32 *)p)[0];
14109   if( iSlot ){
14110     Mem6Chunk *pChunk;
14111     mem6Enter();
14112     pChunk = (Mem6Chunk *)(&((u8 *)p)[-1 * iSlot]);
14113     chunkFree(pChunk, p);
14114     if( chunkIsEmpty(pChunk) ){
14115       freeChunk(pChunk);
14116     }
14117     mem6Leave();
14118   }else{
14119     free(p);
14120   }
14121 }
14122
14123 static void *memsys6Realloc(void *p, int nByte){
14124   void *p2;
14125
14126   if( p && nByte<=memsys6Size(p) ){
14127     p2 = p;
14128   }else{
14129     p2 = memsys6Malloc(nByte);
14130     if( p && p2 ){
14131       memcpy(p2, p, memsys6Size(p));
14132       memsys6Free(p);
14133     }
14134   }
14135
14136   return p2;
14137 }
14138
14139 static int memsys6Roundup(int n){
14140   if( n>mem6.nThreshold ){
14141     return n;
14142   }else{
14143     return (1<<roundupLog2(n));
14144   }
14145 }
14146
14147 static int memsys6Init(void *pCtx){
14148   u8 bMemstat = sqlite3Config.bMemstat;
14149   mem6.nMinAlloc = (1 << LOG2_MINALLOC);
14150   mem6.pChunk = 0;
14151   mem6.nThreshold = sqlite3Config.nSmall;
14152   if( mem6.nThreshold<=0 ){
14153     mem6.nThreshold = SMALL_MALLOC_DEFAULT_THRESHOLD;
14154   }
14155   mem6.nLogThreshold = roundupLog2(mem6.nThreshold) - LOG2_MINALLOC;
14156   if( !bMemstat ){
14157     mem6.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
14158   }
14159   return SQLITE_OK;
14160 }
14161
14162 static void memsys6Shutdown(void *pCtx){
14163   memset(&mem6, 0, sizeof(mem6));
14164 }
14165
14166 /*
14167 ** This routine is the only routine in this file with external 
14168 ** linkage. It returns a pointer to a static sqlite3_mem_methods
14169 ** struct populated with the memsys6 methods.
14170 */
14171 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys6(void){
14172   static const sqlite3_mem_methods memsys6Methods = {
14173      memsys6Malloc,
14174      memsys6Free,
14175      memsys6Realloc,
14176      memsys6Size,
14177      memsys6Roundup,
14178      memsys6Init,
14179      memsys6Shutdown,
14180      0
14181   };
14182   return &memsys6Methods;
14183 }
14184
14185 #endif
14186
14187 /************** End of mem6.c ************************************************/
14188 /************** Begin file mutex.c *******************************************/
14189 /*
14190 ** 2007 August 14
14191 **
14192 ** The author disclaims copyright to this source code.  In place of
14193 ** a legal notice, here is a blessing:
14194 **
14195 **    May you do good and not evil.
14196 **    May you find forgiveness for yourself and forgive others.
14197 **    May you share freely, never taking more than you give.
14198 **
14199 *************************************************************************
14200 ** This file contains the C functions that implement mutexes.
14201 **
14202 ** The implementation in this file does not provide any mutual
14203 ** exclusion and is thus suitable for use only in applications
14204 ** that use SQLite in a single thread.  But this implementation
14205 ** does do a lot of error checking on mutexes to make sure they
14206 ** are called correctly and at appropriate times.  Hence, this
14207 ** implementation is suitable for testing.
14208 ** debugging purposes
14209 **
14210 ** $Id: mutex.c,v 1.27 2008/06/19 08:51:24 danielk1977 Exp $
14211 */
14212
14213 #ifndef SQLITE_MUTEX_NOOP
14214 /*
14215 ** Initialize the mutex system.
14216 */
14217 SQLITE_PRIVATE int sqlite3MutexInit(void){ 
14218   int rc = SQLITE_OK;
14219   if( sqlite3Config.bCoreMutex ){
14220     if( !sqlite3Config.mutex.xMutexAlloc ){
14221       /* If the xMutexAlloc method has not been set, then the user did not
14222       ** install a mutex implementation via sqlite3_config() prior to 
14223       ** sqlite3_initialize() being called. This block copies pointers to
14224       ** the default implementation into the sqlite3Config structure.
14225       **
14226       ** The danger is that although sqlite3_config() is not a threadsafe
14227       ** API, sqlite3_initialize() is, and so multiple threads may be
14228       ** attempting to run this function simultaneously. To guard write
14229       ** access to the sqlite3Config structure, the 'MASTER' static mutex
14230       ** is obtained before modifying it.
14231       */
14232       sqlite3_mutex_methods *p = sqlite3DefaultMutex();
14233       sqlite3_mutex *pMaster = 0;
14234   
14235       rc = p->xMutexInit();
14236       if( rc==SQLITE_OK ){
14237         pMaster = p->xMutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14238         assert(pMaster);
14239         p->xMutexEnter(pMaster);
14240         assert( sqlite3Config.mutex.xMutexAlloc==0 
14241              || sqlite3Config.mutex.xMutexAlloc==p->xMutexAlloc
14242         );
14243         if( !sqlite3Config.mutex.xMutexAlloc ){
14244           sqlite3Config.mutex = *p;
14245         }
14246         p->xMutexLeave(pMaster);
14247       }
14248     }else{
14249       rc = sqlite3Config.mutex.xMutexInit();
14250     }
14251   }
14252
14253   return rc;
14254 }
14255
14256 /*
14257 ** Shutdown the mutex system. This call frees resources allocated by
14258 ** sqlite3MutexInit().
14259 */
14260 SQLITE_PRIVATE int sqlite3MutexEnd(void){
14261   int rc = SQLITE_OK;
14262   rc = sqlite3Config.mutex.xMutexEnd();
14263   return rc;
14264 }
14265
14266 /*
14267 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
14268 */
14269 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
14270 #ifndef SQLITE_OMIT_AUTOINIT
14271   if( sqlite3_initialize() ) return 0;
14272 #endif
14273   return sqlite3Config.mutex.xMutexAlloc(id);
14274 }
14275
14276 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
14277   if( !sqlite3Config.bCoreMutex ){
14278     return 0;
14279   }
14280   return sqlite3Config.mutex.xMutexAlloc(id);
14281 }
14282
14283 /*
14284 ** Free a dynamic mutex.
14285 */
14286 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
14287   if( p ){
14288     sqlite3Config.mutex.xMutexFree(p);
14289   }
14290 }
14291
14292 /*
14293 ** Obtain the mutex p. If some other thread already has the mutex, block
14294 ** until it can be obtained.
14295 */
14296 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
14297   if( p ){
14298     sqlite3Config.mutex.xMutexEnter(p);
14299   }
14300 }
14301
14302 /*
14303 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
14304 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
14305 */
14306 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
14307   int rc = SQLITE_OK;
14308   if( p ){
14309     return sqlite3Config.mutex.xMutexTry(p);
14310   }
14311   return rc;
14312 }
14313
14314 /*
14315 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
14316 ** entered by the same thread.  The behavior is undefined if the mutex 
14317 ** is not currently entered. If a NULL pointer is passed as an argument
14318 ** this function is a no-op.
14319 */
14320 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
14321   if( p ){
14322     sqlite3Config.mutex.xMutexLeave(p);
14323   }
14324 }
14325
14326 #ifndef NDEBUG
14327 /*
14328 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
14329 ** intended for use inside assert() statements.
14330 */
14331 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
14332   return p==0 || sqlite3Config.mutex.xMutexHeld(p);
14333 }
14334 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
14335   return p==0 || sqlite3Config.mutex.xMutexNotheld(p);
14336 }
14337 #endif
14338
14339 #endif
14340
14341 #ifdef SQLITE_MUTEX_NOOP_DEBUG
14342 /*
14343 ** In this implementation, mutexes do not provide any mutual exclusion.
14344 ** But the error checking is provided.  This implementation is useful
14345 ** for test purposes.
14346 */
14347
14348 /*
14349 ** The mutex object
14350 */
14351 struct sqlite3_mutex {
14352   int id;     /* The mutex type */
14353   int cnt;    /* Number of entries without a matching leave */
14354 };
14355
14356 /*
14357 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
14358 ** intended for use inside assert() statements.
14359 */
14360 static int noopMutexHeld(sqlite3_mutex *p){
14361   return p==0 || p->cnt>0;
14362 }
14363 static int noopMutexNotheld(sqlite3_mutex *p){
14364   return p==0 || p->cnt==0;
14365 }
14366
14367 /*
14368 ** Initialize and deinitialize the mutex subsystem.
14369 */
14370 static int noopMutexInit(void){ return SQLITE_OK; }
14371 static int noopMutexEnd(void){ return SQLITE_OK; }
14372
14373 /*
14374 ** The sqlite3_mutex_alloc() routine allocates a new
14375 ** mutex and returns a pointer to it.  If it returns NULL
14376 ** that means that a mutex could not be allocated. 
14377 */
14378 static sqlite3_mutex *noopMutexAlloc(int id){
14379   static sqlite3_mutex aStatic[6];
14380   sqlite3_mutex *pNew = 0;
14381   switch( id ){
14382     case SQLITE_MUTEX_FAST:
14383     case SQLITE_MUTEX_RECURSIVE: {
14384       pNew = sqlite3Malloc(sizeof(*pNew));
14385       if( pNew ){
14386         pNew->id = id;
14387         pNew->cnt = 0;
14388       }
14389       break;
14390     }
14391     default: {
14392       assert( id-2 >= 0 );
14393       assert( id-2 < sizeof(aStatic)/sizeof(aStatic[0]) );
14394       pNew = &aStatic[id-2];
14395       pNew->id = id;
14396       break;
14397     }
14398   }
14399   return pNew;
14400 }
14401
14402 /*
14403 ** This routine deallocates a previously allocated mutex.
14404 */
14405 static void noopMutexFree(sqlite3_mutex *p){
14406   assert( p->cnt==0 );
14407   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
14408   sqlite3_free(p);
14409 }
14410
14411 /*
14412 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
14413 ** to enter a mutex.  If another thread is already within the mutex,
14414 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
14415 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
14416 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
14417 ** be entered multiple times by the same thread.  In such cases the,
14418 ** mutex must be exited an equal number of times before another thread
14419 ** can enter.  If the same thread tries to enter any other kind of mutex
14420 ** more than once, the behavior is undefined.
14421 */
14422 static void noopMutexEnter(sqlite3_mutex *p){
14423   assert( p->id==SQLITE_MUTEX_RECURSIVE || noopMutexNotheld(p) );
14424   p->cnt++;
14425 }
14426 static int noopMutexTry(sqlite3_mutex *p){
14427   assert( p->id==SQLITE_MUTEX_RECURSIVE || noopMutexNotheld(p) );
14428   p->cnt++;
14429   return SQLITE_OK;
14430 }
14431
14432 /*
14433 ** The sqlite3_mutex_leave() routine exits a mutex that was
14434 ** previously entered by the same thread.  The behavior
14435 ** is undefined if the mutex is not currently entered or
14436 ** is not currently allocated.  SQLite will never do either.
14437 */
14438 static void noopMutexLeave(sqlite3_mutex *p){
14439   assert( noopMutexHeld(p) );
14440   p->cnt--;
14441   assert( p->id==SQLITE_MUTEX_RECURSIVE || noopMutexNotheld(p) );
14442 }
14443
14444 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
14445   static sqlite3_mutex_methods sMutex = {
14446     noopMutexInit,
14447     noopMutexEnd,
14448     noopMutexAlloc,
14449     noopMutexFree,
14450     noopMutexEnter,
14451     noopMutexTry,
14452     noopMutexLeave,
14453
14454     noopMutexHeld,
14455     noopMutexNotheld
14456   };
14457
14458   return &sMutex;
14459 }
14460 #endif /* SQLITE_MUTEX_NOOP_DEBUG */
14461
14462 /************** End of mutex.c ***********************************************/
14463 /************** Begin file mutex_os2.c ***************************************/
14464 /*
14465 ** 2007 August 28
14466 **
14467 ** The author disclaims copyright to this source code.  In place of
14468 ** a legal notice, here is a blessing:
14469 **
14470 **    May you do good and not evil.
14471 **    May you find forgiveness for yourself and forgive others.
14472 **    May you share freely, never taking more than you give.
14473 **
14474 *************************************************************************
14475 ** This file contains the C functions that implement mutexes for OS/2
14476 **
14477 ** $Id: mutex_os2.c,v 1.10 2008/06/23 22:13:28 pweilbacher Exp $
14478 */
14479
14480 /*
14481 ** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
14482 ** See the mutex.h file for details.
14483 */
14484 #ifdef SQLITE_MUTEX_OS2
14485
14486 /********************** OS/2 Mutex Implementation **********************
14487 **
14488 ** This implementation of mutexes is built using the OS/2 API.
14489 */
14490
14491 /*
14492 ** The mutex object
14493 ** Each recursive mutex is an instance of the following structure.
14494 */
14495 struct sqlite3_mutex {
14496   HMTX mutex;       /* Mutex controlling the lock */
14497   int  id;          /* Mutex type */
14498   int  nRef;        /* Number of references */
14499   TID  owner;       /* Thread holding this mutex */
14500 };
14501
14502 #define OS2_MUTEX_INITIALIZER   0,0,0,0
14503
14504 /*
14505 ** Initialize and deinitialize the mutex subsystem.
14506 */
14507 static int os2MutexInit(void){ return SQLITE_OK; }
14508 static int os2MutexEnd(void){ return SQLITE_OK; }
14509
14510 /*
14511 ** The sqlite3_mutex_alloc() routine allocates a new
14512 ** mutex and returns a pointer to it.  If it returns NULL
14513 ** that means that a mutex could not be allocated. 
14514 ** SQLite will unwind its stack and return an error.  The argument
14515 ** to sqlite3_mutex_alloc() is one of these integer constants:
14516 **
14517 ** <ul>
14518 ** <li>  SQLITE_MUTEX_FAST               0
14519 ** <li>  SQLITE_MUTEX_RECURSIVE          1
14520 ** <li>  SQLITE_MUTEX_STATIC_MASTER      2
14521 ** <li>  SQLITE_MUTEX_STATIC_MEM         3
14522 ** <li>  SQLITE_MUTEX_STATIC_PRNG        4
14523 ** </ul>
14524 **
14525 ** The first two constants cause sqlite3_mutex_alloc() to create
14526 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
14527 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
14528 ** The mutex implementation does not need to make a distinction
14529 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
14530 ** not want to.  But SQLite will only request a recursive mutex in
14531 ** cases where it really needs one.  If a faster non-recursive mutex
14532 ** implementation is available on the host platform, the mutex subsystem
14533 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
14534 **
14535 ** The other allowed parameters to sqlite3_mutex_alloc() each return
14536 ** a pointer to a static preexisting mutex.  Three static mutexes are
14537 ** used by the current version of SQLite.  Future versions of SQLite
14538 ** may add additional static mutexes.  Static mutexes are for internal
14539 ** use by SQLite only.  Applications that use SQLite mutexes should
14540 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
14541 ** SQLITE_MUTEX_RECURSIVE.
14542 **
14543 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
14544 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
14545 ** returns a different mutex on every call.  But for the static
14546 ** mutex types, the same mutex is returned on every call that has
14547 ** the same type number.
14548 */
14549 static sqlite3_mutex *os2MutexAlloc(int iType){
14550   sqlite3_mutex *p = NULL;
14551   switch( iType ){
14552     case SQLITE_MUTEX_FAST:
14553     case SQLITE_MUTEX_RECURSIVE: {
14554       p = sqlite3MallocZero( sizeof(*p) );
14555       if( p ){
14556         p->id = iType;
14557         if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
14558           sqlite3_free( p );
14559           p = NULL;
14560         }
14561       }
14562       break;
14563     }
14564     default: {
14565       static volatile int isInit = 0;
14566       static sqlite3_mutex staticMutexes[] = {
14567         { OS2_MUTEX_INITIALIZER, },
14568         { OS2_MUTEX_INITIALIZER, },
14569         { OS2_MUTEX_INITIALIZER, },
14570         { OS2_MUTEX_INITIALIZER, },
14571         { OS2_MUTEX_INITIALIZER, },
14572         { OS2_MUTEX_INITIALIZER, },
14573       };
14574       if ( !isInit ){
14575         APIRET rc;
14576         PTIB ptib;
14577         PPIB ppib;
14578         HMTX mutex;
14579         char name[32];
14580         DosGetInfoBlocks( &ptib, &ppib );
14581         sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
14582                           ppib->pib_ulpid );
14583         while( !isInit ){
14584           mutex = 0;
14585           rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
14586           if( rc == NO_ERROR ){
14587             int i;
14588             if( !isInit ){
14589               for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
14590                 DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
14591               }
14592               isInit = 1;
14593             }
14594             DosCloseMutexSem( mutex );
14595           }else if( rc == ERROR_DUPLICATE_NAME ){
14596             DosSleep( 1 );
14597           }else{
14598             return p;
14599           }
14600         }
14601       }
14602       assert( iType-2 >= 0 );
14603       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
14604       p = &staticMutexes[iType-2];
14605       p->id = iType;
14606       break;
14607     }
14608   }
14609   return p;
14610 }
14611
14612
14613 /*
14614 ** This routine deallocates a previously allocated mutex.
14615 ** SQLite is careful to deallocate every mutex that it allocates.
14616 */
14617 static void os2MutexFree(sqlite3_mutex *p){
14618   if( p==0 ) return;
14619   assert( p->nRef==0 );
14620   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
14621   DosCloseMutexSem( p->mutex );
14622   sqlite3_free( p );
14623 }
14624
14625 /*
14626 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
14627 ** to enter a mutex.  If another thread is already within the mutex,
14628 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
14629 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
14630 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
14631 ** be entered multiple times by the same thread.  In such cases the,
14632 ** mutex must be exited an equal number of times before another thread
14633 ** can enter.  If the same thread tries to enter any other kind of mutex
14634 ** more than once, the behavior is undefined.
14635 */
14636 static void os2MutexEnter(sqlite3_mutex *p){
14637   TID tid;
14638   PID holder1;
14639   ULONG holder2;
14640   if( p==0 ) return;
14641   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
14642   DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
14643   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
14644   p->owner = tid;
14645   p->nRef++;
14646 }
14647 static int os2MutexTry(sqlite3_mutex *p){
14648   int rc;
14649   TID tid;
14650   PID holder1;
14651   ULONG holder2;
14652   if( p==0 ) return SQLITE_OK;
14653   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
14654   if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR) {
14655     DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
14656     p->owner = tid;
14657     p->nRef++;
14658     rc = SQLITE_OK;
14659   } else {
14660     rc = SQLITE_BUSY;
14661   }
14662
14663   return rc;
14664 }
14665
14666 /*
14667 ** The sqlite3_mutex_leave() routine exits a mutex that was
14668 ** previously entered by the same thread.  The behavior
14669 ** is undefined if the mutex is not currently entered or
14670 ** is not currently allocated.  SQLite will never do either.
14671 */
14672 static void os2MutexLeave(sqlite3_mutex *p){
14673   TID tid;
14674   PID holder1;
14675   ULONG holder2;
14676   if( p==0 ) return;
14677   assert( p->nRef>0 );
14678   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
14679   assert( p->owner==tid );
14680   p->nRef--;
14681   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
14682   DosReleaseMutexSem(p->mutex);
14683 }
14684
14685 #ifdef SQLITE_DEBUG
14686 /*
14687 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
14688 ** intended for use inside assert() statements.
14689 */
14690 static int os2MutexHeld(sqlite3_mutex *p){
14691   TID tid;
14692   PID pid;
14693   ULONG ulCount;
14694   PTIB ptib;
14695   if( p!=0 ) {
14696     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
14697   } else {
14698     DosGetInfoBlocks(&ptib, NULL);
14699     tid = ptib->tib_ptib2->tib2_ultid;
14700   }
14701   return p==0 || (p->nRef!=0 && p->owner==tid);
14702 }
14703 static int os2MutexNotheld(sqlite3_mutex *p){
14704   TID tid;
14705   PID pid;
14706   ULONG ulCount;
14707   PTIB ptib;
14708   if( p!= 0 ) {
14709     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
14710   } else {
14711     DosGetInfoBlocks(&ptib, NULL);
14712     tid = ptib->tib_ptib2->tib2_ultid;
14713   }
14714   return p==0 || p->nRef==0 || p->owner!=tid;
14715 }
14716 #endif
14717
14718 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
14719   static sqlite3_mutex_methods sMutex = {
14720     os2MutexInit,
14721     os2MutexEnd,
14722     os2MutexAlloc,
14723     os2MutexFree,
14724     os2MutexEnter,
14725     os2MutexTry,
14726     os2MutexLeave,
14727 #ifdef SQLITE_DEBUG
14728     os2MutexHeld,
14729     os2MutexNotheld
14730 #endif
14731   };
14732
14733   return &sMutex;
14734 }
14735 #endif /* SQLITE_MUTEX_OS2 */
14736
14737 /************** End of mutex_os2.c *******************************************/
14738 /************** Begin file mutex_unix.c **************************************/
14739 /*
14740 ** 2007 August 28
14741 **
14742 ** The author disclaims copyright to this source code.  In place of
14743 ** a legal notice, here is a blessing:
14744 **
14745 **    May you do good and not evil.
14746 **    May you find forgiveness for yourself and forgive others.
14747 **    May you share freely, never taking more than you give.
14748 **
14749 *************************************************************************
14750 ** This file contains the C functions that implement mutexes for pthreads
14751 **
14752 ** $Id: mutex_unix.c,v 1.13 2008/07/16 12:33:24 drh Exp $
14753 */
14754
14755 /*
14756 ** The code in this file is only used if we are compiling threadsafe
14757 ** under unix with pthreads.
14758 **
14759 ** Note that this implementation requires a version of pthreads that
14760 ** supports recursive mutexes.
14761 */
14762 #ifdef SQLITE_MUTEX_PTHREADS
14763
14764 #include <pthread.h>
14765
14766
14767 /*
14768 ** Each recursive mutex is an instance of the following structure.
14769 */
14770 struct sqlite3_mutex {
14771   pthread_mutex_t mutex;     /* Mutex controlling the lock */
14772   int id;                    /* Mutex type */
14773   int nRef;                  /* Number of entrances */
14774   pthread_t owner;           /* Thread that is within this mutex */
14775 #ifdef SQLITE_DEBUG
14776   int trace;                 /* True to trace changes */
14777 #endif
14778 };
14779 #ifdef SQLITE_DEBUG
14780 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
14781 #else
14782 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0 }
14783 #endif
14784
14785 /*
14786 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
14787 ** intended for use only inside assert() statements.  On some platforms,
14788 ** there might be race conditions that can cause these routines to
14789 ** deliver incorrect results.  In particular, if pthread_equal() is
14790 ** not an atomic operation, then these routines might delivery
14791 ** incorrect results.  On most platforms, pthread_equal() is a 
14792 ** comparison of two integers and is therefore atomic.  But we are
14793 ** told that HPUX is not such a platform.  If so, then these routines
14794 ** will not always work correctly on HPUX.
14795 **
14796 ** On those platforms where pthread_equal() is not atomic, SQLite
14797 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
14798 ** make sure no assert() statements are evaluated and hence these
14799 ** routines are never called.
14800 */
14801 #ifndef NDEBUG
14802 static int pthreadMutexHeld(sqlite3_mutex *p){
14803   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
14804 }
14805 static int pthreadMutexNotheld(sqlite3_mutex *p){
14806   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
14807 }
14808 #endif
14809
14810 /*
14811 ** Initialize and deinitialize the mutex subsystem.
14812 */
14813 static int pthreadMutexInit(void){ return SQLITE_OK; }
14814 static int pthreadMutexEnd(void){ return SQLITE_OK; }
14815
14816 /*
14817 ** The sqlite3_mutex_alloc() routine allocates a new
14818 ** mutex and returns a pointer to it.  If it returns NULL
14819 ** that means that a mutex could not be allocated.  SQLite
14820 ** will unwind its stack and return an error.  The argument
14821 ** to sqlite3_mutex_alloc() is one of these integer constants:
14822 **
14823 ** <ul>
14824 ** <li>  SQLITE_MUTEX_FAST
14825 ** <li>  SQLITE_MUTEX_RECURSIVE
14826 ** <li>  SQLITE_MUTEX_STATIC_MASTER
14827 ** <li>  SQLITE_MUTEX_STATIC_MEM
14828 ** <li>  SQLITE_MUTEX_STATIC_MEM2
14829 ** <li>  SQLITE_MUTEX_STATIC_PRNG
14830 ** <li>  SQLITE_MUTEX_STATIC_LRU
14831 ** </ul>
14832 **
14833 ** The first two constants cause sqlite3_mutex_alloc() to create
14834 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
14835 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
14836 ** The mutex implementation does not need to make a distinction
14837 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
14838 ** not want to.  But SQLite will only request a recursive mutex in
14839 ** cases where it really needs one.  If a faster non-recursive mutex
14840 ** implementation is available on the host platform, the mutex subsystem
14841 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
14842 **
14843 ** The other allowed parameters to sqlite3_mutex_alloc() each return
14844 ** a pointer to a static preexisting mutex.  Three static mutexes are
14845 ** used by the current version of SQLite.  Future versions of SQLite
14846 ** may add additional static mutexes.  Static mutexes are for internal
14847 ** use by SQLite only.  Applications that use SQLite mutexes should
14848 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
14849 ** SQLITE_MUTEX_RECURSIVE.
14850 **
14851 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
14852 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
14853 ** returns a different mutex on every call.  But for the static 
14854 ** mutex types, the same mutex is returned on every call that has
14855 ** the same type number.
14856 */
14857 static sqlite3_mutex *pthreadMutexAlloc(int iType){
14858   static sqlite3_mutex staticMutexes[] = {
14859     SQLITE3_MUTEX_INITIALIZER,
14860     SQLITE3_MUTEX_INITIALIZER,
14861     SQLITE3_MUTEX_INITIALIZER,
14862     SQLITE3_MUTEX_INITIALIZER,
14863     SQLITE3_MUTEX_INITIALIZER,
14864     SQLITE3_MUTEX_INITIALIZER
14865   };
14866   sqlite3_mutex *p;
14867   switch( iType ){
14868     case SQLITE_MUTEX_RECURSIVE: {
14869       p = sqlite3MallocZero( sizeof(*p) );
14870       if( p ){
14871 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
14872         /* If recursive mutexes are not available, we will have to
14873         ** build our own.  See below. */
14874         pthread_mutex_init(&p->mutex, 0);
14875 #else
14876         /* Use a recursive mutex if it is available */
14877         pthread_mutexattr_t recursiveAttr;
14878         pthread_mutexattr_init(&recursiveAttr);
14879         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
14880         pthread_mutex_init(&p->mutex, &recursiveAttr);
14881         pthread_mutexattr_destroy(&recursiveAttr);
14882 #endif
14883         p->id = iType;
14884       }
14885       break;
14886     }
14887     case SQLITE_MUTEX_FAST: {
14888       p = sqlite3MallocZero( sizeof(*p) );
14889       if( p ){
14890         p->id = iType;
14891         pthread_mutex_init(&p->mutex, 0);
14892       }
14893       break;
14894     }
14895     default: {
14896       assert( iType-2 >= 0 );
14897       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
14898       p = &staticMutexes[iType-2];
14899       p->id = iType;
14900       break;
14901     }
14902   }
14903   return p;
14904 }
14905
14906
14907 /*
14908 ** This routine deallocates a previously
14909 ** allocated mutex.  SQLite is careful to deallocate every
14910 ** mutex that it allocates.
14911 */
14912 static void pthreadMutexFree(sqlite3_mutex *p){
14913   assert( p->nRef==0 );
14914   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
14915   pthread_mutex_destroy(&p->mutex);
14916   sqlite3_free(p);
14917 }
14918
14919 /*
14920 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
14921 ** to enter a mutex.  If another thread is already within the mutex,
14922 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
14923 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
14924 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
14925 ** be entered multiple times by the same thread.  In such cases the,
14926 ** mutex must be exited an equal number of times before another thread
14927 ** can enter.  If the same thread tries to enter any other kind of mutex
14928 ** more than once, the behavior is undefined.
14929 */
14930 static void pthreadMutexEnter(sqlite3_mutex *p){
14931   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
14932
14933 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
14934   /* If recursive mutexes are not available, then we have to grow
14935   ** our own.  This implementation assumes that pthread_equal()
14936   ** is atomic - that it cannot be deceived into thinking self
14937   ** and p->owner are equal if p->owner changes between two values
14938   ** that are not equal to self while the comparison is taking place.
14939   ** This implementation also assumes a coherent cache - that 
14940   ** separate processes cannot read different values from the same
14941   ** address at the same time.  If either of these two conditions
14942   ** are not met, then the mutexes will fail and problems will result.
14943   */
14944   {
14945     pthread_t self = pthread_self();
14946     if( p->nRef>0 && pthread_equal(p->owner, self) ){
14947       p->nRef++;
14948     }else{
14949       pthread_mutex_lock(&p->mutex);
14950       assert( p->nRef==0 );
14951       p->owner = self;
14952       p->nRef = 1;
14953     }
14954   }
14955 #else
14956   /* Use the built-in recursive mutexes if they are available.
14957   */
14958   pthread_mutex_lock(&p->mutex);
14959   p->owner = pthread_self();
14960   p->nRef++;
14961 #endif
14962
14963 #ifdef SQLITE_DEBUG
14964   if( p->trace ){
14965     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
14966   }
14967 #endif
14968 }
14969 static int pthreadMutexTry(sqlite3_mutex *p){
14970   int rc;
14971   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
14972
14973 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
14974   /* If recursive mutexes are not available, then we have to grow
14975   ** our own.  This implementation assumes that pthread_equal()
14976   ** is atomic - that it cannot be deceived into thinking self
14977   ** and p->owner are equal if p->owner changes between two values
14978   ** that are not equal to self while the comparison is taking place.
14979   ** This implementation also assumes a coherent cache - that 
14980   ** separate processes cannot read different values from the same
14981   ** address at the same time.  If either of these two conditions
14982   ** are not met, then the mutexes will fail and problems will result.
14983   */
14984   {
14985     pthread_t self = pthread_self();
14986     if( p->nRef>0 && pthread_equal(p->owner, self) ){
14987       p->nRef++;
14988       rc = SQLITE_OK;
14989     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
14990       assert( p->nRef==0 );
14991       p->owner = self;
14992       p->nRef = 1;
14993       rc = SQLITE_OK;
14994     }else{
14995       rc = SQLITE_BUSY;
14996     }
14997   }
14998 #else
14999   /* Use the built-in recursive mutexes if they are available.
15000   */
15001   if( pthread_mutex_trylock(&p->mutex)==0 ){
15002     p->owner = pthread_self();
15003     p->nRef++;
15004     rc = SQLITE_OK;
15005   }else{
15006     rc = SQLITE_BUSY;
15007   }
15008 #endif
15009
15010 #ifdef SQLITE_DEBUG
15011   if( rc==SQLITE_OK && p->trace ){
15012     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15013   }
15014 #endif
15015   return rc;
15016 }
15017
15018 /*
15019 ** The sqlite3_mutex_leave() routine exits a mutex that was
15020 ** previously entered by the same thread.  The behavior
15021 ** is undefined if the mutex is not currently entered or
15022 ** is not currently allocated.  SQLite will never do either.
15023 */
15024 static void pthreadMutexLeave(sqlite3_mutex *p){
15025   assert( pthreadMutexHeld(p) );
15026   p->nRef--;
15027   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
15028
15029 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15030   if( p->nRef==0 ){
15031     pthread_mutex_unlock(&p->mutex);
15032   }
15033 #else
15034   pthread_mutex_unlock(&p->mutex);
15035 #endif
15036
15037 #ifdef SQLITE_DEBUG
15038   if( p->trace ){
15039     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15040   }
15041 #endif
15042 }
15043
15044 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15045   static sqlite3_mutex_methods sMutex = {
15046     pthreadMutexInit,
15047     pthreadMutexEnd,
15048     pthreadMutexAlloc,
15049     pthreadMutexFree,
15050     pthreadMutexEnter,
15051     pthreadMutexTry,
15052     pthreadMutexLeave,
15053 #ifdef SQLITE_DEBUG
15054     pthreadMutexHeld,
15055     pthreadMutexNotheld
15056 #endif
15057   };
15058
15059   return &sMutex;
15060 }
15061
15062 #endif /* SQLITE_MUTEX_PTHREAD */
15063
15064 /************** End of mutex_unix.c ******************************************/
15065 /************** Begin file mutex_w32.c ***************************************/
15066 /*
15067 ** 2007 August 14
15068 **
15069 ** The author disclaims copyright to this source code.  In place of
15070 ** a legal notice, here is a blessing:
15071 **
15072 **    May you do good and not evil.
15073 **    May you find forgiveness for yourself and forgive others.
15074 **    May you share freely, never taking more than you give.
15075 **
15076 *************************************************************************
15077 ** This file contains the C functions that implement mutexes for win32
15078 **
15079 ** $Id: mutex_w32.c,v 1.11 2008/06/26 10:41:19 danielk1977 Exp $
15080 */
15081
15082 /*
15083 ** The code in this file is only used if we are compiling multithreaded
15084 ** on a win32 system.
15085 */
15086 #ifdef SQLITE_MUTEX_W32
15087
15088 /*
15089 ** Each recursive mutex is an instance of the following structure.
15090 */
15091 struct sqlite3_mutex {
15092   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
15093   int id;                    /* Mutex type */
15094   int nRef;                  /* Number of enterances */
15095   DWORD owner;               /* Thread holding this mutex */
15096 };
15097
15098 /*
15099 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
15100 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
15101 **
15102 ** Here is an interesting observation:  Win95, Win98, and WinME lack
15103 ** the LockFileEx() API.  But we can still statically link against that
15104 ** API as long as we don't call it win running Win95/98/ME.  A call to
15105 ** this routine is used to determine if the host is Win95/98/ME or
15106 ** WinNT/2K/XP so that we will know whether or not we can safely call
15107 ** the LockFileEx() API.
15108 */
15109 #if SQLITE_OS_WINCE
15110 # define mutexIsNT()  (1)
15111 #else
15112   static int mutexIsNT(void){
15113     static int osType = 0;
15114     if( osType==0 ){
15115       OSVERSIONINFO sInfo;
15116       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
15117       GetVersionEx(&sInfo);
15118       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
15119     }
15120     return osType==2;
15121   }
15122 #endif /* SQLITE_OS_WINCE */
15123
15124
15125 #ifdef SQLITE_DEBUG
15126 /*
15127 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15128 ** intended for use only inside assert() statements.
15129 */
15130 static int winMutexHeld(sqlite3_mutex *p){
15131   return p->nRef!=0 && p->owner==GetCurrentThreadId();
15132 }
15133 static int winMutexNotheld(sqlite3_mutex *p){
15134   return p->nRef==0 || p->owner!=GetCurrentThreadId();
15135 }
15136 #endif
15137
15138
15139 /*
15140 ** Initialize and deinitialize the mutex subsystem.
15141 */
15142 static int winMutexInit(void){ return SQLITE_OK; }
15143 static int winMutexEnd(void){ return SQLITE_OK; }
15144
15145 /*
15146 ** The sqlite3_mutex_alloc() routine allocates a new
15147 ** mutex and returns a pointer to it.  If it returns NULL
15148 ** that means that a mutex could not be allocated.  SQLite
15149 ** will unwind its stack and return an error.  The argument
15150 ** to sqlite3_mutex_alloc() is one of these integer constants:
15151 **
15152 ** <ul>
15153 ** <li>  SQLITE_MUTEX_FAST               0
15154 ** <li>  SQLITE_MUTEX_RECURSIVE          1
15155 ** <li>  SQLITE_MUTEX_STATIC_MASTER      2
15156 ** <li>  SQLITE_MUTEX_STATIC_MEM         3
15157 ** <li>  SQLITE_MUTEX_STATIC_PRNG        4
15158 ** </ul>
15159 **
15160 ** The first two constants cause sqlite3_mutex_alloc() to create
15161 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15162 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15163 ** The mutex implementation does not need to make a distinction
15164 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15165 ** not want to.  But SQLite will only request a recursive mutex in
15166 ** cases where it really needs one.  If a faster non-recursive mutex
15167 ** implementation is available on the host platform, the mutex subsystem
15168 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
15169 **
15170 ** The other allowed parameters to sqlite3_mutex_alloc() each return
15171 ** a pointer to a static preexisting mutex.  Three static mutexes are
15172 ** used by the current version of SQLite.  Future versions of SQLite
15173 ** may add additional static mutexes.  Static mutexes are for internal
15174 ** use by SQLite only.  Applications that use SQLite mutexes should
15175 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15176 ** SQLITE_MUTEX_RECURSIVE.
15177 **
15178 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15179 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15180 ** returns a different mutex on every call.  But for the static 
15181 ** mutex types, the same mutex is returned on every call that has
15182 ** the same type number.
15183 */
15184 static sqlite3_mutex *winMutexAlloc(int iType){
15185   sqlite3_mutex *p;
15186
15187   switch( iType ){
15188     case SQLITE_MUTEX_FAST:
15189     case SQLITE_MUTEX_RECURSIVE: {
15190       p = sqlite3MallocZero( sizeof(*p) );
15191       if( p ){
15192         p->id = iType;
15193         InitializeCriticalSection(&p->mutex);
15194       }
15195       break;
15196     }
15197     default: {
15198       static sqlite3_mutex staticMutexes[6];
15199       static int isInit = 0;
15200       while( !isInit ){
15201         static long lock = 0;
15202         if( InterlockedIncrement(&lock)==1 ){
15203           int i;
15204           for(i=0; i<sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++){
15205             InitializeCriticalSection(&staticMutexes[i].mutex);
15206           }
15207           isInit = 1;
15208         }else{
15209           Sleep(1);
15210         }
15211       }
15212       assert( iType-2 >= 0 );
15213       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
15214       p = &staticMutexes[iType-2];
15215       p->id = iType;
15216       break;
15217     }
15218   }
15219   return p;
15220 }
15221
15222
15223 /*
15224 ** This routine deallocates a previously
15225 ** allocated mutex.  SQLite is careful to deallocate every
15226 ** mutex that it allocates.
15227 */
15228 static void winMutexFree(sqlite3_mutex *p){
15229   assert( p );
15230   assert( p->nRef==0 );
15231   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15232   DeleteCriticalSection(&p->mutex);
15233   sqlite3_free(p);
15234 }
15235
15236 /*
15237 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15238 ** to enter a mutex.  If another thread is already within the mutex,
15239 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15240 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15241 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15242 ** be entered multiple times by the same thread.  In such cases the,
15243 ** mutex must be exited an equal number of times before another thread
15244 ** can enter.  If the same thread tries to enter any other kind of mutex
15245 ** more than once, the behavior is undefined.
15246 */
15247 static void winMutexEnter(sqlite3_mutex *p){
15248   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) );
15249   EnterCriticalSection(&p->mutex);
15250   p->owner = GetCurrentThreadId(); 
15251   p->nRef++;
15252 }
15253 static int winMutexTry(sqlite3_mutex *p){
15254   int rc = SQLITE_BUSY;
15255   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) );
15256   /*
15257   ** The sqlite3_mutex_try() routine is very rarely used, and when it
15258   ** is used it is merely an optimization.  So it is OK for it to always
15259   ** fail.  
15260   **
15261   ** The TryEnterCriticalSection() interface is only available on WinNT.
15262   ** And some windows compilers complain if you try to use it without
15263   ** first doing some #defines that prevent SQLite from building on Win98.
15264   ** For that reason, we will omit this optimization for now.  See
15265   ** ticket #2685.
15266   */
15267 #if 0
15268   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
15269     p->owner = GetCurrentThreadId();
15270     p->nRef++;
15271     rc = SQLITE_OK;
15272   }
15273 #endif
15274   return rc;
15275 }
15276
15277 /*
15278 ** The sqlite3_mutex_leave() routine exits a mutex that was
15279 ** previously entered by the same thread.  The behavior
15280 ** is undefined if the mutex is not currently entered or
15281 ** is not currently allocated.  SQLite will never do either.
15282 */
15283 static void winMutexLeave(sqlite3_mutex *p){
15284   assert( p->nRef>0 );
15285   assert( p->owner==GetCurrentThreadId() );
15286   p->nRef--;
15287   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
15288   LeaveCriticalSection(&p->mutex);
15289 }
15290
15291 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15292   static sqlite3_mutex_methods sMutex = {
15293     winMutexInit,
15294     winMutexEnd,
15295     winMutexAlloc,
15296     winMutexFree,
15297     winMutexEnter,
15298     winMutexTry,
15299     winMutexLeave,
15300 #ifdef SQLITE_DEBUG
15301     winMutexHeld,
15302     winMutexNotheld
15303 #endif
15304   };
15305
15306   return &sMutex;
15307 }
15308 #endif /* SQLITE_MUTEX_W32 */
15309
15310 /************** End of mutex_w32.c *******************************************/
15311 /************** Begin file malloc.c ******************************************/
15312 /*
15313 ** 2001 September 15
15314 **
15315 ** The author disclaims copyright to this source code.  In place of
15316 ** a legal notice, here is a blessing:
15317 **
15318 **    May you do good and not evil.
15319 **    May you find forgiveness for yourself and forgive others.
15320 **    May you share freely, never taking more than you give.
15321 **
15322 *************************************************************************
15323 **
15324 ** Memory allocation functions used throughout sqlite.
15325 **
15326 ** $Id: malloc.c,v 1.34 2008/08/05 17:53:23 drh Exp $
15327 */
15328
15329 /*
15330 ** This routine runs when the memory allocator sees that the
15331 ** total memory allocation is about to exceed the soft heap
15332 ** limit.
15333 */
15334 static void softHeapLimitEnforcer(
15335   void *NotUsed, 
15336   sqlite3_int64 inUse,
15337   int allocSize
15338 ){
15339   sqlite3_release_memory(allocSize);
15340 }
15341
15342 /*
15343 ** Set the soft heap-size limit for the library. Passing a zero or 
15344 ** negative value indicates no limit.
15345 */
15346 SQLITE_API void sqlite3_soft_heap_limit(int n){
15347   sqlite3_uint64 iLimit;
15348   int overage;
15349   if( n<0 ){
15350     iLimit = 0;
15351   }else{
15352     iLimit = n;
15353   }
15354   sqlite3_initialize();
15355   if( iLimit>0 ){
15356     sqlite3_memory_alarm(softHeapLimitEnforcer, 0, iLimit);
15357   }else{
15358     sqlite3_memory_alarm(0, 0, 0);
15359   }
15360   overage = sqlite3_memory_used() - n;
15361   if( overage>0 ){
15362     sqlite3_release_memory(overage);
15363   }
15364 }
15365
15366 /*
15367 ** Attempt to release up to n bytes of non-essential memory currently
15368 ** held by SQLite. An example of non-essential memory is memory used to
15369 ** cache database pages that are not currently in use.
15370 */
15371 SQLITE_API int sqlite3_release_memory(int n){
15372 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
15373   int nRet = sqlite3VdbeReleaseMemory(n);
15374   nRet += sqlite3PagerReleaseMemory(n-nRet);
15375   return nRet;
15376 #else
15377   return SQLITE_OK;
15378 #endif
15379 }
15380
15381 /*
15382 ** State information local to the memory allocation subsystem.
15383 */
15384 static struct {
15385   sqlite3_mutex *mutex;         /* Mutex to serialize access */
15386
15387   /*
15388   ** The alarm callback and its arguments.  The mem0.mutex lock will
15389   ** be held while the callback is running.  Recursive calls into
15390   ** the memory subsystem are allowed, but no new callbacks will be
15391   ** issued.  The alarmBusy variable is set to prevent recursive
15392   ** callbacks.
15393   */
15394   sqlite3_int64 alarmThreshold;
15395   void (*alarmCallback)(void*, sqlite3_int64,int);
15396   void *alarmArg;
15397   int alarmBusy;
15398
15399   /*
15400   ** Pointers to the end of sqlite3Config.pScratch and
15401   ** sqlite3Config.pPage to a block of memory that records
15402   ** which pages are available.
15403   */
15404   u32 *aScratchFree;
15405   u32 *aPageFree;
15406
15407   /* Number of free pages for scratch and page-cache memory */
15408   u32 nScratchFree;
15409   u32 nPageFree;
15410 } mem0;
15411
15412 /*
15413 ** Initialize the memory allocation subsystem.
15414 */
15415 SQLITE_PRIVATE int sqlite3MallocInit(void){
15416   if( sqlite3Config.m.xMalloc==0 ){
15417     sqlite3MemSetDefault();
15418   }
15419   memset(&mem0, 0, sizeof(mem0));
15420   if( sqlite3Config.bCoreMutex ){
15421     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15422   }
15423   if( sqlite3Config.pScratch && sqlite3Config.szScratch>=100
15424       && sqlite3Config.nScratch>=0 ){
15425     int i;
15426     sqlite3Config.szScratch -= 4;
15427     mem0.aScratchFree = (u32*)&((char*)sqlite3Config.pScratch)
15428                   [sqlite3Config.szScratch*sqlite3Config.nScratch];
15429     for(i=0; i<sqlite3Config.nScratch; i++){ mem0.aScratchFree[i] = i; }
15430     mem0.nScratchFree = sqlite3Config.nScratch;
15431   }else{
15432     sqlite3Config.pScratch = 0;
15433     sqlite3Config.szScratch = 0;
15434   }
15435   if( sqlite3Config.pPage && sqlite3Config.szPage>=512
15436       && sqlite3Config.nPage>=1 ){
15437     int i;
15438     int overhead;
15439     int sz = sqlite3Config.szPage;
15440     int n = sqlite3Config.nPage;
15441     overhead = (4*n + sz - 1)/sz;
15442     sqlite3Config.nPage -= overhead;
15443     mem0.aPageFree = (u32*)&((char*)sqlite3Config.pPage)
15444                   [sqlite3Config.szPage*sqlite3Config.nPage];
15445     for(i=0; i<sqlite3Config.nPage; i++){ mem0.aPageFree[i] = i; }
15446     mem0.nPageFree = sqlite3Config.nPage;
15447   }else{
15448     sqlite3Config.pPage = 0;
15449     sqlite3Config.szPage = 0;
15450   }
15451   return sqlite3Config.m.xInit(sqlite3Config.m.pAppData);
15452 }
15453
15454 /*
15455 ** Deinitialize the memory allocation subsystem.
15456 */
15457 SQLITE_PRIVATE void sqlite3MallocEnd(void){
15458   sqlite3Config.m.xShutdown(sqlite3Config.m.pAppData);
15459   memset(&mem0, 0, sizeof(mem0));
15460 }
15461
15462 /*
15463 ** Return the amount of memory currently checked out.
15464 */
15465 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
15466   int n, mx;
15467   sqlite3_int64 res;
15468   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
15469   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
15470   return res;
15471 }
15472
15473 /*
15474 ** Return the maximum amount of memory that has ever been
15475 ** checked out since either the beginning of this process
15476 ** or since the most recent reset.
15477 */
15478 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
15479   int n, mx;
15480   sqlite3_int64 res;
15481   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
15482   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
15483   return res;
15484 }
15485
15486 /*
15487 ** Change the alarm callback
15488 */
15489 SQLITE_API int sqlite3_memory_alarm(
15490   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
15491   void *pArg,
15492   sqlite3_int64 iThreshold
15493 ){
15494   sqlite3_mutex_enter(mem0.mutex);
15495   mem0.alarmCallback = xCallback;
15496   mem0.alarmArg = pArg;
15497   mem0.alarmThreshold = iThreshold;
15498   sqlite3_mutex_leave(mem0.mutex);
15499   return SQLITE_OK;
15500 }
15501
15502 /*
15503 ** Trigger the alarm 
15504 */
15505 static void sqlite3MallocAlarm(int nByte){
15506   void (*xCallback)(void*,sqlite3_int64,int);
15507   sqlite3_int64 nowUsed;
15508   void *pArg;
15509   if( mem0.alarmCallback==0 || mem0.alarmBusy  ) return;
15510   mem0.alarmBusy = 1;
15511   xCallback = mem0.alarmCallback;
15512   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
15513   pArg = mem0.alarmArg;
15514   sqlite3_mutex_leave(mem0.mutex);
15515   xCallback(pArg, nowUsed, nByte);
15516   sqlite3_mutex_enter(mem0.mutex);
15517   mem0.alarmBusy = 0;
15518 }
15519
15520 /*
15521 ** Do a memory allocation with statistics and alarms.  Assume the
15522 ** lock is already held.
15523 */
15524 static int mallocWithAlarm(int n, void **pp){
15525   int nFull;
15526   void *p;
15527   assert( sqlite3_mutex_held(mem0.mutex) );
15528   nFull = sqlite3Config.m.xRoundup(n);
15529   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
15530   if( mem0.alarmCallback!=0 ){
15531     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
15532     if( nUsed+nFull >= mem0.alarmThreshold ){
15533       sqlite3MallocAlarm(nFull);
15534     }
15535   }
15536   p = sqlite3Config.m.xMalloc(nFull);
15537   if( p==0 && mem0.alarmCallback ){
15538     sqlite3MallocAlarm(nFull);
15539     p = sqlite3Config.m.xMalloc(nFull);
15540   }
15541   if( p ){
15542     nFull = sqlite3MallocSize(p);
15543     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
15544   }
15545   *pp = p;
15546   return nFull;
15547 }
15548
15549 /*
15550 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
15551 ** assumes the memory subsystem has already been initialized.
15552 */
15553 SQLITE_PRIVATE void *sqlite3Malloc(int n){
15554   void *p;
15555   if( n<=0 ){
15556     p = 0;
15557   }else if( sqlite3Config.bMemstat ){
15558     sqlite3_mutex_enter(mem0.mutex);
15559     mallocWithAlarm(n, &p);
15560     sqlite3_mutex_leave(mem0.mutex);
15561   }else{
15562     p = sqlite3Config.m.xMalloc(n);
15563   }
15564   return p;
15565 }
15566
15567 /*
15568 ** This version of the memory allocation is for use by the application.
15569 ** First make sure the memory subsystem is initialized, then do the
15570 ** allocation.
15571 */
15572 SQLITE_API void *sqlite3_malloc(int n){
15573 #ifndef SQLITE_OMIT_AUTOINIT
15574   if( sqlite3_initialize() ) return 0;
15575 #endif
15576   return sqlite3Malloc(n);
15577 }
15578
15579 /*
15580 ** Each thread may only have a single outstanding allocation from
15581 ** xScratchMalloc().  We verify this constraint in the single-threaded
15582 ** case by setting scratchAllocOut to 1 when an allocation
15583 ** is outstanding clearing it when the allocation is freed.
15584 */
15585 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
15586 static int scratchAllocOut = 0;
15587 #endif
15588
15589
15590 /*
15591 ** Allocate memory that is to be used and released right away.
15592 ** This routine is similar to alloca() in that it is not intended
15593 ** for situations where the memory might be held long-term.  This
15594 ** routine is intended to get memory to old large transient data
15595 ** structures that would not normally fit on the stack of an
15596 ** embedded processor.
15597 */
15598 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
15599   void *p;
15600   assert( n>0 );
15601
15602 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
15603   /* Verify that no more than one scratch allocation per thread
15604   ** is outstanding at one time.  (This is only checked in the
15605   ** single-threaded case since checking in the multi-threaded case
15606   ** would be much more complicated.) */
15607   assert( scratchAllocOut==0 );
15608 #endif
15609
15610   if( sqlite3Config.szScratch<n ){
15611     goto scratch_overflow;
15612   }else{  
15613     sqlite3_mutex_enter(mem0.mutex);
15614     if( mem0.nScratchFree==0 ){
15615       sqlite3_mutex_leave(mem0.mutex);
15616       goto scratch_overflow;
15617     }else{
15618       int i;
15619       i = mem0.aScratchFree[--mem0.nScratchFree];
15620       sqlite3_mutex_leave(mem0.mutex);
15621       i *= sqlite3Config.szScratch;
15622       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
15623       sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
15624       p = (void*)&((char*)sqlite3Config.pScratch)[i];
15625     }
15626   }
15627 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
15628   scratchAllocOut = p!=0;
15629 #endif
15630
15631   return p;
15632
15633 scratch_overflow:
15634   if( sqlite3Config.bMemstat ){
15635     sqlite3_mutex_enter(mem0.mutex);
15636     sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
15637     n = mallocWithAlarm(n, &p);
15638     if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
15639     sqlite3_mutex_leave(mem0.mutex);
15640   }else{
15641     p = sqlite3Config.m.xMalloc(n);
15642   }
15643 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
15644   scratchAllocOut = p!=0;
15645 #endif
15646   return p;    
15647 }
15648 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
15649   if( p ){
15650
15651 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
15652     /* Verify that no more than one scratch allocation per thread
15653     ** is outstanding at one time.  (This is only checked in the
15654     ** single-threaded case since checking in the multi-threaded case
15655     ** would be much more complicated.) */
15656     assert( scratchAllocOut==1 );
15657     scratchAllocOut = 0;
15658 #endif
15659
15660     if( sqlite3Config.pScratch==0
15661            || p<sqlite3Config.pScratch
15662            || p>=(void*)mem0.aScratchFree ){
15663       if( sqlite3Config.bMemstat ){
15664         int iSize = sqlite3MallocSize(p);
15665         sqlite3_mutex_enter(mem0.mutex);
15666         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
15667         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
15668         sqlite3Config.m.xFree(p);
15669         sqlite3_mutex_leave(mem0.mutex);
15670       }else{
15671         sqlite3Config.m.xFree(p);
15672       }
15673     }else{
15674       int i;
15675       i = (u8 *)p - (u8 *)sqlite3Config.pScratch;
15676       i /= sqlite3Config.szScratch;
15677       assert( i>=0 && i<sqlite3Config.nScratch );
15678       sqlite3_mutex_enter(mem0.mutex);
15679       assert( mem0.nScratchFree<sqlite3Config.nScratch );
15680       mem0.aScratchFree[mem0.nScratchFree++] = i;
15681       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
15682       sqlite3_mutex_leave(mem0.mutex);
15683     }
15684   }
15685 }
15686
15687 /*
15688 ** Allocate memory to be used by the page cache.  Make use of the
15689 ** memory buffer provided by SQLITE_CONFIG_PAGECACHE if there is one
15690 ** and that memory is of the right size and is not completely
15691 ** consumed.  Otherwise, failover to sqlite3Malloc().
15692 */
15693 SQLITE_PRIVATE void *sqlite3PageMalloc(int n){
15694   void *p;
15695   assert( n>0 );
15696   assert( (n & (n-1))==0 );
15697   assert( n>=512 && n<=32768 );
15698
15699   if( sqlite3Config.szPage<n ){
15700     goto page_overflow;
15701   }else{  
15702     sqlite3_mutex_enter(mem0.mutex);
15703     if( mem0.nPageFree==0 ){
15704       sqlite3_mutex_leave(mem0.mutex);
15705       goto page_overflow;
15706     }else{
15707       int i;
15708       i = mem0.aPageFree[--mem0.nPageFree];
15709       sqlite3_mutex_leave(mem0.mutex);
15710       i *= sqlite3Config.szPage;
15711       sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, n);
15712       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
15713       p = (void*)&((char*)sqlite3Config.pPage)[i];
15714     }
15715   }
15716   return p;
15717
15718 page_overflow:
15719   if( sqlite3Config.bMemstat ){
15720     sqlite3_mutex_enter(mem0.mutex);
15721     sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, n);
15722     n = mallocWithAlarm(n, &p);
15723     if( p ) sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, n);
15724     sqlite3_mutex_leave(mem0.mutex);
15725   }else{
15726     p = sqlite3Config.m.xMalloc(n);
15727   }
15728   return p;    
15729 }
15730 SQLITE_PRIVATE void sqlite3PageFree(void *p){
15731   if( p ){
15732     if( sqlite3Config.pPage==0
15733            || p<sqlite3Config.pPage
15734            || p>=(void*)mem0.aPageFree ){
15735       /* In this case, the page allocation was obtained from a regular 
15736       ** call to sqlite3_mem_methods.xMalloc() (a page-cache-memory 
15737       ** "overflow"). Free the block with sqlite3_mem_methods.xFree().
15738       */
15739       if( sqlite3Config.bMemstat ){
15740         int iSize = sqlite3MallocSize(p);
15741         sqlite3_mutex_enter(mem0.mutex);
15742         sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
15743         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
15744         sqlite3Config.m.xFree(p);
15745         sqlite3_mutex_leave(mem0.mutex);
15746       }else{
15747         sqlite3Config.m.xFree(p);
15748       }
15749     }else{
15750       /* The page allocation was allocated from the sqlite3Config.pPage
15751       ** buffer. In this case all that is add the index of the page in
15752       ** the sqlite3Config.pPage array to the set of free indexes stored
15753       ** in the mem0.aPageFree[] array.
15754       */
15755       int i;
15756       i = (u8 *)p - (u8 *)sqlite3Config.pPage;
15757       i /= sqlite3Config.szPage;
15758       assert( i>=0 && i<sqlite3Config.nPage );
15759       sqlite3_mutex_enter(mem0.mutex);
15760       assert( mem0.nPageFree<sqlite3Config.nPage );
15761       mem0.aPageFree[mem0.nPageFree++] = i;
15762       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
15763       sqlite3_mutex_leave(mem0.mutex);
15764 #if !defined(NDEBUG) && 0
15765       /* Assert that a duplicate was not just inserted into aPageFree[]. */
15766       for(i=0; i<mem0.nPageFree-1; i++){
15767         assert( mem0.aPageFree[i]!=mem0.aPageFree[mem0.nPageFree-1] );
15768       }
15769 #endif
15770     }
15771   }
15772 }
15773
15774 /*
15775 ** TRUE if p is a lookaside memory allocation from db
15776 */
15777 static int isLookaside(sqlite3 *db, void *p){
15778   return db && p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
15779 }
15780
15781 /*
15782 ** Return the size of a memory allocation previously obtained from
15783 ** sqlite3Malloc() or sqlite3_malloc().
15784 */
15785 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
15786   return sqlite3Config.m.xSize(p);
15787 }
15788 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
15789   if( isLookaside(db, p) ){
15790     return db->lookaside.sz;
15791   }else{
15792     return sqlite3Config.m.xSize(p);
15793   }
15794 }
15795
15796 /*
15797 ** Free memory previously obtained from sqlite3Malloc().
15798 */
15799 SQLITE_API void sqlite3_free(void *p){
15800   if( p==0 ) return;
15801   if( sqlite3Config.bMemstat ){
15802     sqlite3_mutex_enter(mem0.mutex);
15803     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
15804     sqlite3Config.m.xFree(p);
15805     sqlite3_mutex_leave(mem0.mutex);
15806   }else{
15807     sqlite3Config.m.xFree(p);
15808   }
15809 }
15810
15811 /*
15812 ** Free memory that might be associated with a particular database
15813 ** connection.
15814 */
15815 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
15816   if( isLookaside(db, p) ){
15817     LookasideSlot *pBuf = (LookasideSlot*)p;
15818     pBuf->pNext = db->lookaside.pFree;
15819     db->lookaside.pFree = pBuf;
15820     db->lookaside.nOut--;
15821   }else{
15822     sqlite3_free(p);
15823   }
15824 }
15825
15826 /*
15827 ** Change the size of an existing memory allocation
15828 */
15829 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
15830   int nOld, nNew;
15831   void *pNew;
15832   if( pOld==0 ){
15833     return sqlite3Malloc(nBytes);
15834   }
15835   if( nBytes<=0 ){
15836     sqlite3_free(pOld);
15837     return 0;
15838   }
15839   nOld = sqlite3MallocSize(pOld);
15840   if( sqlite3Config.bMemstat ){
15841     sqlite3_mutex_enter(mem0.mutex);
15842     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
15843     nNew = sqlite3Config.m.xRoundup(nBytes);
15844     if( nOld==nNew ){
15845       pNew = pOld;
15846     }else{
15847       if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >= 
15848             mem0.alarmThreshold ){
15849         sqlite3MallocAlarm(nNew-nOld);
15850       }
15851       pNew = sqlite3Config.m.xRealloc(pOld, nNew);
15852       if( pNew==0 && mem0.alarmCallback ){
15853         sqlite3MallocAlarm(nBytes);
15854         pNew = sqlite3Config.m.xRealloc(pOld, nNew);
15855       }
15856       if( pNew ){
15857         nNew = sqlite3MallocSize(pNew);
15858         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
15859       }
15860     }
15861     sqlite3_mutex_leave(mem0.mutex);
15862   }else{
15863     pNew = sqlite3Config.m.xRealloc(pOld, nBytes);
15864   }
15865   return pNew;
15866 }
15867
15868 /*
15869 ** The public interface to sqlite3Realloc.  Make sure that the memory
15870 ** subsystem is initialized prior to invoking sqliteRealloc.
15871 */
15872 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
15873 #ifndef SQLITE_OMIT_AUTOINIT
15874   if( sqlite3_initialize() ) return 0;
15875 #endif
15876   return sqlite3Realloc(pOld, n);
15877 }
15878
15879
15880 /*
15881 ** Allocate and zero memory.
15882 */ 
15883 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
15884   void *p = sqlite3Malloc(n);
15885   if( p ){
15886     memset(p, 0, n);
15887   }
15888   return p;
15889 }
15890
15891 /*
15892 ** Allocate and zero memory.  If the allocation fails, make
15893 ** the mallocFailed flag in the connection pointer.
15894 */
15895 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
15896   void *p = sqlite3DbMallocRaw(db, n);
15897   if( p ){
15898     memset(p, 0, n);
15899   }
15900   return p;
15901 }
15902
15903 /*
15904 ** Allocate and zero memory.  If the allocation fails, make
15905 ** the mallocFailed flag in the connection pointer.
15906 */
15907 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
15908   void *p;
15909   if( db ){
15910     LookasideSlot *pBuf;
15911     if( db->mallocFailed ){
15912       return 0;
15913     }
15914     if( db->lookaside.bEnabled && n<=db->lookaside.sz
15915          && (pBuf = db->lookaside.pFree)!=0 ){
15916       db->lookaside.pFree = pBuf->pNext;
15917       db->lookaside.nOut++;
15918       if( db->lookaside.nOut>db->lookaside.mxOut ){
15919         db->lookaside.mxOut = db->lookaside.nOut;
15920       }
15921       return (void*)pBuf;
15922     }
15923   }
15924   p = sqlite3Malloc(n);
15925   if( !p && db ){
15926     db->mallocFailed = 1;
15927   }
15928   return p;
15929 }
15930
15931 /*
15932 ** Resize the block of memory pointed to by p to n bytes. If the
15933 ** resize fails, set the mallocFailed flag in the connection object.
15934 */
15935 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
15936   void *pNew = 0;
15937   if( db->mallocFailed==0 ){
15938     if( p==0 ){
15939       return sqlite3DbMallocRaw(db, n);
15940     }
15941     if( isLookaside(db, p) ){
15942       if( n<=db->lookaside.sz ){
15943         return p;
15944       }
15945       pNew = sqlite3DbMallocRaw(db, n);
15946       if( pNew ){
15947         memcpy(pNew, p, db->lookaside.sz);
15948         sqlite3DbFree(db, p);
15949       }
15950     }else{
15951       pNew = sqlite3_realloc(p, n);
15952       if( !pNew ){
15953         db->mallocFailed = 1;
15954       }
15955     }
15956   }
15957   return pNew;
15958 }
15959
15960 /*
15961 ** Attempt to reallocate p.  If the reallocation fails, then free p
15962 ** and set the mallocFailed flag in the database connection.
15963 */
15964 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
15965   void *pNew;
15966   pNew = sqlite3DbRealloc(db, p, n);
15967   if( !pNew ){
15968     sqlite3DbFree(db, p);
15969   }
15970   return pNew;
15971 }
15972
15973 /*
15974 ** Make a copy of a string in memory obtained from sqliteMalloc(). These 
15975 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
15976 ** is because when memory debugging is turned on, these two functions are 
15977 ** called via macros that record the current file and line number in the
15978 ** ThreadData structure.
15979 */
15980 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
15981   char *zNew;
15982   size_t n;
15983   if( z==0 ){
15984     return 0;
15985   }
15986   n = strlen(z)+1;
15987   assert( (n&0x7fffffff)==n );
15988   zNew = sqlite3DbMallocRaw(db, (int)n);
15989   if( zNew ){
15990     memcpy(zNew, z, n);
15991   }
15992   return zNew;
15993 }
15994 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
15995   char *zNew;
15996   if( z==0 ){
15997     return 0;
15998   }
15999   assert( (n&0x7fffffff)==n );
16000   zNew = sqlite3DbMallocRaw(db, n+1);
16001   if( zNew ){
16002     memcpy(zNew, z, n);
16003     zNew[n] = 0;
16004   }
16005   return zNew;
16006 }
16007
16008 /*
16009 ** Create a string from the zFromat argument and the va_list that follows.
16010 ** Store the string in memory obtained from sqliteMalloc() and make *pz
16011 ** point to that string.
16012 */
16013 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
16014   va_list ap;
16015   char *z;
16016
16017   va_start(ap, zFormat);
16018   z = sqlite3VMPrintf(db, zFormat, ap);
16019   va_end(ap);
16020   sqlite3DbFree(db, *pz);
16021   *pz = z;
16022 }
16023
16024
16025 /*
16026 ** This function must be called before exiting any API function (i.e. 
16027 ** returning control to the user) that has called sqlite3_malloc or
16028 ** sqlite3_realloc.
16029 **
16030 ** The returned value is normally a copy of the second argument to this
16031 ** function. However, if a malloc() failure has occured since the previous
16032 ** invocation SQLITE_NOMEM is returned instead. 
16033 **
16034 ** If the first argument, db, is not NULL and a malloc() error has occured,
16035 ** then the connection error-code (the value returned by sqlite3_errcode())
16036 ** is set to SQLITE_NOMEM.
16037 */
16038 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
16039   /* If the db handle is not NULL, then we must hold the connection handle
16040   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
16041   ** is unsafe, as is the call to sqlite3Error().
16042   */
16043   assert( !db || sqlite3_mutex_held(db->mutex) );
16044   if( db && db->mallocFailed ){
16045     sqlite3Error(db, SQLITE_NOMEM, 0);
16046     db->mallocFailed = 0;
16047     rc = SQLITE_NOMEM;
16048   }
16049   return rc & (db ? db->errMask : 0xff);
16050 }
16051
16052 /************** End of malloc.c **********************************************/
16053 /************** Begin file printf.c ******************************************/
16054 /*
16055 ** The "printf" code that follows dates from the 1980's.  It is in
16056 ** the public domain.  The original comments are included here for
16057 ** completeness.  They are very out-of-date but might be useful as
16058 ** an historical reference.  Most of the "enhancements" have been backed
16059 ** out so that the functionality is now the same as standard printf().
16060 **
16061 ** $Id: printf.c,v 1.93 2008/07/28 19:34:53 drh Exp $
16062 **
16063 **************************************************************************
16064 **
16065 ** The following modules is an enhanced replacement for the "printf" subroutines
16066 ** found in the standard C library.  The following enhancements are
16067 ** supported:
16068 **
16069 **      +  Additional functions.  The standard set of "printf" functions
16070 **         includes printf, fprintf, sprintf, vprintf, vfprintf, and
16071 **         vsprintf.  This module adds the following:
16072 **
16073 **           *  snprintf -- Works like sprintf, but has an extra argument
16074 **                          which is the size of the buffer written to.
16075 **
16076 **           *  mprintf --  Similar to sprintf.  Writes output to memory
16077 **                          obtained from malloc.
16078 **
16079 **           *  xprintf --  Calls a function to dispose of output.
16080 **
16081 **           *  nprintf --  No output, but returns the number of characters
16082 **                          that would have been output by printf.
16083 **
16084 **           *  A v- version (ex: vsnprintf) of every function is also
16085 **              supplied.
16086 **
16087 **      +  A few extensions to the formatting notation are supported:
16088 **
16089 **           *  The "=" flag (similar to "-") causes the output to be
16090 **              be centered in the appropriately sized field.
16091 **
16092 **           *  The %b field outputs an integer in binary notation.
16093 **
16094 **           *  The %c field now accepts a precision.  The character output
16095 **              is repeated by the number of times the precision specifies.
16096 **
16097 **           *  The %' field works like %c, but takes as its character the
16098 **              next character of the format string, instead of the next
16099 **              argument.  For example,  printf("%.78'-")  prints 78 minus
16100 **              signs, the same as  printf("%.78c",'-').
16101 **
16102 **      +  When compiled using GCC on a SPARC, this version of printf is
16103 **         faster than the library printf for SUN OS 4.1.
16104 **
16105 **      +  All functions are fully reentrant.
16106 **
16107 */
16108
16109 /*
16110 ** Conversion types fall into various categories as defined by the
16111 ** following enumeration.
16112 */
16113 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
16114 #define etFLOAT       2 /* Floating point.  %f */
16115 #define etEXP         3 /* Exponentional notation. %e and %E */
16116 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
16117 #define etSIZE        5 /* Return number of characters processed so far. %n */
16118 #define etSTRING      6 /* Strings. %s */
16119 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
16120 #define etPERCENT     8 /* Percent symbol. %% */
16121 #define etCHARX       9 /* Characters. %c */
16122 /* The rest are extensions, not normally found in printf() */
16123 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
16124 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
16125                           NULL pointers replaced by SQL NULL.  %Q */
16126 #define etTOKEN      12 /* a pointer to a Token structure */
16127 #define etSRCLIST    13 /* a pointer to a SrcList */
16128 #define etPOINTER    14 /* The %p conversion */
16129 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
16130 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
16131
16132
16133 /*
16134 ** An "etByte" is an 8-bit unsigned value.
16135 */
16136 typedef unsigned char etByte;
16137
16138 /*
16139 ** Each builtin conversion character (ex: the 'd' in "%d") is described
16140 ** by an instance of the following structure
16141 */
16142 typedef struct et_info {   /* Information about each format field */
16143   char fmttype;            /* The format field code letter */
16144   etByte base;             /* The base for radix conversion */
16145   etByte flags;            /* One or more of FLAG_ constants below */
16146   etByte type;             /* Conversion paradigm */
16147   etByte charset;          /* Offset into aDigits[] of the digits string */
16148   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
16149 } et_info;
16150
16151 /*
16152 ** Allowed values for et_info.flags
16153 */
16154 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
16155 #define FLAG_INTERN  2     /* True if for internal use only */
16156 #define FLAG_STRING  4     /* Allow infinity precision */
16157
16158
16159 /*
16160 ** The following table is searched linearly, so it is good to put the
16161 ** most frequently used conversion types first.
16162 */
16163 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
16164 static const char aPrefix[] = "-x0\000X0";
16165 static const et_info fmtinfo[] = {
16166   {  'd', 10, 1, etRADIX,      0,  0 },
16167   {  's',  0, 4, etSTRING,     0,  0 },
16168   {  'g',  0, 1, etGENERIC,    30, 0 },
16169   {  'z',  0, 4, etDYNSTRING,  0,  0 },
16170   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
16171   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
16172   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
16173   {  'c',  0, 0, etCHARX,      0,  0 },
16174   {  'o',  8, 0, etRADIX,      0,  2 },
16175   {  'u', 10, 0, etRADIX,      0,  0 },
16176   {  'x', 16, 0, etRADIX,      16, 1 },
16177   {  'X', 16, 0, etRADIX,      0,  4 },
16178 #ifndef SQLITE_OMIT_FLOATING_POINT
16179   {  'f',  0, 1, etFLOAT,      0,  0 },
16180   {  'e',  0, 1, etEXP,        30, 0 },
16181   {  'E',  0, 1, etEXP,        14, 0 },
16182   {  'G',  0, 1, etGENERIC,    14, 0 },
16183 #endif
16184   {  'i', 10, 1, etRADIX,      0,  0 },
16185   {  'n',  0, 0, etSIZE,       0,  0 },
16186   {  '%',  0, 0, etPERCENT,    0,  0 },
16187   {  'p', 16, 0, etPOINTER,    0,  1 },
16188   {  'T',  0, 2, etTOKEN,      0,  0 },
16189   {  'S',  0, 2, etSRCLIST,    0,  0 },
16190   {  'r', 10, 3, etORDINAL,    0,  0 },
16191 };
16192 #define etNINFO  (sizeof(fmtinfo)/sizeof(fmtinfo[0]))
16193
16194 /*
16195 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
16196 ** conversions will work.
16197 */
16198 #ifndef SQLITE_OMIT_FLOATING_POINT
16199 /*
16200 ** "*val" is a double such that 0.1 <= *val < 10.0
16201 ** Return the ascii code for the leading digit of *val, then
16202 ** multiply "*val" by 10.0 to renormalize.
16203 **
16204 ** Example:
16205 **     input:     *val = 3.14159
16206 **     output:    *val = 1.4159    function return = '3'
16207 **
16208 ** The counter *cnt is incremented each time.  After counter exceeds
16209 ** 16 (the number of significant digits in a 64-bit float) '0' is
16210 ** always returned.
16211 */
16212 static int et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
16213   int digit;
16214   LONGDOUBLE_TYPE d;
16215   if( (*cnt)++ >= 16 ) return '0';
16216   digit = (int)*val;
16217   d = digit;
16218   digit += '0';
16219   *val = (*val - d)*10.0;
16220   return digit;
16221 }
16222 #endif /* SQLITE_OMIT_FLOATING_POINT */
16223
16224 /*
16225 ** Append N space characters to the given string buffer.
16226 */
16227 static void appendSpace(StrAccum *pAccum, int N){
16228   static const char zSpaces[] = "                             ";
16229   while( N>=sizeof(zSpaces)-1 ){
16230     sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
16231     N -= sizeof(zSpaces)-1;
16232   }
16233   if( N>0 ){
16234     sqlite3StrAccumAppend(pAccum, zSpaces, N);
16235   }
16236 }
16237
16238 /*
16239 ** On machines with a small stack size, you can redefine the
16240 ** SQLITE_PRINT_BUF_SIZE to be less than 350.  But beware - for
16241 ** smaller values some %f conversions may go into an infinite loop.
16242 */
16243 #ifndef SQLITE_PRINT_BUF_SIZE
16244 # define SQLITE_PRINT_BUF_SIZE 350
16245 #endif
16246 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
16247
16248 /*
16249 ** The root program.  All variations call this core.
16250 **
16251 ** INPUTS:
16252 **   func   This is a pointer to a function taking three arguments
16253 **            1. A pointer to anything.  Same as the "arg" parameter.
16254 **            2. A pointer to the list of characters to be output
16255 **               (Note, this list is NOT null terminated.)
16256 **            3. An integer number of characters to be output.
16257 **               (Note: This number might be zero.)
16258 **
16259 **   arg    This is the pointer to anything which will be passed as the
16260 **          first argument to "func".  Use it for whatever you like.
16261 **
16262 **   fmt    This is the format string, as in the usual print.
16263 **
16264 **   ap     This is a pointer to a list of arguments.  Same as in
16265 **          vfprint.
16266 **
16267 ** OUTPUTS:
16268 **          The return value is the total number of characters sent to
16269 **          the function "func".  Returns -1 on a error.
16270 **
16271 ** Note that the order in which automatic variables are declared below
16272 ** seems to make a big difference in determining how fast this beast
16273 ** will run.
16274 */
16275 SQLITE_PRIVATE void sqlite3VXPrintf(
16276   StrAccum *pAccum,                  /* Accumulate results here */
16277   int useExtended,                   /* Allow extended %-conversions */
16278   const char *fmt,                   /* Format string */
16279   va_list ap                         /* arguments */
16280 ){
16281   int c;                     /* Next character in the format string */
16282   char *bufpt;               /* Pointer to the conversion buffer */
16283   int precision;             /* Precision of the current field */
16284   int length;                /* Length of the field */
16285   int idx;                   /* A general purpose loop counter */
16286   int width;                 /* Width of the current field */
16287   etByte flag_leftjustify;   /* True if "-" flag is present */
16288   etByte flag_plussign;      /* True if "+" flag is present */
16289   etByte flag_blanksign;     /* True if " " flag is present */
16290   etByte flag_alternateform; /* True if "#" flag is present */
16291   etByte flag_altform2;      /* True if "!" flag is present */
16292   etByte flag_zeropad;       /* True if field width constant starts with zero */
16293   etByte flag_long;          /* True if "l" flag is present */
16294   etByte flag_longlong;      /* True if the "ll" flag is present */
16295   etByte done;               /* Loop termination flag */
16296   sqlite_uint64 longvalue;   /* Value for integer types */
16297   LONGDOUBLE_TYPE realvalue; /* Value for real types */
16298   const et_info *infop;      /* Pointer to the appropriate info structure */
16299   char buf[etBUFSIZE];       /* Conversion buffer */
16300   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
16301   etByte errorflag = 0;      /* True if an error is encountered */
16302   etByte xtype;              /* Conversion paradigm */
16303   char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
16304 #ifndef SQLITE_OMIT_FLOATING_POINT
16305   int  exp, e2;              /* exponent of real numbers */
16306   double rounder;            /* Used for rounding floating point values */
16307   etByte flag_dp;            /* True if decimal point should be shown */
16308   etByte flag_rtz;           /* True if trailing zeros should be removed */
16309   etByte flag_exp;           /* True to force display of the exponent */
16310   int nsd;                   /* Number of significant digits returned */
16311 #endif
16312
16313   length = 0;
16314   bufpt = 0;
16315   for(; (c=(*fmt))!=0; ++fmt){
16316     if( c!='%' ){
16317       int amt;
16318       bufpt = (char *)fmt;
16319       amt = 1;
16320       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
16321       sqlite3StrAccumAppend(pAccum, bufpt, amt);
16322       if( c==0 ) break;
16323     }
16324     if( (c=(*++fmt))==0 ){
16325       errorflag = 1;
16326       sqlite3StrAccumAppend(pAccum, "%", 1);
16327       break;
16328     }
16329     /* Find out what flags are present */
16330     flag_leftjustify = flag_plussign = flag_blanksign = 
16331      flag_alternateform = flag_altform2 = flag_zeropad = 0;
16332     done = 0;
16333     do{
16334       switch( c ){
16335         case '-':   flag_leftjustify = 1;     break;
16336         case '+':   flag_plussign = 1;        break;
16337         case ' ':   flag_blanksign = 1;       break;
16338         case '#':   flag_alternateform = 1;   break;
16339         case '!':   flag_altform2 = 1;        break;
16340         case '0':   flag_zeropad = 1;         break;
16341         default:    done = 1;                 break;
16342       }
16343     }while( !done && (c=(*++fmt))!=0 );
16344     /* Get the field width */
16345     width = 0;
16346     if( c=='*' ){
16347       width = va_arg(ap,int);
16348       if( width<0 ){
16349         flag_leftjustify = 1;
16350         width = -width;
16351       }
16352       c = *++fmt;
16353     }else{
16354       while( c>='0' && c<='9' ){
16355         width = width*10 + c - '0';
16356         c = *++fmt;
16357       }
16358     }
16359     if( width > etBUFSIZE-10 ){
16360       width = etBUFSIZE-10;
16361     }
16362     /* Get the precision */
16363     if( c=='.' ){
16364       precision = 0;
16365       c = *++fmt;
16366       if( c=='*' ){
16367         precision = va_arg(ap,int);
16368         if( precision<0 ) precision = -precision;
16369         c = *++fmt;
16370       }else{
16371         while( c>='0' && c<='9' ){
16372           precision = precision*10 + c - '0';
16373           c = *++fmt;
16374         }
16375       }
16376     }else{
16377       precision = -1;
16378     }
16379     /* Get the conversion type modifier */
16380     if( c=='l' ){
16381       flag_long = 1;
16382       c = *++fmt;
16383       if( c=='l' ){
16384         flag_longlong = 1;
16385         c = *++fmt;
16386       }else{
16387         flag_longlong = 0;
16388       }
16389     }else{
16390       flag_long = flag_longlong = 0;
16391     }
16392     /* Fetch the info entry for the field */
16393     infop = 0;
16394     for(idx=0; idx<etNINFO; idx++){
16395       if( c==fmtinfo[idx].fmttype ){
16396         infop = &fmtinfo[idx];
16397         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
16398           xtype = infop->type;
16399         }else{
16400           return;
16401         }
16402         break;
16403       }
16404     }
16405     zExtra = 0;
16406     if( infop==0 ){
16407       return;
16408     }
16409
16410
16411     /* Limit the precision to prevent overflowing buf[] during conversion */
16412     if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
16413       precision = etBUFSIZE-40;
16414     }
16415
16416     /*
16417     ** At this point, variables are initialized as follows:
16418     **
16419     **   flag_alternateform          TRUE if a '#' is present.
16420     **   flag_altform2               TRUE if a '!' is present.
16421     **   flag_plussign               TRUE if a '+' is present.
16422     **   flag_leftjustify            TRUE if a '-' is present or if the
16423     **                               field width was negative.
16424     **   flag_zeropad                TRUE if the width began with 0.
16425     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
16426     **                               the conversion character.
16427     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
16428     **                               the conversion character.
16429     **   flag_blanksign              TRUE if a ' ' is present.
16430     **   width                       The specified field width.  This is
16431     **                               always non-negative.  Zero is the default.
16432     **   precision                   The specified precision.  The default
16433     **                               is -1.
16434     **   xtype                       The class of the conversion.
16435     **   infop                       Pointer to the appropriate info struct.
16436     */
16437     switch( xtype ){
16438       case etPOINTER:
16439         flag_longlong = sizeof(char*)==sizeof(i64);
16440         flag_long = sizeof(char*)==sizeof(long int);
16441         /* Fall through into the next case */
16442       case etORDINAL:
16443       case etRADIX:
16444         if( infop->flags & FLAG_SIGNED ){
16445           i64 v;
16446           if( flag_longlong )   v = va_arg(ap,i64);
16447           else if( flag_long )  v = va_arg(ap,long int);
16448           else                  v = va_arg(ap,int);
16449           if( v<0 ){
16450             longvalue = -v;
16451             prefix = '-';
16452           }else{
16453             longvalue = v;
16454             if( flag_plussign )        prefix = '+';
16455             else if( flag_blanksign )  prefix = ' ';
16456             else                       prefix = 0;
16457           }
16458         }else{
16459           if( flag_longlong )   longvalue = va_arg(ap,u64);
16460           else if( flag_long )  longvalue = va_arg(ap,unsigned long int);
16461           else                  longvalue = va_arg(ap,unsigned int);
16462           prefix = 0;
16463         }
16464         if( longvalue==0 ) flag_alternateform = 0;
16465         if( flag_zeropad && precision<width-(prefix!=0) ){
16466           precision = width-(prefix!=0);
16467         }
16468         bufpt = &buf[etBUFSIZE-1];
16469         if( xtype==etORDINAL ){
16470           static const char zOrd[] = "thstndrd";
16471           int x = longvalue % 10;
16472           if( x>=4 || (longvalue/10)%10==1 ){
16473             x = 0;
16474           }
16475           buf[etBUFSIZE-3] = zOrd[x*2];
16476           buf[etBUFSIZE-2] = zOrd[x*2+1];
16477           bufpt -= 2;
16478         }
16479         {
16480           register const char *cset;      /* Use registers for speed */
16481           register int base;
16482           cset = &aDigits[infop->charset];
16483           base = infop->base;
16484           do{                                           /* Convert to ascii */
16485             *(--bufpt) = cset[longvalue%base];
16486             longvalue = longvalue/base;
16487           }while( longvalue>0 );
16488         }
16489         length = &buf[etBUFSIZE-1]-bufpt;
16490         for(idx=precision-length; idx>0; idx--){
16491           *(--bufpt) = '0';                             /* Zero pad */
16492         }
16493         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
16494         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
16495           const char *pre;
16496           char x;
16497           pre = &aPrefix[infop->prefix];
16498           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
16499         }
16500         length = &buf[etBUFSIZE-1]-bufpt;
16501         break;
16502       case etFLOAT:
16503       case etEXP:
16504       case etGENERIC:
16505         realvalue = va_arg(ap,double);
16506 #ifndef SQLITE_OMIT_FLOATING_POINT
16507         if( precision<0 ) precision = 6;         /* Set default precision */
16508         if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
16509         if( realvalue<0.0 ){
16510           realvalue = -realvalue;
16511           prefix = '-';
16512         }else{
16513           if( flag_plussign )          prefix = '+';
16514           else if( flag_blanksign )    prefix = ' ';
16515           else                         prefix = 0;
16516         }
16517         if( xtype==etGENERIC && precision>0 ) precision--;
16518 #if 0
16519         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
16520         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
16521 #else
16522         /* It makes more sense to use 0.5 */
16523         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
16524 #endif
16525         if( xtype==etFLOAT ) realvalue += rounder;
16526         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
16527         exp = 0;
16528         if( sqlite3IsNaN(realvalue) ){
16529           bufpt = "NaN";
16530           length = 3;
16531           break;
16532         }
16533         if( realvalue>0.0 ){
16534           while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
16535           while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
16536           while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
16537           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
16538           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
16539           if( exp>350 ){
16540             if( prefix=='-' ){
16541               bufpt = "-Inf";
16542             }else if( prefix=='+' ){
16543               bufpt = "+Inf";
16544             }else{
16545               bufpt = "Inf";
16546             }
16547             length = strlen(bufpt);
16548             break;
16549           }
16550         }
16551         bufpt = buf;
16552         /*
16553         ** If the field type is etGENERIC, then convert to either etEXP
16554         ** or etFLOAT, as appropriate.
16555         */
16556         flag_exp = xtype==etEXP;
16557         if( xtype!=etFLOAT ){
16558           realvalue += rounder;
16559           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
16560         }
16561         if( xtype==etGENERIC ){
16562           flag_rtz = !flag_alternateform;
16563           if( exp<-4 || exp>precision ){
16564             xtype = etEXP;
16565           }else{
16566             precision = precision - exp;
16567             xtype = etFLOAT;
16568           }
16569         }else{
16570           flag_rtz = 0;
16571         }
16572         if( xtype==etEXP ){
16573           e2 = 0;
16574         }else{
16575           e2 = exp;
16576         }
16577         nsd = 0;
16578         flag_dp = (precision>0) | flag_alternateform | flag_altform2;
16579         /* The sign in front of the number */
16580         if( prefix ){
16581           *(bufpt++) = prefix;
16582         }
16583         /* Digits prior to the decimal point */
16584         if( e2<0 ){
16585           *(bufpt++) = '0';
16586         }else{
16587           for(; e2>=0; e2--){
16588             *(bufpt++) = et_getdigit(&realvalue,&nsd);
16589           }
16590         }
16591         /* The decimal point */
16592         if( flag_dp ){
16593           *(bufpt++) = '.';
16594         }
16595         /* "0" digits after the decimal point but before the first
16596         ** significant digit of the number */
16597         for(e2++; e2<0; precision--, e2++){
16598           assert( precision>0 );
16599           *(bufpt++) = '0';
16600         }
16601         /* Significant digits after the decimal point */
16602         while( (precision--)>0 ){
16603           *(bufpt++) = et_getdigit(&realvalue,&nsd);
16604         }
16605         /* Remove trailing zeros and the "." if no digits follow the "." */
16606         if( flag_rtz && flag_dp ){
16607           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
16608           assert( bufpt>buf );
16609           if( bufpt[-1]=='.' ){
16610             if( flag_altform2 ){
16611               *(bufpt++) = '0';
16612             }else{
16613               *(--bufpt) = 0;
16614             }
16615           }
16616         }
16617         /* Add the "eNNN" suffix */
16618         if( flag_exp || xtype==etEXP ){
16619           *(bufpt++) = aDigits[infop->charset];
16620           if( exp<0 ){
16621             *(bufpt++) = '-'; exp = -exp;
16622           }else{
16623             *(bufpt++) = '+';
16624           }
16625           if( exp>=100 ){
16626             *(bufpt++) = (exp/100)+'0';                /* 100's digit */
16627             exp %= 100;
16628           }
16629           *(bufpt++) = exp/10+'0';                     /* 10's digit */
16630           *(bufpt++) = exp%10+'0';                     /* 1's digit */
16631         }
16632         *bufpt = 0;
16633
16634         /* The converted number is in buf[] and zero terminated. Output it.
16635         ** Note that the number is in the usual order, not reversed as with
16636         ** integer conversions. */
16637         length = bufpt-buf;
16638         bufpt = buf;
16639
16640         /* Special case:  Add leading zeros if the flag_zeropad flag is
16641         ** set and we are not left justified */
16642         if( flag_zeropad && !flag_leftjustify && length < width){
16643           int i;
16644           int nPad = width - length;
16645           for(i=width; i>=nPad; i--){
16646             bufpt[i] = bufpt[i-nPad];
16647           }
16648           i = prefix!=0;
16649           while( nPad-- ) bufpt[i++] = '0';
16650           length = width;
16651         }
16652 #endif
16653         break;
16654       case etSIZE:
16655         *(va_arg(ap,int*)) = pAccum->nChar;
16656         length = width = 0;
16657         break;
16658       case etPERCENT:
16659         buf[0] = '%';
16660         bufpt = buf;
16661         length = 1;
16662         break;
16663       case etCHARX:
16664         c = buf[0] = va_arg(ap,int);
16665         if( precision>=0 ){
16666           for(idx=1; idx<precision; idx++) buf[idx] = c;
16667           length = precision;
16668         }else{
16669           length =1;
16670         }
16671         bufpt = buf;
16672         break;
16673       case etSTRING:
16674       case etDYNSTRING:
16675         bufpt = va_arg(ap,char*);
16676         if( bufpt==0 ){
16677           bufpt = "";
16678         }else if( xtype==etDYNSTRING ){
16679           zExtra = bufpt;
16680         }
16681         if( precision>=0 ){
16682           for(length=0; length<precision && bufpt[length]; length++){}
16683         }else{
16684           length = strlen(bufpt);
16685         }
16686         break;
16687       case etSQLESCAPE:
16688       case etSQLESCAPE2:
16689       case etSQLESCAPE3: {
16690         int i, j, n, ch, isnull;
16691         int needQuote;
16692         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
16693         char *escarg = va_arg(ap,char*);
16694         isnull = escarg==0;
16695         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
16696         for(i=n=0; (ch=escarg[i])!=0; i++){
16697           if( ch==q )  n++;
16698         }
16699         needQuote = !isnull && xtype==etSQLESCAPE2;
16700         n += i + 1 + needQuote*2;
16701         if( n>etBUFSIZE ){
16702           bufpt = zExtra = sqlite3Malloc( n );
16703           if( bufpt==0 ) return;
16704         }else{
16705           bufpt = buf;
16706         }
16707         j = 0;
16708         if( needQuote ) bufpt[j++] = q;
16709         for(i=0; (ch=escarg[i])!=0; i++){
16710           bufpt[j++] = ch;
16711           if( ch==q ) bufpt[j++] = ch;
16712         }
16713         if( needQuote ) bufpt[j++] = q;
16714         bufpt[j] = 0;
16715         length = j;
16716         /* The precision is ignored on %q and %Q */
16717         /* if( precision>=0 && precision<length ) length = precision; */
16718         break;
16719       }
16720       case etTOKEN: {
16721         Token *pToken = va_arg(ap, Token*);
16722         if( pToken ){
16723           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
16724         }
16725         length = width = 0;
16726         break;
16727       }
16728       case etSRCLIST: {
16729         SrcList *pSrc = va_arg(ap, SrcList*);
16730         int k = va_arg(ap, int);
16731         struct SrcList_item *pItem = &pSrc->a[k];
16732         assert( k>=0 && k<pSrc->nSrc );
16733         if( pItem->zDatabase ){
16734           sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
16735           sqlite3StrAccumAppend(pAccum, ".", 1);
16736         }
16737         sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
16738         length = width = 0;
16739         break;
16740       }
16741     }/* End switch over the format type */
16742     /*
16743     ** The text of the conversion is pointed to by "bufpt" and is
16744     ** "length" characters long.  The field width is "width".  Do
16745     ** the output.
16746     */
16747     if( !flag_leftjustify ){
16748       register int nspace;
16749       nspace = width-length;
16750       if( nspace>0 ){
16751         appendSpace(pAccum, nspace);
16752       }
16753     }
16754     if( length>0 ){
16755       sqlite3StrAccumAppend(pAccum, bufpt, length);
16756     }
16757     if( flag_leftjustify ){
16758       register int nspace;
16759       nspace = width-length;
16760       if( nspace>0 ){
16761         appendSpace(pAccum, nspace);
16762       }
16763     }
16764     if( zExtra ){
16765       sqlite3_free(zExtra);
16766     }
16767   }/* End for loop over the format string */
16768 } /* End of function */
16769
16770 /*
16771 ** Append N bytes of text from z to the StrAccum object.
16772 */
16773 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
16774   if( p->tooBig | p->mallocFailed ){
16775     return;
16776   }
16777   if( N<0 ){
16778     N = strlen(z);
16779   }
16780   if( N==0 ){
16781     return;
16782   }
16783   if( p->nChar+N >= p->nAlloc ){
16784     char *zNew;
16785     if( !p->useMalloc ){
16786       p->tooBig = 1;
16787       N = p->nAlloc - p->nChar - 1;
16788       if( N<=0 ){
16789         return;
16790       }
16791     }else{
16792       i64 szNew = p->nChar;
16793       szNew += N + 1;
16794       if( szNew > p->mxAlloc ){
16795         sqlite3StrAccumReset(p);
16796         p->tooBig = 1;
16797         return;
16798       }else{
16799         p->nAlloc = szNew;
16800       }
16801       zNew = sqlite3DbMallocRaw(p->db, p->nAlloc );
16802       if( zNew ){
16803         memcpy(zNew, p->zText, p->nChar);
16804         sqlite3StrAccumReset(p);
16805         p->zText = zNew;
16806       }else{
16807         p->mallocFailed = 1;
16808         sqlite3StrAccumReset(p);
16809         return;
16810       }
16811     }
16812   }
16813   memcpy(&p->zText[p->nChar], z, N);
16814   p->nChar += N;
16815 }
16816
16817 /*
16818 ** Finish off a string by making sure it is zero-terminated.
16819 ** Return a pointer to the resulting string.  Return a NULL
16820 ** pointer if any kind of error was encountered.
16821 */
16822 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
16823   if( p->zText ){
16824     p->zText[p->nChar] = 0;
16825     if( p->useMalloc && p->zText==p->zBase ){
16826       p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
16827       if( p->zText ){
16828         memcpy(p->zText, p->zBase, p->nChar+1);
16829       }else{
16830         p->mallocFailed = 1;
16831       }
16832     }
16833   }
16834   return p->zText;
16835 }
16836
16837 /*
16838 ** Reset an StrAccum string.  Reclaim all malloced memory.
16839 */
16840 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
16841   if( p->zText!=p->zBase ){
16842     sqlite3DbFree(p->db, p->zText);
16843   }
16844   p->zText = 0;
16845 }
16846
16847 /*
16848 ** Initialize a string accumulator
16849 */
16850 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
16851   p->zText = p->zBase = zBase;
16852   p->db = 0;
16853   p->nChar = 0;
16854   p->nAlloc = n;
16855   p->mxAlloc = mx;
16856   p->useMalloc = 1;
16857   p->tooBig = 0;
16858   p->mallocFailed = 0;
16859 }
16860
16861 /*
16862 ** Print into memory obtained from sqliteMalloc().  Use the internal
16863 ** %-conversion extensions.
16864 */
16865 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
16866   char *z;
16867   char zBase[SQLITE_PRINT_BUF_SIZE];
16868   StrAccum acc;
16869   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
16870                       db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH);
16871   acc.db = db;
16872   sqlite3VXPrintf(&acc, 1, zFormat, ap);
16873   z = sqlite3StrAccumFinish(&acc);
16874   if( acc.mallocFailed && db ){
16875     db->mallocFailed = 1;
16876   }
16877   return z;
16878 }
16879
16880 /*
16881 ** Print into memory obtained from sqliteMalloc().  Use the internal
16882 ** %-conversion extensions.
16883 */
16884 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
16885   va_list ap;
16886   char *z;
16887   va_start(ap, zFormat);
16888   z = sqlite3VMPrintf(db, zFormat, ap);
16889   va_end(ap);
16890   return z;
16891 }
16892
16893 /*
16894 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
16895 ** the string and before returnning.  This routine is intended to be used
16896 ** to modify an existing string.  For example:
16897 **
16898 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
16899 **
16900 */
16901 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
16902   va_list ap;
16903   char *z;
16904   va_start(ap, zFormat);
16905   z = sqlite3VMPrintf(db, zFormat, ap);
16906   va_end(ap);
16907   sqlite3DbFree(db, zStr);
16908   return z;
16909 }
16910
16911 /*
16912 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
16913 ** %-conversion extensions.
16914 */
16915 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
16916   char *z;
16917   char zBase[SQLITE_PRINT_BUF_SIZE];
16918   StrAccum acc;
16919 #ifndef SQLITE_OMIT_AUTOINIT
16920   if( sqlite3_initialize() ) return 0;
16921 #endif
16922   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
16923   sqlite3VXPrintf(&acc, 0, zFormat, ap);
16924   z = sqlite3StrAccumFinish(&acc);
16925   return z;
16926 }
16927
16928 /*
16929 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
16930 ** %-conversion extensions.
16931 */
16932 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
16933   va_list ap;
16934   char *z;
16935 #ifndef SQLITE_OMIT_AUTOINIT
16936   if( sqlite3_initialize() ) return 0;
16937 #endif
16938   va_start(ap, zFormat);
16939   z = sqlite3_vmprintf(zFormat, ap);
16940   va_end(ap);
16941   return z;
16942 }
16943
16944 /*
16945 ** sqlite3_snprintf() works like snprintf() except that it ignores the
16946 ** current locale settings.  This is important for SQLite because we
16947 ** are not able to use a "," as the decimal point in place of "." as
16948 ** specified by some locales.
16949 */
16950 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
16951   char *z;
16952   va_list ap;
16953   StrAccum acc;
16954
16955   if( n<=0 ){
16956     return zBuf;
16957   }
16958   sqlite3StrAccumInit(&acc, zBuf, n, 0);
16959   acc.useMalloc = 0;
16960   va_start(ap,zFormat);
16961   sqlite3VXPrintf(&acc, 0, zFormat, ap);
16962   va_end(ap);
16963   z = sqlite3StrAccumFinish(&acc);
16964   return z;
16965 }
16966
16967 #if defined(SQLITE_DEBUG)
16968 /*
16969 ** A version of printf() that understands %lld.  Used for debugging.
16970 ** The printf() built into some versions of windows does not understand %lld
16971 ** and segfaults if you give it a long long int.
16972 */
16973 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
16974   va_list ap;
16975   StrAccum acc;
16976   char zBuf[500];
16977   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
16978   acc.useMalloc = 0;
16979   va_start(ap,zFormat);
16980   sqlite3VXPrintf(&acc, 0, zFormat, ap);
16981   va_end(ap);
16982   sqlite3StrAccumFinish(&acc);
16983   fprintf(stdout,"%s", zBuf);
16984   fflush(stdout);
16985 }
16986 #endif
16987
16988 /************** End of printf.c **********************************************/
16989 /************** Begin file random.c ******************************************/
16990 /*
16991 ** 2001 September 15
16992 **
16993 ** The author disclaims copyright to this source code.  In place of
16994 ** a legal notice, here is a blessing:
16995 **
16996 **    May you do good and not evil.
16997 **    May you find forgiveness for yourself and forgive others.
16998 **    May you share freely, never taking more than you give.
16999 **
17000 *************************************************************************
17001 ** This file contains code to implement a pseudo-random number
17002 ** generator (PRNG) for SQLite.
17003 **
17004 ** Random numbers are used by some of the database backends in order
17005 ** to generate random integer keys for tables or random filenames.
17006 **
17007 ** $Id: random.c,v 1.25 2008/06/19 01:03:18 drh Exp $
17008 */
17009
17010
17011 /* All threads share a single random number generator.
17012 ** This structure is the current state of the generator.
17013 */
17014 static struct sqlite3PrngType {
17015   unsigned char isInit;          /* True if initialized */
17016   unsigned char i, j;            /* State variables */
17017   unsigned char s[256];          /* State variables */
17018 } sqlite3Prng;
17019
17020 /*
17021 ** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
17022 ** must be held while executing this routine.
17023 **
17024 ** Why not just use a library random generator like lrand48() for this?
17025 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
17026 ** good source of random numbers.  The lrand48() library function may
17027 ** well be good enough.  But maybe not.  Or maybe lrand48() has some
17028 ** subtle problems on some systems that could cause problems.  It is hard
17029 ** to know.  To minimize the risk of problems due to bad lrand48()
17030 ** implementations, SQLite uses this random number generator based
17031 ** on RC4, which we know works very well.
17032 **
17033 ** (Later):  Actually, OP_NewRowid does not depend on a good source of
17034 ** randomness any more.  But we will leave this code in all the same.
17035 */
17036 static int randomByte(void){
17037   unsigned char t;
17038
17039
17040   /* Initialize the state of the random number generator once,
17041   ** the first time this routine is called.  The seed value does
17042   ** not need to contain a lot of randomness since we are not
17043   ** trying to do secure encryption or anything like that...
17044   **
17045   ** Nothing in this file or anywhere else in SQLite does any kind of
17046   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
17047   ** number generator) not as an encryption device.
17048   */
17049   if( !sqlite3Prng.isInit ){
17050     int i;
17051     char k[256];
17052     sqlite3Prng.j = 0;
17053     sqlite3Prng.i = 0;
17054     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
17055     for(i=0; i<256; i++){
17056       sqlite3Prng.s[i] = i;
17057     }
17058     for(i=0; i<256; i++){
17059       sqlite3Prng.j += sqlite3Prng.s[i] + k[i];
17060       t = sqlite3Prng.s[sqlite3Prng.j];
17061       sqlite3Prng.s[sqlite3Prng.j] = sqlite3Prng.s[i];
17062       sqlite3Prng.s[i] = t;
17063     }
17064     sqlite3Prng.isInit = 1;
17065   }
17066
17067   /* Generate and return single random byte
17068   */
17069   sqlite3Prng.i++;
17070   t = sqlite3Prng.s[sqlite3Prng.i];
17071   sqlite3Prng.j += t;
17072   sqlite3Prng.s[sqlite3Prng.i] = sqlite3Prng.s[sqlite3Prng.j];
17073   sqlite3Prng.s[sqlite3Prng.j] = t;
17074   t += sqlite3Prng.s[sqlite3Prng.i];
17075   return sqlite3Prng.s[t];
17076 }
17077
17078 /*
17079 ** Return N random bytes.
17080 */
17081 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
17082   unsigned char *zBuf = pBuf;
17083 #ifndef SQLITE_MUTEX_NOOP
17084   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
17085 #endif
17086   sqlite3_mutex_enter(mutex);
17087   while( N-- ){
17088     *(zBuf++) = randomByte();
17089   }
17090   sqlite3_mutex_leave(mutex);
17091 }
17092
17093 #ifndef SQLITE_OMIT_BUILTIN_TEST
17094 /*
17095 ** For testing purposes, we sometimes want to preserve the state of
17096 ** PRNG and restore the PRNG to its saved state at a later time.
17097 ** The sqlite3_test_control() interface calls these routines to
17098 ** control the PRNG.
17099 */
17100 static struct sqlite3PrngType sqlite3SavedPrng;
17101 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
17102   memcpy(&sqlite3SavedPrng, &sqlite3Prng, sizeof(sqlite3Prng));
17103 }
17104 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
17105   memcpy(&sqlite3Prng, &sqlite3SavedPrng, sizeof(sqlite3Prng));
17106 }
17107 SQLITE_PRIVATE void sqlite3PrngResetState(void){
17108   sqlite3Prng.isInit = 0;
17109 }
17110 #endif /* SQLITE_OMIT_BUILTIN_TEST */
17111
17112 /************** End of random.c **********************************************/
17113 /************** Begin file utf.c *********************************************/
17114 /*
17115 ** 2004 April 13
17116 **
17117 ** The author disclaims copyright to this source code.  In place of
17118 ** a legal notice, here is a blessing:
17119 **
17120 **    May you do good and not evil.
17121 **    May you find forgiveness for yourself and forgive others.
17122 **    May you share freely, never taking more than you give.
17123 **
17124 *************************************************************************
17125 ** This file contains routines used to translate between UTF-8, 
17126 ** UTF-16, UTF-16BE, and UTF-16LE.
17127 **
17128 ** $Id: utf.c,v 1.63 2008/07/29 11:25:14 danielk1977 Exp $
17129 **
17130 ** Notes on UTF-8:
17131 **
17132 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
17133 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
17134 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
17135 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
17136 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
17137 **
17138 **
17139 ** Notes on UTF-16:  (with wwww+1==uuuuu)
17140 **
17141 **      Word-0               Word-1          Value
17142 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
17143 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
17144 **
17145 **
17146 ** BOM or Byte Order Mark:
17147 **     0xff 0xfe   little-endian utf-16 follows
17148 **     0xfe 0xff   big-endian utf-16 follows
17149 **
17150 */
17151 /************** Include vdbeInt.h in the middle of utf.c *********************/
17152 /************** Begin file vdbeInt.h *****************************************/
17153 /*
17154 ** 2003 September 6
17155 **
17156 ** The author disclaims copyright to this source code.  In place of
17157 ** a legal notice, here is a blessing:
17158 **
17159 **    May you do good and not evil.
17160 **    May you find forgiveness for yourself and forgive others.
17161 **    May you share freely, never taking more than you give.
17162 **
17163 *************************************************************************
17164 ** This is the header file for information that is private to the
17165 ** VDBE.  This information used to all be at the top of the single
17166 ** source code file "vdbe.c".  When that file became too big (over
17167 ** 6000 lines long) it was split up into several smaller files and
17168 ** this header information was factored out.
17169 **
17170 ** $Id: vdbeInt.h,v 1.153 2008/08/02 03:50:39 drh Exp $
17171 */
17172 #ifndef _VDBEINT_H_
17173 #define _VDBEINT_H_
17174
17175 /*
17176 ** intToKey() and keyToInt() used to transform the rowid.  But with
17177 ** the latest versions of the design they are no-ops.
17178 */
17179 #define keyToInt(X)   (X)
17180 #define intToKey(X)   (X)
17181
17182
17183 /*
17184 ** SQL is translated into a sequence of instructions to be
17185 ** executed by a virtual machine.  Each instruction is an instance
17186 ** of the following structure.
17187 */
17188 typedef struct VdbeOp Op;
17189
17190 /*
17191 ** Boolean values
17192 */
17193 typedef unsigned char Bool;
17194
17195 /*
17196 ** A cursor is a pointer into a single BTree within a database file.
17197 ** The cursor can seek to a BTree entry with a particular key, or
17198 ** loop over all entries of the Btree.  You can also insert new BTree
17199 ** entries or retrieve the key or data from the entry that the cursor
17200 ** is currently pointing to.
17201 ** 
17202 ** Every cursor that the virtual machine has open is represented by an
17203 ** instance of the following structure.
17204 **
17205 ** If the Cursor.isTriggerRow flag is set it means that this cursor is
17206 ** really a single row that represents the NEW or OLD pseudo-table of
17207 ** a row trigger.  The data for the row is stored in Cursor.pData and
17208 ** the rowid is in Cursor.iKey.
17209 */
17210 struct Cursor {
17211   BtCursor *pCursor;    /* The cursor structure of the backend */
17212   int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
17213   i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
17214   i64 nextRowid;        /* Next rowid returned by OP_NewRowid */
17215   Bool zeroed;          /* True if zeroed out and ready for reuse */
17216   Bool rowidIsValid;    /* True if lastRowid is valid */
17217   Bool atFirst;         /* True if pointing to first entry */
17218   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
17219   Bool nullRow;         /* True if pointing to a row with no data */
17220   Bool nextRowidValid;  /* True if the nextRowid field is valid */
17221   Bool pseudoTable;     /* This is a NEW or OLD pseudo-tables of a trigger */
17222   Bool ephemPseudoTable;
17223   Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
17224   Bool isTable;         /* True if a table requiring integer keys */
17225   Bool isIndex;         /* True if an index containing keys only - no data */
17226   u8 bogusIncrKey;      /* Something for pIncrKey to point to if pKeyInfo==0 */
17227   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
17228   Btree *pBt;           /* Separate file holding temporary table */
17229   int nData;            /* Number of bytes in pData */
17230   char *pData;          /* Data for a NEW or OLD pseudo-table */
17231   i64 iKey;             /* Key for the NEW or OLD pseudo-table row */
17232   u8 *pIncrKey;         /* Pointer to pKeyInfo->incrKey */
17233   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
17234   int nField;           /* Number of fields in the header */
17235   i64 seqCount;         /* Sequence counter */
17236   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
17237   const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
17238
17239   /* Cached information about the header for the data record that the
17240   ** cursor is currently pointing to.  Only valid if cacheValid is true.
17241   ** aRow might point to (ephemeral) data for the current row, or it might
17242   ** be NULL.
17243   */
17244   int cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
17245   int payloadSize;      /* Total number of bytes in the record */
17246   u32 *aType;           /* Type values for all entries in the record */
17247   u32 *aOffset;         /* Cached offsets to the start of each columns data */
17248   u8 *aRow;             /* Data for the current row, if all on one page */
17249 };
17250 typedef struct Cursor Cursor;
17251
17252 /*
17253 ** A value for Cursor.cacheValid that means the cache is always invalid.
17254 */
17255 #define CACHE_STALE 0
17256
17257 /*
17258 ** Internally, the vdbe manipulates nearly all SQL values as Mem
17259 ** structures. Each Mem struct may cache multiple representations (string,
17260 ** integer etc.) of the same value.  A value (and therefore Mem structure)
17261 ** has the following properties:
17262 **
17263 ** Each value has a manifest type. The manifest type of the value stored
17264 ** in a Mem struct is returned by the MemType(Mem*) macro. The type is
17265 ** one of SQLITE_NULL, SQLITE_INTEGER, SQLITE_REAL, SQLITE_TEXT or
17266 ** SQLITE_BLOB.
17267 */
17268 struct Mem {
17269   union {
17270     i64 i;              /* Integer value. Or FuncDef* when flags==MEM_Agg */
17271     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
17272   } u;
17273   double r;           /* Real value */
17274   sqlite3 *db;        /* The associated database connection */
17275   char *z;            /* String or BLOB value */
17276   int n;              /* Number of characters in string value, excluding '\0' */
17277   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
17278   u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
17279   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
17280   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
17281   char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
17282 };
17283
17284 /* One or more of the following flags are set to indicate the validOK
17285 ** representations of the value stored in the Mem struct.
17286 **
17287 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
17288 ** No other flags may be set in this case.
17289 **
17290 ** If the MEM_Str flag is set then Mem.z points at a string representation.
17291 ** Usually this is encoded in the same unicode encoding as the main
17292 ** database (see below for exceptions). If the MEM_Term flag is also
17293 ** set, then the string is nul terminated. The MEM_Int and MEM_Real 
17294 ** flags may coexist with the MEM_Str flag.
17295 **
17296 ** Multiple of these values can appear in Mem.flags.  But only one
17297 ** at a time can appear in Mem.type.
17298 */
17299 #define MEM_Null      0x0001   /* Value is NULL */
17300 #define MEM_Str       0x0002   /* Value is a string */
17301 #define MEM_Int       0x0004   /* Value is an integer */
17302 #define MEM_Real      0x0008   /* Value is a real number */
17303 #define MEM_Blob      0x0010   /* Value is a BLOB */
17304
17305 #define MemSetTypeFlag(p, f) \
17306   ((p)->flags = ((p)->flags&~(MEM_Int|MEM_Real|MEM_Null|MEM_Blob|MEM_Str))|f)
17307
17308 /* Whenever Mem contains a valid string or blob representation, one of
17309 ** the following flags must be set to determine the memory management
17310 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
17311 ** string is \000 or \u0000 terminated
17312 */
17313 #define MEM_Term      0x0020   /* String rep is nul terminated */
17314 #define MEM_Dyn       0x0040   /* Need to call sqliteFree() on Mem.z */
17315 #define MEM_Static    0x0080   /* Mem.z points to a static string */
17316 #define MEM_Ephem     0x0100   /* Mem.z points to an ephemeral string */
17317 #define MEM_Agg       0x0400   /* Mem.z points to an agg function context */
17318 #define MEM_Zero      0x0800   /* Mem.i contains count of 0s appended to blob */
17319
17320 #ifdef SQLITE_OMIT_INCRBLOB
17321   #undef MEM_Zero
17322   #define MEM_Zero 0x0000
17323 #endif
17324
17325
17326 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
17327 ** additional information about auxiliary information bound to arguments
17328 ** of the function.  This is used to implement the sqlite3_get_auxdata()
17329 ** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
17330 ** that can be associated with a constant argument to a function.  This
17331 ** allows functions such as "regexp" to compile their constant regular
17332 ** expression argument once and reused the compiled code for multiple
17333 ** invocations.
17334 */
17335 struct VdbeFunc {
17336   FuncDef *pFunc;               /* The definition of the function */
17337   int nAux;                     /* Number of entries allocated for apAux[] */
17338   struct AuxData {
17339     void *pAux;                   /* Aux data for the i-th argument */
17340     void (*xDelete)(void *);      /* Destructor for the aux data */
17341   } apAux[1];                   /* One slot for each function argument */
17342 };
17343
17344 /*
17345 ** The "context" argument for a installable function.  A pointer to an
17346 ** instance of this structure is the first argument to the routines used
17347 ** implement the SQL functions.
17348 **
17349 ** There is a typedef for this structure in sqlite.h.  So all routines,
17350 ** even the public interface to SQLite, can use a pointer to this structure.
17351 ** But this file is the only place where the internal details of this
17352 ** structure are known.
17353 **
17354 ** This structure is defined inside of vdbeInt.h because it uses substructures
17355 ** (Mem) which are only defined there.
17356 */
17357 struct sqlite3_context {
17358   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
17359   VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
17360   Mem s;                /* The return value is stored here */
17361   Mem *pMem;            /* Memory cell used to store aggregate context */
17362   int isError;          /* Error code returned by the function. */
17363   CollSeq *pColl;       /* Collating sequence */
17364 };
17365
17366 /*
17367 ** A Set structure is used for quick testing to see if a value
17368 ** is part of a small set.  Sets are used to implement code like
17369 ** this:
17370 **            x.y IN ('hi','hoo','hum')
17371 */
17372 typedef struct Set Set;
17373 struct Set {
17374   Hash hash;             /* A set is just a hash table */
17375   HashElem *prev;        /* Previously accessed hash elemen */
17376 };
17377
17378 /*
17379 ** A FifoPage structure holds a single page of valves.  Pages are arranged
17380 ** in a list.
17381 */
17382 typedef struct FifoPage FifoPage;
17383 struct FifoPage {
17384   int nSlot;         /* Number of entries aSlot[] */
17385   int iWrite;        /* Push the next value into this entry in aSlot[] */
17386   int iRead;         /* Read the next value from this entry in aSlot[] */
17387   FifoPage *pNext;   /* Next page in the fifo */
17388   i64 aSlot[1];      /* One or more slots for rowid values */
17389 };
17390
17391 /*
17392 ** The Fifo structure is typedef-ed in vdbeInt.h.  But the implementation
17393 ** of that structure is private to this file.
17394 **
17395 ** The Fifo structure describes the entire fifo.  
17396 */
17397 typedef struct Fifo Fifo;
17398 struct Fifo {
17399   int nEntry;         /* Total number of entries */
17400   sqlite3 *db;        /* The associated database connection */
17401   FifoPage *pFirst;   /* First page on the list */
17402   FifoPage *pLast;    /* Last page on the list */
17403 };
17404
17405 /*
17406 ** A Context stores the last insert rowid, the last statement change count,
17407 ** and the current statement change count (i.e. changes since last statement).
17408 ** The current keylist is also stored in the context.
17409 ** Elements of Context structure type make up the ContextStack, which is
17410 ** updated by the ContextPush and ContextPop opcodes (used by triggers).
17411 ** The context is pushed before executing a trigger a popped when the
17412 ** trigger finishes.
17413 */
17414 typedef struct Context Context;
17415 struct Context {
17416   i64 lastRowid;    /* Last insert rowid (sqlite3.lastRowid) */
17417   int nChange;      /* Statement changes (Vdbe.nChanges)     */
17418   Fifo sFifo;       /* Records that will participate in a DELETE or UPDATE */
17419 };
17420
17421 /*
17422 ** An instance of the virtual machine.  This structure contains the complete
17423 ** state of the virtual machine.
17424 **
17425 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_compile()
17426 ** is really a pointer to an instance of this structure.
17427 **
17428 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
17429 ** any virtual table method invocations made by the vdbe program. It is
17430 ** set to 2 for xDestroy method calls and 1 for all other methods. This
17431 ** variable is used for two purposes: to allow xDestroy methods to execute
17432 ** "DROP TABLE" statements and to prevent some nasty side effects of
17433 ** malloc failure when SQLite is invoked recursively by a virtual table 
17434 ** method function.
17435 */
17436 struct Vdbe {
17437   sqlite3 *db;        /* The whole database */
17438   Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
17439   int nOp;            /* Number of instructions in the program */
17440   int nOpAlloc;       /* Number of slots allocated for aOp[] */
17441   Op *aOp;            /* Space to hold the virtual machine's program */
17442   int nLabel;         /* Number of labels used */
17443   int nLabelAlloc;    /* Number of slots allocated in aLabel[] */
17444   int *aLabel;        /* Space to hold the labels */
17445   Mem **apArg;        /* Arguments to currently executing user function */
17446   Mem *aColName;      /* Column names to return */
17447   int nCursor;        /* Number of slots in apCsr[] */
17448   Cursor **apCsr;     /* One element of this array for each open cursor */
17449   int nVar;           /* Number of entries in aVar[] */
17450   Mem *aVar;          /* Values for the OP_Variable opcode. */
17451   char **azVar;       /* Name of variables */
17452   int okVar;          /* True if azVar[] has been initialized */
17453   int magic;              /* Magic number for sanity checking */
17454   int nMem;               /* Number of memory locations currently allocated */
17455   Mem *aMem;              /* The memory locations */
17456   int nCallback;          /* Number of callbacks invoked so far */
17457   int cacheCtr;           /* Cursor row cache generation counter */
17458   Fifo sFifo;             /* A list of ROWIDs */
17459   int contextStackTop;    /* Index of top element in the context stack */
17460   int contextStackDepth;  /* The size of the "context" stack */
17461   Context *contextStack;  /* Stack used by opcodes ContextPush & ContextPop*/
17462   int pc;                 /* The program counter */
17463   int rc;                 /* Value to return */
17464   unsigned uniqueCnt;     /* Used by OP_MakeRecord when P2!=0 */
17465   int errorAction;        /* Recovery action to do in case of an error */
17466   int inTempTrans;        /* True if temp database is transactioned */
17467   int nResColumn;         /* Number of columns in one row of the result set */
17468   char **azResColumn;     /* Values for one row of result */ 
17469   char *zErrMsg;          /* Error message written here */
17470   Mem *pResultSet;        /* Pointer to an array of results */
17471   u8 explain;             /* True if EXPLAIN present on SQL command */
17472   u8 changeCntOn;         /* True to update the change-counter */
17473   u8 expired;             /* True if the VM needs to be recompiled */
17474   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
17475   u8 inVtabMethod;        /* See comments above */
17476   int nChange;            /* Number of db changes made since last reset */
17477   i64 startTime;          /* Time when query started - used for profiling */
17478   int btreeMask;          /* Bitmask of db->aDb[] entries referenced */
17479   BtreeMutexArray aMutex; /* An array of Btree used here and needing locks */
17480   int nSql;             /* Number of bytes in zSql */
17481   char *zSql;           /* Text of the SQL statement that generated this */
17482 #ifdef SQLITE_DEBUG
17483   FILE *trace;        /* Write an execution trace here, if not NULL */
17484 #endif
17485   int openedStatement;  /* True if this VM has opened a statement journal */
17486 #ifdef SQLITE_SSE
17487   int fetchId;          /* Statement number used by sqlite3_fetch_statement */
17488   int lru;              /* Counter used for LRU cache replacement */
17489 #endif
17490 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
17491   Vdbe *pLruPrev;
17492   Vdbe *pLruNext;
17493 #endif
17494 };
17495
17496 /*
17497 ** An instance of the following structure holds information about a
17498 ** single index record that has already been parsed out into individual
17499 ** values.
17500 **
17501 ** A record is an object that contains one or more fields of data.
17502 ** Records are used to store the content of a table row and to store
17503 ** the key of an index.  A blob encoding of a record is created by
17504 ** the OP_MakeRecord opcode of the VDBE and is disassemblied by the
17505 ** OP_Column opcode.
17506 **
17507 ** This structure holds a record that has already been disassembled
17508 ** into its constitutent fields.
17509 */
17510 struct UnpackedRecord {
17511   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
17512   u16 nField;         /* Number of entries in apMem[] */
17513   u8 needFree;        /* True if memory obtained from sqlite3_malloc() */
17514   u8 needDestroy;     /* True if apMem[]s should be destroyed on close */
17515   Mem *aMem;          /* Values */
17516 };
17517
17518 /*
17519 ** The following are allowed values for Vdbe.magic
17520 */
17521 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
17522 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
17523 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
17524 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
17525
17526 /*
17527 ** Function prototypes
17528 */
17529 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, Cursor*);
17530 void sqliteVdbePopStack(Vdbe*,int);
17531 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(Cursor*);
17532 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
17533 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
17534 #endif
17535 SQLITE_PRIVATE int sqlite3VdbeSerialTypeLen(u32);
17536 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
17537 SQLITE_PRIVATE int sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
17538 SQLITE_PRIVATE int sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
17539 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
17540
17541 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
17542 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(Cursor*,UnpackedRecord *,int,const unsigned char*,int*);
17543 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(BtCursor *, i64 *);
17544 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
17545 SQLITE_PRIVATE int sqlite3VdbeIdxRowidLen(const u8*, int, int*);
17546 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
17547 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
17548 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
17549 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
17550 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
17551 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
17552 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
17553 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
17554 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
17555 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
17556 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
17557 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
17558 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
17559 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
17560 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
17561 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
17562 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
17563 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
17564 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
17565 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
17566 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
17567 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
17568 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
17569 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
17570 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
17571 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
17572 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
17573 SQLITE_PRIVATE int sqlite3VdbeOpcodeHasProperty(int, int);
17574 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
17575 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
17576 SQLITE_PRIVATE int sqlite3VdbeReleaseBuffers(Vdbe *p);
17577 #endif
17578
17579 #ifndef NDEBUG
17580 SQLITE_PRIVATE   void sqlite3VdbeMemSanity(Mem*);
17581 #endif
17582 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
17583 #ifdef SQLITE_DEBUG
17584 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
17585 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
17586 #endif
17587 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
17588 SQLITE_PRIVATE void sqlite3VdbeFifoInit(Fifo*, sqlite3*);
17589 SQLITE_PRIVATE int sqlite3VdbeFifoPush(Fifo*, i64);
17590 SQLITE_PRIVATE int sqlite3VdbeFifoPop(Fifo*, i64*);
17591 SQLITE_PRIVATE void sqlite3VdbeFifoClear(Fifo*);
17592
17593 #ifndef SQLITE_OMIT_INCRBLOB
17594 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
17595 #else
17596   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
17597 #endif
17598
17599 #endif /* !defined(_VDBEINT_H_) */
17600
17601 /************** End of vdbeInt.h *********************************************/
17602 /************** Continuing where we left off in utf.c ************************/
17603
17604 /*
17605 ** The following constant value is used by the SQLITE_BIGENDIAN and
17606 ** SQLITE_LITTLEENDIAN macros.
17607 */
17608 SQLITE_PRIVATE const int sqlite3one = 1;
17609
17610 /*
17611 ** This lookup table is used to help decode the first byte of
17612 ** a multi-byte UTF8 character.
17613 */
17614 static const unsigned char sqlite3UtfTrans1[] = {
17615   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
17616   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
17617   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
17618   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
17619   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
17620   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
17621   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
17622   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
17623 };
17624
17625
17626 #define WRITE_UTF8(zOut, c) {                          \
17627   if( c<0x00080 ){                                     \
17628     *zOut++ = (c&0xFF);                                \
17629   }                                                    \
17630   else if( c<0x00800 ){                                \
17631     *zOut++ = 0xC0 + ((c>>6)&0x1F);                    \
17632     *zOut++ = 0x80 + (c & 0x3F);                       \
17633   }                                                    \
17634   else if( c<0x10000 ){                                \
17635     *zOut++ = 0xE0 + ((c>>12)&0x0F);                   \
17636     *zOut++ = 0x80 + ((c>>6) & 0x3F);                  \
17637     *zOut++ = 0x80 + (c & 0x3F);                       \
17638   }else{                                               \
17639     *zOut++ = 0xF0 + ((c>>18) & 0x07);                 \
17640     *zOut++ = 0x80 + ((c>>12) & 0x3F);                 \
17641     *zOut++ = 0x80 + ((c>>6) & 0x3F);                  \
17642     *zOut++ = 0x80 + (c & 0x3F);                       \
17643   }                                                    \
17644 }
17645
17646 #define WRITE_UTF16LE(zOut, c) {                                \
17647   if( c<=0xFFFF ){                                              \
17648     *zOut++ = (c&0x00FF);                                       \
17649     *zOut++ = ((c>>8)&0x00FF);                                  \
17650   }else{                                                        \
17651     *zOut++ = (((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
17652     *zOut++ = (0x00D8 + (((c-0x10000)>>18)&0x03));              \
17653     *zOut++ = (c&0x00FF);                                       \
17654     *zOut++ = (0x00DC + ((c>>8)&0x03));                         \
17655   }                                                             \
17656 }
17657
17658 #define WRITE_UTF16BE(zOut, c) {                                \
17659   if( c<=0xFFFF ){                                              \
17660     *zOut++ = ((c>>8)&0x00FF);                                  \
17661     *zOut++ = (c&0x00FF);                                       \
17662   }else{                                                        \
17663     *zOut++ = (0x00D8 + (((c-0x10000)>>18)&0x03));              \
17664     *zOut++ = (((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
17665     *zOut++ = (0x00DC + ((c>>8)&0x03));                         \
17666     *zOut++ = (c&0x00FF);                                       \
17667   }                                                             \
17668 }
17669
17670 #define READ_UTF16LE(zIn, c){                                         \
17671   c = (*zIn++);                                                       \
17672   c += ((*zIn++)<<8);                                                 \
17673   if( c>=0xD800 && c<0xE000 ){                                       \
17674     int c2 = (*zIn++);                                                \
17675     c2 += ((*zIn++)<<8);                                              \
17676     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
17677     if( (c & 0xFFFF0000)==0 ) c = 0xFFFD;                             \
17678   }                                                                   \
17679 }
17680
17681 #define READ_UTF16BE(zIn, c){                                         \
17682   c = ((*zIn++)<<8);                                                  \
17683   c += (*zIn++);                                                      \
17684   if( c>=0xD800 && c<0xE000 ){                                       \
17685     int c2 = ((*zIn++)<<8);                                           \
17686     c2 += (*zIn++);                                                   \
17687     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
17688     if( (c & 0xFFFF0000)==0 ) c = 0xFFFD;                             \
17689   }                                                                   \
17690 }
17691
17692 /*
17693 ** Translate a single UTF-8 character.  Return the unicode value.
17694 **
17695 ** During translation, assume that the byte that zTerm points
17696 ** is a 0x00.
17697 **
17698 ** Write a pointer to the next unread byte back into *pzNext.
17699 **
17700 ** Notes On Invalid UTF-8:
17701 **
17702 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
17703 **     be encoded as a multi-byte character.  Any multi-byte character that
17704 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
17705 **
17706 **  *  This routine never allows a UTF16 surrogate value to be encoded.
17707 **     If a multi-byte character attempts to encode a value between
17708 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
17709 **
17710 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
17711 **     byte of a character are interpreted as single-byte characters
17712 **     and rendered as themselves even though they are technically
17713 **     invalid characters.
17714 **
17715 **  *  This routine accepts an infinite number of different UTF8 encodings
17716 **     for unicode values 0x80 and greater.  It do not change over-length
17717 **     encodings to 0xfffd as some systems recommend.
17718 */
17719 #define READ_UTF8(zIn, zTerm, c)                           \
17720   c = *(zIn++);                                            \
17721   if( c>=0xc0 ){                                           \
17722     c = sqlite3UtfTrans1[c-0xc0];                          \
17723     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
17724       c = (c<<6) + (0x3f & *(zIn++));                      \
17725     }                                                      \
17726     if( c<0x80                                             \
17727         || (c&0xFFFFF800)==0xD800                          \
17728         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
17729   }
17730 SQLITE_PRIVATE int sqlite3Utf8Read(
17731   const unsigned char *z,         /* First byte of UTF-8 character */
17732   const unsigned char *zTerm,     /* Pretend this byte is 0x00 */
17733   const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
17734 ){
17735   int c;
17736   READ_UTF8(z, zTerm, c);
17737   *pzNext = z;
17738   return c;
17739 }
17740
17741
17742
17743
17744 /*
17745 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
17746 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
17747 */ 
17748 /* #define TRANSLATE_TRACE 1 */
17749
17750 #ifndef SQLITE_OMIT_UTF16
17751 /*
17752 ** This routine transforms the internal text encoding used by pMem to
17753 ** desiredEnc. It is an error if the string is already of the desired
17754 ** encoding, or if *pMem does not contain a string value.
17755 */
17756 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
17757   int len;                    /* Maximum length of output string in bytes */
17758   unsigned char *zOut;                  /* Output buffer */
17759   unsigned char *zIn;                   /* Input iterator */
17760   unsigned char *zTerm;                 /* End of input */
17761   unsigned char *z;                     /* Output iterator */
17762   unsigned int c;
17763
17764   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
17765   assert( pMem->flags&MEM_Str );
17766   assert( pMem->enc!=desiredEnc );
17767   assert( pMem->enc!=0 );
17768   assert( pMem->n>=0 );
17769
17770 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
17771   {
17772     char zBuf[100];
17773     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
17774     fprintf(stderr, "INPUT:  %s\n", zBuf);
17775   }
17776 #endif
17777
17778   /* If the translation is between UTF-16 little and big endian, then 
17779   ** all that is required is to swap the byte order. This case is handled
17780   ** differently from the others.
17781   */
17782   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
17783     u8 temp;
17784     int rc;
17785     rc = sqlite3VdbeMemMakeWriteable(pMem);
17786     if( rc!=SQLITE_OK ){
17787       assert( rc==SQLITE_NOMEM );
17788       return SQLITE_NOMEM;
17789     }
17790     zIn = (u8*)pMem->z;
17791     zTerm = &zIn[pMem->n];
17792     while( zIn<zTerm ){
17793       temp = *zIn;
17794       *zIn = *(zIn+1);
17795       zIn++;
17796       *zIn++ = temp;
17797     }
17798     pMem->enc = desiredEnc;
17799     goto translate_out;
17800   }
17801
17802   /* Set len to the maximum number of bytes required in the output buffer. */
17803   if( desiredEnc==SQLITE_UTF8 ){
17804     /* When converting from UTF-16, the maximum growth results from
17805     ** translating a 2-byte character to a 4-byte UTF-8 character.
17806     ** A single byte is required for the output string
17807     ** nul-terminator.
17808     */
17809     len = pMem->n * 2 + 1;
17810   }else{
17811     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
17812     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
17813     ** character. Two bytes are required in the output buffer for the
17814     ** nul-terminator.
17815     */
17816     len = pMem->n * 2 + 2;
17817   }
17818
17819   /* Set zIn to point at the start of the input buffer and zTerm to point 1
17820   ** byte past the end.
17821   **
17822   ** Variable zOut is set to point at the output buffer, space obtained
17823   ** from sqlite3_malloc().
17824   */
17825   zIn = (u8*)pMem->z;
17826   zTerm = &zIn[pMem->n];
17827   zOut = sqlite3DbMallocRaw(pMem->db, len);
17828   if( !zOut ){
17829     return SQLITE_NOMEM;
17830   }
17831   z = zOut;
17832
17833   if( pMem->enc==SQLITE_UTF8 ){
17834     if( desiredEnc==SQLITE_UTF16LE ){
17835       /* UTF-8 -> UTF-16 Little-endian */
17836       while( zIn<zTerm ){
17837         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
17838         READ_UTF8(zIn, zTerm, c);
17839         WRITE_UTF16LE(z, c);
17840       }
17841     }else{
17842       assert( desiredEnc==SQLITE_UTF16BE );
17843       /* UTF-8 -> UTF-16 Big-endian */
17844       while( zIn<zTerm ){
17845         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
17846         READ_UTF8(zIn, zTerm, c);
17847         WRITE_UTF16BE(z, c);
17848       }
17849     }
17850     pMem->n = z - zOut;
17851     *z++ = 0;
17852   }else{
17853     assert( desiredEnc==SQLITE_UTF8 );
17854     if( pMem->enc==SQLITE_UTF16LE ){
17855       /* UTF-16 Little-endian -> UTF-8 */
17856       while( zIn<zTerm ){
17857         READ_UTF16LE(zIn, c); 
17858         WRITE_UTF8(z, c);
17859       }
17860     }else{
17861       /* UTF-16 Big-endian -> UTF-8 */
17862       while( zIn<zTerm ){
17863         READ_UTF16BE(zIn, c); 
17864         WRITE_UTF8(z, c);
17865       }
17866     }
17867     pMem->n = z - zOut;
17868   }
17869   *z = 0;
17870   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
17871
17872   sqlite3VdbeMemRelease(pMem);
17873   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
17874   pMem->enc = desiredEnc;
17875   pMem->flags |= (MEM_Term|MEM_Dyn);
17876   pMem->z = (char*)zOut;
17877   pMem->zMalloc = pMem->z;
17878
17879 translate_out:
17880 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
17881   {
17882     char zBuf[100];
17883     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
17884     fprintf(stderr, "OUTPUT: %s\n", zBuf);
17885   }
17886 #endif
17887   return SQLITE_OK;
17888 }
17889
17890 /*
17891 ** This routine checks for a byte-order mark at the beginning of the 
17892 ** UTF-16 string stored in *pMem. If one is present, it is removed and
17893 ** the encoding of the Mem adjusted. This routine does not do any
17894 ** byte-swapping, it just sets Mem.enc appropriately.
17895 **
17896 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
17897 ** changed by this function.
17898 */
17899 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
17900   int rc = SQLITE_OK;
17901   u8 bom = 0;
17902
17903   if( pMem->n<0 || pMem->n>1 ){
17904     u8 b1 = *(u8 *)pMem->z;
17905     u8 b2 = *(((u8 *)pMem->z) + 1);
17906     if( b1==0xFE && b2==0xFF ){
17907       bom = SQLITE_UTF16BE;
17908     }
17909     if( b1==0xFF && b2==0xFE ){
17910       bom = SQLITE_UTF16LE;
17911     }
17912   }
17913   
17914   if( bom ){
17915     rc = sqlite3VdbeMemMakeWriteable(pMem);
17916     if( rc==SQLITE_OK ){
17917       pMem->n -= 2;
17918       memmove(pMem->z, &pMem->z[2], pMem->n);
17919       pMem->z[pMem->n] = '\0';
17920       pMem->z[pMem->n+1] = '\0';
17921       pMem->flags |= MEM_Term;
17922       pMem->enc = bom;
17923     }
17924   }
17925   return rc;
17926 }
17927 #endif /* SQLITE_OMIT_UTF16 */
17928
17929 /*
17930 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
17931 ** return the number of unicode characters in pZ up to (but not including)
17932 ** the first 0x00 byte. If nByte is not less than zero, return the
17933 ** number of unicode characters in the first nByte of pZ (or up to 
17934 ** the first 0x00, whichever comes first).
17935 */
17936 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
17937   int r = 0;
17938   const u8 *z = (const u8*)zIn;
17939   const u8 *zTerm;
17940   if( nByte>=0 ){
17941     zTerm = &z[nByte];
17942   }else{
17943     zTerm = (const u8*)(-1);
17944   }
17945   assert( z<=zTerm );
17946   while( *z!=0 && z<zTerm ){
17947     SQLITE_SKIP_UTF8(z);
17948     r++;
17949   }
17950   return r;
17951 }
17952
17953 /* This test function is not currently used by the automated test-suite. 
17954 ** Hence it is only available in debug builds.
17955 */
17956 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
17957 /*
17958 ** Translate UTF-8 to UTF-8.
17959 **
17960 ** This has the effect of making sure that the string is well-formed
17961 ** UTF-8.  Miscoded characters are removed.
17962 **
17963 ** The translation is done in-place (since it is impossible for the
17964 ** correct UTF-8 encoding to be longer than a malformed encoding).
17965 */
17966 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
17967   unsigned char *zOut = zIn;
17968   unsigned char *zStart = zIn;
17969   unsigned char *zTerm;
17970   u32 c;
17971
17972   while( zIn[0] ){
17973     c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn);
17974     if( c!=0xfffd ){
17975       WRITE_UTF8(zOut, c);
17976     }
17977   }
17978   *zOut = 0;
17979   return zOut - zStart;
17980 }
17981 #endif
17982
17983 #ifndef SQLITE_OMIT_UTF16
17984 /*
17985 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
17986 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
17987 ** be freed by the calling function.
17988 **
17989 ** NULL is returned if there is an allocation error.
17990 */
17991 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte){
17992   Mem m;
17993   memset(&m, 0, sizeof(m));
17994   m.db = db;
17995   sqlite3VdbeMemSetStr(&m, z, nByte, SQLITE_UTF16NATIVE, SQLITE_STATIC);
17996   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
17997   if( db->mallocFailed ){
17998     sqlite3VdbeMemRelease(&m);
17999     m.z = 0;
18000   }
18001   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
18002   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
18003   return (m.flags & MEM_Dyn)!=0 ? m.z : sqlite3DbStrDup(db, m.z);
18004 }
18005
18006 /*
18007 ** pZ is a UTF-16 encoded unicode string. If nChar is less than zero,
18008 ** return the number of bytes up to (but not including), the first pair
18009 ** of consecutive 0x00 bytes in pZ. If nChar is not less than zero,
18010 ** then return the number of bytes in the first nChar unicode characters
18011 ** in pZ (or up until the first pair of 0x00 bytes, whichever comes first).
18012 */
18013 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
18014   unsigned int c = 1;
18015   char const *z = zIn;
18016   int n = 0;
18017   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
18018     /* Using an "if (SQLITE_UTF16NATIVE==SQLITE_UTF16BE)" construct here
18019     ** and in other parts of this file means that at one branch will
18020     ** not be covered by coverage testing on any single host. But coverage
18021     ** will be complete if the tests are run on both a little-endian and 
18022     ** big-endian host. Because both the UTF16NATIVE and SQLITE_UTF16BE
18023     ** macros are constant at compile time the compiler can determine
18024     ** which branch will be followed. It is therefore assumed that no runtime
18025     ** penalty is paid for this "if" statement.
18026     */
18027     while( c && ((nChar<0) || n<nChar) ){
18028       READ_UTF16BE(z, c);
18029       n++;
18030     }
18031   }else{
18032     while( c && ((nChar<0) || n<nChar) ){
18033       READ_UTF16LE(z, c);
18034       n++;
18035     }
18036   }
18037   return (z-(char const *)zIn)-((c==0)?2:0);
18038 }
18039
18040 #if defined(SQLITE_TEST)
18041 /*
18042 ** This routine is called from the TCL test function "translate_selftest".
18043 ** It checks that the primitives for serializing and deserializing
18044 ** characters in each encoding are inverses of each other.
18045 */
18046 SQLITE_PRIVATE void sqlite3UtfSelfTest(){
18047   unsigned int i, t;
18048   unsigned char zBuf[20];
18049   unsigned char *z;
18050   unsigned char *zTerm;
18051   int n;
18052   unsigned int c;
18053
18054   for(i=0; i<0x00110000; i++){
18055     z = zBuf;
18056     WRITE_UTF8(z, i);
18057     n = z-zBuf;
18058     z[0] = 0;
18059     zTerm = z;
18060     z = zBuf;
18061     c = sqlite3Utf8Read(z, zTerm, (const u8**)&z);
18062     t = i;
18063     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
18064     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
18065     assert( c==t );
18066     assert( (z-zBuf)==n );
18067   }
18068   for(i=0; i<0x00110000; i++){
18069     if( i>=0xD800 && i<0xE000 ) continue;
18070     z = zBuf;
18071     WRITE_UTF16LE(z, i);
18072     n = z-zBuf;
18073     z[0] = 0;
18074     z = zBuf;
18075     READ_UTF16LE(z, c);
18076     assert( c==i );
18077     assert( (z-zBuf)==n );
18078   }
18079   for(i=0; i<0x00110000; i++){
18080     if( i>=0xD800 && i<0xE000 ) continue;
18081     z = zBuf;
18082     WRITE_UTF16BE(z, i);
18083     n = z-zBuf;
18084     z[0] = 0;
18085     z = zBuf;
18086     READ_UTF16BE(z, c);
18087     assert( c==i );
18088     assert( (z-zBuf)==n );
18089   }
18090 }
18091 #endif /* SQLITE_TEST */
18092 #endif /* SQLITE_OMIT_UTF16 */
18093
18094 /************** End of utf.c *************************************************/
18095 /************** Begin file util.c ********************************************/
18096 /*
18097 ** 2001 September 15
18098 **
18099 ** The author disclaims copyright to this source code.  In place of
18100 ** a legal notice, here is a blessing:
18101 **
18102 **    May you do good and not evil.
18103 **    May you find forgiveness for yourself and forgive others.
18104 **    May you share freely, never taking more than you give.
18105 **
18106 *************************************************************************
18107 ** Utility functions used throughout sqlite.
18108 **
18109 ** This file contains functions for allocating memory, comparing
18110 ** strings, and stuff like that.
18111 **
18112 ** $Id: util.c,v 1.241 2008/07/28 19:34:54 drh Exp $
18113 */
18114
18115
18116 /*
18117 ** Return true if the floating point value is Not a Number (NaN).
18118 */
18119 SQLITE_PRIVATE int sqlite3IsNaN(double x){
18120   /* This NaN test sometimes fails if compiled on GCC with -ffast-math.
18121   ** On the other hand, the use of -ffast-math comes with the following
18122   ** warning:
18123   **
18124   **      This option [-ffast-math] should never be turned on by any
18125   **      -O option since it can result in incorrect output for programs
18126   **      which depend on an exact implementation of IEEE or ISO 
18127   **      rules/specifications for math functions.
18128   **
18129   ** Under MSVC, this NaN test may fail if compiled with a floating-
18130   ** point precision mode other than /fp:precise.  From the MSDN 
18131   ** documentation:
18132   **
18133   **      The compiler [with /fp:precise] will properly handle comparisons 
18134   **      involving NaN. For example, x != x evaluates to true if x is NaN 
18135   **      ...
18136   */
18137 #ifdef __FAST_MATH__
18138 # error SQLite will not work correctly with the -ffast-math option of GCC.
18139 #endif
18140   volatile double y = x;
18141   volatile double z = y;
18142   return y!=z;
18143 }
18144
18145 /*
18146 ** Return the length of a string, except do not allow the string length
18147 ** to exceed the SQLITE_LIMIT_LENGTH setting.
18148 */
18149 SQLITE_PRIVATE int sqlite3Strlen(sqlite3 *db, const char *z){
18150   const char *z2 = z;
18151   int len;
18152   size_t x;
18153   while( *z2 ){ z2++; }
18154   x = z2 - z;
18155   len = 0x7fffffff & x;
18156   if( len!=x || len > db->aLimit[SQLITE_LIMIT_LENGTH] ){
18157     return db->aLimit[SQLITE_LIMIT_LENGTH];
18158   }else{
18159     return len;
18160   }
18161 }
18162
18163 /*
18164 ** Set the most recent error code and error string for the sqlite
18165 ** handle "db". The error code is set to "err_code".
18166 **
18167 ** If it is not NULL, string zFormat specifies the format of the
18168 ** error string in the style of the printf functions: The following
18169 ** format characters are allowed:
18170 **
18171 **      %s      Insert a string
18172 **      %z      A string that should be freed after use
18173 **      %d      Insert an integer
18174 **      %T      Insert a token
18175 **      %S      Insert the first element of a SrcList
18176 **
18177 ** zFormat and any string tokens that follow it are assumed to be
18178 ** encoded in UTF-8.
18179 **
18180 ** To clear the most recent error for sqlite handle "db", sqlite3Error
18181 ** should be called with err_code set to SQLITE_OK and zFormat set
18182 ** to NULL.
18183 */
18184 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
18185   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
18186     db->errCode = err_code;
18187     if( zFormat ){
18188       char *z;
18189       va_list ap;
18190       va_start(ap, zFormat);
18191       z = sqlite3VMPrintf(db, zFormat, ap);
18192       va_end(ap);
18193       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
18194     }else{
18195       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
18196     }
18197   }
18198 }
18199
18200 /*
18201 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
18202 ** The following formatting characters are allowed:
18203 **
18204 **      %s      Insert a string
18205 **      %z      A string that should be freed after use
18206 **      %d      Insert an integer
18207 **      %T      Insert a token
18208 **      %S      Insert the first element of a SrcList
18209 **
18210 ** This function should be used to report any error that occurs whilst
18211 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
18212 ** last thing the sqlite3_prepare() function does is copy the error
18213 ** stored by this function into the database handle using sqlite3Error().
18214 ** Function sqlite3Error() should be used during statement execution
18215 ** (sqlite3_step() etc.).
18216 */
18217 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
18218   va_list ap;
18219   sqlite3 *db = pParse->db;
18220   pParse->nErr++;
18221   sqlite3DbFree(db, pParse->zErrMsg);
18222   va_start(ap, zFormat);
18223   pParse->zErrMsg = sqlite3VMPrintf(db, zFormat, ap);
18224   va_end(ap);
18225   if( pParse->rc==SQLITE_OK ){
18226     pParse->rc = SQLITE_ERROR;
18227   }
18228 }
18229
18230 /*
18231 ** Clear the error message in pParse, if any
18232 */
18233 SQLITE_PRIVATE void sqlite3ErrorClear(Parse *pParse){
18234   sqlite3DbFree(pParse->db, pParse->zErrMsg);
18235   pParse->zErrMsg = 0;
18236   pParse->nErr = 0;
18237 }
18238
18239 /*
18240 ** Convert an SQL-style quoted string into a normal string by removing
18241 ** the quote characters.  The conversion is done in-place.  If the
18242 ** input does not begin with a quote character, then this routine
18243 ** is a no-op.
18244 **
18245 ** 2002-Feb-14: This routine is extended to remove MS-Access style
18246 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
18247 ** "a-b-c".
18248 */
18249 SQLITE_PRIVATE void sqlite3Dequote(char *z){
18250   int quote;
18251   int i, j;
18252   if( z==0 ) return;
18253   quote = z[0];
18254   switch( quote ){
18255     case '\'':  break;
18256     case '"':   break;
18257     case '`':   break;                /* For MySQL compatibility */
18258     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
18259     default:    return;
18260   }
18261   for(i=1, j=0; z[i]; i++){
18262     if( z[i]==quote ){
18263       if( z[i+1]==quote ){
18264         z[j++] = quote;
18265         i++;
18266       }else{
18267         z[j++] = 0;
18268         break;
18269       }
18270     }else{
18271       z[j++] = z[i];
18272     }
18273   }
18274 }
18275
18276 /* Convenient short-hand */
18277 #define UpperToLower sqlite3UpperToLower
18278
18279 /*
18280 ** Some systems have stricmp().  Others have strcasecmp().  Because
18281 ** there is no consistency, we will define our own.
18282 */
18283 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
18284   register unsigned char *a, *b;
18285   a = (unsigned char *)zLeft;
18286   b = (unsigned char *)zRight;
18287   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
18288   return UpperToLower[*a] - UpperToLower[*b];
18289 }
18290 SQLITE_PRIVATE int sqlite3StrNICmp(const char *zLeft, const char *zRight, int N){
18291   register unsigned char *a, *b;
18292   a = (unsigned char *)zLeft;
18293   b = (unsigned char *)zRight;
18294   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
18295   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
18296 }
18297
18298 /*
18299 ** Return TRUE if z is a pure numeric string.  Return FALSE if the
18300 ** string contains any character which is not part of a number. If
18301 ** the string is numeric and contains the '.' character, set *realnum
18302 ** to TRUE (otherwise FALSE).
18303 **
18304 ** An empty string is considered non-numeric.
18305 */
18306 SQLITE_PRIVATE int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
18307   int incr = (enc==SQLITE_UTF8?1:2);
18308   if( enc==SQLITE_UTF16BE ) z++;
18309   if( *z=='-' || *z=='+' ) z += incr;
18310   if( !isdigit(*(u8*)z) ){
18311     return 0;
18312   }
18313   z += incr;
18314   if( realnum ) *realnum = 0;
18315   while( isdigit(*(u8*)z) ){ z += incr; }
18316   if( *z=='.' ){
18317     z += incr;
18318     if( !isdigit(*(u8*)z) ) return 0;
18319     while( isdigit(*(u8*)z) ){ z += incr; }
18320     if( realnum ) *realnum = 1;
18321   }
18322   if( *z=='e' || *z=='E' ){
18323     z += incr;
18324     if( *z=='+' || *z=='-' ) z += incr;
18325     if( !isdigit(*(u8*)z) ) return 0;
18326     while( isdigit(*(u8*)z) ){ z += incr; }
18327     if( realnum ) *realnum = 1;
18328   }
18329   return *z==0;
18330 }
18331
18332 /*
18333 ** The string z[] is an ascii representation of a real number.
18334 ** Convert this string to a double.
18335 **
18336 ** This routine assumes that z[] really is a valid number.  If it
18337 ** is not, the result is undefined.
18338 **
18339 ** This routine is used instead of the library atof() function because
18340 ** the library atof() might want to use "," as the decimal point instead
18341 ** of "." depending on how locale is set.  But that would cause problems
18342 ** for SQL.  So this routine always uses "." regardless of locale.
18343 */
18344 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult){
18345 #ifndef SQLITE_OMIT_FLOATING_POINT
18346   int sign = 1;
18347   const char *zBegin = z;
18348   LONGDOUBLE_TYPE v1 = 0.0;
18349   int nSignificant = 0;
18350   while( isspace(*(u8*)z) ) z++;
18351   if( *z=='-' ){
18352     sign = -1;
18353     z++;
18354   }else if( *z=='+' ){
18355     z++;
18356   }
18357   while( z[0]=='0' ){
18358     z++;
18359   }
18360   while( isdigit(*(u8*)z) ){
18361     v1 = v1*10.0 + (*z - '0');
18362     z++;
18363     nSignificant++;
18364   }
18365   if( *z=='.' ){
18366     LONGDOUBLE_TYPE divisor = 1.0;
18367     z++;
18368     if( nSignificant==0 ){
18369       while( z[0]=='0' ){
18370         divisor *= 10.0;
18371         z++;
18372       }
18373     }
18374     while( isdigit(*(u8*)z) ){
18375       if( nSignificant<18 ){
18376         v1 = v1*10.0 + (*z - '0');
18377         divisor *= 10.0;
18378         nSignificant++;
18379       }
18380       z++;
18381     }
18382     v1 /= divisor;
18383   }
18384   if( *z=='e' || *z=='E' ){
18385     int esign = 1;
18386     int eval = 0;
18387     LONGDOUBLE_TYPE scale = 1.0;
18388     z++;
18389     if( *z=='-' ){
18390       esign = -1;
18391       z++;
18392     }else if( *z=='+' ){
18393       z++;
18394     }
18395     while( isdigit(*(u8*)z) ){
18396       eval = eval*10 + *z - '0';
18397       z++;
18398     }
18399     while( eval>=64 ){ scale *= 1.0e+64; eval -= 64; }
18400     while( eval>=16 ){ scale *= 1.0e+16; eval -= 16; }
18401     while( eval>=4 ){ scale *= 1.0e+4; eval -= 4; }
18402     while( eval>=1 ){ scale *= 1.0e+1; eval -= 1; }
18403     if( esign<0 ){
18404       v1 /= scale;
18405     }else{
18406       v1 *= scale;
18407     }
18408   }
18409   *pResult = sign<0 ? -v1 : v1;
18410   return z - zBegin;
18411 #else
18412   return sqlite3Atoi64(z, pResult);
18413 #endif /* SQLITE_OMIT_FLOATING_POINT */
18414 }
18415
18416 /*
18417 ** Compare the 19-character string zNum against the text representation
18418 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
18419 ** if zNum is less than, equal to, or greater than the string.
18420 **
18421 ** Unlike memcmp() this routine is guaranteed to return the difference
18422 ** in the values of the last digit if the only difference is in the
18423 ** last digit.  So, for example,
18424 **
18425 **      compare2pow63("9223372036854775800")
18426 **
18427 ** will return -8.
18428 */
18429 static int compare2pow63(const char *zNum){
18430   int c;
18431   c = memcmp(zNum,"922337203685477580",18);
18432   if( c==0 ){
18433     c = zNum[18] - '8';
18434   }
18435   return c;
18436 }
18437
18438
18439 /*
18440 ** Return TRUE if zNum is a 64-bit signed integer and write
18441 ** the value of the integer into *pNum.  If zNum is not an integer
18442 ** or is an integer that is too large to be expressed with 64 bits,
18443 ** then return false.
18444 **
18445 ** When this routine was originally written it dealt with only
18446 ** 32-bit numbers.  At that time, it was much faster than the
18447 ** atoi() library routine in RedHat 7.2.
18448 */
18449 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum){
18450   i64 v = 0;
18451   int neg;
18452   int i, c;
18453   const char *zStart;
18454   while( isspace(*(u8*)zNum) ) zNum++;
18455   if( *zNum=='-' ){
18456     neg = 1;
18457     zNum++;
18458   }else if( *zNum=='+' ){
18459     neg = 0;
18460     zNum++;
18461   }else{
18462     neg = 0;
18463   }
18464   zStart = zNum;
18465   while( zNum[0]=='0' ){ zNum++; } /* Skip over leading zeros. Ticket #2454 */
18466   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
18467     v = v*10 + c - '0';
18468   }
18469   *pNum = neg ? -v : v;
18470   if( c!=0 || (i==0 && zStart==zNum) || i>19 ){
18471     /* zNum is empty or contains non-numeric text or is longer
18472     ** than 19 digits (thus guaranting that it is too large) */
18473     return 0;
18474   }else if( i<19 ){
18475     /* Less than 19 digits, so we know that it fits in 64 bits */
18476     return 1;
18477   }else{
18478     /* 19-digit numbers must be no larger than 9223372036854775807 if positive
18479     ** or 9223372036854775808 if negative.  Note that 9223372036854665808
18480     ** is 2^63. */
18481     return compare2pow63(zNum)<neg;
18482   }
18483 }
18484
18485 /*
18486 ** The string zNum represents an integer.  There might be some other
18487 ** information following the integer too, but that part is ignored.
18488 ** If the integer that the prefix of zNum represents will fit in a
18489 ** 64-bit signed integer, return TRUE.  Otherwise return FALSE.
18490 **
18491 ** This routine returns FALSE for the string -9223372036854775808 even that
18492 ** that number will, in theory fit in a 64-bit integer.  Positive
18493 ** 9223373036854775808 will not fit in 64 bits.  So it seems safer to return
18494 ** false.
18495 */
18496 SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *zNum, int negFlag){
18497   int i, c;
18498   int neg = 0;
18499   if( *zNum=='-' ){
18500     neg = 1;
18501     zNum++;
18502   }else if( *zNum=='+' ){
18503     zNum++;
18504   }
18505   if( negFlag ) neg = 1-neg;
18506   while( *zNum=='0' ){
18507     zNum++;   /* Skip leading zeros.  Ticket #2454 */
18508   }
18509   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
18510   if( i<19 ){
18511     /* Guaranteed to fit if less than 19 digits */
18512     return 1;
18513   }else if( i>19 ){
18514     /* Guaranteed to be too big if greater than 19 digits */
18515     return 0;
18516   }else{
18517     /* Compare against 2^63. */
18518     return compare2pow63(zNum)<neg;
18519   }
18520 }
18521
18522 /*
18523 ** If zNum represents an integer that will fit in 32-bits, then set
18524 ** *pValue to that integer and return true.  Otherwise return false.
18525 **
18526 ** Any non-numeric characters that following zNum are ignored.
18527 ** This is different from sqlite3Atoi64() which requires the
18528 ** input number to be zero-terminated.
18529 */
18530 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
18531   sqlite_int64 v = 0;
18532   int i, c;
18533   int neg = 0;
18534   if( zNum[0]=='-' ){
18535     neg = 1;
18536     zNum++;
18537   }else if( zNum[0]=='+' ){
18538     zNum++;
18539   }
18540   while( zNum[0]=='0' ) zNum++;
18541   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
18542     v = v*10 + c;
18543   }
18544
18545   /* The longest decimal representation of a 32 bit integer is 10 digits:
18546   **
18547   **             1234567890
18548   **     2^31 -> 2147483648
18549   */
18550   if( i>10 ){
18551     return 0;
18552   }
18553   if( v-neg>2147483647 ){
18554     return 0;
18555   }
18556   if( neg ){
18557     v = -v;
18558   }
18559   *pValue = (int)v;
18560   return 1;
18561 }
18562
18563 /*
18564 ** The variable-length integer encoding is as follows:
18565 **
18566 ** KEY:
18567 **         A = 0xxxxxxx    7 bits of data and one flag bit
18568 **         B = 1xxxxxxx    7 bits of data and one flag bit
18569 **         C = xxxxxxxx    8 bits of data
18570 **
18571 **  7 bits - A
18572 ** 14 bits - BA
18573 ** 21 bits - BBA
18574 ** 28 bits - BBBA
18575 ** 35 bits - BBBBA
18576 ** 42 bits - BBBBBA
18577 ** 49 bits - BBBBBBA
18578 ** 56 bits - BBBBBBBA
18579 ** 64 bits - BBBBBBBBC
18580 */
18581
18582 /*
18583 ** Write a 64-bit variable-length integer to memory starting at p[0].
18584 ** The length of data write will be between 1 and 9 bytes.  The number
18585 ** of bytes written is returned.
18586 **
18587 ** A variable-length integer consists of the lower 7 bits of each byte
18588 ** for all bytes that have the 8th bit set and one byte with the 8th
18589 ** bit clear.  Except, if we get to the 9th byte, it stores the full
18590 ** 8 bits and is the last byte.
18591 */
18592 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
18593   int i, j, n;
18594   u8 buf[10];
18595   if( v & (((u64)0xff000000)<<32) ){
18596     p[8] = v;
18597     v >>= 8;
18598     for(i=7; i>=0; i--){
18599       p[i] = (v & 0x7f) | 0x80;
18600       v >>= 7;
18601     }
18602     return 9;
18603   }    
18604   n = 0;
18605   do{
18606     buf[n++] = (v & 0x7f) | 0x80;
18607     v >>= 7;
18608   }while( v!=0 );
18609   buf[0] &= 0x7f;
18610   assert( n<=9 );
18611   for(i=0, j=n-1; j>=0; j--, i++){
18612     p[i] = buf[j];
18613   }
18614   return n;
18615 }
18616
18617 /*
18618 ** This routine is a faster version of sqlite3PutVarint() that only
18619 ** works for 32-bit positive integers and which is optimized for
18620 ** the common case of small integers.  A MACRO version, putVarint32,
18621 ** is provided which inlines the single-byte case.  All code should use
18622 ** the MACRO version as this function assumes the single-byte case has
18623 ** already been handled.
18624 */
18625 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
18626 #ifndef putVarint32
18627   if( (v & ~0x7f)==0 ){
18628     p[0] = v;
18629     return 1;
18630   }
18631 #endif
18632   if( (v & ~0x3fff)==0 ){
18633     p[0] = (v>>7) | 0x80;
18634     p[1] = v & 0x7f;
18635     return 2;
18636   }
18637   return sqlite3PutVarint(p, v);
18638 }
18639
18640 /*
18641 ** Read a 64-bit variable-length integer from memory starting at p[0].
18642 ** Return the number of bytes read.  The value is stored in *v.
18643 */
18644 SQLITE_PRIVATE int sqlite3GetVarint(const unsigned char *p, u64 *v){
18645   u32 a,b,s;
18646
18647   a = *p;
18648   /* a: p0 (unmasked) */
18649   if (!(a&0x80))
18650   {
18651     *v = a;
18652     return 1;
18653   }
18654
18655   p++;
18656   b = *p;
18657   /* b: p1 (unmasked) */
18658   if (!(b&0x80))
18659   {
18660     a &= 0x7f;
18661     a = a<<7;
18662     a |= b;
18663     *v = a;
18664     return 2;
18665   }
18666
18667   p++;
18668   a = a<<14;
18669   a |= *p;
18670   /* a: p0<<14 | p2 (unmasked) */
18671   if (!(a&0x80))
18672   {
18673     a &= (0x7f<<14)|(0x7f);
18674     b &= 0x7f;
18675     b = b<<7;
18676     a |= b;
18677     *v = a;
18678     return 3;
18679   }
18680
18681   /* CSE1 from below */
18682   a &= (0x7f<<14)|(0x7f);
18683   p++;
18684   b = b<<14;
18685   b |= *p;
18686   /* b: p1<<14 | p3 (unmasked) */
18687   if (!(b&0x80))
18688   {
18689     b &= (0x7f<<14)|(0x7f);
18690     /* moved CSE1 up */
18691     /* a &= (0x7f<<14)|(0x7f); */
18692     a = a<<7;
18693     a |= b;
18694     *v = a;
18695     return 4;
18696   }
18697
18698   /* a: p0<<14 | p2 (masked) */
18699   /* b: p1<<14 | p3 (unmasked) */
18700   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
18701   /* moved CSE1 up */
18702   /* a &= (0x7f<<14)|(0x7f); */
18703   b &= (0x7f<<14)|(0x7f);
18704   s = a;
18705   /* s: p0<<14 | p2 (masked) */
18706
18707   p++;
18708   a = a<<14;
18709   a |= *p;
18710   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
18711   if (!(a&0x80))
18712   {
18713     /* we can skip these cause they were (effectively) done above in calc'ing s */
18714     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
18715     /* b &= (0x7f<<14)|(0x7f); */
18716     b = b<<7;
18717     a |= b;
18718     s = s>>18;
18719     *v = ((u64)s)<<32 | a;
18720     return 5;
18721   }
18722
18723   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
18724   s = s<<7;
18725   s |= b;
18726   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
18727
18728   p++;
18729   b = b<<14;
18730   b |= *p;
18731   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
18732   if (!(b&0x80))
18733   {
18734     /* we can skip this cause it was (effectively) done above in calc'ing s */
18735     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
18736     a &= (0x7f<<14)|(0x7f);
18737     a = a<<7;
18738     a |= b;
18739     s = s>>18;
18740     *v = ((u64)s)<<32 | a;
18741     return 6;
18742   }
18743
18744   p++;
18745   a = a<<14;
18746   a |= *p;
18747   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
18748   if (!(a&0x80))
18749   {
18750     a &= (0x7f<<28)|(0x7f<<14)|(0x7f);
18751     b &= (0x7f<<14)|(0x7f);
18752     b = b<<7;
18753     a |= b;
18754     s = s>>11;
18755     *v = ((u64)s)<<32 | a;
18756     return 7;
18757   }
18758
18759   /* CSE2 from below */
18760   a &= (0x7f<<14)|(0x7f);
18761   p++;
18762   b = b<<14;
18763   b |= *p;
18764   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
18765   if (!(b&0x80))
18766   {
18767     b &= (0x7f<<28)|(0x7f<<14)|(0x7f);
18768     /* moved CSE2 up */
18769     /* a &= (0x7f<<14)|(0x7f); */
18770     a = a<<7;
18771     a |= b;
18772     s = s>>4;
18773     *v = ((u64)s)<<32 | a;
18774     return 8;
18775   }
18776
18777   p++;
18778   a = a<<15;
18779   a |= *p;
18780   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
18781
18782   /* moved CSE2 up */
18783   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
18784   b &= (0x7f<<14)|(0x7f);
18785   b = b<<8;
18786   a |= b;
18787
18788   s = s<<4;
18789   b = p[-4];
18790   b &= 0x7f;
18791   b = b>>3;
18792   s |= b;
18793
18794   *v = ((u64)s)<<32 | a;
18795
18796   return 9;
18797 }
18798
18799 /*
18800 ** Read a 32-bit variable-length integer from memory starting at p[0].
18801 ** Return the number of bytes read.  The value is stored in *v.
18802 ** A MACRO version, getVarint32, is provided which inlines the 
18803 ** single-byte case.  All code should use the MACRO version as 
18804 ** this function assumes the single-byte case has already been handled.
18805 */
18806 SQLITE_PRIVATE int sqlite3GetVarint32(const unsigned char *p, u32 *v){
18807   u32 a,b;
18808
18809   a = *p;
18810   /* a: p0 (unmasked) */
18811 #ifndef getVarint32
18812   if (!(a&0x80))
18813   {
18814     *v = a;
18815     return 1;
18816   }
18817 #endif
18818
18819   p++;
18820   b = *p;
18821   /* b: p1 (unmasked) */
18822   if (!(b&0x80))
18823   {
18824     a &= 0x7f;
18825     a = a<<7;
18826     *v = a | b;
18827     return 2;
18828   }
18829
18830   p++;
18831   a = a<<14;
18832   a |= *p;
18833   /* a: p0<<14 | p2 (unmasked) */
18834   if (!(a&0x80))
18835   {
18836     a &= (0x7f<<14)|(0x7f);
18837     b &= 0x7f;
18838     b = b<<7;
18839     *v = a | b;
18840     return 3;
18841   }
18842
18843   p++;
18844   b = b<<14;
18845   b |= *p;
18846   /* b: p1<<14 | p3 (unmasked) */
18847   if (!(b&0x80))
18848   {
18849     b &= (0x7f<<14)|(0x7f);
18850     a &= (0x7f<<14)|(0x7f);
18851     a = a<<7;
18852     *v = a | b;
18853     return 4;
18854   }
18855
18856   p++;
18857   a = a<<14;
18858   a |= *p;
18859   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
18860   if (!(a&0x80))
18861   {
18862     a &= (0x7f<<28)|(0x7f<<14)|(0x7f);
18863     b &= (0x7f<<28)|(0x7f<<14)|(0x7f);
18864     b = b<<7;
18865     *v = a | b;
18866     return 5;
18867   }
18868
18869   /* We can only reach this point when reading a corrupt database
18870   ** file.  In that case we are not in any hurry.  Use the (relatively
18871   ** slow) general-purpose sqlite3GetVarint() routine to extract the
18872   ** value. */
18873   {
18874     u64 v64;
18875     int n;
18876
18877     p -= 4;
18878     n = sqlite3GetVarint(p, &v64);
18879     assert( n>5 && n<=9 );
18880     *v = (u32)v64;
18881     return n;
18882   }
18883 }
18884
18885 /*
18886 ** Return the number of bytes that will be needed to store the given
18887 ** 64-bit integer.
18888 */
18889 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
18890   int i = 0;
18891   do{
18892     i++;
18893     v >>= 7;
18894   }while( v!=0 && i<9 );
18895   return i;
18896 }
18897
18898
18899 /*
18900 ** Read or write a four-byte big-endian integer value.
18901 */
18902 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
18903   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
18904 }
18905 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
18906   p[0] = v>>24;
18907   p[1] = v>>16;
18908   p[2] = v>>8;
18909   p[3] = v;
18910 }
18911
18912
18913
18914 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
18915 /*
18916 ** Translate a single byte of Hex into an integer.
18917 ** This routinen only works if h really is a valid hexadecimal
18918 ** character:  0..9a..fA..F
18919 */
18920 static int hexToInt(int h){
18921   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
18922 #ifdef SQLITE_ASCII
18923   h += 9*(1&(h>>6));
18924 #endif
18925 #ifdef SQLITE_EBCDIC
18926   h += 9*(1&~(h>>4));
18927 #endif
18928   return h & 0xf;
18929 }
18930 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
18931
18932 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
18933 /*
18934 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
18935 ** value.  Return a pointer to its binary value.  Space to hold the
18936 ** binary value has been obtained from malloc and must be freed by
18937 ** the calling routine.
18938 */
18939 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
18940   char *zBlob;
18941   int i;
18942
18943   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
18944   n--;
18945   if( zBlob ){
18946     for(i=0; i<n; i+=2){
18947       zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
18948     }
18949     zBlob[i/2] = 0;
18950   }
18951   return zBlob;
18952 }
18953 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
18954
18955
18956 /*
18957 ** Change the sqlite.magic from SQLITE_MAGIC_OPEN to SQLITE_MAGIC_BUSY.
18958 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_OPEN
18959 ** when this routine is called.
18960 **
18961 ** This routine is called when entering an SQLite API.  The SQLITE_MAGIC_OPEN
18962 ** value indicates that the database connection passed into the API is
18963 ** open and is not being used by another thread.  By changing the value
18964 ** to SQLITE_MAGIC_BUSY we indicate that the connection is in use.
18965 ** sqlite3SafetyOff() below will change the value back to SQLITE_MAGIC_OPEN
18966 ** when the API exits. 
18967 **
18968 ** This routine is a attempt to detect if two threads use the
18969 ** same sqlite* pointer at the same time.  There is a race 
18970 ** condition so it is possible that the error is not detected.
18971 ** But usually the problem will be seen.  The result will be an
18972 ** error which can be used to debug the application that is
18973 ** using SQLite incorrectly.
18974 **
18975 ** Ticket #202:  If db->magic is not a valid open value, take care not
18976 ** to modify the db structure at all.  It could be that db is a stale
18977 ** pointer.  In other words, it could be that there has been a prior
18978 ** call to sqlite3_close(db) and db has been deallocated.  And we do
18979 ** not want to write into deallocated memory.
18980 */
18981 #ifdef SQLITE_DEBUG
18982 SQLITE_PRIVATE int sqlite3SafetyOn(sqlite3 *db){
18983   if( db->magic==SQLITE_MAGIC_OPEN ){
18984     db->magic = SQLITE_MAGIC_BUSY;
18985     assert( sqlite3_mutex_held(db->mutex) );
18986     return 0;
18987   }else if( db->magic==SQLITE_MAGIC_BUSY ){
18988     db->magic = SQLITE_MAGIC_ERROR;
18989     db->u1.isInterrupted = 1;
18990   }
18991   return 1;
18992 }
18993 #endif
18994
18995 /*
18996 ** Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN.
18997 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY
18998 ** when this routine is called.
18999 */
19000 #ifdef SQLITE_DEBUG
19001 SQLITE_PRIVATE int sqlite3SafetyOff(sqlite3 *db){
19002   if( db->magic==SQLITE_MAGIC_BUSY ){
19003     db->magic = SQLITE_MAGIC_OPEN;
19004     assert( sqlite3_mutex_held(db->mutex) );
19005     return 0;
19006   }else{
19007     db->magic = SQLITE_MAGIC_ERROR;
19008     db->u1.isInterrupted = 1;
19009     return 1;
19010   }
19011 }
19012 #endif
19013
19014 /*
19015 ** Check to make sure we have a valid db pointer.  This test is not
19016 ** foolproof but it does provide some measure of protection against
19017 ** misuse of the interface such as passing in db pointers that are
19018 ** NULL or which have been previously closed.  If this routine returns
19019 ** 1 it means that the db pointer is valid and 0 if it should not be
19020 ** dereferenced for any reason.  The calling function should invoke
19021 ** SQLITE_MISUSE immediately.
19022 **
19023 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
19024 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
19025 ** open properly and is not fit for general use but which can be
19026 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
19027 */
19028 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
19029   int magic;
19030   if( db==0 ) return 0;
19031   magic = db->magic;
19032   if( magic!=SQLITE_MAGIC_OPEN &&
19033       magic!=SQLITE_MAGIC_BUSY ) return 0;
19034   return 1;
19035 }
19036 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
19037   int magic;
19038   if( db==0 ) return 0;
19039   magic = db->magic;
19040   if( magic!=SQLITE_MAGIC_SICK &&
19041       magic!=SQLITE_MAGIC_OPEN &&
19042       magic!=SQLITE_MAGIC_BUSY ) return 0;
19043   return 1;
19044 }
19045
19046 /************** End of util.c ************************************************/
19047 /************** Begin file hash.c ********************************************/
19048 /*
19049 ** 2001 September 22
19050 **
19051 ** The author disclaims copyright to this source code.  In place of
19052 ** a legal notice, here is a blessing:
19053 **
19054 **    May you do good and not evil.
19055 **    May you find forgiveness for yourself and forgive others.
19056 **    May you share freely, never taking more than you give.
19057 **
19058 *************************************************************************
19059 ** This is the implementation of generic hash-tables
19060 ** used in SQLite.
19061 **
19062 ** $Id: hash.c,v 1.30 2008/06/20 14:59:51 danielk1977 Exp $
19063 */
19064
19065 /* Turn bulk memory into a hash table object by initializing the
19066 ** fields of the Hash structure.
19067 **
19068 ** "pNew" is a pointer to the hash table that is to be initialized.
19069 ** keyClass is one of the constants SQLITE_HASH_INT, SQLITE_HASH_POINTER,
19070 ** SQLITE_HASH_BINARY, or SQLITE_HASH_STRING.  The value of keyClass 
19071 ** determines what kind of key the hash table will use.  "copyKey" is
19072 ** true if the hash table should make its own private copy of keys and
19073 ** false if it should just use the supplied pointer.  CopyKey only makes
19074 ** sense for SQLITE_HASH_STRING and SQLITE_HASH_BINARY and is ignored
19075 ** for other key classes.
19076 */
19077 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew, int keyClass, int copyKey){
19078   assert( pNew!=0 );
19079   assert( keyClass>=SQLITE_HASH_STRING && keyClass<=SQLITE_HASH_BINARY );
19080   pNew->keyClass = keyClass;
19081 #if 0
19082   if( keyClass==SQLITE_HASH_POINTER || keyClass==SQLITE_HASH_INT ) copyKey = 0;
19083 #endif
19084   pNew->copyKey = copyKey;
19085   pNew->first = 0;
19086   pNew->count = 0;
19087   pNew->htsize = 0;
19088   pNew->ht = 0;
19089 }
19090
19091 /* Remove all entries from a hash table.  Reclaim all memory.
19092 ** Call this routine to delete a hash table or to reset a hash table
19093 ** to the empty state.
19094 */
19095 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
19096   HashElem *elem;         /* For looping over all elements of the table */
19097
19098   assert( pH!=0 );
19099   elem = pH->first;
19100   pH->first = 0;
19101   sqlite3_free(pH->ht);
19102   pH->ht = 0;
19103   pH->htsize = 0;
19104   while( elem ){
19105     HashElem *next_elem = elem->next;
19106     if( pH->copyKey && elem->pKey ){
19107       sqlite3_free(elem->pKey);
19108     }
19109     sqlite3_free(elem);
19110     elem = next_elem;
19111   }
19112   pH->count = 0;
19113 }
19114
19115 #if 0 /* NOT USED */
19116 /*
19117 ** Hash and comparison functions when the mode is SQLITE_HASH_INT
19118 */
19119 static int intHash(const void *pKey, int nKey){
19120   return nKey ^ (nKey<<8) ^ (nKey>>8);
19121 }
19122 static int intCompare(const void *pKey1, int n1, const void *pKey2, int n2){
19123   return n2 - n1;
19124 }
19125 #endif
19126
19127 #if 0 /* NOT USED */
19128 /*
19129 ** Hash and comparison functions when the mode is SQLITE_HASH_POINTER
19130 */
19131 static int ptrHash(const void *pKey, int nKey){
19132   uptr x = Addr(pKey);
19133   return x ^ (x<<8) ^ (x>>8);
19134 }
19135 static int ptrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
19136   if( pKey1==pKey2 ) return 0;
19137   if( pKey1<pKey2 ) return -1;
19138   return 1;
19139 }
19140 #endif
19141
19142 /*
19143 ** Hash and comparison functions when the mode is SQLITE_HASH_STRING
19144 */
19145 static int strHash(const void *pKey, int nKey){
19146   const char *z = (const char *)pKey;
19147   int h = 0;
19148   if( nKey<=0 ) nKey = strlen(z);
19149   while( nKey > 0  ){
19150     h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
19151     nKey--;
19152   }
19153   return h & 0x7fffffff;
19154 }
19155 static int strCompare(const void *pKey1, int n1, const void *pKey2, int n2){
19156   if( n1!=n2 ) return 1;
19157   return sqlite3StrNICmp((const char*)pKey1,(const char*)pKey2,n1);
19158 }
19159
19160 /*
19161 ** Hash and comparison functions when the mode is SQLITE_HASH_BINARY
19162 */
19163 static int binHash(const void *pKey, int nKey){
19164   int h = 0;
19165   const char *z = (const char *)pKey;
19166   while( nKey-- > 0 ){
19167     h = (h<<3) ^ h ^ *(z++);
19168   }
19169   return h & 0x7fffffff;
19170 }
19171 static int binCompare(const void *pKey1, int n1, const void *pKey2, int n2){
19172   if( n1!=n2 ) return 1;
19173   return memcmp(pKey1,pKey2,n1);
19174 }
19175
19176 /*
19177 ** Return a pointer to the appropriate hash function given the key class.
19178 **
19179 ** The C syntax in this function definition may be unfamilar to some 
19180 ** programmers, so we provide the following additional explanation:
19181 **
19182 ** The name of the function is "hashFunction".  The function takes a
19183 ** single parameter "keyClass".  The return value of hashFunction()
19184 ** is a pointer to another function.  Specifically, the return value
19185 ** of hashFunction() is a pointer to a function that takes two parameters
19186 ** with types "const void*" and "int" and returns an "int".
19187 */
19188 static int (*hashFunction(int keyClass))(const void*,int){
19189 #if 0  /* HASH_INT and HASH_POINTER are never used */
19190   switch( keyClass ){
19191     case SQLITE_HASH_INT:     return &intHash;
19192     case SQLITE_HASH_POINTER: return &ptrHash;
19193     case SQLITE_HASH_STRING:  return &strHash;
19194     case SQLITE_HASH_BINARY:  return &binHash;;
19195     default: break;
19196   }
19197   return 0;
19198 #else
19199   if( keyClass==SQLITE_HASH_STRING ){
19200     return &strHash;
19201   }else{
19202     assert( keyClass==SQLITE_HASH_BINARY );
19203     return &binHash;
19204   }
19205 #endif
19206 }
19207
19208 /*
19209 ** Return a pointer to the appropriate hash function given the key class.
19210 **
19211 ** For help in interpreted the obscure C code in the function definition,
19212 ** see the header comment on the previous function.
19213 */
19214 static int (*compareFunction(int keyClass))(const void*,int,const void*,int){
19215 #if 0 /* HASH_INT and HASH_POINTER are never used */
19216   switch( keyClass ){
19217     case SQLITE_HASH_INT:     return &intCompare;
19218     case SQLITE_HASH_POINTER: return &ptrCompare;
19219     case SQLITE_HASH_STRING:  return &strCompare;
19220     case SQLITE_HASH_BINARY:  return &binCompare;
19221     default: break;
19222   }
19223   return 0;
19224 #else
19225   if( keyClass==SQLITE_HASH_STRING ){
19226     return &strCompare;
19227   }else{
19228     assert( keyClass==SQLITE_HASH_BINARY );
19229     return &binCompare;
19230   }
19231 #endif
19232 }
19233
19234 /* Link an element into the hash table
19235 */
19236 static void insertElement(
19237   Hash *pH,              /* The complete hash table */
19238   struct _ht *pEntry,    /* The entry into which pNew is inserted */
19239   HashElem *pNew         /* The element to be inserted */
19240 ){
19241   HashElem *pHead;       /* First element already in pEntry */
19242   pHead = pEntry->chain;
19243   if( pHead ){
19244     pNew->next = pHead;
19245     pNew->prev = pHead->prev;
19246     if( pHead->prev ){ pHead->prev->next = pNew; }
19247     else             { pH->first = pNew; }
19248     pHead->prev = pNew;
19249   }else{
19250     pNew->next = pH->first;
19251     if( pH->first ){ pH->first->prev = pNew; }
19252     pNew->prev = 0;
19253     pH->first = pNew;
19254   }
19255   pEntry->count++;
19256   pEntry->chain = pNew;
19257 }
19258
19259
19260 /* Resize the hash table so that it cantains "new_size" buckets.
19261 ** "new_size" must be a power of 2.  The hash table might fail 
19262 ** to resize if sqlite3_malloc() fails.
19263 */
19264 static void rehash(Hash *pH, int new_size){
19265   struct _ht *new_ht;            /* The new hash table */
19266   HashElem *elem, *next_elem;    /* For looping over existing elements */
19267   int (*xHash)(const void*,int); /* The hash function */
19268
19269 #ifdef SQLITE_MALLOC_SOFT_LIMIT
19270   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
19271     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
19272   }
19273   if( new_size==pH->htsize ) return;
19274 #endif
19275
19276   /* There is a call to sqlite3_malloc() inside rehash(). If there is
19277   ** already an allocation at pH->ht, then if this malloc() fails it
19278   ** is benign (since failing to resize a hash table is a performance
19279   ** hit only, not a fatal error).
19280   */
19281   if( pH->htsize>0 ) sqlite3BeginBenignMalloc();
19282   new_ht = (struct _ht *)sqlite3MallocZero( new_size*sizeof(struct _ht) );
19283   if( pH->htsize>0 ) sqlite3EndBenignMalloc();
19284
19285   if( new_ht==0 ) return;
19286   sqlite3_free(pH->ht);
19287   pH->ht = new_ht;
19288   pH->htsize = new_size;
19289   xHash = hashFunction(pH->keyClass);
19290   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
19291     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
19292     next_elem = elem->next;
19293     insertElement(pH, &new_ht[h], elem);
19294   }
19295 }
19296
19297 /* This function (for internal use only) locates an element in an
19298 ** hash table that matches the given key.  The hash for this key has
19299 ** already been computed and is passed as the 4th parameter.
19300 */
19301 static HashElem *findElementGivenHash(
19302   const Hash *pH,     /* The pH to be searched */
19303   const void *pKey,   /* The key we are searching for */
19304   int nKey,
19305   int h               /* The hash for this key. */
19306 ){
19307   HashElem *elem;                /* Used to loop thru the element list */
19308   int count;                     /* Number of elements left to test */
19309   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
19310
19311   if( pH->ht ){
19312     struct _ht *pEntry = &pH->ht[h];
19313     elem = pEntry->chain;
19314     count = pEntry->count;
19315     xCompare = compareFunction(pH->keyClass);
19316     while( count-- && elem ){
19317       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
19318         return elem;
19319       }
19320       elem = elem->next;
19321     }
19322   }
19323   return 0;
19324 }
19325
19326 /* Remove a single entry from the hash table given a pointer to that
19327 ** element and a hash on the element's key.
19328 */
19329 static void removeElementGivenHash(
19330   Hash *pH,         /* The pH containing "elem" */
19331   HashElem* elem,   /* The element to be removed from the pH */
19332   int h             /* Hash value for the element */
19333 ){
19334   struct _ht *pEntry;
19335   if( elem->prev ){
19336     elem->prev->next = elem->next; 
19337   }else{
19338     pH->first = elem->next;
19339   }
19340   if( elem->next ){
19341     elem->next->prev = elem->prev;
19342   }
19343   pEntry = &pH->ht[h];
19344   if( pEntry->chain==elem ){
19345     pEntry->chain = elem->next;
19346   }
19347   pEntry->count--;
19348   if( pEntry->count<=0 ){
19349     pEntry->chain = 0;
19350   }
19351   if( pH->copyKey ){
19352     sqlite3_free(elem->pKey);
19353   }
19354   sqlite3_free( elem );
19355   pH->count--;
19356   if( pH->count<=0 ){
19357     assert( pH->first==0 );
19358     assert( pH->count==0 );
19359     sqlite3HashClear(pH);
19360   }
19361 }
19362
19363 /* Attempt to locate an element of the hash table pH with a key
19364 ** that matches pKey,nKey.  Return a pointer to the corresponding 
19365 ** HashElem structure for this element if it is found, or NULL
19366 ** otherwise.
19367 */
19368 SQLITE_PRIVATE HashElem *sqlite3HashFindElem(const Hash *pH, const void *pKey, int nKey){
19369   int h;             /* A hash on key */
19370   HashElem *elem;    /* The element that matches key */
19371   int (*xHash)(const void*,int);  /* The hash function */
19372
19373   if( pH==0 || pH->ht==0 ) return 0;
19374   xHash = hashFunction(pH->keyClass);
19375   assert( xHash!=0 );
19376   h = (*xHash)(pKey,nKey);
19377   elem = findElementGivenHash(pH,pKey,nKey, h % pH->htsize);
19378   return elem;
19379 }
19380
19381 /* Attempt to locate an element of the hash table pH with a key
19382 ** that matches pKey,nKey.  Return the data for this element if it is
19383 ** found, or NULL if there is no match.
19384 */
19385 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const void *pKey, int nKey){
19386   HashElem *elem;    /* The element that matches key */
19387   elem = sqlite3HashFindElem(pH, pKey, nKey);
19388   return elem ? elem->data : 0;
19389 }
19390
19391 /* Insert an element into the hash table pH.  The key is pKey,nKey
19392 ** and the data is "data".
19393 **
19394 ** If no element exists with a matching key, then a new
19395 ** element is created.  A copy of the key is made if the copyKey
19396 ** flag is set.  NULL is returned.
19397 **
19398 ** If another element already exists with the same key, then the
19399 ** new data replaces the old data and the old data is returned.
19400 ** The key is not copied in this instance.  If a malloc fails, then
19401 ** the new data is returned and the hash table is unchanged.
19402 **
19403 ** If the "data" parameter to this function is NULL, then the
19404 ** element corresponding to "key" is removed from the hash table.
19405 */
19406 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const void *pKey, int nKey, void *data){
19407   int hraw;             /* Raw hash value of the key */
19408   int h;                /* the hash of the key modulo hash table size */
19409   HashElem *elem;       /* Used to loop thru the element list */
19410   HashElem *new_elem;   /* New element added to the pH */
19411   int (*xHash)(const void*,int);  /* The hash function */
19412
19413   assert( pH!=0 );
19414   xHash = hashFunction(pH->keyClass);
19415   assert( xHash!=0 );
19416   hraw = (*xHash)(pKey, nKey);
19417   if( pH->htsize ){
19418     h = hraw % pH->htsize;
19419     elem = findElementGivenHash(pH,pKey,nKey,h);
19420     if( elem ){
19421       void *old_data = elem->data;
19422       if( data==0 ){
19423         removeElementGivenHash(pH,elem,h);
19424       }else{
19425         elem->data = data;
19426         if( !pH->copyKey ){
19427           elem->pKey = (void *)pKey;
19428         }
19429         assert(nKey==elem->nKey);
19430       }
19431       return old_data;
19432     }
19433   }
19434   if( data==0 ) return 0;
19435   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
19436   if( new_elem==0 ) return data;
19437   if( pH->copyKey && pKey!=0 ){
19438     new_elem->pKey = sqlite3Malloc( nKey );
19439     if( new_elem->pKey==0 ){
19440       sqlite3_free(new_elem);
19441       return data;
19442     }
19443     memcpy((void*)new_elem->pKey, pKey, nKey);
19444   }else{
19445     new_elem->pKey = (void*)pKey;
19446   }
19447   new_elem->nKey = nKey;
19448   pH->count++;
19449   if( pH->htsize==0 ){
19450     rehash(pH, 128/sizeof(pH->ht[0]));
19451     if( pH->htsize==0 ){
19452       pH->count = 0;
19453       if( pH->copyKey ){
19454         sqlite3_free(new_elem->pKey);
19455       }
19456       sqlite3_free(new_elem);
19457       return data;
19458     }
19459   }
19460   if( pH->count > pH->htsize ){
19461     rehash(pH,pH->htsize*2);
19462   }
19463   assert( pH->htsize>0 );
19464   h = hraw % pH->htsize;
19465   insertElement(pH, &pH->ht[h], new_elem);
19466   new_elem->data = data;
19467   return 0;
19468 }
19469
19470 /************** End of hash.c ************************************************/
19471 /************** Begin file opcodes.c *****************************************/
19472 /* Automatically generated.  Do not edit */
19473 /* See the mkopcodec.awk script for details. */
19474 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
19475 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
19476  static const char *const azName[] = { "?",
19477      /*   1 */ "VNext",
19478      /*   2 */ "Affinity",
19479      /*   3 */ "Column",
19480      /*   4 */ "SetCookie",
19481      /*   5 */ "Sequence",
19482      /*   6 */ "MoveGt",
19483      /*   7 */ "RowKey",
19484      /*   8 */ "SCopy",
19485      /*   9 */ "OpenWrite",
19486      /*  10 */ "If",
19487      /*  11 */ "VRowid",
19488      /*  12 */ "CollSeq",
19489      /*  13 */ "OpenRead",
19490      /*  14 */ "Expire",
19491      /*  15 */ "AutoCommit",
19492      /*  16 */ "Not",
19493      /*  17 */ "Pagecount",
19494      /*  18 */ "IntegrityCk",
19495      /*  19 */ "Sort",
19496      /*  20 */ "Copy",
19497      /*  21 */ "Trace",
19498      /*  22 */ "Function",
19499      /*  23 */ "IfNeg",
19500      /*  24 */ "Noop",
19501      /*  25 */ "Return",
19502      /*  26 */ "NewRowid",
19503      /*  27 */ "Variable",
19504      /*  28 */ "String",
19505      /*  29 */ "RealAffinity",
19506      /*  30 */ "VRename",
19507      /*  31 */ "ParseSchema",
19508      /*  32 */ "VOpen",
19509      /*  33 */ "Close",
19510      /*  34 */ "CreateIndex",
19511      /*  35 */ "IsUnique",
19512      /*  36 */ "NotFound",
19513      /*  37 */ "Int64",
19514      /*  38 */ "MustBeInt",
19515      /*  39 */ "Halt",
19516      /*  40 */ "Rowid",
19517      /*  41 */ "IdxLT",
19518      /*  42 */ "AddImm",
19519      /*  43 */ "Statement",
19520      /*  44 */ "RowData",
19521      /*  45 */ "MemMax",
19522      /*  46 */ "NotExists",
19523      /*  47 */ "Gosub",
19524      /*  48 */ "Integer",
19525      /*  49 */ "Prev",
19526      /*  50 */ "VColumn",
19527      /*  51 */ "CreateTable",
19528      /*  52 */ "Last",
19529      /*  53 */ "IncrVacuum",
19530      /*  54 */ "IdxRowid",
19531      /*  55 */ "ResetCount",
19532      /*  56 */ "FifoWrite",
19533      /*  57 */ "ContextPush",
19534      /*  58 */ "Yield",
19535      /*  59 */ "DropTrigger",
19536      /*  60 */ "Or",
19537      /*  61 */ "And",
19538      /*  62 */ "DropIndex",
19539      /*  63 */ "IdxGE",
19540      /*  64 */ "IdxDelete",
19541      /*  65 */ "IsNull",
19542      /*  66 */ "NotNull",
19543      /*  67 */ "Ne",
19544      /*  68 */ "Eq",
19545      /*  69 */ "Gt",
19546      /*  70 */ "Le",
19547      /*  71 */ "Lt",
19548      /*  72 */ "Ge",
19549      /*  73 */ "Vacuum",
19550      /*  74 */ "BitAnd",
19551      /*  75 */ "BitOr",
19552      /*  76 */ "ShiftLeft",
19553      /*  77 */ "ShiftRight",
19554      /*  78 */ "Add",
19555      /*  79 */ "Subtract",
19556      /*  80 */ "Multiply",
19557      /*  81 */ "Divide",
19558      /*  82 */ "Remainder",
19559      /*  83 */ "Concat",
19560      /*  84 */ "MoveLe",
19561      /*  85 */ "IfNot",
19562      /*  86 */ "DropTable",
19563      /*  87 */ "BitNot",
19564      /*  88 */ "String8",
19565      /*  89 */ "MakeRecord",
19566      /*  90 */ "ResultRow",
19567      /*  91 */ "Delete",
19568      /*  92 */ "AggFinal",
19569      /*  93 */ "Compare",
19570      /*  94 */ "Goto",
19571      /*  95 */ "TableLock",
19572      /*  96 */ "FifoRead",
19573      /*  97 */ "Clear",
19574      /*  98 */ "MoveLt",
19575      /*  99 */ "VerifyCookie",
19576      /* 100 */ "AggStep",
19577      /* 101 */ "SetNumColumns",
19578      /* 102 */ "Transaction",
19579      /* 103 */ "VFilter",
19580      /* 104 */ "VDestroy",
19581      /* 105 */ "ContextPop",
19582      /* 106 */ "Next",
19583      /* 107 */ "IdxInsert",
19584      /* 108 */ "Insert",
19585      /* 109 */ "Destroy",
19586      /* 110 */ "ReadCookie",
19587      /* 111 */ "ForceInt",
19588      /* 112 */ "LoadAnalysis",
19589      /* 113 */ "Explain",
19590      /* 114 */ "OpenPseudo",
19591      /* 115 */ "OpenEphemeral",
19592      /* 116 */ "Null",
19593      /* 117 */ "Move",
19594      /* 118 */ "Blob",
19595      /* 119 */ "Rewind",
19596      /* 120 */ "MoveGe",
19597      /* 121 */ "VBegin",
19598      /* 122 */ "VUpdate",
19599      /* 123 */ "IfZero",
19600      /* 124 */ "VCreate",
19601      /* 125 */ "Real",
19602      /* 126 */ "Found",
19603      /* 127 */ "IfPos",
19604      /* 128 */ "NullRow",
19605      /* 129 */ "Jump",
19606      /* 130 */ "Permutation",
19607      /* 131 */ "NotUsed_131",
19608      /* 132 */ "NotUsed_132",
19609      /* 133 */ "NotUsed_133",
19610      /* 134 */ "NotUsed_134",
19611      /* 135 */ "NotUsed_135",
19612      /* 136 */ "NotUsed_136",
19613      /* 137 */ "NotUsed_137",
19614      /* 138 */ "ToText",
19615      /* 139 */ "ToBlob",
19616      /* 140 */ "ToNumeric",
19617      /* 141 */ "ToInt",
19618      /* 142 */ "ToReal",
19619   };
19620   return azName[i];
19621 }
19622 #endif
19623
19624 /************** End of opcodes.c *********************************************/
19625 /************** Begin file os_os2.c ******************************************/
19626 /*
19627 ** 2006 Feb 14
19628 **
19629 ** The author disclaims copyright to this source code.  In place of
19630 ** a legal notice, here is a blessing:
19631 **
19632 **    May you do good and not evil.
19633 **    May you find forgiveness for yourself and forgive others.
19634 **    May you share freely, never taking more than you give.
19635 **
19636 ******************************************************************************
19637 **
19638 ** This file contains code that is specific to OS/2.
19639 **
19640 ** $Id: os_os2.c,v 1.55 2008/07/29 18:49:29 pweilbacher Exp $
19641 */
19642
19643
19644 #if SQLITE_OS_OS2
19645
19646 /*
19647 ** A Note About Memory Allocation:
19648 **
19649 ** This driver uses malloc()/free() directly rather than going through
19650 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
19651 ** are designed for use on embedded systems where memory is scarce and
19652 ** malloc failures happen frequently.  OS/2 does not typically run on
19653 ** embedded systems, and when it does the developers normally have bigger
19654 ** problems to worry about than running out of memory.  So there is not
19655 ** a compelling need to use the wrappers.
19656 **
19657 ** But there is a good reason to not use the wrappers.  If we use the
19658 ** wrappers then we will get simulated malloc() failures within this
19659 ** driver.  And that causes all kinds of problems for our tests.  We
19660 ** could enhance SQLite to deal with simulated malloc failures within
19661 ** the OS driver, but the code to deal with those failure would not
19662 ** be exercised on Linux (which does not need to malloc() in the driver)
19663 ** and so we would have difficulty writing coverage tests for that
19664 ** code.  Better to leave the code out, we think.
19665 **
19666 ** The point of this discussion is as follows:  When creating a new
19667 ** OS layer for an embedded system, if you use this file as an example,
19668 ** avoid the use of malloc()/free().  Those routines work ok on OS/2
19669 ** desktops but not so well in embedded systems.
19670 */
19671
19672 /*
19673 ** Macros used to determine whether or not to use threads.
19674 */
19675 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
19676 # define SQLITE_OS2_THREADS 1
19677 #endif
19678
19679 /*
19680 ** Include code that is common to all os_*.c files
19681 */
19682 /************** Include os_common.h in the middle of os_os2.c ****************/
19683 /************** Begin file os_common.h ***************************************/
19684 /*
19685 ** 2004 May 22
19686 **
19687 ** The author disclaims copyright to this source code.  In place of
19688 ** a legal notice, here is a blessing:
19689 **
19690 **    May you do good and not evil.
19691 **    May you find forgiveness for yourself and forgive others.
19692 **    May you share freely, never taking more than you give.
19693 **
19694 ******************************************************************************
19695 **
19696 ** This file contains macros and a little bit of code that is common to
19697 ** all of the platform-specific files (os_*.c) and is #included into those
19698 ** files.
19699 **
19700 ** This file should be #included by the os_*.c files only.  It is not a
19701 ** general purpose header file.
19702 **
19703 ** $Id: os_common.h,v 1.37 2008/05/29 20:22:37 shane Exp $
19704 */
19705 #ifndef _OS_COMMON_H_
19706 #define _OS_COMMON_H_
19707
19708 /*
19709 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
19710 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
19711 ** switch.  The following code should catch this problem at compile-time.
19712 */
19713 #ifdef MEMORY_DEBUG
19714 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
19715 #endif
19716
19717
19718 /*
19719  * When testing, this global variable stores the location of the
19720  * pending-byte in the database file.
19721  */
19722 #ifdef SQLITE_TEST
19723 SQLITE_API unsigned int sqlite3_pending_byte = 0x40000000;
19724 #endif
19725
19726 #ifdef SQLITE_DEBUG
19727 SQLITE_PRIVATE int sqlite3OSTrace = 0;
19728 #define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
19729 #define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
19730 #define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
19731 #define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
19732 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
19733 #define OSTRACE6(X,Y,Z,A,B,C) \
19734     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
19735 #define OSTRACE7(X,Y,Z,A,B,C,D) \
19736     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
19737 #else
19738 #define OSTRACE1(X)
19739 #define OSTRACE2(X,Y)
19740 #define OSTRACE3(X,Y,Z)
19741 #define OSTRACE4(X,Y,Z,A)
19742 #define OSTRACE5(X,Y,Z,A,B)
19743 #define OSTRACE6(X,Y,Z,A,B,C)
19744 #define OSTRACE7(X,Y,Z,A,B,C,D)
19745 #endif
19746
19747 /*
19748 ** Macros for performance tracing.  Normally turned off.  Only works
19749 ** on i486 hardware.
19750 */
19751 #ifdef SQLITE_PERFORMANCE_TRACE
19752
19753 /* 
19754 ** hwtime.h contains inline assembler code for implementing 
19755 ** high-performance timing routines.
19756 */
19757 /************** Include hwtime.h in the middle of os_common.h ****************/
19758 /************** Begin file hwtime.h ******************************************/
19759 /*
19760 ** 2008 May 27
19761 **
19762 ** The author disclaims copyright to this source code.  In place of
19763 ** a legal notice, here is a blessing:
19764 **
19765 **    May you do good and not evil.
19766 **    May you find forgiveness for yourself and forgive others.
19767 **    May you share freely, never taking more than you give.
19768 **
19769 ******************************************************************************
19770 **
19771 ** This file contains inline asm code for retrieving "high-performance"
19772 ** counters for x86 class CPUs.
19773 **
19774 ** $Id: hwtime.h,v 1.3 2008/08/01 14:33:15 shane Exp $
19775 */
19776 #ifndef _HWTIME_H_
19777 #define _HWTIME_H_
19778
19779 /*
19780 ** The following routine only works on pentium-class (or newer) processors.
19781 ** It uses the RDTSC opcode to read the cycle count value out of the
19782 ** processor and returns that value.  This can be used for high-res
19783 ** profiling.
19784 */
19785 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
19786       (defined(i386) || defined(__i386__) || defined(_M_IX86))
19787
19788   #if defined(__GNUC__)
19789
19790   __inline__ sqlite_uint64 sqlite3Hwtime(void){
19791      unsigned int lo, hi;
19792      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
19793      return (sqlite_uint64)hi << 32 | lo;
19794   }
19795
19796   #elif defined(_MSC_VER)
19797
19798   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
19799      __asm {
19800         rdtsc
19801         ret       ; return value at EDX:EAX
19802      }
19803   }
19804
19805   #endif
19806
19807 #elif (defined(__GNUC__) && defined(__x86_64__))
19808
19809   __inline__ sqlite_uint64 sqlite3Hwtime(void){
19810       unsigned long val;
19811       __asm__ __volatile__ ("rdtsc" : "=A" (val));
19812       return val;
19813   }
19814  
19815 #elif (defined(__GNUC__) && defined(__ppc__))
19816
19817   __inline__ sqlite_uint64 sqlite3Hwtime(void){
19818       unsigned long long retval;
19819       unsigned long junk;
19820       __asm__ __volatile__ ("\n\
19821           1:      mftbu   %1\n\
19822                   mftb    %L0\n\
19823                   mftbu   %0\n\
19824                   cmpw    %0,%1\n\
19825                   bne     1b"
19826                   : "=r" (retval), "=r" (junk));
19827       return retval;
19828   }
19829
19830 #else
19831
19832   #error Need implementation of sqlite3Hwtime() for your platform.
19833
19834   /*
19835   ** To compile without implementing sqlite3Hwtime() for your platform,
19836   ** you can remove the above #error and use the following
19837   ** stub function.  You will lose timing support for many
19838   ** of the debugging and testing utilities, but it should at
19839   ** least compile and run.
19840   */
19841 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
19842
19843 #endif
19844
19845 #endif /* !defined(_HWTIME_H_) */
19846
19847 /************** End of hwtime.h **********************************************/
19848 /************** Continuing where we left off in os_common.h ******************/
19849
19850 static sqlite_uint64 g_start;
19851 static sqlite_uint64 g_elapsed;
19852 #define TIMER_START       g_start=sqlite3Hwtime()
19853 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
19854 #define TIMER_ELAPSED     g_elapsed
19855 #else
19856 #define TIMER_START
19857 #define TIMER_END
19858 #define TIMER_ELAPSED     ((sqlite_uint64)0)
19859 #endif
19860
19861 /*
19862 ** If we compile with the SQLITE_TEST macro set, then the following block
19863 ** of code will give us the ability to simulate a disk I/O error.  This
19864 ** is used for testing the I/O recovery logic.
19865 */
19866 #ifdef SQLITE_TEST
19867 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
19868 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
19869 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
19870 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
19871 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
19872 SQLITE_API int sqlite3_diskfull_pending = 0;
19873 SQLITE_API int sqlite3_diskfull = 0;
19874 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
19875 #define SimulateIOError(CODE)  \
19876   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
19877        || sqlite3_io_error_pending-- == 1 )  \
19878               { local_ioerr(); CODE; }
19879 static void local_ioerr(){
19880   IOTRACE(("IOERR\n"));
19881   sqlite3_io_error_hit++;
19882   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
19883 }
19884 #define SimulateDiskfullError(CODE) \
19885    if( sqlite3_diskfull_pending ){ \
19886      if( sqlite3_diskfull_pending == 1 ){ \
19887        local_ioerr(); \
19888        sqlite3_diskfull = 1; \
19889        sqlite3_io_error_hit = 1; \
19890        CODE; \
19891      }else{ \
19892        sqlite3_diskfull_pending--; \
19893      } \
19894    }
19895 #else
19896 #define SimulateIOErrorBenign(X)
19897 #define SimulateIOError(A)
19898 #define SimulateDiskfullError(A)
19899 #endif
19900
19901 /*
19902 ** When testing, keep a count of the number of open files.
19903 */
19904 #ifdef SQLITE_TEST
19905 SQLITE_API int sqlite3_open_file_count = 0;
19906 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
19907 #else
19908 #define OpenCounter(X)
19909 #endif
19910
19911 #endif /* !defined(_OS_COMMON_H_) */
19912
19913 /************** End of os_common.h *******************************************/
19914 /************** Continuing where we left off in os_os2.c *********************/
19915
19916 /*
19917 ** The os2File structure is subclass of sqlite3_file specific for the OS/2
19918 ** protability layer.
19919 */
19920 typedef struct os2File os2File;
19921 struct os2File {
19922   const sqlite3_io_methods *pMethod;  /* Always the first entry */
19923   HFILE h;                  /* Handle for accessing the file */
19924   char* pathToDel;          /* Name of file to delete on close, NULL if not */
19925   unsigned char locktype;   /* Type of lock currently held on this file */
19926 };
19927
19928 #define LOCK_TIMEOUT 10L /* the default locking timeout */
19929
19930 /*****************************************************************************
19931 ** The next group of routines implement the I/O methods specified
19932 ** by the sqlite3_io_methods object.
19933 ******************************************************************************/
19934
19935 /*
19936 ** Close a file.
19937 */
19938 static int os2Close( sqlite3_file *id ){
19939   APIRET rc = NO_ERROR;
19940   os2File *pFile;
19941   if( id && (pFile = (os2File*)id) != 0 ){
19942     OSTRACE2( "CLOSE %d\n", pFile->h );
19943     rc = DosClose( pFile->h );
19944     pFile->locktype = NO_LOCK;
19945     if( pFile->pathToDel != NULL ){
19946       rc = DosForceDelete( (PSZ)pFile->pathToDel );
19947       free( pFile->pathToDel );
19948       pFile->pathToDel = NULL;
19949     }
19950     id = 0;
19951     OpenCounter( -1 );
19952   }
19953
19954   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
19955 }
19956
19957 /*
19958 ** Read data from a file into a buffer.  Return SQLITE_OK if all
19959 ** bytes were read successfully and SQLITE_IOERR if anything goes
19960 ** wrong.
19961 */
19962 static int os2Read(
19963   sqlite3_file *id,               /* File to read from */
19964   void *pBuf,                     /* Write content into this buffer */
19965   int amt,                        /* Number of bytes to read */
19966   sqlite3_int64 offset            /* Begin reading at this offset */
19967 ){
19968   ULONG fileLocation = 0L;
19969   ULONG got;
19970   os2File *pFile = (os2File*)id;
19971   assert( id!=0 );
19972   SimulateIOError( return SQLITE_IOERR_READ );
19973   OSTRACE3( "READ %d lock=%d\n", pFile->h, pFile->locktype );
19974   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
19975     return SQLITE_IOERR;
19976   }
19977   if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
19978     return SQLITE_IOERR_READ;
19979   }
19980   if( got == (ULONG)amt )
19981     return SQLITE_OK;
19982   else {
19983     memset(&((char*)pBuf)[got], 0, amt-got);
19984     return SQLITE_IOERR_SHORT_READ;
19985   }
19986 }
19987
19988 /*
19989 ** Write data from a buffer into a file.  Return SQLITE_OK on success
19990 ** or some other error code on failure.
19991 */
19992 static int os2Write(
19993   sqlite3_file *id,               /* File to write into */
19994   const void *pBuf,               /* The bytes to be written */
19995   int amt,                        /* Number of bytes to write */
19996   sqlite3_int64 offset            /* Offset into the file to begin writing at */
19997 ){
19998   ULONG fileLocation = 0L;
19999   APIRET rc = NO_ERROR;
20000   ULONG wrote;
20001   os2File *pFile = (os2File*)id;
20002   assert( id!=0 );
20003   SimulateIOError( return SQLITE_IOERR_WRITE );
20004   SimulateDiskfullError( return SQLITE_FULL );
20005   OSTRACE3( "WRITE %d lock=%d\n", pFile->h, pFile->locktype );
20006   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
20007     return SQLITE_IOERR;
20008   }
20009   assert( amt>0 );
20010   while( amt > 0 &&
20011          ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
20012          wrote > 0
20013   ){
20014     amt -= wrote;
20015     pBuf = &((char*)pBuf)[wrote];
20016   }
20017
20018   return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
20019 }
20020
20021 /*
20022 ** Truncate an open file to a specified size
20023 */
20024 static int os2Truncate( sqlite3_file *id, i64 nByte ){
20025   APIRET rc = NO_ERROR;
20026   os2File *pFile = (os2File*)id;
20027   OSTRACE3( "TRUNCATE %d %lld\n", pFile->h, nByte );
20028   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
20029   rc = DosSetFileSize( pFile->h, nByte );
20030   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
20031 }
20032
20033 #ifdef SQLITE_TEST
20034 /*
20035 ** Count the number of fullsyncs and normal syncs.  This is used to test
20036 ** that syncs and fullsyncs are occuring at the right times.
20037 */
20038 SQLITE_API int sqlite3_sync_count = 0;
20039 SQLITE_API int sqlite3_fullsync_count = 0;
20040 #endif
20041
20042 /*
20043 ** Make sure all writes to a particular file are committed to disk.
20044 */
20045 static int os2Sync( sqlite3_file *id, int flags ){
20046   os2File *pFile = (os2File*)id;
20047   OSTRACE3( "SYNC %d lock=%d\n", pFile->h, pFile->locktype );
20048 #ifdef SQLITE_TEST
20049   if( flags & SQLITE_SYNC_FULL){
20050     sqlite3_fullsync_count++;
20051   }
20052   sqlite3_sync_count++;
20053 #endif
20054   return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
20055 }
20056
20057 /*
20058 ** Determine the current size of a file in bytes
20059 */
20060 static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
20061   APIRET rc = NO_ERROR;
20062   FILESTATUS3 fsts3FileInfo;
20063   memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
20064   assert( id!=0 );
20065   SimulateIOError( return SQLITE_IOERR );
20066   rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
20067   if( rc == NO_ERROR ){
20068     *pSize = fsts3FileInfo.cbFile;
20069     return SQLITE_OK;
20070   }else{
20071     return SQLITE_IOERR;
20072   }
20073 }
20074
20075 /*
20076 ** Acquire a reader lock.
20077 */
20078 static int getReadLock( os2File *pFile ){
20079   FILELOCK  LockArea,
20080             UnlockArea;
20081   APIRET res;
20082   memset(&LockArea, 0, sizeof(LockArea));
20083   memset(&UnlockArea, 0, sizeof(UnlockArea));
20084   LockArea.lOffset = SHARED_FIRST;
20085   LockArea.lRange = SHARED_SIZE;
20086   UnlockArea.lOffset = 0L;
20087   UnlockArea.lRange = 0L;
20088   res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
20089   OSTRACE3( "GETREADLOCK %d res=%d\n", pFile->h, res );
20090   return res;
20091 }
20092
20093 /*
20094 ** Undo a readlock
20095 */
20096 static int unlockReadLock( os2File *id ){
20097   FILELOCK  LockArea,
20098             UnlockArea;
20099   APIRET res;
20100   memset(&LockArea, 0, sizeof(LockArea));
20101   memset(&UnlockArea, 0, sizeof(UnlockArea));
20102   LockArea.lOffset = 0L;
20103   LockArea.lRange = 0L;
20104   UnlockArea.lOffset = SHARED_FIRST;
20105   UnlockArea.lRange = SHARED_SIZE;
20106   res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
20107   OSTRACE3( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res );
20108   return res;
20109 }
20110
20111 /*
20112 ** Lock the file with the lock specified by parameter locktype - one
20113 ** of the following:
20114 **
20115 **     (1) SHARED_LOCK
20116 **     (2) RESERVED_LOCK
20117 **     (3) PENDING_LOCK
20118 **     (4) EXCLUSIVE_LOCK
20119 **
20120 ** Sometimes when requesting one lock state, additional lock states
20121 ** are inserted in between.  The locking might fail on one of the later
20122 ** transitions leaving the lock state different from what it started but
20123 ** still short of its goal.  The following chart shows the allowed
20124 ** transitions and the inserted intermediate states:
20125 **
20126 **    UNLOCKED -> SHARED
20127 **    SHARED -> RESERVED
20128 **    SHARED -> (PENDING) -> EXCLUSIVE
20129 **    RESERVED -> (PENDING) -> EXCLUSIVE
20130 **    PENDING -> EXCLUSIVE
20131 **
20132 ** This routine will only increase a lock.  The os2Unlock() routine
20133 ** erases all locks at once and returns us immediately to locking level 0.
20134 ** It is not possible to lower the locking level one step at a time.  You
20135 ** must go straight to locking level 0.
20136 */
20137 static int os2Lock( sqlite3_file *id, int locktype ){
20138   int rc = SQLITE_OK;       /* Return code from subroutines */
20139   APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
20140   int newLocktype;       /* Set pFile->locktype to this value before exiting */
20141   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
20142   FILELOCK  LockArea,
20143             UnlockArea;
20144   os2File *pFile = (os2File*)id;
20145   memset(&LockArea, 0, sizeof(LockArea));
20146   memset(&UnlockArea, 0, sizeof(UnlockArea));
20147   assert( pFile!=0 );
20148   OSTRACE4( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype );
20149
20150   /* If there is already a lock of this type or more restrictive on the
20151   ** os2File, do nothing. Don't use the end_lock: exit path, as
20152   ** sqlite3_mutex_enter() hasn't been called yet.
20153   */
20154   if( pFile->locktype>=locktype ){
20155     OSTRACE3( "LOCK %d %d ok (already held)\n", pFile->h, locktype );
20156     return SQLITE_OK;
20157   }
20158
20159   /* Make sure the locking sequence is correct
20160   */
20161   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
20162   assert( locktype!=PENDING_LOCK );
20163   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
20164
20165   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
20166   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
20167   ** the PENDING_LOCK byte is temporary.
20168   */
20169   newLocktype = pFile->locktype;
20170   if( pFile->locktype==NO_LOCK
20171       || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
20172   ){
20173     LockArea.lOffset = PENDING_BYTE;
20174     LockArea.lRange = 1L;
20175     UnlockArea.lOffset = 0L;
20176     UnlockArea.lRange = 0L;
20177
20178     /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
20179     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
20180     if( res == NO_ERROR ){
20181       gotPendingLock = 1;
20182       OSTRACE3( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res );
20183     }
20184   }
20185
20186   /* Acquire a shared lock
20187   */
20188   if( locktype==SHARED_LOCK && res == NO_ERROR ){
20189     assert( pFile->locktype==NO_LOCK );
20190     res = getReadLock(pFile);
20191     if( res == NO_ERROR ){
20192       newLocktype = SHARED_LOCK;
20193     }
20194     OSTRACE3( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res );
20195   }
20196
20197   /* Acquire a RESERVED lock
20198   */
20199   if( locktype==RESERVED_LOCK && res == NO_ERROR ){
20200     assert( pFile->locktype==SHARED_LOCK );
20201     LockArea.lOffset = RESERVED_BYTE;
20202     LockArea.lRange = 1L;
20203     UnlockArea.lOffset = 0L;
20204     UnlockArea.lRange = 0L;
20205     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20206     if( res == NO_ERROR ){
20207       newLocktype = RESERVED_LOCK;
20208     }
20209     OSTRACE3( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res );
20210   }
20211
20212   /* Acquire a PENDING lock
20213   */
20214   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
20215     newLocktype = PENDING_LOCK;
20216     gotPendingLock = 0;
20217     OSTRACE2( "LOCK %d acquire pending lock. pending lock boolean unset.\n", pFile->h );
20218   }
20219
20220   /* Acquire an EXCLUSIVE lock
20221   */
20222   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
20223     assert( pFile->locktype>=SHARED_LOCK );
20224     res = unlockReadLock(pFile);
20225     OSTRACE2( "unreadlock = %d\n", res );
20226     LockArea.lOffset = SHARED_FIRST;
20227     LockArea.lRange = SHARED_SIZE;
20228     UnlockArea.lOffset = 0L;
20229     UnlockArea.lRange = 0L;
20230     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20231     if( res == NO_ERROR ){
20232       newLocktype = EXCLUSIVE_LOCK;
20233     }else{
20234       OSTRACE2( "OS/2 error-code = %d\n", res );
20235       getReadLock(pFile);
20236     }
20237     OSTRACE3( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res );
20238   }
20239
20240   /* If we are holding a PENDING lock that ought to be released, then
20241   ** release it now.
20242   */
20243   if( gotPendingLock && locktype==SHARED_LOCK ){
20244     int r;
20245     LockArea.lOffset = 0L;
20246     LockArea.lRange = 0L;
20247     UnlockArea.lOffset = PENDING_BYTE;
20248     UnlockArea.lRange = 1L;
20249     r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20250     OSTRACE3( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r );
20251   }
20252
20253   /* Update the state of the lock has held in the file descriptor then
20254   ** return the appropriate result code.
20255   */
20256   if( res == NO_ERROR ){
20257     rc = SQLITE_OK;
20258   }else{
20259     OSTRACE4( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
20260               locktype, newLocktype );
20261     rc = SQLITE_BUSY;
20262   }
20263   pFile->locktype = newLocktype;
20264   OSTRACE3( "LOCK %d now %d\n", pFile->h, pFile->locktype );
20265   return rc;
20266 }
20267
20268 /*
20269 ** This routine checks if there is a RESERVED lock held on the specified
20270 ** file by this or any other process. If such a lock is held, return
20271 ** non-zero, otherwise zero.
20272 */
20273 static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
20274   int r = 0;
20275   os2File *pFile = (os2File*)id;
20276   assert( pFile!=0 );
20277   if( pFile->locktype>=RESERVED_LOCK ){
20278     r = 1;
20279     OSTRACE3( "TEST WR-LOCK %d %d (local)\n", pFile->h, r );
20280   }else{
20281     FILELOCK  LockArea,
20282               UnlockArea;
20283     APIRET rc = NO_ERROR;
20284     memset(&LockArea, 0, sizeof(LockArea));
20285     memset(&UnlockArea, 0, sizeof(UnlockArea));
20286     LockArea.lOffset = RESERVED_BYTE;
20287     LockArea.lRange = 1L;
20288     UnlockArea.lOffset = 0L;
20289     UnlockArea.lRange = 0L;
20290     rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20291     OSTRACE3( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc );
20292     if( rc == NO_ERROR ){
20293       APIRET rcu = NO_ERROR; /* return code for unlocking */
20294       LockArea.lOffset = 0L;
20295       LockArea.lRange = 0L;
20296       UnlockArea.lOffset = RESERVED_BYTE;
20297       UnlockArea.lRange = 1L;
20298       rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20299       OSTRACE3( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu );
20300     }
20301     r = !(rc == NO_ERROR);
20302     OSTRACE3( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r );
20303   }
20304   *pOut = r;
20305   return SQLITE_OK;
20306 }
20307
20308 /*
20309 ** Lower the locking level on file descriptor id to locktype.  locktype
20310 ** must be either NO_LOCK or SHARED_LOCK.
20311 **
20312 ** If the locking level of the file descriptor is already at or below
20313 ** the requested locking level, this routine is a no-op.
20314 **
20315 ** It is not possible for this routine to fail if the second argument
20316 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
20317 ** might return SQLITE_IOERR;
20318 */
20319 static int os2Unlock( sqlite3_file *id, int locktype ){
20320   int type;
20321   os2File *pFile = (os2File*)id;
20322   APIRET rc = SQLITE_OK;
20323   APIRET res = NO_ERROR;
20324   FILELOCK  LockArea,
20325             UnlockArea;
20326   memset(&LockArea, 0, sizeof(LockArea));
20327   memset(&UnlockArea, 0, sizeof(UnlockArea));
20328   assert( pFile!=0 );
20329   assert( locktype<=SHARED_LOCK );
20330   OSTRACE4( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype );
20331   type = pFile->locktype;
20332   if( type>=EXCLUSIVE_LOCK ){
20333     LockArea.lOffset = 0L;
20334     LockArea.lRange = 0L;
20335     UnlockArea.lOffset = SHARED_FIRST;
20336     UnlockArea.lRange = SHARED_SIZE;
20337     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20338     OSTRACE3( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res );
20339     if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
20340       /* This should never happen.  We should always be able to
20341       ** reacquire the read lock */
20342       OSTRACE3( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype );
20343       rc = SQLITE_IOERR_UNLOCK;
20344     }
20345   }
20346   if( type>=RESERVED_LOCK ){
20347     LockArea.lOffset = 0L;
20348     LockArea.lRange = 0L;
20349     UnlockArea.lOffset = RESERVED_BYTE;
20350     UnlockArea.lRange = 1L;
20351     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20352     OSTRACE3( "UNLOCK %d reserved res=%d\n", pFile->h, res );
20353   }
20354   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
20355     res = unlockReadLock(pFile);
20356     OSTRACE5( "UNLOCK %d is %d want %d res=%d\n", pFile->h, type, locktype, res );
20357   }
20358   if( type>=PENDING_LOCK ){
20359     LockArea.lOffset = 0L;
20360     LockArea.lRange = 0L;
20361     UnlockArea.lOffset = PENDING_BYTE;
20362     UnlockArea.lRange = 1L;
20363     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20364     OSTRACE3( "UNLOCK %d pending res=%d\n", pFile->h, res );
20365   }
20366   pFile->locktype = locktype;
20367   OSTRACE3( "UNLOCK %d now %d\n", pFile->h, pFile->locktype );
20368   return rc;
20369 }
20370
20371 /*
20372 ** Control and query of the open file handle.
20373 */
20374 static int os2FileControl(sqlite3_file *id, int op, void *pArg){
20375   switch( op ){
20376     case SQLITE_FCNTL_LOCKSTATE: {
20377       *(int*)pArg = ((os2File*)id)->locktype;
20378       OSTRACE3( "FCNTL_LOCKSTATE %d lock=%d\n", ((os2File*)id)->h, ((os2File*)id)->locktype );
20379       return SQLITE_OK;
20380     }
20381   }
20382   return SQLITE_ERROR;
20383 }
20384
20385 /*
20386 ** Return the sector size in bytes of the underlying block device for
20387 ** the specified file. This is almost always 512 bytes, but may be
20388 ** larger for some devices.
20389 **
20390 ** SQLite code assumes this function cannot fail. It also assumes that
20391 ** if two files are created in the same file-system directory (i.e.
20392 ** a database and its journal file) that the sector size will be the
20393 ** same for both.
20394 */
20395 static int os2SectorSize(sqlite3_file *id){
20396   return SQLITE_DEFAULT_SECTOR_SIZE;
20397 }
20398
20399 /*
20400 ** Return a vector of device characteristics.
20401 */
20402 static int os2DeviceCharacteristics(sqlite3_file *id){
20403   return 0;
20404 }
20405
20406
20407 /*
20408 ** Character set conversion objects used by conversion routines.
20409 */
20410 static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
20411 static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */
20412
20413 /*
20414 ** Helper function to initialize the conversion objects from and to UTF-8.
20415 */
20416 static void initUconvObjects( void ){
20417   if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
20418     ucUtf8 = NULL;
20419   if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
20420     uclCp = NULL;
20421 }
20422
20423 /*
20424 ** Helper function to free the conversion objects from and to UTF-8.
20425 */
20426 static void freeUconvObjects( void ){
20427   if ( ucUtf8 )
20428     UniFreeUconvObject( ucUtf8 );
20429   if ( uclCp )
20430     UniFreeUconvObject( uclCp );
20431   ucUtf8 = NULL;
20432   uclCp = NULL;
20433 }
20434
20435 /*
20436 ** Helper function to convert UTF-8 filenames to local OS/2 codepage.
20437 ** The two-step process: first convert the incoming UTF-8 string
20438 ** into UCS-2 and then from UCS-2 to the current codepage.
20439 ** The returned char pointer has to be freed.
20440 */
20441 static char *convertUtf8PathToCp( const char *in ){
20442   UniChar tempPath[CCHMAXPATH];
20443   char *out = (char *)calloc( CCHMAXPATH, 1 );
20444
20445   if( !out )
20446     return NULL;
20447
20448   if( !ucUtf8 || !uclCp )
20449     initUconvObjects();
20450
20451   /* determine string for the conversion of UTF-8 which is CP1208 */
20452   if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
20453     return out; /* if conversion fails, return the empty string */
20454
20455   /* conversion for current codepage which can be used for paths */
20456   UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
20457
20458   return out;
20459 }
20460
20461 /*
20462 ** Helper function to convert filenames from local codepage to UTF-8.
20463 ** The two-step process: first convert the incoming codepage-specific
20464 ** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
20465 ** The returned char pointer has to be freed.
20466 **
20467 ** This function is non-static to be able to use this in shell.c and
20468 ** similar applications that take command line arguments.
20469 */
20470 char *convertCpPathToUtf8( const char *in ){
20471   UniChar tempPath[CCHMAXPATH];
20472   char *out = (char *)calloc( CCHMAXPATH, 1 );
20473
20474   if( !out )
20475     return NULL;
20476
20477   if( !ucUtf8 || !uclCp )
20478     initUconvObjects();
20479
20480   /* conversion for current codepage which can be used for paths */
20481   if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
20482     return out; /* if conversion fails, return the empty string */
20483
20484   /* determine string for the conversion of UTF-8 which is CP1208 */
20485   UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
20486
20487   return out;
20488 }
20489
20490 /*
20491 ** This vector defines all the methods that can operate on an
20492 ** sqlite3_file for os2.
20493 */
20494 static const sqlite3_io_methods os2IoMethod = {
20495   1,                        /* iVersion */
20496   os2Close,
20497   os2Read,
20498   os2Write,
20499   os2Truncate,
20500   os2Sync,
20501   os2FileSize,
20502   os2Lock,
20503   os2Unlock,
20504   os2CheckReservedLock,
20505   os2FileControl,
20506   os2SectorSize,
20507   os2DeviceCharacteristics
20508 };
20509
20510 /***************************************************************************
20511 ** Here ends the I/O methods that form the sqlite3_io_methods object.
20512 **
20513 ** The next block of code implements the VFS methods.
20514 ****************************************************************************/
20515
20516 /*
20517 ** Create a temporary file name in zBuf.  zBuf must be big enough to
20518 ** hold at pVfs->mxPathname characters.
20519 */
20520 static int getTempname(int nBuf, char *zBuf ){
20521   static const unsigned char zChars[] =
20522     "abcdefghijklmnopqrstuvwxyz"
20523     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
20524     "0123456789";
20525   int i, j;
20526   char zTempPathBuf[3];
20527   PSZ zTempPath = (PSZ)&zTempPathBuf;
20528   if( sqlite3_temp_directory ){
20529     zTempPath = sqlite3_temp_directory;
20530   }else{
20531     if( DosScanEnv( (PSZ)"TEMP", &zTempPath ) ){
20532       if( DosScanEnv( (PSZ)"TMP", &zTempPath ) ){
20533         if( DosScanEnv( (PSZ)"TMPDIR", &zTempPath ) ){
20534            ULONG ulDriveNum = 0, ulDriveMap = 0;
20535            DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
20536            sprintf( (char*)zTempPath, "%c:", (char)( 'A' + ulDriveNum - 1 ) );
20537         }
20538       }
20539     }
20540   }
20541   /* Strip off a trailing slashes or backslashes, otherwise we would get *
20542    * multiple (back)slashes which causes DosOpen() to fail.              *
20543    * Trailing spaces are not allowed, either.                            */
20544   j = strlen(zTempPath);
20545   while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/'
20546                     || zTempPath[j-1] == ' ' ) ){
20547     j--;
20548   }
20549   zTempPath[j] = '\0';
20550   if( !sqlite3_temp_directory ){
20551     char *zTempPathUTF = convertCpPathToUtf8( zTempPath );
20552     sqlite3_snprintf( nBuf-30, zBuf,
20553                       "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPathUTF );
20554     free( zTempPathUTF );
20555   }else{
20556     sqlite3_snprintf( nBuf-30, zBuf,
20557                       "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath );
20558   }
20559   j = strlen( zBuf );
20560   sqlite3_randomness( 20, &zBuf[j] );
20561   for( i = 0; i < 20; i++, j++ ){
20562     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
20563   }
20564   zBuf[j] = 0;
20565   OSTRACE2( "TEMP FILENAME: %s\n", zBuf );
20566   return SQLITE_OK;
20567 }
20568
20569
20570 /*
20571 ** Turn a relative pathname into a full pathname.  Write the full
20572 ** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
20573 ** bytes in size.
20574 */
20575 static int os2FullPathname(
20576   sqlite3_vfs *pVfs,          /* Pointer to vfs object */
20577   const char *zRelative,      /* Possibly relative input path */
20578   int nFull,                  /* Size of output buffer in bytes */
20579   char *zFull                 /* Output buffer */
20580 ){
20581   char *zRelativeCp = convertUtf8PathToCp( zRelative );
20582   char zFullCp[CCHMAXPATH] = "\0";
20583   char *zFullUTF;
20584   APIRET rc = DosQueryPathInfo( zRelativeCp, FIL_QUERYFULLNAME, zFullCp,
20585                                 CCHMAXPATH );
20586   free( zRelativeCp );
20587   zFullUTF = convertCpPathToUtf8( zFullCp );
20588   sqlite3_snprintf( nFull, zFull, zFullUTF );
20589   free( zFullUTF );
20590   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
20591 }
20592
20593
20594 /*
20595 ** Open a file.
20596 */
20597 static int os2Open(
20598   sqlite3_vfs *pVfs,            /* Not used */
20599   const char *zName,            /* Name of the file */
20600   sqlite3_file *id,             /* Write the SQLite file handle here */
20601   int flags,                    /* Open mode flags */
20602   int *pOutFlags                /* Status return flags */
20603 ){
20604   HFILE h;
20605   ULONG ulFileAttribute = 0;
20606   ULONG ulOpenFlags = 0;
20607   ULONG ulOpenMode = 0;
20608   os2File *pFile = (os2File*)id;
20609   APIRET rc = NO_ERROR;
20610   ULONG ulAction;
20611   char *zNameCp;
20612   char zTmpname[CCHMAXPATH+1];    /* Buffer to hold name of temp file */
20613
20614   /* If the second argument to this function is NULL, generate a 
20615   ** temporary file name to use 
20616   */
20617   if( !zName ){
20618     int rc = getTempname(CCHMAXPATH+1, zTmpname);
20619     if( rc!=SQLITE_OK ){
20620       return rc;
20621     }
20622     zName = zTmpname;
20623   }
20624
20625
20626   memset( pFile, 0, sizeof(*pFile) );
20627
20628   OSTRACE2( "OPEN want %d\n", flags );
20629
20630   /*ulOpenMode = flags & SQLITE_OPEN_READWRITE ? OPEN_ACCESS_READWRITE : OPEN_ACCESS_READONLY;*/
20631   if( flags & SQLITE_OPEN_READWRITE ){
20632     ulOpenMode |= OPEN_ACCESS_READWRITE;
20633     OSTRACE1( "OPEN read/write\n" );
20634   }else{
20635     ulOpenMode |= OPEN_ACCESS_READONLY;
20636     OSTRACE1( "OPEN read only\n" );
20637   }
20638
20639   /*ulOpenFlags = flags & SQLITE_OPEN_CREATE ? OPEN_ACTION_CREATE_IF_NEW : OPEN_ACTION_FAIL_IF_NEW;*/
20640   if( flags & SQLITE_OPEN_CREATE ){
20641     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW;
20642     OSTRACE1( "OPEN open new/create\n" );
20643   }else{
20644     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW;
20645     OSTRACE1( "OPEN open existing\n" );
20646   }
20647
20648   /*ulOpenMode |= flags & SQLITE_OPEN_MAIN_DB ? OPEN_SHARE_DENYNONE : OPEN_SHARE_DENYWRITE;*/
20649   if( flags & SQLITE_OPEN_MAIN_DB ){
20650     ulOpenMode |= OPEN_SHARE_DENYNONE;
20651     OSTRACE1( "OPEN share read/write\n" );
20652   }else{
20653     ulOpenMode |= OPEN_SHARE_DENYWRITE;
20654     OSTRACE1( "OPEN share read only\n" );
20655   }
20656
20657   if( flags & (SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_TEMP_JOURNAL
20658                | SQLITE_OPEN_SUBJOURNAL) ){
20659     char pathUtf8[CCHMAXPATH];
20660 #ifdef NDEBUG /* when debugging we want to make sure it is deleted */
20661     ulFileAttribute = FILE_HIDDEN;
20662 #endif
20663     ulFileAttribute = FILE_NORMAL;
20664     os2FullPathname( pVfs, zName, CCHMAXPATH, pathUtf8 );
20665     pFile->pathToDel = convertUtf8PathToCp( pathUtf8 );
20666     OSTRACE1( "OPEN hidden/delete on close file attributes\n" );
20667   }else{
20668     ulFileAttribute = FILE_ARCHIVED | FILE_NORMAL;
20669     pFile->pathToDel = NULL;
20670     OSTRACE1( "OPEN normal file attribute\n" );
20671   }
20672
20673   /* always open in random access mode for possibly better speed */
20674   ulOpenMode |= OPEN_FLAGS_RANDOM;
20675   ulOpenMode |= OPEN_FLAGS_FAIL_ON_ERROR;
20676   ulOpenMode |= OPEN_FLAGS_NOINHERIT;
20677
20678   zNameCp = convertUtf8PathToCp( zName );
20679   rc = DosOpen( (PSZ)zNameCp,
20680                 &h,
20681                 &ulAction,
20682                 0L,
20683                 ulFileAttribute,
20684                 ulOpenFlags,
20685                 ulOpenMode,
20686                 (PEAOP2)NULL );
20687   free( zNameCp );
20688   if( rc != NO_ERROR ){
20689     OSTRACE7( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulAttr=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
20690               rc, zName, ulAction, ulFileAttribute, ulOpenFlags, ulOpenMode );
20691     if( pFile->pathToDel )
20692       free( pFile->pathToDel );
20693     pFile->pathToDel = NULL;
20694     if( flags & SQLITE_OPEN_READWRITE ){
20695       OSTRACE2( "OPEN %d Invalid handle\n", ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE) );
20696       return os2Open( pVfs, zName, id,
20697                       ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE),
20698                       pOutFlags );
20699     }else{
20700       return SQLITE_CANTOPEN;
20701     }
20702   }
20703
20704   if( pOutFlags ){
20705     *pOutFlags = flags & SQLITE_OPEN_READWRITE ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
20706   }
20707
20708   pFile->pMethod = &os2IoMethod;
20709   pFile->h = h;
20710   OpenCounter(+1);
20711   OSTRACE3( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags );
20712   return SQLITE_OK;
20713 }
20714
20715 /*
20716 ** Delete the named file.
20717 */
20718 static int os2Delete(
20719   sqlite3_vfs *pVfs,                     /* Not used on os2 */
20720   const char *zFilename,                 /* Name of file to delete */
20721   int syncDir                            /* Not used on os2 */
20722 ){
20723   APIRET rc = NO_ERROR;
20724   char *zFilenameCp = convertUtf8PathToCp( zFilename );
20725   SimulateIOError( return SQLITE_IOERR_DELETE );
20726   rc = DosDelete( (PSZ)zFilenameCp );
20727   free( zFilenameCp );
20728   OSTRACE2( "DELETE \"%s\"\n", zFilename );
20729   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
20730 }
20731
20732 /*
20733 ** Check the existance and status of a file.
20734 */
20735 static int os2Access(
20736   sqlite3_vfs *pVfs,        /* Not used on os2 */
20737   const char *zFilename,    /* Name of file to check */
20738   int flags,                /* Type of test to make on this file */
20739   int *pOut                 /* Write results here */
20740 ){
20741   FILESTATUS3 fsts3ConfigInfo;
20742   APIRET rc = NO_ERROR;
20743   char *zFilenameCp = convertUtf8PathToCp( zFilename );
20744
20745   memset( &fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo) );
20746   rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
20747                          &fsts3ConfigInfo, sizeof(FILESTATUS3) );
20748   free( zFilenameCp );
20749   OSTRACE4( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
20750             fsts3ConfigInfo.attrFile, flags, rc );
20751   switch( flags ){
20752     case SQLITE_ACCESS_READ:
20753     case SQLITE_ACCESS_EXISTS:
20754       rc = (rc == NO_ERROR);
20755       OSTRACE3( "ACCESS %s access of read and exists  rc=%d\n", zFilename, rc );
20756       break;
20757     case SQLITE_ACCESS_READWRITE:
20758       rc = (rc == NO_ERROR) && ( (fsts3ConfigInfo.attrFile & FILE_READONLY) == 0 );
20759       OSTRACE3( "ACCESS %s access of read/write  rc=%d\n", zFilename, rc );
20760       break;
20761     default:
20762       assert( !"Invalid flags argument" );
20763   }
20764   *pOut = rc;
20765   return SQLITE_OK;
20766 }
20767
20768
20769 #ifndef SQLITE_OMIT_LOAD_EXTENSION
20770 /*
20771 ** Interfaces for opening a shared library, finding entry points
20772 ** within the shared library, and closing the shared library.
20773 */
20774 /*
20775 ** Interfaces for opening a shared library, finding entry points
20776 ** within the shared library, and closing the shared library.
20777 */
20778 static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
20779   UCHAR loadErr[256];
20780   HMODULE hmod;
20781   APIRET rc;
20782   char *zFilenameCp = convertUtf8PathToCp(zFilename);
20783   rc = DosLoadModule((PSZ)loadErr, sizeof(loadErr), zFilenameCp, &hmod);
20784   free(zFilenameCp);
20785   return rc != NO_ERROR ? 0 : (void*)hmod;
20786 }
20787 /*
20788 ** A no-op since the error code is returned on the DosLoadModule call.
20789 ** os2Dlopen returns zero if DosLoadModule is not successful.
20790 */
20791 static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
20792 /* no-op */
20793 }
20794 static void *os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
20795   PFN pfn;
20796   APIRET rc;
20797   rc = DosQueryProcAddr((HMODULE)pHandle, 0L, zSymbol, &pfn);
20798   if( rc != NO_ERROR ){
20799     /* if the symbol itself was not found, search again for the same
20800      * symbol with an extra underscore, that might be needed depending
20801      * on the calling convention */
20802     char _zSymbol[256] = "_";
20803     strncat(_zSymbol, zSymbol, 255);
20804     rc = DosQueryProcAddr((HMODULE)pHandle, 0L, _zSymbol, &pfn);
20805   }
20806   return rc != NO_ERROR ? 0 : (void*)pfn;
20807 }
20808 static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
20809   DosFreeModule((HMODULE)pHandle);
20810 }
20811 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
20812   #define os2DlOpen 0
20813   #define os2DlError 0
20814   #define os2DlSym 0
20815   #define os2DlClose 0
20816 #endif
20817
20818
20819 /*
20820 ** Write up to nBuf bytes of randomness into zBuf.
20821 */
20822 static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
20823   ULONG sizeofULong = sizeof(ULONG);
20824   int n = 0;
20825   if( sizeof(DATETIME) <= nBuf - n ){
20826     DATETIME x;
20827     DosGetDateTime(&x);
20828     memcpy(&zBuf[n], &x, sizeof(x));
20829     n += sizeof(x);
20830   }
20831
20832   if( sizeofULong <= nBuf - n ){
20833     PPIB ppib;
20834     DosGetInfoBlocks(NULL, &ppib);
20835     memcpy(&zBuf[n], &ppib->pib_ulpid, sizeofULong);
20836     n += sizeofULong;
20837   }
20838
20839   if( sizeofULong <= nBuf - n ){
20840     PTIB ptib;
20841     DosGetInfoBlocks(&ptib, NULL);
20842     memcpy(&zBuf[n], &ptib->tib_ptib2->tib2_ultid, sizeofULong);
20843     n += sizeofULong;
20844   }
20845
20846   /* if we still haven't filled the buffer yet the following will */
20847   /* grab everything once instead of making several calls for a single item */
20848   if( sizeofULong <= nBuf - n ){
20849     ULONG ulSysInfo[QSV_MAX];
20850     DosQuerySysInfo(1L, QSV_MAX, ulSysInfo, sizeofULong * QSV_MAX);
20851
20852     memcpy(&zBuf[n], &ulSysInfo[QSV_MS_COUNT - 1], sizeofULong);
20853     n += sizeofULong;
20854
20855     if( sizeofULong <= nBuf - n ){
20856       memcpy(&zBuf[n], &ulSysInfo[QSV_TIMER_INTERVAL - 1], sizeofULong);
20857       n += sizeofULong;
20858     }
20859     if( sizeofULong <= nBuf - n ){
20860       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_LOW - 1], sizeofULong);
20861       n += sizeofULong;
20862     }
20863     if( sizeofULong <= nBuf - n ){
20864       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_HIGH - 1], sizeofULong);
20865       n += sizeofULong;
20866     }
20867     if( sizeofULong <= nBuf - n ){
20868       memcpy(&zBuf[n], &ulSysInfo[QSV_TOTAVAILMEM - 1], sizeofULong);
20869       n += sizeofULong;
20870     }
20871   }
20872
20873   return n;
20874 }
20875
20876 /*
20877 ** Sleep for a little while.  Return the amount of time slept.
20878 ** The argument is the number of microseconds we want to sleep.
20879 ** The return value is the number of microseconds of sleep actually
20880 ** requested from the underlying operating system, a number which
20881 ** might be greater than or equal to the argument, but not less
20882 ** than the argument.
20883 */
20884 static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
20885   DosSleep( (microsec/1000) );
20886   return microsec;
20887 }
20888
20889 /*
20890 ** The following variable, if set to a non-zero value, becomes the result
20891 ** returned from sqlite3OsCurrentTime().  This is used for testing.
20892 */
20893 #ifdef SQLITE_TEST
20894 SQLITE_API int sqlite3_current_time = 0;
20895 #endif
20896
20897 /*
20898 ** Find the current time (in Universal Coordinated Time).  Write the
20899 ** current time and date as a Julian Day number into *prNow and
20900 ** return 0.  Return 1 if the time and date cannot be found.
20901 */
20902 int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
20903   double now;
20904   SHORT minute; /* needs to be able to cope with negative timezone offset */
20905   USHORT second, hour,
20906          day, month, year;
20907   DATETIME dt;
20908   DosGetDateTime( &dt );
20909   second = (USHORT)dt.seconds;
20910   minute = (SHORT)dt.minutes + dt.timezone;
20911   hour = (USHORT)dt.hours;
20912   day = (USHORT)dt.day;
20913   month = (USHORT)dt.month;
20914   year = (USHORT)dt.year;
20915
20916   /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
20917      http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c */
20918   /* Calculate the Julian days */
20919   now = day - 32076 +
20920     1461*(year + 4800 + (month - 14)/12)/4 +
20921     367*(month - 2 - (month - 14)/12*12)/12 -
20922     3*((year + 4900 + (month - 14)/12)/100)/4;
20923
20924   /* Add the fractional hours, mins and seconds */
20925   now += (hour + 12.0)/24.0;
20926   now += minute/1440.0;
20927   now += second/86400.0;
20928   *prNow = now;
20929 #ifdef SQLITE_TEST
20930   if( sqlite3_current_time ){
20931     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
20932   }
20933 #endif
20934   return 0;
20935 }
20936
20937 static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
20938   return 0;
20939 }
20940
20941 /*
20942 ** Initialize and deinitialize the operating system interface.
20943 */
20944 SQLITE_API int sqlite3_os_init(void){
20945   static sqlite3_vfs os2Vfs = {
20946     1,                 /* iVersion */
20947     sizeof(os2File),   /* szOsFile */
20948     CCHMAXPATH,        /* mxPathname */
20949     0,                 /* pNext */
20950     "os2",             /* zName */
20951     0,                 /* pAppData */
20952
20953     os2Open,           /* xOpen */
20954     os2Delete,         /* xDelete */
20955     os2Access,         /* xAccess */
20956     os2FullPathname,   /* xFullPathname */
20957     os2DlOpen,         /* xDlOpen */
20958     os2DlError,        /* xDlError */
20959     os2DlSym,          /* xDlSym */
20960     os2DlClose,        /* xDlClose */
20961     os2Randomness,     /* xRandomness */
20962     os2Sleep,          /* xSleep */
20963     os2CurrentTime,    /* xCurrentTime */
20964     os2GetLastError    /* xGetLastError */
20965   };
20966   sqlite3_vfs_register(&os2Vfs, 1);
20967   initUconvObjects();
20968   return SQLITE_OK;
20969 }
20970 SQLITE_API int sqlite3_os_end(void){
20971   freeUconvObjects();
20972   return SQLITE_OK;
20973 }
20974
20975 #endif /* SQLITE_OS_OS2 */
20976
20977 /************** End of os_os2.c **********************************************/
20978 /************** Begin file os_unix.c *****************************************/
20979 /*
20980 ** 2004 May 22
20981 **
20982 ** The author disclaims copyright to this source code.  In place of
20983 ** a legal notice, here is a blessing:
20984 **
20985 **    May you do good and not evil.
20986 **    May you find forgiveness for yourself and forgive others.
20987 **    May you share freely, never taking more than you give.
20988 **
20989 ******************************************************************************
20990 **
20991 ** This file contains code that is specific to Unix systems.
20992 **
20993 ** $Id: os_unix.c,v 1.195 2008/07/30 17:28:04 drh Exp $
20994 */
20995 #if SQLITE_OS_UNIX              /* This file is used on unix only */
20996
20997 /*
20998 ** If SQLITE_ENABLE_LOCKING_STYLE is defined, then several different 
20999 ** locking implementations are provided:
21000 **
21001 **   * POSIX locking (the default),
21002 **   * No locking,
21003 **   * Dot-file locking,
21004 **   * flock() locking,
21005 **   * AFP locking (OSX only).
21006 */
21007 /* #define SQLITE_ENABLE_LOCKING_STYLE 0 */
21008
21009 /*
21010 ** These #defines should enable >2GB file support on Posix if the
21011 ** underlying operating system supports it.  If the OS lacks
21012 ** large file support, these should be no-ops.
21013 **
21014 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
21015 ** on the compiler command line.  This is necessary if you are compiling
21016 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
21017 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
21018 ** without this option, LFS is enable.  But LFS does not exist in the kernel
21019 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
21020 ** portability you should omit LFS.
21021 */
21022 #ifndef SQLITE_DISABLE_LFS
21023 # define _LARGE_FILE       1
21024 # ifndef _FILE_OFFSET_BITS
21025 #   define _FILE_OFFSET_BITS 64
21026 # endif
21027 # define _LARGEFILE_SOURCE 1
21028 #endif
21029
21030 /*
21031 ** standard include files.
21032 */
21033 #include <sys/types.h>
21034 #include <sys/stat.h>
21035 #include <fcntl.h>
21036 #include <unistd.h>
21037 #include <sys/time.h>
21038 #include <errno.h>
21039
21040 #ifdef SQLITE_ENABLE_LOCKING_STYLE
21041 #include <sys/ioctl.h>
21042 #include <sys/param.h>
21043 #include <sys/mount.h>
21044 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
21045
21046 /*
21047 ** If we are to be thread-safe, include the pthreads header and define
21048 ** the SQLITE_UNIX_THREADS macro.
21049 */
21050 #if SQLITE_THREADSAFE
21051 # define SQLITE_UNIX_THREADS 1
21052 #endif
21053
21054 /*
21055 ** Default permissions when creating a new file
21056 */
21057 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
21058 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
21059 #endif
21060
21061 /*
21062 ** Maximum supported path-length.
21063 */
21064 #define MAX_PATHNAME 512
21065
21066
21067 /*
21068 ** The unixFile structure is subclass of sqlite3_file specific for the unix
21069 ** protability layer.
21070 */
21071 typedef struct unixFile unixFile;
21072 struct unixFile {
21073   sqlite3_io_methods const *pMethod;  /* Always the first entry */
21074 #ifdef SQLITE_TEST
21075   /* In test mode, increase the size of this structure a bit so that 
21076   ** it is larger than the struct CrashFile defined in test6.c.
21077   */
21078   char aPadding[32];
21079 #endif
21080   struct openCnt *pOpen;    /* Info about all open fd's on this inode */
21081   struct lockInfo *pLock;   /* Info about locks on this inode */
21082 #ifdef SQLITE_ENABLE_LOCKING_STYLE
21083   void *lockingContext;     /* Locking style specific state */
21084 #endif
21085   int h;                    /* The file descriptor */
21086   unsigned char locktype;   /* The type of lock held on this fd */
21087   int dirfd;                /* File descriptor for the directory */
21088 #if SQLITE_THREADSAFE
21089   pthread_t tid;            /* The thread that "owns" this unixFile */
21090 #endif
21091 };
21092
21093 /*
21094 ** Include code that is common to all os_*.c files
21095 */
21096 /************** Include os_common.h in the middle of os_unix.c ***************/
21097 /************** Begin file os_common.h ***************************************/
21098 /*
21099 ** 2004 May 22
21100 **
21101 ** The author disclaims copyright to this source code.  In place of
21102 ** a legal notice, here is a blessing:
21103 **
21104 **    May you do good and not evil.
21105 **    May you find forgiveness for yourself and forgive others.
21106 **    May you share freely, never taking more than you give.
21107 **
21108 ******************************************************************************
21109 **
21110 ** This file contains macros and a little bit of code that is common to
21111 ** all of the platform-specific files (os_*.c) and is #included into those
21112 ** files.
21113 **
21114 ** This file should be #included by the os_*.c files only.  It is not a
21115 ** general purpose header file.
21116 **
21117 ** $Id: os_common.h,v 1.37 2008/05/29 20:22:37 shane Exp $
21118 */
21119 #ifndef _OS_COMMON_H_
21120 #define _OS_COMMON_H_
21121
21122 /*
21123 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
21124 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
21125 ** switch.  The following code should catch this problem at compile-time.
21126 */
21127 #ifdef MEMORY_DEBUG
21128 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
21129 #endif
21130
21131
21132 /*
21133  * When testing, this global variable stores the location of the
21134  * pending-byte in the database file.
21135  */
21136 #ifdef SQLITE_TEST
21137 SQLITE_API unsigned int sqlite3_pending_byte = 0x40000000;
21138 #endif
21139
21140 #ifdef SQLITE_DEBUG
21141 SQLITE_PRIVATE int sqlite3OSTrace = 0;
21142 #define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
21143 #define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
21144 #define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
21145 #define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
21146 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
21147 #define OSTRACE6(X,Y,Z,A,B,C) \
21148     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
21149 #define OSTRACE7(X,Y,Z,A,B,C,D) \
21150     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
21151 #else
21152 #define OSTRACE1(X)
21153 #define OSTRACE2(X,Y)
21154 #define OSTRACE3(X,Y,Z)
21155 #define OSTRACE4(X,Y,Z,A)
21156 #define OSTRACE5(X,Y,Z,A,B)
21157 #define OSTRACE6(X,Y,Z,A,B,C)
21158 #define OSTRACE7(X,Y,Z,A,B,C,D)
21159 #endif
21160
21161 /*
21162 ** Macros for performance tracing.  Normally turned off.  Only works
21163 ** on i486 hardware.
21164 */
21165 #ifdef SQLITE_PERFORMANCE_TRACE
21166
21167 /* 
21168 ** hwtime.h contains inline assembler code for implementing 
21169 ** high-performance timing routines.
21170 */
21171 /************** Include hwtime.h in the middle of os_common.h ****************/
21172 /************** Begin file hwtime.h ******************************************/
21173 /*
21174 ** 2008 May 27
21175 **
21176 ** The author disclaims copyright to this source code.  In place of
21177 ** a legal notice, here is a blessing:
21178 **
21179 **    May you do good and not evil.
21180 **    May you find forgiveness for yourself and forgive others.
21181 **    May you share freely, never taking more than you give.
21182 **
21183 ******************************************************************************
21184 **
21185 ** This file contains inline asm code for retrieving "high-performance"
21186 ** counters for x86 class CPUs.
21187 **
21188 ** $Id: hwtime.h,v 1.3 2008/08/01 14:33:15 shane Exp $
21189 */
21190 #ifndef _HWTIME_H_
21191 #define _HWTIME_H_
21192
21193 /*
21194 ** The following routine only works on pentium-class (or newer) processors.
21195 ** It uses the RDTSC opcode to read the cycle count value out of the
21196 ** processor and returns that value.  This can be used for high-res
21197 ** profiling.
21198 */
21199 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
21200       (defined(i386) || defined(__i386__) || defined(_M_IX86))
21201
21202   #if defined(__GNUC__)
21203
21204   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21205      unsigned int lo, hi;
21206      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
21207      return (sqlite_uint64)hi << 32 | lo;
21208   }
21209
21210   #elif defined(_MSC_VER)
21211
21212   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
21213      __asm {
21214         rdtsc
21215         ret       ; return value at EDX:EAX
21216      }
21217   }
21218
21219   #endif
21220
21221 #elif (defined(__GNUC__) && defined(__x86_64__))
21222
21223   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21224       unsigned long val;
21225       __asm__ __volatile__ ("rdtsc" : "=A" (val));
21226       return val;
21227   }
21228  
21229 #elif (defined(__GNUC__) && defined(__ppc__))
21230
21231   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21232       unsigned long long retval;
21233       unsigned long junk;
21234       __asm__ __volatile__ ("\n\
21235           1:      mftbu   %1\n\
21236                   mftb    %L0\n\
21237                   mftbu   %0\n\
21238                   cmpw    %0,%1\n\
21239                   bne     1b"
21240                   : "=r" (retval), "=r" (junk));
21241       return retval;
21242   }
21243
21244 #else
21245
21246   #error Need implementation of sqlite3Hwtime() for your platform.
21247
21248   /*
21249   ** To compile without implementing sqlite3Hwtime() for your platform,
21250   ** you can remove the above #error and use the following
21251   ** stub function.  You will lose timing support for many
21252   ** of the debugging and testing utilities, but it should at
21253   ** least compile and run.
21254   */
21255 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
21256
21257 #endif
21258
21259 #endif /* !defined(_HWTIME_H_) */
21260
21261 /************** End of hwtime.h **********************************************/
21262 /************** Continuing where we left off in os_common.h ******************/
21263
21264 static sqlite_uint64 g_start;
21265 static sqlite_uint64 g_elapsed;
21266 #define TIMER_START       g_start=sqlite3Hwtime()
21267 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
21268 #define TIMER_ELAPSED     g_elapsed
21269 #else
21270 #define TIMER_START
21271 #define TIMER_END
21272 #define TIMER_ELAPSED     ((sqlite_uint64)0)
21273 #endif
21274
21275 /*
21276 ** If we compile with the SQLITE_TEST macro set, then the following block
21277 ** of code will give us the ability to simulate a disk I/O error.  This
21278 ** is used for testing the I/O recovery logic.
21279 */
21280 #ifdef SQLITE_TEST
21281 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
21282 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
21283 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
21284 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
21285 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
21286 SQLITE_API int sqlite3_diskfull_pending = 0;
21287 SQLITE_API int sqlite3_diskfull = 0;
21288 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
21289 #define SimulateIOError(CODE)  \
21290   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
21291        || sqlite3_io_error_pending-- == 1 )  \
21292               { local_ioerr(); CODE; }
21293 static void local_ioerr(){
21294   IOTRACE(("IOERR\n"));
21295   sqlite3_io_error_hit++;
21296   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
21297 }
21298 #define SimulateDiskfullError(CODE) \
21299    if( sqlite3_diskfull_pending ){ \
21300      if( sqlite3_diskfull_pending == 1 ){ \
21301        local_ioerr(); \
21302        sqlite3_diskfull = 1; \
21303        sqlite3_io_error_hit = 1; \
21304        CODE; \
21305      }else{ \
21306        sqlite3_diskfull_pending--; \
21307      } \
21308    }
21309 #else
21310 #define SimulateIOErrorBenign(X)
21311 #define SimulateIOError(A)
21312 #define SimulateDiskfullError(A)
21313 #endif
21314
21315 /*
21316 ** When testing, keep a count of the number of open files.
21317 */
21318 #ifdef SQLITE_TEST
21319 SQLITE_API int sqlite3_open_file_count = 0;
21320 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
21321 #else
21322 #define OpenCounter(X)
21323 #endif
21324
21325 #endif /* !defined(_OS_COMMON_H_) */
21326
21327 /************** End of os_common.h *******************************************/
21328 /************** Continuing where we left off in os_unix.c ********************/
21329
21330 /*
21331 ** Define various macros that are missing from some systems.
21332 */
21333 #ifndef O_LARGEFILE
21334 # define O_LARGEFILE 0
21335 #endif
21336 #ifdef SQLITE_DISABLE_LFS
21337 # undef O_LARGEFILE
21338 # define O_LARGEFILE 0
21339 #endif
21340 #ifndef O_NOFOLLOW
21341 # define O_NOFOLLOW 0
21342 #endif
21343 #ifndef O_BINARY
21344 # define O_BINARY 0
21345 #endif
21346
21347 /*
21348 ** The DJGPP compiler environment looks mostly like Unix, but it
21349 ** lacks the fcntl() system call.  So redefine fcntl() to be something
21350 ** that always succeeds.  This means that locking does not occur under
21351 ** DJGPP.  But it is DOS - what did you expect?
21352 */
21353 #ifdef __DJGPP__
21354 # define fcntl(A,B,C) 0
21355 #endif
21356
21357 /*
21358 ** The threadid macro resolves to the thread-id or to 0.  Used for
21359 ** testing and debugging only.
21360 */
21361 #if SQLITE_THREADSAFE
21362 #define threadid pthread_self()
21363 #else
21364 #define threadid 0
21365 #endif
21366
21367 /*
21368 ** Set or check the unixFile.tid field.  This field is set when an unixFile
21369 ** is first opened.  All subsequent uses of the unixFile verify that the
21370 ** same thread is operating on the unixFile.  Some operating systems do
21371 ** not allow locks to be overridden by other threads and that restriction
21372 ** means that sqlite3* database handles cannot be moved from one thread
21373 ** to another.  This logic makes sure a user does not try to do that
21374 ** by mistake.
21375 **
21376 ** Version 3.3.1 (2006-01-15):  unixFile can be moved from one thread to
21377 ** another as long as we are running on a system that supports threads
21378 ** overriding each others locks (which now the most common behavior)
21379 ** or if no locks are held.  But the unixFile.pLock field needs to be
21380 ** recomputed because its key includes the thread-id.  See the 
21381 ** transferOwnership() function below for additional information
21382 */
21383 #if SQLITE_THREADSAFE
21384 # define SET_THREADID(X)   (X)->tid = pthread_self()
21385 # define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
21386                             !pthread_equal((X)->tid, pthread_self()))
21387 #else
21388 # define SET_THREADID(X)
21389 # define CHECK_THREADID(X) 0
21390 #endif
21391
21392 /*
21393 ** Here is the dirt on POSIX advisory locks:  ANSI STD 1003.1 (1996)
21394 ** section 6.5.2.2 lines 483 through 490 specify that when a process
21395 ** sets or clears a lock, that operation overrides any prior locks set
21396 ** by the same process.  It does not explicitly say so, but this implies
21397 ** that it overrides locks set by the same process using a different
21398 ** file descriptor.  Consider this test case:
21399 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
21400 **
21401 ** Suppose ./file1 and ./file2 are really the same file (because
21402 ** one is a hard or symbolic link to the other) then if you set
21403 ** an exclusive lock on fd1, then try to get an exclusive lock
21404 ** on fd2, it works.  I would have expected the second lock to
21405 ** fail since there was already a lock on the file due to fd1.
21406 ** But not so.  Since both locks came from the same process, the
21407 ** second overrides the first, even though they were on different
21408 ** file descriptors opened on different file names.
21409 **
21410 ** Bummer.  If you ask me, this is broken.  Badly broken.  It means
21411 ** that we cannot use POSIX locks to synchronize file access among
21412 ** competing threads of the same process.  POSIX locks will work fine
21413 ** to synchronize access for threads in separate processes, but not
21414 ** threads within the same process.
21415 **
21416 ** To work around the problem, SQLite has to manage file locks internally
21417 ** on its own.  Whenever a new database is opened, we have to find the
21418 ** specific inode of the database file (the inode is determined by the
21419 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
21420 ** and check for locks already existing on that inode.  When locks are
21421 ** created or removed, we have to look at our own internal record of the
21422 ** locks to see if another thread has previously set a lock on that same
21423 ** inode.
21424 **
21425 ** The sqlite3_file structure for POSIX is no longer just an integer file
21426 ** descriptor.  It is now a structure that holds the integer file
21427 ** descriptor and a pointer to a structure that describes the internal
21428 ** locks on the corresponding inode.  There is one locking structure
21429 ** per inode, so if the same inode is opened twice, both unixFile structures
21430 ** point to the same locking structure.  The locking structure keeps
21431 ** a reference count (so we will know when to delete it) and a "cnt"
21432 ** field that tells us its internal lock status.  cnt==0 means the
21433 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
21434 ** cnt>0 means there are cnt shared locks on the file.
21435 **
21436 ** Any attempt to lock or unlock a file first checks the locking
21437 ** structure.  The fcntl() system call is only invoked to set a 
21438 ** POSIX lock if the internal lock structure transitions between
21439 ** a locked and an unlocked state.
21440 **
21441 ** 2004-Jan-11:
21442 ** More recent discoveries about POSIX advisory locks.  (The more
21443 ** I discover, the more I realize the a POSIX advisory locks are
21444 ** an abomination.)
21445 **
21446 ** If you close a file descriptor that points to a file that has locks,
21447 ** all locks on that file that are owned by the current process are
21448 ** released.  To work around this problem, each unixFile structure contains
21449 ** a pointer to an openCnt structure.  There is one openCnt structure
21450 ** per open inode, which means that multiple unixFile can point to a single
21451 ** openCnt.  When an attempt is made to close an unixFile, if there are
21452 ** other unixFile open on the same inode that are holding locks, the call
21453 ** to close() the file descriptor is deferred until all of the locks clear.
21454 ** The openCnt structure keeps a list of file descriptors that need to
21455 ** be closed and that list is walked (and cleared) when the last lock
21456 ** clears.
21457 **
21458 ** First, under Linux threads, because each thread has a separate
21459 ** process ID, lock operations in one thread do not override locks
21460 ** to the same file in other threads.  Linux threads behave like
21461 ** separate processes in this respect.  But, if you close a file
21462 ** descriptor in linux threads, all locks are cleared, even locks
21463 ** on other threads and even though the other threads have different
21464 ** process IDs.  Linux threads is inconsistent in this respect.
21465 ** (I'm beginning to think that linux threads is an abomination too.)
21466 ** The consequence of this all is that the hash table for the lockInfo
21467 ** structure has to include the process id as part of its key because
21468 ** locks in different threads are treated as distinct.  But the 
21469 ** openCnt structure should not include the process id in its
21470 ** key because close() clears lock on all threads, not just the current
21471 ** thread.  Were it not for this goofiness in linux threads, we could
21472 ** combine the lockInfo and openCnt structures into a single structure.
21473 **
21474 ** 2004-Jun-28:
21475 ** On some versions of linux, threads can override each others locks.
21476 ** On others not.  Sometimes you can change the behavior on the same
21477 ** system by setting the LD_ASSUME_KERNEL environment variable.  The
21478 ** POSIX standard is silent as to which behavior is correct, as far
21479 ** as I can tell, so other versions of unix might show the same
21480 ** inconsistency.  There is no little doubt in my mind that posix
21481 ** advisory locks and linux threads are profoundly broken.
21482 **
21483 ** To work around the inconsistencies, we have to test at runtime 
21484 ** whether or not threads can override each others locks.  This test
21485 ** is run once, the first time any lock is attempted.  A static 
21486 ** variable is set to record the results of this test for future
21487 ** use.
21488 */
21489
21490 /*
21491 ** An instance of the following structure serves as the key used
21492 ** to locate a particular lockInfo structure given its inode.
21493 **
21494 ** If threads cannot override each others locks, then we set the
21495 ** lockKey.tid field to the thread ID.  If threads can override
21496 ** each others locks then tid is always set to zero.  tid is omitted
21497 ** if we compile without threading support.
21498 */
21499 struct lockKey {
21500   dev_t dev;       /* Device number */
21501   ino_t ino;       /* Inode number */
21502 #if SQLITE_THREADSAFE
21503   pthread_t tid;   /* Thread ID or zero if threads can override each other */
21504 #endif
21505 };
21506
21507 /*
21508 ** An instance of the following structure is allocated for each open
21509 ** inode on each thread with a different process ID.  (Threads have
21510 ** different process IDs on linux, but not on most other unixes.)
21511 **
21512 ** A single inode can have multiple file descriptors, so each unixFile
21513 ** structure contains a pointer to an instance of this object and this
21514 ** object keeps a count of the number of unixFile pointing to it.
21515 */
21516 struct lockInfo {
21517   struct lockKey key;  /* The lookup key */
21518   int cnt;             /* Number of SHARED locks held */
21519   int locktype;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
21520   int nRef;            /* Number of pointers to this structure */
21521   struct lockInfo *pNext, *pPrev;   /* List of all lockInfo objects */
21522 };
21523
21524 /*
21525 ** An instance of the following structure serves as the key used
21526 ** to locate a particular openCnt structure given its inode.  This
21527 ** is the same as the lockKey except that the thread ID is omitted.
21528 */
21529 struct openKey {
21530   dev_t dev;   /* Device number */
21531   ino_t ino;   /* Inode number */
21532 };
21533
21534 /*
21535 ** An instance of the following structure is allocated for each open
21536 ** inode.  This structure keeps track of the number of locks on that
21537 ** inode.  If a close is attempted against an inode that is holding
21538 ** locks, the close is deferred until all locks clear by adding the
21539 ** file descriptor to be closed to the pending list.
21540 */
21541 struct openCnt {
21542   struct openKey key;   /* The lookup key */
21543   int nRef;             /* Number of pointers to this structure */
21544   int nLock;            /* Number of outstanding locks */
21545   int nPending;         /* Number of pending close() operations */
21546   int *aPending;        /* Malloced space holding fd's awaiting a close() */
21547   struct openCnt *pNext, *pPrev;   /* List of all openCnt objects */
21548 };
21549
21550 /*
21551 ** List of all lockInfo and openCnt objects.  This used to be a hash
21552 ** table.  But the number of objects is rarely more than a dozen and
21553 ** never exceeds a few thousand.  And lookup is not on a critical
21554 ** path oo a simple linked list will suffice.
21555 */
21556 static struct lockInfo *lockList = 0;
21557 static struct openCnt *openList = 0;
21558
21559 /*
21560 ** The locking styles are associated with the different file locking
21561 ** capabilities supported by different file systems.  
21562 **
21563 ** POSIX locking style fully supports shared and exclusive byte-range locks 
21564 ** AFP locking only supports exclusive byte-range locks
21565 ** FLOCK only supports a single file-global exclusive lock
21566 ** DOTLOCK isn't a true locking style, it refers to the use of a special
21567 **   file named the same as the database file with a '.lock' extension, this
21568 **   can be used on file systems that do not offer any reliable file locking
21569 ** NO locking means that no locking will be attempted, this is only used for
21570 **   read-only file systems currently
21571 ** UNSUPPORTED means that no locking will be attempted, this is only used for
21572 **   file systems that are known to be unsupported
21573 */
21574 #define LOCKING_STYLE_POSIX        1
21575 #define LOCKING_STYLE_NONE         2
21576 #define LOCKING_STYLE_DOTFILE      3
21577 #define LOCKING_STYLE_FLOCK        4
21578 #define LOCKING_STYLE_AFP          5
21579
21580 /*
21581 ** Helper functions to obtain and relinquish the global mutex.
21582 */
21583 static void enterMutex(){
21584   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
21585 }
21586 static void leaveMutex(){
21587   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
21588 }
21589
21590 #if SQLITE_THREADSAFE
21591 /*
21592 ** This variable records whether or not threads can override each others
21593 ** locks.
21594 **
21595 **    0:  No.  Threads cannot override each others locks.
21596 **    1:  Yes.  Threads can override each others locks.
21597 **   -1:  We don't know yet.
21598 **
21599 ** On some systems, we know at compile-time if threads can override each
21600 ** others locks.  On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
21601 ** will be set appropriately.  On other systems, we have to check at
21602 ** runtime.  On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
21603 ** undefined.
21604 **
21605 ** This variable normally has file scope only.  But during testing, we make
21606 ** it a global so that the test code can change its value in order to verify
21607 ** that the right stuff happens in either case.
21608 */
21609 #ifndef SQLITE_THREAD_OVERRIDE_LOCK
21610 # define SQLITE_THREAD_OVERRIDE_LOCK -1
21611 #endif
21612 #ifdef SQLITE_TEST
21613 int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
21614 #else
21615 static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
21616 #endif
21617
21618 /*
21619 ** This structure holds information passed into individual test
21620 ** threads by the testThreadLockingBehavior() routine.
21621 */
21622 struct threadTestData {
21623   int fd;                /* File to be locked */
21624   struct flock lock;     /* The locking operation */
21625   int result;            /* Result of the locking operation */
21626 };
21627
21628 #ifdef SQLITE_LOCK_TRACE
21629 /*
21630 ** Print out information about all locking operations.
21631 **
21632 ** This routine is used for troubleshooting locks on multithreaded
21633 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
21634 ** command-line option on the compiler.  This code is normally
21635 ** turned off.
21636 */
21637 static int lockTrace(int fd, int op, struct flock *p){
21638   char *zOpName, *zType;
21639   int s;
21640   int savedErrno;
21641   if( op==F_GETLK ){
21642     zOpName = "GETLK";
21643   }else if( op==F_SETLK ){
21644     zOpName = "SETLK";
21645   }else{
21646     s = fcntl(fd, op, p);
21647     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
21648     return s;
21649   }
21650   if( p->l_type==F_RDLCK ){
21651     zType = "RDLCK";
21652   }else if( p->l_type==F_WRLCK ){
21653     zType = "WRLCK";
21654   }else if( p->l_type==F_UNLCK ){
21655     zType = "UNLCK";
21656   }else{
21657     assert( 0 );
21658   }
21659   assert( p->l_whence==SEEK_SET );
21660   s = fcntl(fd, op, p);
21661   savedErrno = errno;
21662   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
21663      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
21664      (int)p->l_pid, s);
21665   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
21666     struct flock l2;
21667     l2 = *p;
21668     fcntl(fd, F_GETLK, &l2);
21669     if( l2.l_type==F_RDLCK ){
21670       zType = "RDLCK";
21671     }else if( l2.l_type==F_WRLCK ){
21672       zType = "WRLCK";
21673     }else if( l2.l_type==F_UNLCK ){
21674       zType = "UNLCK";
21675     }else{
21676       assert( 0 );
21677     }
21678     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
21679        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
21680   }
21681   errno = savedErrno;
21682   return s;
21683 }
21684 #define fcntl lockTrace
21685 #endif /* SQLITE_LOCK_TRACE */
21686
21687 /*
21688 ** The testThreadLockingBehavior() routine launches two separate
21689 ** threads on this routine.  This routine attempts to lock a file
21690 ** descriptor then returns.  The success or failure of that attempt
21691 ** allows the testThreadLockingBehavior() procedure to determine
21692 ** whether or not threads can override each others locks.
21693 */
21694 static void *threadLockingTest(void *pArg){
21695   struct threadTestData *pData = (struct threadTestData*)pArg;
21696   pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
21697   return pArg;
21698 }
21699
21700 /*
21701 ** This procedure attempts to determine whether or not threads
21702 ** can override each others locks then sets the 
21703 ** threadsOverrideEachOthersLocks variable appropriately.
21704 */
21705 static void testThreadLockingBehavior(int fd_orig){
21706   int fd;
21707   struct threadTestData d[2];
21708   pthread_t t[2];
21709
21710   fd = dup(fd_orig);
21711   if( fd<0 ) return;
21712   memset(d, 0, sizeof(d));
21713   d[0].fd = fd;
21714   d[0].lock.l_type = F_RDLCK;
21715   d[0].lock.l_len = 1;
21716   d[0].lock.l_start = 0;
21717   d[0].lock.l_whence = SEEK_SET;
21718   d[1] = d[0];
21719   d[1].lock.l_type = F_WRLCK;
21720   pthread_create(&t[0], 0, threadLockingTest, &d[0]);
21721   pthread_create(&t[1], 0, threadLockingTest, &d[1]);
21722   pthread_join(t[0], 0);
21723   pthread_join(t[1], 0);
21724   close(fd);
21725   threadsOverrideEachOthersLocks =  d[0].result==0 && d[1].result==0;
21726 }
21727 #endif /* SQLITE_THREADSAFE */
21728
21729 /*
21730 ** Release a lockInfo structure previously allocated by findLockInfo().
21731 */
21732 static void releaseLockInfo(struct lockInfo *pLock){
21733   if( pLock ){
21734     pLock->nRef--;
21735     if( pLock->nRef==0 ){
21736       if( pLock->pPrev ){
21737         assert( pLock->pPrev->pNext==pLock );
21738         pLock->pPrev->pNext = pLock->pNext;
21739       }else{
21740         assert( lockList==pLock );
21741         lockList = pLock->pNext;
21742       }
21743       if( pLock->pNext ){
21744         assert( pLock->pNext->pPrev==pLock );
21745         pLock->pNext->pPrev = pLock->pPrev;
21746       }
21747       sqlite3_free(pLock);
21748     }
21749   }
21750 }
21751
21752 /*
21753 ** Release a openCnt structure previously allocated by findLockInfo().
21754 */
21755 static void releaseOpenCnt(struct openCnt *pOpen){
21756   if( pOpen ){
21757     pOpen->nRef--;
21758     if( pOpen->nRef==0 ){
21759       if( pOpen->pPrev ){
21760         assert( pOpen->pPrev->pNext==pOpen );
21761         pOpen->pPrev->pNext = pOpen->pNext;
21762       }else{
21763         assert( openList==pOpen );
21764         openList = pOpen->pNext;
21765       }
21766       if( pOpen->pNext ){
21767         assert( pOpen->pNext->pPrev==pOpen );
21768         pOpen->pNext->pPrev = pOpen->pPrev;
21769       }
21770       sqlite3_free(pOpen->aPending);
21771       sqlite3_free(pOpen);
21772     }
21773   }
21774 }
21775
21776 #ifdef SQLITE_ENABLE_LOCKING_STYLE
21777 /*
21778 ** Tests a byte-range locking query to see if byte range locks are 
21779 ** supported, if not we fall back to dotlockLockingStyle.
21780 */
21781 static int testLockingStyle(int fd){
21782   struct flock lockInfo;
21783
21784   /* Test byte-range lock using fcntl(). If the call succeeds, 
21785   ** assume that the file-system supports POSIX style locks. 
21786   */
21787   lockInfo.l_len = 1;
21788   lockInfo.l_start = 0;
21789   lockInfo.l_whence = SEEK_SET;
21790   lockInfo.l_type = F_RDLCK;
21791   if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
21792     return LOCKING_STYLE_POSIX;
21793   }
21794   
21795   /* Testing for flock() can give false positives.  So if if the above 
21796   ** test fails, then we fall back to using dot-file style locking.
21797   */  
21798   return LOCKING_STYLE_DOTFILE;
21799 }
21800 #endif
21801
21802 /* 
21803 ** If SQLITE_ENABLE_LOCKING_STYLE is defined, this function Examines the 
21804 ** f_fstypename entry in the statfs structure as returned by stat() for 
21805 ** the file system hosting the database file and selects  the appropriate
21806 ** locking style based on its value.  These values and assignments are 
21807 ** based on Darwin/OSX behavior and have not been thoroughly tested on 
21808 ** other systems.
21809 **
21810 ** If SQLITE_ENABLE_LOCKING_STYLE is not defined, this function always
21811 ** returns LOCKING_STYLE_POSIX.
21812 */
21813 static int detectLockingStyle(
21814   sqlite3_vfs *pVfs,
21815   const char *filePath, 
21816   int fd
21817 ){
21818 #ifdef SQLITE_ENABLE_LOCKING_STYLE
21819   struct Mapping {
21820     const char *zFilesystem;
21821     int eLockingStyle;
21822   } aMap[] = {
21823     { "hfs",    LOCKING_STYLE_POSIX },
21824     { "ufs",    LOCKING_STYLE_POSIX },
21825     { "afpfs",  LOCKING_STYLE_AFP },
21826     { "smbfs",  LOCKING_STYLE_FLOCK },
21827     { "msdos",  LOCKING_STYLE_DOTFILE },
21828     { "webdav", LOCKING_STYLE_NONE },
21829     { 0, 0 }
21830   };
21831   int i;
21832   struct statfs fsInfo;
21833
21834   if( !filePath ){
21835     return LOCKING_STYLE_NONE;
21836   }
21837   if( pVfs->pAppData ){
21838     return (int)pVfs->pAppData;
21839   }
21840
21841   if( statfs(filePath, &fsInfo) != -1 ){
21842     if( fsInfo.f_flags & MNT_RDONLY ){
21843       return LOCKING_STYLE_NONE;
21844     }
21845     for(i=0; aMap[i].zFilesystem; i++){
21846       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
21847         return aMap[i].eLockingStyle;
21848       }
21849     }
21850   }
21851
21852   /* Default case. Handles, amongst others, "nfs". */
21853   return testLockingStyle(fd);  
21854 #endif
21855   return LOCKING_STYLE_POSIX;
21856 }
21857
21858 /*
21859 ** Given a file descriptor, locate lockInfo and openCnt structures that
21860 ** describes that file descriptor.  Create new ones if necessary.  The
21861 ** return values might be uninitialized if an error occurs.
21862 **
21863 ** Return an appropriate error code.
21864 */
21865 static int findLockInfo(
21866   int fd,                      /* The file descriptor used in the key */
21867   struct lockInfo **ppLock,    /* Return the lockInfo structure here */
21868   struct openCnt **ppOpen      /* Return the openCnt structure here */
21869 ){
21870   int rc;
21871   struct lockKey key1;
21872   struct openKey key2;
21873   struct stat statbuf;
21874   struct lockInfo *pLock;
21875   struct openCnt *pOpen;
21876   rc = fstat(fd, &statbuf);
21877   if( rc!=0 ){
21878 #ifdef EOVERFLOW
21879     if( errno==EOVERFLOW ) return SQLITE_NOLFS;
21880 #endif
21881     return SQLITE_IOERR;
21882   }
21883
21884   /* On OS X on an msdos filesystem, the inode number is reported
21885   ** incorrectly for zero-size files.  See ticket #3260.  To work
21886   ** around this problem (we consider it a bug in OS X, not SQLite)
21887   ** we always increase the file size to 1 by writing a single byte
21888   ** prior to accessing the inode number.  The one byte written is
21889   ** an ASCII 'S' character which also happens to be the first byte
21890   ** in the header of every SQLite database.  In this way, if there
21891   ** is a race condition such that another thread has already populated
21892   ** the first page of the database, no damage is done.
21893   */
21894   if( statbuf.st_size==0 ){
21895     write(fd, "S", 1);
21896     rc = fstat(fd, &statbuf);
21897     if( rc!=0 ){
21898       return SQLITE_IOERR;
21899     }
21900   }
21901
21902   memset(&key1, 0, sizeof(key1));
21903   key1.dev = statbuf.st_dev;
21904   key1.ino = statbuf.st_ino;
21905 #if SQLITE_THREADSAFE
21906   if( threadsOverrideEachOthersLocks<0 ){
21907     testThreadLockingBehavior(fd);
21908   }
21909   key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
21910 #endif
21911   memset(&key2, 0, sizeof(key2));
21912   key2.dev = statbuf.st_dev;
21913   key2.ino = statbuf.st_ino;
21914   pLock = lockList;
21915   while( pLock && memcmp(&key1, &pLock->key, sizeof(key1)) ){
21916     pLock = pLock->pNext;
21917   }
21918   if( pLock==0 ){
21919     pLock = sqlite3_malloc( sizeof(*pLock) );
21920     if( pLock==0 ){
21921       rc = SQLITE_NOMEM;
21922       goto exit_findlockinfo;
21923     }
21924     pLock->key = key1;
21925     pLock->nRef = 1;
21926     pLock->cnt = 0;
21927     pLock->locktype = 0;
21928     pLock->pNext = lockList;
21929     pLock->pPrev = 0;
21930     if( lockList ) lockList->pPrev = pLock;
21931     lockList = pLock;
21932   }else{
21933     pLock->nRef++;
21934   }
21935   *ppLock = pLock;
21936   if( ppOpen!=0 ){
21937     pOpen = openList;
21938     while( pOpen && memcmp(&key2, &pOpen->key, sizeof(key2)) ){
21939       pOpen = pOpen->pNext;
21940     }
21941     if( pOpen==0 ){
21942       pOpen = sqlite3_malloc( sizeof(*pOpen) );
21943       if( pOpen==0 ){
21944         releaseLockInfo(pLock);
21945         rc = SQLITE_NOMEM;
21946         goto exit_findlockinfo;
21947       }
21948       pOpen->key = key2;
21949       pOpen->nRef = 1;
21950       pOpen->nLock = 0;
21951       pOpen->nPending = 0;
21952       pOpen->aPending = 0;
21953       pOpen->pNext = openList;
21954       pOpen->pPrev = 0;
21955       if( openList ) openList->pPrev = pOpen;
21956       openList = pOpen;
21957     }else{
21958       pOpen->nRef++;
21959     }
21960     *ppOpen = pOpen;
21961   }
21962
21963 exit_findlockinfo:
21964   return rc;
21965 }
21966
21967 #ifdef SQLITE_DEBUG
21968 /*
21969 ** Helper function for printing out trace information from debugging
21970 ** binaries. This returns the string represetation of the supplied
21971 ** integer lock-type.
21972 */
21973 static const char *locktypeName(int locktype){
21974   switch( locktype ){
21975   case NO_LOCK: return "NONE";
21976   case SHARED_LOCK: return "SHARED";
21977   case RESERVED_LOCK: return "RESERVED";
21978   case PENDING_LOCK: return "PENDING";
21979   case EXCLUSIVE_LOCK: return "EXCLUSIVE";
21980   }
21981   return "ERROR";
21982 }
21983 #endif
21984
21985 /*
21986 ** If we are currently in a different thread than the thread that the
21987 ** unixFile argument belongs to, then transfer ownership of the unixFile
21988 ** over to the current thread.
21989 **
21990 ** A unixFile is only owned by a thread on systems where one thread is
21991 ** unable to override locks created by a different thread.  RedHat9 is
21992 ** an example of such a system.
21993 **
21994 ** Ownership transfer is only allowed if the unixFile is currently unlocked.
21995 ** If the unixFile is locked and an ownership is wrong, then return
21996 ** SQLITE_MISUSE.  SQLITE_OK is returned if everything works.
21997 */
21998 #if SQLITE_THREADSAFE
21999 static int transferOwnership(unixFile *pFile){
22000   int rc;
22001   pthread_t hSelf;
22002   if( threadsOverrideEachOthersLocks ){
22003     /* Ownership transfers not needed on this system */
22004     return SQLITE_OK;
22005   }
22006   hSelf = pthread_self();
22007   if( pthread_equal(pFile->tid, hSelf) ){
22008     /* We are still in the same thread */
22009     OSTRACE1("No-transfer, same thread\n");
22010     return SQLITE_OK;
22011   }
22012   if( pFile->locktype!=NO_LOCK ){
22013     /* We cannot change ownership while we are holding a lock! */
22014     return SQLITE_MISUSE;
22015   }
22016   OSTRACE4("Transfer ownership of %d from %d to %d\n",
22017             pFile->h, pFile->tid, hSelf);
22018   pFile->tid = hSelf;
22019   if (pFile->pLock != NULL) {
22020     releaseLockInfo(pFile->pLock);
22021     rc = findLockInfo(pFile->h, &pFile->pLock, 0);
22022     OSTRACE5("LOCK    %d is now %s(%s,%d)\n", pFile->h,
22023            locktypeName(pFile->locktype),
22024            locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
22025     return rc;
22026   } else {
22027     return SQLITE_OK;
22028   }
22029 }
22030 #else
22031   /* On single-threaded builds, ownership transfer is a no-op */
22032 # define transferOwnership(X) SQLITE_OK
22033 #endif
22034
22035 /*
22036 ** Seek to the offset passed as the second argument, then read cnt 
22037 ** bytes into pBuf. Return the number of bytes actually read.
22038 **
22039 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
22040 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
22041 ** one system to another.  Since SQLite does not define USE_PREAD
22042 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
22043 ** See tickets #2741 and #2681.
22044 */
22045 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
22046   int got;
22047   i64 newOffset;
22048   TIMER_START;
22049 #if defined(USE_PREAD)
22050   got = pread(id->h, pBuf, cnt, offset);
22051   SimulateIOError( got = -1 );
22052 #elif defined(USE_PREAD64)
22053   got = pread64(id->h, pBuf, cnt, offset);
22054   SimulateIOError( got = -1 );
22055 #else
22056   newOffset = lseek(id->h, offset, SEEK_SET);
22057   SimulateIOError( newOffset-- );
22058   if( newOffset!=offset ){
22059     return -1;
22060   }
22061   got = read(id->h, pBuf, cnt);
22062 #endif
22063   TIMER_END;
22064   OSTRACE5("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
22065   return got;
22066 }
22067
22068 /*
22069 ** Read data from a file into a buffer.  Return SQLITE_OK if all
22070 ** bytes were read successfully and SQLITE_IOERR if anything goes
22071 ** wrong.
22072 */
22073 static int unixRead(
22074   sqlite3_file *id, 
22075   void *pBuf, 
22076   int amt,
22077   sqlite3_int64 offset
22078 ){
22079   int got;
22080   assert( id );
22081   got = seekAndRead((unixFile*)id, offset, pBuf, amt);
22082   if( got==amt ){
22083     return SQLITE_OK;
22084   }else if( got<0 ){
22085     return SQLITE_IOERR_READ;
22086   }else{
22087     memset(&((char*)pBuf)[got], 0, amt-got);
22088     return SQLITE_IOERR_SHORT_READ;
22089   }
22090 }
22091
22092 /*
22093 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
22094 ** Return the number of bytes actually read.  Update the offset.
22095 */
22096 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
22097   int got;
22098   i64 newOffset;
22099   TIMER_START;
22100 #if defined(USE_PREAD)
22101   got = pwrite(id->h, pBuf, cnt, offset);
22102 #elif defined(USE_PREAD64)
22103   got = pwrite64(id->h, pBuf, cnt, offset);
22104 #else
22105   newOffset = lseek(id->h, offset, SEEK_SET);
22106   if( newOffset!=offset ){
22107     return -1;
22108   }
22109   got = write(id->h, pBuf, cnt);
22110 #endif
22111   TIMER_END;
22112   OSTRACE5("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
22113   return got;
22114 }
22115
22116
22117 /*
22118 ** Write data from a buffer into a file.  Return SQLITE_OK on success
22119 ** or some other error code on failure.
22120 */
22121 static int unixWrite(
22122   sqlite3_file *id, 
22123   const void *pBuf, 
22124   int amt,
22125   sqlite3_int64 offset 
22126 ){
22127   int wrote = 0;
22128   assert( id );
22129   assert( amt>0 );
22130   while( amt>0 && (wrote = seekAndWrite((unixFile*)id, offset, pBuf, amt))>0 ){
22131     amt -= wrote;
22132     offset += wrote;
22133     pBuf = &((char*)pBuf)[wrote];
22134   }
22135   SimulateIOError(( wrote=(-1), amt=1 ));
22136   SimulateDiskfullError(( wrote=0, amt=1 ));
22137   if( amt>0 ){
22138     if( wrote<0 ){
22139       return SQLITE_IOERR_WRITE;
22140     }else{
22141       return SQLITE_FULL;
22142     }
22143   }
22144   return SQLITE_OK;
22145 }
22146
22147 #ifdef SQLITE_TEST
22148 /*
22149 ** Count the number of fullsyncs and normal syncs.  This is used to test
22150 ** that syncs and fullsyncs are occuring at the right times.
22151 */
22152 SQLITE_API int sqlite3_sync_count = 0;
22153 SQLITE_API int sqlite3_fullsync_count = 0;
22154 #endif
22155
22156 /*
22157 ** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
22158 ** Otherwise use fsync() in its place.
22159 */
22160 #ifndef HAVE_FDATASYNC
22161 # define fdatasync fsync
22162 #endif
22163
22164 /*
22165 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
22166 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
22167 ** only available on Mac OS X.  But that could change.
22168 */
22169 #ifdef F_FULLFSYNC
22170 # define HAVE_FULLFSYNC 1
22171 #else
22172 # define HAVE_FULLFSYNC 0
22173 #endif
22174
22175
22176 /*
22177 ** The fsync() system call does not work as advertised on many
22178 ** unix systems.  The following procedure is an attempt to make
22179 ** it work better.
22180 **
22181 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
22182 ** for testing when we want to run through the test suite quickly.
22183 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
22184 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
22185 ** or power failure will likely corrupt the database file.
22186 */
22187 static int full_fsync(int fd, int fullSync, int dataOnly){
22188   int rc;
22189
22190   /* Record the number of times that we do a normal fsync() and 
22191   ** FULLSYNC.  This is used during testing to verify that this procedure
22192   ** gets called with the correct arguments.
22193   */
22194 #ifdef SQLITE_TEST
22195   if( fullSync ) sqlite3_fullsync_count++;
22196   sqlite3_sync_count++;
22197 #endif
22198
22199   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
22200   ** no-op
22201   */
22202 #ifdef SQLITE_NO_SYNC
22203   rc = SQLITE_OK;
22204 #else
22205
22206 #if HAVE_FULLFSYNC
22207   if( fullSync ){
22208     rc = fcntl(fd, F_FULLFSYNC, 0);
22209   }else{
22210     rc = 1;
22211   }
22212   /* If the FULLFSYNC failed, fall back to attempting an fsync().
22213    * It shouldn't be possible for fullfsync to fail on the local 
22214    * file system (on OSX), so failure indicates that FULLFSYNC
22215    * isn't supported for this file system. So, attempt an fsync 
22216    * and (for now) ignore the overhead of a superfluous fcntl call.  
22217    * It'd be better to detect fullfsync support once and avoid 
22218    * the fcntl call every time sync is called.
22219    */
22220   if( rc ) rc = fsync(fd);
22221
22222 #else 
22223   if( dataOnly ){
22224     rc = fdatasync(fd);
22225   }else{
22226     rc = fsync(fd);
22227   }
22228 #endif /* HAVE_FULLFSYNC */
22229 #endif /* defined(SQLITE_NO_SYNC) */
22230
22231   return rc;
22232 }
22233
22234 /*
22235 ** Make sure all writes to a particular file are committed to disk.
22236 **
22237 ** If dataOnly==0 then both the file itself and its metadata (file
22238 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
22239 ** file data is synced.
22240 **
22241 ** Under Unix, also make sure that the directory entry for the file
22242 ** has been created by fsync-ing the directory that contains the file.
22243 ** If we do not do this and we encounter a power failure, the directory
22244 ** entry for the journal might not exist after we reboot.  The next
22245 ** SQLite to access the file will not know that the journal exists (because
22246 ** the directory entry for the journal was never created) and the transaction
22247 ** will not roll back - possibly leading to database corruption.
22248 */
22249 static int unixSync(sqlite3_file *id, int flags){
22250   int rc;
22251   unixFile *pFile = (unixFile*)id;
22252
22253   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
22254   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
22255
22256   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
22257   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
22258       || (flags&0x0F)==SQLITE_SYNC_FULL
22259   );
22260
22261   assert( pFile );
22262   OSTRACE2("SYNC    %-3d\n", pFile->h);
22263   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
22264   SimulateIOError( rc=1 );
22265   if( rc ){
22266     return SQLITE_IOERR_FSYNC;
22267   }
22268   if( pFile->dirfd>=0 ){
22269     OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
22270             HAVE_FULLFSYNC, isFullsync);
22271 #ifndef SQLITE_DISABLE_DIRSYNC
22272     /* The directory sync is only attempted if full_fsync is
22273     ** turned off or unavailable.  If a full_fsync occurred above,
22274     ** then the directory sync is superfluous.
22275     */
22276     if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
22277        /*
22278        ** We have received multiple reports of fsync() returning
22279        ** errors when applied to directories on certain file systems.
22280        ** A failed directory sync is not a big deal.  So it seems
22281        ** better to ignore the error.  Ticket #1657
22282        */
22283        /* return SQLITE_IOERR; */
22284     }
22285 #endif
22286     close(pFile->dirfd);  /* Only need to sync once, so close the directory */
22287     pFile->dirfd = -1;    /* when we are done. */
22288   }
22289   return SQLITE_OK;
22290 }
22291
22292 /*
22293 ** Truncate an open file to a specified size
22294 */
22295 static int unixTruncate(sqlite3_file *id, i64 nByte){
22296   int rc;
22297   assert( id );
22298   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
22299   rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
22300   if( rc ){
22301     return SQLITE_IOERR_TRUNCATE;
22302   }else{
22303     return SQLITE_OK;
22304   }
22305 }
22306
22307 /*
22308 ** Determine the current size of a file in bytes
22309 */
22310 static int unixFileSize(sqlite3_file *id, i64 *pSize){
22311   int rc;
22312   struct stat buf;
22313   assert( id );
22314   rc = fstat(((unixFile*)id)->h, &buf);
22315   SimulateIOError( rc=1 );
22316   if( rc!=0 ){
22317     return SQLITE_IOERR_FSTAT;
22318   }
22319   *pSize = buf.st_size;
22320
22321   /* When opening a zero-size database, the findLockInfo() procedure
22322   ** writes a single byte into that file in order to work around a bug
22323   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
22324   ** layers, we need to report this file size as zero even though it is
22325   ** really 1.   Ticket #3260.
22326   */
22327   if( *pSize==1 ) *pSize = 0;
22328
22329
22330   return SQLITE_OK;
22331 }
22332
22333 /*
22334 ** This routine checks if there is a RESERVED lock held on the specified
22335 ** file by this or any other process. If such a lock is held, return
22336 ** non-zero.  If the file is unlocked or holds only SHARED locks, then
22337 ** return zero.
22338 */
22339 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
22340   int r = 0;
22341   unixFile *pFile = (unixFile*)id;
22342
22343   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
22344
22345   assert( pFile );
22346   enterMutex(); /* Because pFile->pLock is shared across threads */
22347
22348   /* Check if a thread in this process holds such a lock */
22349   if( pFile->pLock->locktype>SHARED_LOCK ){
22350     r = 1;
22351   }
22352
22353   /* Otherwise see if some other process holds it.
22354   */
22355   if( !r ){
22356     struct flock lock;
22357     lock.l_whence = SEEK_SET;
22358     lock.l_start = RESERVED_BYTE;
22359     lock.l_len = 1;
22360     lock.l_type = F_WRLCK;
22361     fcntl(pFile->h, F_GETLK, &lock);
22362     if( lock.l_type!=F_UNLCK ){
22363       r = 1;
22364     }
22365   }
22366   
22367   leaveMutex();
22368   OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
22369
22370   *pResOut = r;
22371   return SQLITE_OK;
22372 }
22373
22374 /*
22375 ** Lock the file with the lock specified by parameter locktype - one
22376 ** of the following:
22377 **
22378 **     (1) SHARED_LOCK
22379 **     (2) RESERVED_LOCK
22380 **     (3) PENDING_LOCK
22381 **     (4) EXCLUSIVE_LOCK
22382 **
22383 ** Sometimes when requesting one lock state, additional lock states
22384 ** are inserted in between.  The locking might fail on one of the later
22385 ** transitions leaving the lock state different from what it started but
22386 ** still short of its goal.  The following chart shows the allowed
22387 ** transitions and the inserted intermediate states:
22388 **
22389 **    UNLOCKED -> SHARED
22390 **    SHARED -> RESERVED
22391 **    SHARED -> (PENDING) -> EXCLUSIVE
22392 **    RESERVED -> (PENDING) -> EXCLUSIVE
22393 **    PENDING -> EXCLUSIVE
22394 **
22395 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
22396 ** routine to lower a locking level.
22397 */
22398 static int unixLock(sqlite3_file *id, int locktype){
22399   /* The following describes the implementation of the various locks and
22400   ** lock transitions in terms of the POSIX advisory shared and exclusive
22401   ** lock primitives (called read-locks and write-locks below, to avoid
22402   ** confusion with SQLite lock names). The algorithms are complicated
22403   ** slightly in order to be compatible with windows systems simultaneously
22404   ** accessing the same database file, in case that is ever required.
22405   **
22406   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
22407   ** byte', each single bytes at well known offsets, and the 'shared byte
22408   ** range', a range of 510 bytes at a well known offset.
22409   **
22410   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
22411   ** byte'.  If this is successful, a random byte from the 'shared byte
22412   ** range' is read-locked and the lock on the 'pending byte' released.
22413   **
22414   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
22415   ** A RESERVED lock is implemented by grabbing a write-lock on the
22416   ** 'reserved byte'. 
22417   **
22418   ** A process may only obtain a PENDING lock after it has obtained a
22419   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
22420   ** on the 'pending byte'. This ensures that no new SHARED locks can be
22421   ** obtained, but existing SHARED locks are allowed to persist. A process
22422   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
22423   ** This property is used by the algorithm for rolling back a journal file
22424   ** after a crash.
22425   **
22426   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
22427   ** implemented by obtaining a write-lock on the entire 'shared byte
22428   ** range'. Since all other locks require a read-lock on one of the bytes
22429   ** within this range, this ensures that no other locks are held on the
22430   ** database. 
22431   **
22432   ** The reason a single byte cannot be used instead of the 'shared byte
22433   ** range' is that some versions of windows do not support read-locks. By
22434   ** locking a random byte from a range, concurrent SHARED locks may exist
22435   ** even if the locking primitive used is always a write-lock.
22436   */
22437   int rc = SQLITE_OK;
22438   unixFile *pFile = (unixFile*)id;
22439   struct lockInfo *pLock = pFile->pLock;
22440   struct flock lock;
22441   int s;
22442
22443   assert( pFile );
22444   OSTRACE7("LOCK    %d %s was %s(%s,%d) pid=%d\n", pFile->h,
22445       locktypeName(locktype), locktypeName(pFile->locktype),
22446       locktypeName(pLock->locktype), pLock->cnt , getpid());
22447
22448   /* If there is already a lock of this type or more restrictive on the
22449   ** unixFile, do nothing. Don't use the end_lock: exit path, as
22450   ** enterMutex() hasn't been called yet.
22451   */
22452   if( pFile->locktype>=locktype ){
22453     OSTRACE3("LOCK    %d %s ok (already held)\n", pFile->h,
22454             locktypeName(locktype));
22455     return SQLITE_OK;
22456   }
22457
22458   /* Make sure the locking sequence is correct
22459   */
22460   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
22461   assert( locktype!=PENDING_LOCK );
22462   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
22463
22464   /* This mutex is needed because pFile->pLock is shared across threads
22465   */
22466   enterMutex();
22467
22468   /* Make sure the current thread owns the pFile.
22469   */
22470   rc = transferOwnership(pFile);
22471   if( rc!=SQLITE_OK ){
22472     leaveMutex();
22473     return rc;
22474   }
22475   pLock = pFile->pLock;
22476
22477   /* If some thread using this PID has a lock via a different unixFile*
22478   ** handle that precludes the requested lock, return BUSY.
22479   */
22480   if( (pFile->locktype!=pLock->locktype && 
22481           (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
22482   ){
22483     rc = SQLITE_BUSY;
22484     goto end_lock;
22485   }
22486
22487   /* If a SHARED lock is requested, and some thread using this PID already
22488   ** has a SHARED or RESERVED lock, then increment reference counts and
22489   ** return SQLITE_OK.
22490   */
22491   if( locktype==SHARED_LOCK && 
22492       (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
22493     assert( locktype==SHARED_LOCK );
22494     assert( pFile->locktype==0 );
22495     assert( pLock->cnt>0 );
22496     pFile->locktype = SHARED_LOCK;
22497     pLock->cnt++;
22498     pFile->pOpen->nLock++;
22499     goto end_lock;
22500   }
22501
22502   lock.l_len = 1L;
22503
22504   lock.l_whence = SEEK_SET;
22505
22506   /* A PENDING lock is needed before acquiring a SHARED lock and before
22507   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
22508   ** be released.
22509   */
22510   if( locktype==SHARED_LOCK 
22511       || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
22512   ){
22513     lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
22514     lock.l_start = PENDING_BYTE;
22515     s = fcntl(pFile->h, F_SETLK, &lock);
22516     if( s==(-1) ){
22517       rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
22518       goto end_lock;
22519     }
22520   }
22521
22522
22523   /* If control gets to this point, then actually go ahead and make
22524   ** operating system calls for the specified lock.
22525   */
22526   if( locktype==SHARED_LOCK ){
22527     assert( pLock->cnt==0 );
22528     assert( pLock->locktype==0 );
22529
22530     /* Now get the read-lock */
22531     lock.l_start = SHARED_FIRST;
22532     lock.l_len = SHARED_SIZE;
22533     s = fcntl(pFile->h, F_SETLK, &lock);
22534
22535     /* Drop the temporary PENDING lock */
22536     lock.l_start = PENDING_BYTE;
22537     lock.l_len = 1L;
22538     lock.l_type = F_UNLCK;
22539     if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
22540       rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
22541       goto end_lock;
22542     }
22543     if( s==(-1) ){
22544       rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
22545     }else{
22546       pFile->locktype = SHARED_LOCK;
22547       pFile->pOpen->nLock++;
22548       pLock->cnt = 1;
22549     }
22550   }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
22551     /* We are trying for an exclusive lock but another thread in this
22552     ** same process is still holding a shared lock. */
22553     rc = SQLITE_BUSY;
22554   }else{
22555     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
22556     ** assumed that there is a SHARED or greater lock on the file
22557     ** already.
22558     */
22559     assert( 0!=pFile->locktype );
22560     lock.l_type = F_WRLCK;
22561     switch( locktype ){
22562       case RESERVED_LOCK:
22563         lock.l_start = RESERVED_BYTE;
22564         break;
22565       case EXCLUSIVE_LOCK:
22566         lock.l_start = SHARED_FIRST;
22567         lock.l_len = SHARED_SIZE;
22568         break;
22569       default:
22570         assert(0);
22571     }
22572     s = fcntl(pFile->h, F_SETLK, &lock);
22573     if( s==(-1) ){
22574       rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
22575     }
22576   }
22577   
22578   if( rc==SQLITE_OK ){
22579     pFile->locktype = locktype;
22580     pLock->locktype = locktype;
22581   }else if( locktype==EXCLUSIVE_LOCK ){
22582     pFile->locktype = PENDING_LOCK;
22583     pLock->locktype = PENDING_LOCK;
22584   }
22585
22586 end_lock:
22587   leaveMutex();
22588   OSTRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
22589       rc==SQLITE_OK ? "ok" : "failed");
22590   return rc;
22591 }
22592
22593 /*
22594 ** Lower the locking level on file descriptor pFile to locktype.  locktype
22595 ** must be either NO_LOCK or SHARED_LOCK.
22596 **
22597 ** If the locking level of the file descriptor is already at or below
22598 ** the requested locking level, this routine is a no-op.
22599 */
22600 static int unixUnlock(sqlite3_file *id, int locktype){
22601   struct lockInfo *pLock;
22602   struct flock lock;
22603   int rc = SQLITE_OK;
22604   unixFile *pFile = (unixFile*)id;
22605   int h;
22606
22607   assert( pFile );
22608   OSTRACE7("UNLOCK  %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
22609       pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
22610
22611   assert( locktype<=SHARED_LOCK );
22612   if( pFile->locktype<=locktype ){
22613     return SQLITE_OK;
22614   }
22615   if( CHECK_THREADID(pFile) ){
22616     return SQLITE_MISUSE;
22617   }
22618   enterMutex();
22619   h = pFile->h;
22620   pLock = pFile->pLock;
22621   assert( pLock->cnt!=0 );
22622   if( pFile->locktype>SHARED_LOCK ){
22623     assert( pLock->locktype==pFile->locktype );
22624     SimulateIOErrorBenign(1);
22625     SimulateIOError( h=(-1) )
22626     SimulateIOErrorBenign(0);
22627     if( locktype==SHARED_LOCK ){
22628       lock.l_type = F_RDLCK;
22629       lock.l_whence = SEEK_SET;
22630       lock.l_start = SHARED_FIRST;
22631       lock.l_len = SHARED_SIZE;
22632       if( fcntl(h, F_SETLK, &lock)==(-1) ){
22633         rc = SQLITE_IOERR_RDLOCK;
22634       }
22635     }
22636     lock.l_type = F_UNLCK;
22637     lock.l_whence = SEEK_SET;
22638     lock.l_start = PENDING_BYTE;
22639     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
22640     if( fcntl(h, F_SETLK, &lock)!=(-1) ){
22641       pLock->locktype = SHARED_LOCK;
22642     }else{
22643       rc = SQLITE_IOERR_UNLOCK;
22644     }
22645   }
22646   if( locktype==NO_LOCK ){
22647     struct openCnt *pOpen;
22648
22649     /* Decrement the shared lock counter.  Release the lock using an
22650     ** OS call only when all threads in this same process have released
22651     ** the lock.
22652     */
22653     pLock->cnt--;
22654     if( pLock->cnt==0 ){
22655       lock.l_type = F_UNLCK;
22656       lock.l_whence = SEEK_SET;
22657       lock.l_start = lock.l_len = 0L;
22658       SimulateIOErrorBenign(1);
22659       SimulateIOError( h=(-1) )
22660       SimulateIOErrorBenign(0);
22661       if( fcntl(h, F_SETLK, &lock)!=(-1) ){
22662         pLock->locktype = NO_LOCK;
22663       }else{
22664         rc = SQLITE_IOERR_UNLOCK;
22665         pLock->cnt = 1;
22666       }
22667     }
22668
22669     /* Decrement the count of locks against this same file.  When the
22670     ** count reaches zero, close any other file descriptors whose close
22671     ** was deferred because of outstanding locks.
22672     */
22673     if( rc==SQLITE_OK ){
22674       pOpen = pFile->pOpen;
22675       pOpen->nLock--;
22676       assert( pOpen->nLock>=0 );
22677       if( pOpen->nLock==0 && pOpen->nPending>0 ){
22678         int i;
22679         for(i=0; i<pOpen->nPending; i++){
22680           close(pOpen->aPending[i]);
22681         }
22682         sqlite3_free(pOpen->aPending);
22683         pOpen->nPending = 0;
22684         pOpen->aPending = 0;
22685       }
22686     }
22687   }
22688   leaveMutex();
22689   if( rc==SQLITE_OK ) pFile->locktype = locktype;
22690   return rc;
22691 }
22692
22693 /*
22694 ** This function performs the parts of the "close file" operation 
22695 ** common to all locking schemes. It closes the directory and file
22696 ** handles, if they are valid, and sets all fields of the unixFile
22697 ** structure to 0.
22698 */
22699 static int closeUnixFile(sqlite3_file *id){
22700   unixFile *pFile = (unixFile*)id;
22701   if( pFile ){
22702     if( pFile->dirfd>=0 ){
22703       close(pFile->dirfd);
22704     }
22705     if( pFile->h>=0 ){
22706       close(pFile->h);
22707     }
22708     OSTRACE2("CLOSE   %-3d\n", pFile->h);
22709     OpenCounter(-1);
22710     memset(pFile, 0, sizeof(unixFile));
22711   }
22712   return SQLITE_OK;
22713 }
22714
22715 /*
22716 ** Close a file.
22717 */
22718 static int unixClose(sqlite3_file *id){
22719   if( id ){
22720     unixFile *pFile = (unixFile *)id;
22721     unixUnlock(id, NO_LOCK);
22722     enterMutex();
22723     if( pFile->pOpen && pFile->pOpen->nLock ){
22724       /* If there are outstanding locks, do not actually close the file just
22725       ** yet because that would clear those locks.  Instead, add the file
22726       ** descriptor to pOpen->aPending.  It will be automatically closed when
22727       ** the last lock is cleared.
22728       */
22729       int *aNew;
22730       struct openCnt *pOpen = pFile->pOpen;
22731       aNew = sqlite3_realloc(pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
22732       if( aNew==0 ){
22733         /* If a malloc fails, just leak the file descriptor */
22734       }else{
22735         pOpen->aPending = aNew;
22736         pOpen->aPending[pOpen->nPending] = pFile->h;
22737         pOpen->nPending++;
22738         pFile->h = -1;
22739       }
22740     }
22741     releaseLockInfo(pFile->pLock);
22742     releaseOpenCnt(pFile->pOpen);
22743     closeUnixFile(id);
22744     leaveMutex();
22745   }
22746   return SQLITE_OK;
22747 }
22748
22749
22750 #ifdef SQLITE_ENABLE_LOCKING_STYLE
22751 #pragma mark AFP Support
22752
22753 /*
22754  ** The afpLockingContext structure contains all afp lock specific state
22755  */
22756 typedef struct afpLockingContext afpLockingContext;
22757 struct afpLockingContext {
22758   unsigned long long sharedLockByte;
22759   const char *filePath;
22760 };
22761
22762 struct ByteRangeLockPB2
22763 {
22764   unsigned long long offset;        /* offset to first byte to lock */
22765   unsigned long long length;        /* nbr of bytes to lock */
22766   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
22767   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
22768   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
22769   int fd;                           /* file desc to assoc this lock with */
22770 };
22771
22772 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
22773
22774 /* 
22775 ** Return 0 on success, 1 on failure.  To match the behavior of the 
22776 ** normal posix file locking (used in unixLock for example), we should 
22777 ** provide 'richer' return codes - specifically to differentiate between
22778 ** 'file busy' and 'file system error' results.
22779 */
22780 static int _AFPFSSetLock(
22781   const char *path, 
22782   int fd, 
22783   unsigned long long offset, 
22784   unsigned long long length, 
22785   int setLockFlag
22786 ){
22787   struct ByteRangeLockPB2       pb;
22788   int                     err;
22789   
22790   pb.unLockFlag = setLockFlag ? 0 : 1;
22791   pb.startEndFlag = 0;
22792   pb.offset = offset;
22793   pb.length = length; 
22794   pb.fd = fd;
22795   OSTRACE5("AFPLOCK setting lock %s for %d in range %llx:%llx\n", 
22796     (setLockFlag?"ON":"OFF"), fd, offset, length);
22797   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
22798   if ( err==-1 ) {
22799     OSTRACE4("AFPLOCK failed to fsctl() '%s' %d %s\n", path, errno, 
22800       strerror(errno));
22801     return 1; /* error */
22802   } else {
22803     return 0;
22804   }
22805 }
22806
22807 /*
22808  ** This routine checks if there is a RESERVED lock held on the specified
22809  ** file by this or any other process. If such a lock is held, return
22810  ** non-zero.  If the file is unlocked or holds only SHARED locks, then
22811  ** return zero.
22812  */
22813 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
22814   int r = 0;
22815   unixFile *pFile = (unixFile*)id;
22816   
22817   assert( pFile ); 
22818   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
22819   
22820   /* Check if a thread in this process holds such a lock */
22821   if( pFile->locktype>SHARED_LOCK ){
22822     r = 1;
22823   }
22824   
22825   /* Otherwise see if some other process holds it.
22826    */
22827   if ( !r ) {
22828     /* lock the byte */
22829     int failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);  
22830     if (failed) {
22831       /* if we failed to get the lock then someone else must have it */
22832       r = 1;
22833     } else {
22834       /* if we succeeded in taking the reserved lock, unlock it to restore
22835       ** the original state */
22836       _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0);
22837     }
22838   }
22839   OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
22840   
22841   *pResOut = r;
22842   return SQLITE_OK;
22843 }
22844
22845 /* AFP-style locking following the behavior of unixLock, see the unixLock 
22846 ** function comments for details of lock management. */
22847 static int afpLock(sqlite3_file *id, int locktype){
22848   int rc = SQLITE_OK;
22849   unixFile *pFile = (unixFile*)id;
22850   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
22851   
22852   assert( pFile );
22853   OSTRACE5("LOCK    %d %s was %s pid=%d\n", pFile->h,
22854          locktypeName(locktype), locktypeName(pFile->locktype), getpid());
22855
22856   /* If there is already a lock of this type or more restrictive on the
22857   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
22858   ** enterMutex() hasn't been called yet.
22859   */
22860   if( pFile->locktype>=locktype ){
22861     OSTRACE3("LOCK    %d %s ok (already held)\n", pFile->h,
22862            locktypeName(locktype));
22863     return SQLITE_OK;
22864   }
22865
22866   /* Make sure the locking sequence is correct
22867   */
22868   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
22869   assert( locktype!=PENDING_LOCK );
22870   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
22871   
22872   /* This mutex is needed because pFile->pLock is shared across threads
22873   */
22874   enterMutex();
22875
22876   /* Make sure the current thread owns the pFile.
22877   */
22878   rc = transferOwnership(pFile);
22879   if( rc!=SQLITE_OK ){
22880     leaveMutex();
22881     return rc;
22882   }
22883     
22884   /* A PENDING lock is needed before acquiring a SHARED lock and before
22885   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
22886   ** be released.
22887   */
22888   if( locktype==SHARED_LOCK 
22889       || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
22890   ){
22891     int failed;
22892     failed = _AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 1);
22893     if (failed) {
22894       rc = SQLITE_BUSY;
22895       goto afp_end_lock;
22896     }
22897   }
22898   
22899   /* If control gets to this point, then actually go ahead and make
22900   ** operating system calls for the specified lock.
22901   */
22902   if( locktype==SHARED_LOCK ){
22903     int lk, failed;
22904     
22905     /* Now get the read-lock */
22906     /* note that the quality of the randomness doesn't matter that much */
22907     lk = random(); 
22908     context->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
22909     failed = _AFPFSSetLock(context->filePath, pFile->h, 
22910       SHARED_FIRST+context->sharedLockByte, 1, 1);
22911     
22912     /* Drop the temporary PENDING lock */
22913     if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)) {
22914       rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
22915       goto afp_end_lock;
22916     }
22917     
22918     if( failed ){
22919       rc = SQLITE_BUSY;
22920     } else {
22921       pFile->locktype = SHARED_LOCK;
22922     }
22923   }else{
22924     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
22925     ** assumed that there is a SHARED or greater lock on the file
22926     ** already.
22927     */
22928     int failed = 0;
22929     assert( 0!=pFile->locktype );
22930     if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
22931         /* Acquire a RESERVED lock */
22932         failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
22933     }
22934     if (!failed && locktype == EXCLUSIVE_LOCK) {
22935       /* Acquire an EXCLUSIVE lock */
22936         
22937       /* Remove the shared lock before trying the range.  we'll need to 
22938       ** reestablish the shared lock if we can't get the  afpUnlock
22939       */
22940       if (!_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
22941                          context->sharedLockByte, 1, 0)) {
22942         /* now attemmpt to get the exclusive lock range */
22943         failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST, 
22944                                SHARED_SIZE, 1);
22945         if (failed && _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
22946                                     context->sharedLockByte, 1, 1)) {
22947           rc = SQLITE_IOERR_RDLOCK; /* this should never happen */
22948         }
22949       } else {
22950         /* */
22951         rc = SQLITE_IOERR_UNLOCK; /* this should never happen */
22952       }
22953     }
22954     if( failed && rc == SQLITE_OK){
22955       rc = SQLITE_BUSY;
22956     }
22957   }
22958   
22959   if( rc==SQLITE_OK ){
22960     pFile->locktype = locktype;
22961   }else if( locktype==EXCLUSIVE_LOCK ){
22962     pFile->locktype = PENDING_LOCK;
22963   }
22964   
22965 afp_end_lock:
22966   leaveMutex();
22967   OSTRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
22968          rc==SQLITE_OK ? "ok" : "failed");
22969   return rc;
22970 }
22971
22972 /*
22973 ** Lower the locking level on file descriptor pFile to locktype.  locktype
22974 ** must be either NO_LOCK or SHARED_LOCK.
22975 **
22976 ** If the locking level of the file descriptor is already at or below
22977 ** the requested locking level, this routine is a no-op.
22978 */
22979 static int afpUnlock(sqlite3_file *id, int locktype) {
22980   int rc = SQLITE_OK;
22981   unixFile *pFile = (unixFile*)id;
22982   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
22983
22984   assert( pFile );
22985   OSTRACE5("UNLOCK  %d %d was %d pid=%d\n", pFile->h, locktype,
22986          pFile->locktype, getpid());
22987   
22988   assert( locktype<=SHARED_LOCK );
22989   if( pFile->locktype<=locktype ){
22990     return SQLITE_OK;
22991   }
22992   if( CHECK_THREADID(pFile) ){
22993     return SQLITE_MISUSE;
22994   }
22995   enterMutex();
22996   if( pFile->locktype>SHARED_LOCK ){
22997     if( locktype==SHARED_LOCK ){
22998       int failed = 0;
22999
23000       /* unlock the exclusive range - then re-establish the shared lock */
23001       if (pFile->locktype==EXCLUSIVE_LOCK) {
23002         failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST, 
23003                                  SHARED_SIZE, 0);
23004         if (!failed) {
23005           /* successfully removed the exclusive lock */
23006           if (_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST+
23007                             context->sharedLockByte, 1, 1)) {
23008             /* failed to re-establish our shared lock */
23009             rc = SQLITE_IOERR_RDLOCK; /* This should never happen */
23010           }
23011         } else {
23012           /* This should never happen - failed to unlock the exclusive range */
23013           rc = SQLITE_IOERR_UNLOCK;
23014         } 
23015       }
23016     }
23017     if (rc == SQLITE_OK && pFile->locktype>=PENDING_LOCK) {
23018       if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)){
23019         /* failed to release the pending lock */
23020         rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
23021       }
23022     } 
23023     if (rc == SQLITE_OK && pFile->locktype>=RESERVED_LOCK) {
23024       if (_AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0)) {
23025         /* failed to release the reserved lock */
23026         rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
23027       }
23028     } 
23029   }
23030   if( locktype==NO_LOCK ){
23031     int failed = _AFPFSSetLock(context->filePath, pFile->h, 
23032                                SHARED_FIRST + context->sharedLockByte, 1, 0);
23033     if (failed) {
23034       rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
23035     }
23036   }
23037   if (rc == SQLITE_OK)
23038     pFile->locktype = locktype;
23039   leaveMutex();
23040   return rc;
23041 }
23042
23043 /*
23044 ** Close a file & cleanup AFP specific locking context 
23045 */
23046 static int afpClose(sqlite3_file *id) {
23047   if( id ){
23048     unixFile *pFile = (unixFile*)id;
23049     afpUnlock(id, NO_LOCK);
23050     sqlite3_free(pFile->lockingContext);
23051   }
23052   return closeUnixFile(id);
23053 }
23054
23055
23056 #pragma mark flock() style locking
23057
23058 /*
23059 ** The flockLockingContext is not used
23060 */
23061 typedef void flockLockingContext;
23062
23063 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
23064   int r = 1;
23065   unixFile *pFile = (unixFile*)id;
23066   
23067   if (pFile->locktype != RESERVED_LOCK) {
23068     /* attempt to get the lock */
23069     int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
23070     if (!rc) {
23071       /* got the lock, unlock it */
23072       flock(pFile->h, LOCK_UN);
23073       r = 0;  /* no one has it reserved */
23074     }
23075   }
23076
23077   *pResOut = r;
23078   return SQLITE_OK;
23079 }
23080
23081 static int flockLock(sqlite3_file *id, int locktype) {
23082   unixFile *pFile = (unixFile*)id;
23083   
23084   /* if we already have a lock, it is exclusive.  
23085   ** Just adjust level and punt on outta here. */
23086   if (pFile->locktype > NO_LOCK) {
23087     pFile->locktype = locktype;
23088     return SQLITE_OK;
23089   }
23090   
23091   /* grab an exclusive lock */
23092   int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
23093   if (rc) {
23094     /* didn't get, must be busy */
23095     return SQLITE_BUSY;
23096   } else {
23097     /* got it, set the type and return ok */
23098     pFile->locktype = locktype;
23099     return SQLITE_OK;
23100   }
23101 }
23102
23103 static int flockUnlock(sqlite3_file *id, int locktype) {
23104   unixFile *pFile = (unixFile*)id;
23105   
23106   assert( locktype<=SHARED_LOCK );
23107   
23108   /* no-op if possible */
23109   if( pFile->locktype==locktype ){
23110     return SQLITE_OK;
23111   }
23112   
23113   /* shared can just be set because we always have an exclusive */
23114   if (locktype==SHARED_LOCK) {
23115     pFile->locktype = locktype;
23116     return SQLITE_OK;
23117   }
23118   
23119   /* no, really, unlock. */
23120   int rc = flock(pFile->h, LOCK_UN);
23121   if (rc)
23122     return SQLITE_IOERR_UNLOCK;
23123   else {
23124     pFile->locktype = NO_LOCK;
23125     return SQLITE_OK;
23126   }
23127 }
23128
23129 /*
23130 ** Close a file.
23131 */
23132 static int flockClose(sqlite3_file *id) {
23133   if( id ){
23134     flockUnlock(id, NO_LOCK);
23135   }
23136   return closeUnixFile(id);
23137 }
23138
23139 #pragma mark Old-School .lock file based locking
23140
23141 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
23142   int r = 1;
23143   unixFile *pFile = (unixFile*)id;
23144   char *zLockFile = (char *)pFile->lockingContext;
23145
23146   if (pFile->locktype != RESERVED_LOCK) {
23147     struct stat statBuf;
23148     if (lstat(zLockFile, &statBuf) != 0){
23149       /* file does not exist, we could have it if we want it */
23150       r = 0;
23151     }
23152   }
23153
23154   *pResOut = r;
23155   return SQLITE_OK;
23156 }
23157
23158 static int dotlockLock(sqlite3_file *id, int locktype) {
23159   unixFile *pFile = (unixFile*)id;
23160   int fd;
23161   char *zLockFile = (char *)pFile->lockingContext;
23162
23163   /* if we already have a lock, it is exclusive.  
23164   ** Just adjust level and punt on outta here. */
23165   if (pFile->locktype > NO_LOCK) {
23166     pFile->locktype = locktype;
23167     
23168     /* Always update the timestamp on the old file */
23169     utimes(zLockFile, NULL);
23170     return SQLITE_OK;
23171   }
23172   
23173   /* check to see if lock file already exists */
23174   struct stat statBuf;
23175   if (lstat(zLockFile,&statBuf) == 0){
23176     return SQLITE_BUSY; /* it does, busy */
23177   }
23178   
23179   /* grab an exclusive lock */
23180   fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
23181   if( fd<0 ){
23182     /* failed to open/create the file, someone else may have stolen the lock */
23183     return SQLITE_BUSY; 
23184   }
23185   close(fd);
23186   
23187   /* got it, set the type and return ok */
23188   pFile->locktype = locktype;
23189   return SQLITE_OK;
23190 }
23191
23192 static int dotlockUnlock(sqlite3_file *id, int locktype) {
23193   unixFile *pFile = (unixFile*)id;
23194   char *zLockFile = (char *)pFile->lockingContext;
23195
23196   assert( locktype<=SHARED_LOCK );
23197   
23198   /* no-op if possible */
23199   if( pFile->locktype==locktype ){
23200     return SQLITE_OK;
23201   }
23202   
23203   /* shared can just be set because we always have an exclusive */
23204   if (locktype==SHARED_LOCK) {
23205     pFile->locktype = locktype;
23206     return SQLITE_OK;
23207   }
23208   
23209   /* no, really, unlock. */
23210   unlink(zLockFile);
23211   pFile->locktype = NO_LOCK;
23212   return SQLITE_OK;
23213 }
23214
23215 /*
23216  ** Close a file.
23217  */
23218 static int dotlockClose(sqlite3_file *id) {
23219   if( id ){
23220     unixFile *pFile = (unixFile*)id;
23221     dotlockUnlock(id, NO_LOCK);
23222     sqlite3_free(pFile->lockingContext);
23223   }
23224   return closeUnixFile(id);
23225 }
23226
23227
23228 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
23229
23230 /*
23231 ** The nolockLockingContext is void
23232 */
23233 typedef void nolockLockingContext;
23234
23235 static int nolockCheckReservedLock(sqlite3_file *id, int *pResOut) {
23236   *pResOut = 0;
23237   return SQLITE_OK;
23238 }
23239
23240 static int nolockLock(sqlite3_file *id, int locktype) {
23241   return SQLITE_OK;
23242 }
23243
23244 static int nolockUnlock(sqlite3_file *id, int locktype) {
23245   return SQLITE_OK;
23246 }
23247
23248 /*
23249 ** Close a file.
23250 */
23251 static int nolockClose(sqlite3_file *id) {
23252   return closeUnixFile(id);
23253 }
23254
23255
23256 /*
23257 ** Information and control of an open file handle.
23258 */
23259 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
23260   switch( op ){
23261     case SQLITE_FCNTL_LOCKSTATE: {
23262       *(int*)pArg = ((unixFile*)id)->locktype;
23263       return SQLITE_OK;
23264     }
23265   }
23266   return SQLITE_ERROR;
23267 }
23268
23269 /*
23270 ** Return the sector size in bytes of the underlying block device for
23271 ** the specified file. This is almost always 512 bytes, but may be
23272 ** larger for some devices.
23273 **
23274 ** SQLite code assumes this function cannot fail. It also assumes that
23275 ** if two files are created in the same file-system directory (i.e.
23276 ** a database and its journal file) that the sector size will be the
23277 ** same for both.
23278 */
23279 static int unixSectorSize(sqlite3_file *id){
23280   return SQLITE_DEFAULT_SECTOR_SIZE;
23281 }
23282
23283 /*
23284 ** Return the device characteristics for the file. This is always 0.
23285 */
23286 static int unixDeviceCharacteristics(sqlite3_file *id){
23287   return 0;
23288 }
23289
23290 /*
23291 ** Initialize the contents of the unixFile structure pointed to by pId.
23292 **
23293 ** When locking extensions are enabled, the filepath and locking style 
23294 ** are needed to determine the unixFile pMethod to use for locking operations.
23295 ** The locking-style specific lockingContext data structure is created 
23296 ** and assigned here also.
23297 */
23298 static int fillInUnixFile(
23299   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
23300   int h,                  /* Open file descriptor of file being opened */
23301   int dirfd,              /* Directory file descriptor */
23302   sqlite3_file *pId,      /* Write to the unixFile structure here */
23303   const char *zFilename,  /* Name of the file being opened */
23304   int noLock              /* Omit locking if true */
23305 ){
23306   int eLockingStyle;
23307   unixFile *pNew = (unixFile *)pId;
23308   int rc = SQLITE_OK;
23309
23310   /* Macro to define the static contents of an sqlite3_io_methods 
23311   ** structure for a unix backend file. Different locking methods
23312   ** require different functions for the xClose, xLock, xUnlock and
23313   ** xCheckReservedLock methods.
23314   */
23315   #define IOMETHODS(xClose, xLock, xUnlock, xCheckReservedLock) {    \
23316     1,                          /* iVersion */                           \
23317     xClose,                     /* xClose */                             \
23318     unixRead,                   /* xRead */                              \
23319     unixWrite,                  /* xWrite */                             \
23320     unixTruncate,               /* xTruncate */                          \
23321     unixSync,                   /* xSync */                              \
23322     unixFileSize,               /* xFileSize */                          \
23323     xLock,                      /* xLock */                              \
23324     xUnlock,                    /* xUnlock */                            \
23325     xCheckReservedLock,         /* xCheckReservedLock */                 \
23326     unixFileControl,            /* xFileControl */                       \
23327     unixSectorSize,             /* xSectorSize */                        \
23328     unixDeviceCharacteristics   /* xDeviceCapabilities */                \
23329   }
23330   static sqlite3_io_methods aIoMethod[] = {
23331     IOMETHODS(unixClose, unixLock, unixUnlock, unixCheckReservedLock) 
23332    ,IOMETHODS(nolockClose, nolockLock, nolockUnlock, nolockCheckReservedLock)
23333 #ifdef SQLITE_ENABLE_LOCKING_STYLE
23334    ,IOMETHODS(dotlockClose, dotlockLock, dotlockUnlock,dotlockCheckReservedLock)
23335    ,IOMETHODS(flockClose, flockLock, flockUnlock, flockCheckReservedLock)
23336    ,IOMETHODS(afpClose, afpLock, afpUnlock, afpCheckReservedLock)
23337 #endif
23338   };
23339   /* The order of the IOMETHODS macros above is important.  It must be the
23340   ** same order as the LOCKING_STYLE numbers
23341   */
23342   assert(LOCKING_STYLE_POSIX==1);
23343   assert(LOCKING_STYLE_NONE==2);
23344   assert(LOCKING_STYLE_DOTFILE==3);
23345   assert(LOCKING_STYLE_FLOCK==4);
23346   assert(LOCKING_STYLE_AFP==5);
23347
23348   assert( pNew->pLock==NULL );
23349   assert( pNew->pOpen==NULL );
23350
23351   OSTRACE3("OPEN    %-3d %s\n", h, zFilename);    
23352   pNew->h = h;
23353   pNew->dirfd = dirfd;
23354   SET_THREADID(pNew);
23355
23356   if( noLock ){
23357     eLockingStyle = LOCKING_STYLE_NONE;
23358   }else{
23359     eLockingStyle = detectLockingStyle(pVfs, zFilename, h);
23360   }
23361
23362   switch( eLockingStyle ){
23363
23364     case LOCKING_STYLE_POSIX: {
23365       enterMutex();
23366       rc = findLockInfo(h, &pNew->pLock, &pNew->pOpen);
23367       leaveMutex();
23368       break;
23369     }
23370
23371 #ifdef SQLITE_ENABLE_LOCKING_STYLE
23372     case LOCKING_STYLE_AFP: {
23373       /* AFP locking uses the file path so it needs to be included in
23374       ** the afpLockingContext.
23375       */
23376       afpLockingContext *pCtx;
23377       pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
23378       if( pCtx==0 ){
23379         rc = SQLITE_NOMEM;
23380       }else{
23381         /* NB: zFilename exists and remains valid until the file is closed
23382         ** according to requirement F11141.  So we do not need to make a
23383         ** copy of the filename. */
23384         pCtx->filePath = zFilename;
23385         srandomdev();
23386       }
23387       break;
23388     }
23389
23390     case LOCKING_STYLE_DOTFILE: {
23391       /* Dotfile locking uses the file path so it needs to be included in
23392       ** the dotlockLockingContext 
23393       */
23394       char *zLockFile;
23395       int nFilename;
23396       nFilename = strlen(zFilename) + 6;
23397       zLockFile = (char *)sqlite3_malloc(nFilename);
23398       if( zLockFile==0 ){
23399         rc = SQLITE_NOMEM;
23400       }else{
23401         sqlite3_snprintf(nFilename, zLockFile, "%s.lock", zFilename);
23402       }
23403       pNew->lockingContext = zLockFile;
23404       break;
23405     }
23406
23407     case LOCKING_STYLE_FLOCK: 
23408     case LOCKING_STYLE_NONE: 
23409       break;
23410 #endif
23411   }
23412
23413   if( rc!=SQLITE_OK ){
23414     if( dirfd>=0 ) close(dirfd);
23415     close(h);
23416   }else{
23417     pNew->pMethod = &aIoMethod[eLockingStyle-1];
23418     OpenCounter(+1);
23419   }
23420   return rc;
23421 }
23422
23423 /*
23424 ** Open a file descriptor to the directory containing file zFilename.
23425 ** If successful, *pFd is set to the opened file descriptor and
23426 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
23427 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
23428 ** value.
23429 **
23430 ** If SQLITE_OK is returned, the caller is responsible for closing
23431 ** the file descriptor *pFd using close().
23432 */
23433 static int openDirectory(const char *zFilename, int *pFd){
23434   int ii;
23435   int fd = -1;
23436   char zDirname[MAX_PATHNAME+1];
23437
23438   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
23439   for(ii=strlen(zDirname); ii>=0 && zDirname[ii]!='/'; ii--);
23440   if( ii>0 ){
23441     zDirname[ii] = '\0';
23442     fd = open(zDirname, O_RDONLY|O_BINARY, 0);
23443     if( fd>=0 ){
23444 #ifdef FD_CLOEXEC
23445       fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
23446 #endif
23447       OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
23448     }
23449   }
23450   *pFd = fd;
23451   return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
23452 }
23453
23454 /*
23455 ** Create a temporary file name in zBuf.  zBuf must be allocated
23456 ** by the calling process and must be big enough to hold at least
23457 ** pVfs->mxPathname bytes.
23458 */
23459 static int getTempname(int nBuf, char *zBuf){
23460   static const char *azDirs[] = {
23461      0,
23462      "/var/tmp",
23463      "/usr/tmp",
23464      "/tmp",
23465      ".",
23466   };
23467   static const unsigned char zChars[] =
23468     "abcdefghijklmnopqrstuvwxyz"
23469     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
23470     "0123456789";
23471   int i, j;
23472   struct stat buf;
23473   const char *zDir = ".";
23474
23475   /* It's odd to simulate an io-error here, but really this is just
23476   ** using the io-error infrastructure to test that SQLite handles this
23477   ** function failing. 
23478   */
23479   SimulateIOError( return SQLITE_IOERR );
23480
23481   azDirs[0] = sqlite3_temp_directory;
23482   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
23483     if( azDirs[i]==0 ) continue;
23484     if( stat(azDirs[i], &buf) ) continue;
23485     if( !S_ISDIR(buf.st_mode) ) continue;
23486     if( access(azDirs[i], 07) ) continue;
23487     zDir = azDirs[i];
23488     break;
23489   }
23490
23491   /* Check that the output buffer is large enough for the temporary file 
23492   ** name. If it is not, return SQLITE_ERROR.
23493   */
23494   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= nBuf ){
23495     return SQLITE_ERROR;
23496   }
23497
23498   do{
23499     sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
23500     j = strlen(zBuf);
23501     sqlite3_randomness(15, &zBuf[j]);
23502     for(i=0; i<15; i++, j++){
23503       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
23504     }
23505     zBuf[j] = 0;
23506   }while( access(zBuf,0)==0 );
23507   return SQLITE_OK;
23508 }
23509
23510
23511 /*
23512 ** Open the file zPath.
23513 ** 
23514 ** Previously, the SQLite OS layer used three functions in place of this
23515 ** one:
23516 **
23517 **     sqlite3OsOpenReadWrite();
23518 **     sqlite3OsOpenReadOnly();
23519 **     sqlite3OsOpenExclusive();
23520 **
23521 ** These calls correspond to the following combinations of flags:
23522 **
23523 **     ReadWrite() ->     (READWRITE | CREATE)
23524 **     ReadOnly()  ->     (READONLY) 
23525 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
23526 **
23527 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
23528 ** true, the file was configured to be automatically deleted when the
23529 ** file handle closed. To achieve the same effect using this new 
23530 ** interface, add the DELETEONCLOSE flag to those specified above for 
23531 ** OpenExclusive().
23532 */
23533 static int unixOpen(
23534   sqlite3_vfs *pVfs, 
23535   const char *zPath, 
23536   sqlite3_file *pFile,
23537   int flags,
23538   int *pOutFlags
23539 ){
23540   int fd = 0;                    /* File descriptor returned by open() */
23541   int dirfd = -1;                /* Directory file descriptor */
23542   int oflags = 0;                /* Flags to pass to open() */
23543   int eType = flags&0xFFFFFF00;  /* Type of file to open */
23544   int noLock;                    /* True to omit locking primitives */
23545
23546   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
23547   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
23548   int isCreate     = (flags & SQLITE_OPEN_CREATE);
23549   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
23550   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
23551
23552   /* If creating a master or main-file journal, this function will open
23553   ** a file-descriptor on the directory too. The first time unixSync()
23554   ** is called the directory file descriptor will be fsync()ed and close()d.
23555   */
23556   int isOpenDirectory = (isCreate && 
23557       (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
23558   );
23559
23560   /* If argument zPath is a NULL pointer, this function is required to open
23561   ** a temporary file. Use this buffer to store the file name in.
23562   */
23563   char zTmpname[MAX_PATHNAME+1];
23564   const char *zName = zPath;
23565
23566   /* Check the following statements are true: 
23567   **
23568   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
23569   **   (b) if CREATE is set, then READWRITE must also be set, and
23570   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
23571   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
23572   */
23573   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
23574   assert(isCreate==0 || isReadWrite);
23575   assert(isExclusive==0 || isCreate);
23576   assert(isDelete==0 || isCreate);
23577
23578   /* The main DB, main journal, and master journal are never automatically
23579   ** deleted
23580   */
23581   assert( eType!=SQLITE_OPEN_MAIN_DB || !isDelete );
23582   assert( eType!=SQLITE_OPEN_MAIN_JOURNAL || !isDelete );
23583   assert( eType!=SQLITE_OPEN_MASTER_JOURNAL || !isDelete );
23584
23585   /* Assert that the upper layer has set one of the "file-type" flags. */
23586   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
23587        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
23588        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
23589        || eType==SQLITE_OPEN_TRANSIENT_DB
23590   );
23591
23592   memset(pFile, 0, sizeof(unixFile));
23593
23594   if( !zName ){
23595     int rc;
23596     assert(isDelete && !isOpenDirectory);
23597     rc = getTempname(MAX_PATHNAME+1, zTmpname);
23598     if( rc!=SQLITE_OK ){
23599       return rc;
23600     }
23601     zName = zTmpname;
23602   }
23603
23604   if( isReadonly )  oflags |= O_RDONLY;
23605   if( isReadWrite ) oflags |= O_RDWR;
23606   if( isCreate )    oflags |= O_CREAT;
23607   if( isExclusive ) oflags |= (O_EXCL|O_NOFOLLOW);
23608   oflags |= (O_LARGEFILE|O_BINARY);
23609
23610   fd = open(zName, oflags, isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
23611   if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
23612     /* Failed to open the file for read/write access. Try read-only. */
23613     flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
23614     flags |= SQLITE_OPEN_READONLY;
23615     return unixOpen(pVfs, zPath, pFile, flags, pOutFlags);
23616   }
23617   if( fd<0 ){
23618     return SQLITE_CANTOPEN;
23619   }
23620   if( isDelete ){
23621     unlink(zName);
23622   }
23623   if( pOutFlags ){
23624     *pOutFlags = flags;
23625   }
23626
23627   assert(fd!=0);
23628   if( isOpenDirectory ){
23629     int rc = openDirectory(zPath, &dirfd);
23630     if( rc!=SQLITE_OK ){
23631       close(fd);
23632       return rc;
23633     }
23634   }
23635
23636 #ifdef FD_CLOEXEC
23637   fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
23638 #endif
23639
23640   noLock = eType!=SQLITE_OPEN_MAIN_DB;
23641   return fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock);
23642 }
23643
23644 /*
23645 ** Delete the file at zPath. If the dirSync argument is true, fsync()
23646 ** the directory after deleting the file.
23647 */
23648 static int unixDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
23649   int rc = SQLITE_OK;
23650   SimulateIOError(return SQLITE_IOERR_DELETE);
23651   unlink(zPath);
23652   if( dirSync ){
23653     int fd;
23654     rc = openDirectory(zPath, &fd);
23655     if( rc==SQLITE_OK ){
23656       if( fsync(fd) ){
23657         rc = SQLITE_IOERR_DIR_FSYNC;
23658       }
23659       close(fd);
23660     }
23661   }
23662   return rc;
23663 }
23664
23665 /*
23666 ** Test the existance of or access permissions of file zPath. The
23667 ** test performed depends on the value of flags:
23668 **
23669 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
23670 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
23671 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
23672 **
23673 ** Otherwise return 0.
23674 */
23675 static int unixAccess(
23676   sqlite3_vfs *pVfs, 
23677   const char *zPath, 
23678   int flags, 
23679   int *pResOut
23680 ){
23681   int amode = 0;
23682   SimulateIOError( return SQLITE_IOERR_ACCESS; );
23683   switch( flags ){
23684     case SQLITE_ACCESS_EXISTS:
23685       amode = F_OK;
23686       break;
23687     case SQLITE_ACCESS_READWRITE:
23688       amode = W_OK|R_OK;
23689       break;
23690     case SQLITE_ACCESS_READ:
23691       amode = R_OK;
23692       break;
23693
23694     default:
23695       assert(!"Invalid flags argument");
23696   }
23697   *pResOut = (access(zPath, amode)==0);
23698   return SQLITE_OK;
23699 }
23700
23701
23702 /*
23703 ** Turn a relative pathname into a full pathname. The relative path
23704 ** is stored as a nul-terminated string in the buffer pointed to by
23705 ** zPath. 
23706 **
23707 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
23708 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
23709 ** this buffer before returning.
23710 */
23711 static int unixFullPathname(
23712   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
23713   const char *zPath,            /* Possibly relative input path */
23714   int nOut,                     /* Size of output buffer in bytes */
23715   char *zOut                    /* Output buffer */
23716 ){
23717
23718   /* It's odd to simulate an io-error here, but really this is just
23719   ** using the io-error infrastructure to test that SQLite handles this
23720   ** function failing. This function could fail if, for example, the
23721   ** current working directly has been unlinked.
23722   */
23723   SimulateIOError( return SQLITE_ERROR );
23724
23725   assert( pVfs->mxPathname==MAX_PATHNAME );
23726   zOut[nOut-1] = '\0';
23727   if( zPath[0]=='/' ){
23728     sqlite3_snprintf(nOut, zOut, "%s", zPath);
23729   }else{
23730     int nCwd;
23731     if( getcwd(zOut, nOut-1)==0 ){
23732       return SQLITE_CANTOPEN;
23733     }
23734     nCwd = strlen(zOut);
23735     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
23736   }
23737   return SQLITE_OK;
23738
23739 #if 0
23740   /*
23741   ** Remove "/./" path elements and convert "/A/./" path elements
23742   ** to just "/".
23743   */
23744   if( zFull ){
23745     int i, j;
23746     for(i=j=0; zFull[i]; i++){
23747       if( zFull[i]=='/' ){
23748         if( zFull[i+1]=='/' ) continue;
23749         if( zFull[i+1]=='.' && zFull[i+2]=='/' ){
23750           i += 1;
23751           continue;
23752         }
23753         if( zFull[i+1]=='.' && zFull[i+2]=='.' && zFull[i+3]=='/' ){
23754           while( j>0 && zFull[j-1]!='/' ){ j--; }
23755           i += 3;
23756           continue;
23757         }
23758       }
23759       zFull[j++] = zFull[i];
23760     }
23761     zFull[j] = 0;
23762   }
23763 #endif
23764 }
23765
23766
23767 #ifndef SQLITE_OMIT_LOAD_EXTENSION
23768 /*
23769 ** Interfaces for opening a shared library, finding entry points
23770 ** within the shared library, and closing the shared library.
23771 */
23772 #include <dlfcn.h>
23773 static void *unixDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
23774   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
23775 }
23776
23777 /*
23778 ** SQLite calls this function immediately after a call to unixDlSym() or
23779 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
23780 ** message is available, it is written to zBufOut. If no error message
23781 ** is available, zBufOut is left unmodified and SQLite uses a default
23782 ** error message.
23783 */
23784 static void unixDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
23785   char *zErr;
23786   enterMutex();
23787   zErr = dlerror();
23788   if( zErr ){
23789     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
23790   }
23791   leaveMutex();
23792 }
23793 static void *unixDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
23794   return dlsym(pHandle, zSymbol);
23795 }
23796 static void unixDlClose(sqlite3_vfs *pVfs, void *pHandle){
23797   dlclose(pHandle);
23798 }
23799 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
23800   #define unixDlOpen  0
23801   #define unixDlError 0
23802   #define unixDlSym   0
23803   #define unixDlClose 0
23804 #endif
23805
23806 /*
23807 ** Write nBuf bytes of random data to the supplied buffer zBuf.
23808 */
23809 static int unixRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
23810
23811   assert(nBuf>=(sizeof(time_t)+sizeof(int)));
23812
23813   /* We have to initialize zBuf to prevent valgrind from reporting
23814   ** errors.  The reports issued by valgrind are incorrect - we would
23815   ** prefer that the randomness be increased by making use of the
23816   ** uninitialized space in zBuf - but valgrind errors tend to worry
23817   ** some users.  Rather than argue, it seems easier just to initialize
23818   ** the whole array and silence valgrind, even if that means less randomness
23819   ** in the random seed.
23820   **
23821   ** When testing, initializing zBuf[] to zero is all we do.  That means
23822   ** that we always use the same random number sequence.  This makes the
23823   ** tests repeatable.
23824   */
23825   memset(zBuf, 0, nBuf);
23826 #if !defined(SQLITE_TEST)
23827   {
23828     int pid, fd;
23829     fd = open("/dev/urandom", O_RDONLY);
23830     if( fd<0 ){
23831       time_t t;
23832       time(&t);
23833       memcpy(zBuf, &t, sizeof(t));
23834       pid = getpid();
23835       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
23836     }else{
23837       read(fd, zBuf, nBuf);
23838       close(fd);
23839     }
23840   }
23841 #endif
23842   return SQLITE_OK;
23843 }
23844
23845
23846 /*
23847 ** Sleep for a little while.  Return the amount of time slept.
23848 ** The argument is the number of microseconds we want to sleep.
23849 ** The return value is the number of microseconds of sleep actually
23850 ** requested from the underlying operating system, a number which
23851 ** might be greater than or equal to the argument, but not less
23852 ** than the argument.
23853 */
23854 static int unixSleep(sqlite3_vfs *pVfs, int microseconds){
23855 #if defined(HAVE_USLEEP) && HAVE_USLEEP
23856   usleep(microseconds);
23857   return microseconds;
23858 #else
23859   int seconds = (microseconds+999999)/1000000;
23860   sleep(seconds);
23861   return seconds*1000000;
23862 #endif
23863 }
23864
23865 /*
23866 ** The following variable, if set to a non-zero value, becomes the result
23867 ** returned from sqlite3OsCurrentTime().  This is used for testing.
23868 */
23869 #ifdef SQLITE_TEST
23870 SQLITE_API int sqlite3_current_time = 0;
23871 #endif
23872
23873 /*
23874 ** Find the current time (in Universal Coordinated Time).  Write the
23875 ** current time and date as a Julian Day number into *prNow and
23876 ** return 0.  Return 1 if the time and date cannot be found.
23877 */
23878 static int unixCurrentTime(sqlite3_vfs *pVfs, double *prNow){
23879 #ifdef NO_GETTOD
23880   time_t t;
23881   time(&t);
23882   *prNow = t/86400.0 + 2440587.5;
23883 #else
23884   struct timeval sNow;
23885   gettimeofday(&sNow, 0);
23886   *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
23887 #endif
23888 #ifdef SQLITE_TEST
23889   if( sqlite3_current_time ){
23890     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
23891   }
23892 #endif
23893   return 0;
23894 }
23895
23896 static int unixGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
23897   return 0;
23898 }
23899
23900 /*
23901 ** Initialize the operating system interface.
23902 */
23903 SQLITE_API int sqlite3_os_init(void){ 
23904   /* Macro to define the static contents of an sqlite3_vfs structure for
23905   ** the unix backend. The two parameters are the values to use for
23906   ** the sqlite3_vfs.zName and sqlite3_vfs.pAppData fields, respectively.
23907   ** 
23908   */
23909   #define UNIXVFS(zVfsName, pVfsAppData) {                  \
23910     1,                    /* iVersion */                    \
23911     sizeof(unixFile),     /* szOsFile */                    \
23912     MAX_PATHNAME,         /* mxPathname */                  \
23913     0,                    /* pNext */                       \
23914     zVfsName,             /* zName */                       \
23915     (void *)pVfsAppData,  /* pAppData */                    \
23916     unixOpen,             /* xOpen */                       \
23917     unixDelete,           /* xDelete */                     \
23918     unixAccess,           /* xAccess */                     \
23919     unixFullPathname,     /* xFullPathname */               \
23920     unixDlOpen,           /* xDlOpen */                     \
23921     unixDlError,          /* xDlError */                    \
23922     unixDlSym,            /* xDlSym */                      \
23923     unixDlClose,          /* xDlClose */                    \
23924     unixRandomness,       /* xRandomness */                 \
23925     unixSleep,            /* xSleep */                      \
23926     unixCurrentTime,      /* xCurrentTime */                \
23927     unixGetLastError      /* xGetLastError */               \
23928   }
23929
23930   static sqlite3_vfs unixVfs = UNIXVFS("unix", 0);
23931 #ifdef SQLITE_ENABLE_LOCKING_STYLE
23932 #if 0
23933   int i;
23934   static sqlite3_vfs aVfs[] = {
23935     UNIXVFS("unix-posix",   LOCKING_STYLE_POSIX), 
23936     UNIXVFS("unix-afp",     LOCKING_STYLE_AFP), 
23937     UNIXVFS("unix-flock",   LOCKING_STYLE_FLOCK), 
23938     UNIXVFS("unix-dotfile", LOCKING_STYLE_DOTFILE), 
23939     UNIXVFS("unix-none",    LOCKING_STYLE_NONE)
23940   };
23941   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
23942     sqlite3_vfs_register(&aVfs[i], 0);
23943   }
23944 #endif
23945 #endif
23946   sqlite3_vfs_register(&unixVfs, 1);
23947   return SQLITE_OK; 
23948 }
23949
23950 /*
23951 ** Shutdown the operating system interface. This is a no-op for unix.
23952 */
23953 SQLITE_API int sqlite3_os_end(void){ 
23954   return SQLITE_OK; 
23955 }
23956  
23957 #endif /* SQLITE_OS_UNIX */
23958
23959 /************** End of os_unix.c *********************************************/
23960 /************** Begin file os_win.c ******************************************/
23961 /*
23962 ** 2004 May 22
23963 **
23964 ** The author disclaims copyright to this source code.  In place of
23965 ** a legal notice, here is a blessing:
23966 **
23967 **    May you do good and not evil.
23968 **    May you find forgiveness for yourself and forgive others.
23969 **    May you share freely, never taking more than you give.
23970 **
23971 ******************************************************************************
23972 **
23973 ** This file contains code that is specific to windows.
23974 **
23975 ** $Id: os_win.c,v 1.132 2008/07/31 01:34:34 shane Exp $
23976 */
23977 #if SQLITE_OS_WIN               /* This file is used for windows only */
23978
23979
23980 /*
23981 ** A Note About Memory Allocation:
23982 **
23983 ** This driver uses malloc()/free() directly rather than going through
23984 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
23985 ** are designed for use on embedded systems where memory is scarce and
23986 ** malloc failures happen frequently.  Win32 does not typically run on
23987 ** embedded systems, and when it does the developers normally have bigger
23988 ** problems to worry about than running out of memory.  So there is not
23989 ** a compelling need to use the wrappers.
23990 **
23991 ** But there is a good reason to not use the wrappers.  If we use the
23992 ** wrappers then we will get simulated malloc() failures within this
23993 ** driver.  And that causes all kinds of problems for our tests.  We
23994 ** could enhance SQLite to deal with simulated malloc failures within
23995 ** the OS driver, but the code to deal with those failure would not
23996 ** be exercised on Linux (which does not need to malloc() in the driver)
23997 ** and so we would have difficulty writing coverage tests for that
23998 ** code.  Better to leave the code out, we think.
23999 **
24000 ** The point of this discussion is as follows:  When creating a new
24001 ** OS layer for an embedded system, if you use this file as an example,
24002 ** avoid the use of malloc()/free().  Those routines work ok on windows
24003 ** desktops but not so well in embedded systems.
24004 */
24005
24006 #include <winbase.h>
24007
24008 #ifdef __CYGWIN__
24009 # include <sys/cygwin.h>
24010 #endif
24011
24012 /*
24013 ** Macros used to determine whether or not to use threads.
24014 */
24015 #if defined(THREADSAFE) && THREADSAFE
24016 # define SQLITE_W32_THREADS 1
24017 #endif
24018
24019 /*
24020 ** Include code that is common to all os_*.c files
24021 */
24022 /************** Include os_common.h in the middle of os_win.c ****************/
24023 /************** Begin file os_common.h ***************************************/
24024 /*
24025 ** 2004 May 22
24026 **
24027 ** The author disclaims copyright to this source code.  In place of
24028 ** a legal notice, here is a blessing:
24029 **
24030 **    May you do good and not evil.
24031 **    May you find forgiveness for yourself and forgive others.
24032 **    May you share freely, never taking more than you give.
24033 **
24034 ******************************************************************************
24035 **
24036 ** This file contains macros and a little bit of code that is common to
24037 ** all of the platform-specific files (os_*.c) and is #included into those
24038 ** files.
24039 **
24040 ** This file should be #included by the os_*.c files only.  It is not a
24041 ** general purpose header file.
24042 **
24043 ** $Id: os_common.h,v 1.37 2008/05/29 20:22:37 shane Exp $
24044 */
24045 #ifndef _OS_COMMON_H_
24046 #define _OS_COMMON_H_
24047
24048 /*
24049 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
24050 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
24051 ** switch.  The following code should catch this problem at compile-time.
24052 */
24053 #ifdef MEMORY_DEBUG
24054 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
24055 #endif
24056
24057
24058 /*
24059  * When testing, this global variable stores the location of the
24060  * pending-byte in the database file.
24061  */
24062 #ifdef SQLITE_TEST
24063 SQLITE_API unsigned int sqlite3_pending_byte = 0x40000000;
24064 #endif
24065
24066 #ifdef SQLITE_DEBUG
24067 SQLITE_PRIVATE int sqlite3OSTrace = 0;
24068 #define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
24069 #define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
24070 #define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
24071 #define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
24072 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
24073 #define OSTRACE6(X,Y,Z,A,B,C) \
24074     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
24075 #define OSTRACE7(X,Y,Z,A,B,C,D) \
24076     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
24077 #else
24078 #define OSTRACE1(X)
24079 #define OSTRACE2(X,Y)
24080 #define OSTRACE3(X,Y,Z)
24081 #define OSTRACE4(X,Y,Z,A)
24082 #define OSTRACE5(X,Y,Z,A,B)
24083 #define OSTRACE6(X,Y,Z,A,B,C)
24084 #define OSTRACE7(X,Y,Z,A,B,C,D)
24085 #endif
24086
24087 /*
24088 ** Macros for performance tracing.  Normally turned off.  Only works
24089 ** on i486 hardware.
24090 */
24091 #ifdef SQLITE_PERFORMANCE_TRACE
24092
24093 /* 
24094 ** hwtime.h contains inline assembler code for implementing 
24095 ** high-performance timing routines.
24096 */
24097 /************** Include hwtime.h in the middle of os_common.h ****************/
24098 /************** Begin file hwtime.h ******************************************/
24099 /*
24100 ** 2008 May 27
24101 **
24102 ** The author disclaims copyright to this source code.  In place of
24103 ** a legal notice, here is a blessing:
24104 **
24105 **    May you do good and not evil.
24106 **    May you find forgiveness for yourself and forgive others.
24107 **    May you share freely, never taking more than you give.
24108 **
24109 ******************************************************************************
24110 **
24111 ** This file contains inline asm code for retrieving "high-performance"
24112 ** counters for x86 class CPUs.
24113 **
24114 ** $Id: hwtime.h,v 1.3 2008/08/01 14:33:15 shane Exp $
24115 */
24116 #ifndef _HWTIME_H_
24117 #define _HWTIME_H_
24118
24119 /*
24120 ** The following routine only works on pentium-class (or newer) processors.
24121 ** It uses the RDTSC opcode to read the cycle count value out of the
24122 ** processor and returns that value.  This can be used for high-res
24123 ** profiling.
24124 */
24125 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
24126       (defined(i386) || defined(__i386__) || defined(_M_IX86))
24127
24128   #if defined(__GNUC__)
24129
24130   __inline__ sqlite_uint64 sqlite3Hwtime(void){
24131      unsigned int lo, hi;
24132      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
24133      return (sqlite_uint64)hi << 32 | lo;
24134   }
24135
24136   #elif defined(_MSC_VER)
24137
24138   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
24139      __asm {
24140         rdtsc
24141         ret       ; return value at EDX:EAX
24142      }
24143   }
24144
24145   #endif
24146
24147 #elif (defined(__GNUC__) && defined(__x86_64__))
24148
24149   __inline__ sqlite_uint64 sqlite3Hwtime(void){
24150       unsigned long val;
24151       __asm__ __volatile__ ("rdtsc" : "=A" (val));
24152       return val;
24153   }
24154  
24155 #elif (defined(__GNUC__) && defined(__ppc__))
24156
24157   __inline__ sqlite_uint64 sqlite3Hwtime(void){
24158       unsigned long long retval;
24159       unsigned long junk;
24160       __asm__ __volatile__ ("\n\
24161           1:      mftbu   %1\n\
24162                   mftb    %L0\n\
24163                   mftbu   %0\n\
24164                   cmpw    %0,%1\n\
24165                   bne     1b"
24166                   : "=r" (retval), "=r" (junk));
24167       return retval;
24168   }
24169
24170 #else
24171
24172   #error Need implementation of sqlite3Hwtime() for your platform.
24173
24174   /*
24175   ** To compile without implementing sqlite3Hwtime() for your platform,
24176   ** you can remove the above #error and use the following
24177   ** stub function.  You will lose timing support for many
24178   ** of the debugging and testing utilities, but it should at
24179   ** least compile and run.
24180   */
24181 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
24182
24183 #endif
24184
24185 #endif /* !defined(_HWTIME_H_) */
24186
24187 /************** End of hwtime.h **********************************************/
24188 /************** Continuing where we left off in os_common.h ******************/
24189
24190 static sqlite_uint64 g_start;
24191 static sqlite_uint64 g_elapsed;
24192 #define TIMER_START       g_start=sqlite3Hwtime()
24193 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
24194 #define TIMER_ELAPSED     g_elapsed
24195 #else
24196 #define TIMER_START
24197 #define TIMER_END
24198 #define TIMER_ELAPSED     ((sqlite_uint64)0)
24199 #endif
24200
24201 /*
24202 ** If we compile with the SQLITE_TEST macro set, then the following block
24203 ** of code will give us the ability to simulate a disk I/O error.  This
24204 ** is used for testing the I/O recovery logic.
24205 */
24206 #ifdef SQLITE_TEST
24207 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
24208 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
24209 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
24210 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
24211 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
24212 SQLITE_API int sqlite3_diskfull_pending = 0;
24213 SQLITE_API int sqlite3_diskfull = 0;
24214 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
24215 #define SimulateIOError(CODE)  \
24216   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
24217        || sqlite3_io_error_pending-- == 1 )  \
24218               { local_ioerr(); CODE; }
24219 static void local_ioerr(){
24220   IOTRACE(("IOERR\n"));
24221   sqlite3_io_error_hit++;
24222   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
24223 }
24224 #define SimulateDiskfullError(CODE) \
24225    if( sqlite3_diskfull_pending ){ \
24226      if( sqlite3_diskfull_pending == 1 ){ \
24227        local_ioerr(); \
24228        sqlite3_diskfull = 1; \
24229        sqlite3_io_error_hit = 1; \
24230        CODE; \
24231      }else{ \
24232        sqlite3_diskfull_pending--; \
24233      } \
24234    }
24235 #else
24236 #define SimulateIOErrorBenign(X)
24237 #define SimulateIOError(A)
24238 #define SimulateDiskfullError(A)
24239 #endif
24240
24241 /*
24242 ** When testing, keep a count of the number of open files.
24243 */
24244 #ifdef SQLITE_TEST
24245 SQLITE_API int sqlite3_open_file_count = 0;
24246 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
24247 #else
24248 #define OpenCounter(X)
24249 #endif
24250
24251 #endif /* !defined(_OS_COMMON_H_) */
24252
24253 /************** End of os_common.h *******************************************/
24254 /************** Continuing where we left off in os_win.c *********************/
24255
24256 /*
24257 ** Determine if we are dealing with WindowsCE - which has a much
24258 ** reduced API.
24259 */
24260 #if defined(SQLITE_OS_WINCE)
24261 # define AreFileApisANSI() 1
24262 #endif
24263
24264 /*
24265 ** WinCE lacks native support for file locking so we have to fake it
24266 ** with some code of our own.
24267 */
24268 #if SQLITE_OS_WINCE
24269 typedef struct winceLock {
24270   int nReaders;       /* Number of reader locks obtained */
24271   BOOL bPending;      /* Indicates a pending lock has been obtained */
24272   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
24273   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
24274 } winceLock;
24275 #endif
24276
24277 /*
24278 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
24279 ** portability layer.
24280 */
24281 typedef struct winFile winFile;
24282 struct winFile {
24283   const sqlite3_io_methods *pMethod;/* Must be first */
24284   HANDLE h;               /* Handle for accessing the file */
24285   unsigned char locktype; /* Type of lock currently held on this file */
24286   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
24287 #if SQLITE_OS_WINCE
24288   WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
24289   HANDLE hMutex;          /* Mutex used to control access to shared lock */  
24290   HANDLE hShared;         /* Shared memory segment used for locking */
24291   winceLock local;        /* Locks obtained by this instance of winFile */
24292   winceLock *shared;      /* Global shared lock memory for the file  */
24293 #endif
24294 };
24295
24296
24297 /*
24298 ** The following variable is (normally) set once and never changes
24299 ** thereafter.  It records whether the operating system is Win95
24300 ** or WinNT.
24301 **
24302 ** 0:   Operating system unknown.
24303 ** 1:   Operating system is Win95.
24304 ** 2:   Operating system is WinNT.
24305 **
24306 ** In order to facilitate testing on a WinNT system, the test fixture
24307 ** can manually set this value to 1 to emulate Win98 behavior.
24308 */
24309 #ifdef SQLITE_TEST
24310 SQLITE_API int sqlite3_os_type = 0;
24311 #else
24312 static int sqlite3_os_type = 0;
24313 #endif
24314
24315 /*
24316 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
24317 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
24318 **
24319 ** Here is an interesting observation:  Win95, Win98, and WinME lack
24320 ** the LockFileEx() API.  But we can still statically link against that
24321 ** API as long as we don't call it win running Win95/98/ME.  A call to
24322 ** this routine is used to determine if the host is Win95/98/ME or
24323 ** WinNT/2K/XP so that we will know whether or not we can safely call
24324 ** the LockFileEx() API.
24325 */
24326 #if SQLITE_OS_WINCE
24327 # define isNT()  (1)
24328 #else
24329   static int isNT(void){
24330     if( sqlite3_os_type==0 ){
24331       OSVERSIONINFO sInfo;
24332       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
24333       GetVersionEx(&sInfo);
24334       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
24335     }
24336     return sqlite3_os_type==2;
24337   }
24338 #endif /* SQLITE_OS_WINCE */
24339
24340 /*
24341 ** Convert a UTF-8 string to microsoft unicode (UTF-16?). 
24342 **
24343 ** Space to hold the returned string is obtained from malloc.
24344 */
24345 static WCHAR *utf8ToUnicode(const char *zFilename){
24346   int nChar;
24347   WCHAR *zWideFilename;
24348
24349   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
24350   zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
24351   if( zWideFilename==0 ){
24352     return 0;
24353   }
24354   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
24355   if( nChar==0 ){
24356     free(zWideFilename);
24357     zWideFilename = 0;
24358   }
24359   return zWideFilename;
24360 }
24361
24362 /*
24363 ** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
24364 ** obtained from malloc().
24365 */
24366 static char *unicodeToUtf8(const WCHAR *zWideFilename){
24367   int nByte;
24368   char *zFilename;
24369
24370   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
24371   zFilename = malloc( nByte );
24372   if( zFilename==0 ){
24373     return 0;
24374   }
24375   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
24376                               0, 0);
24377   if( nByte == 0 ){
24378     free(zFilename);
24379     zFilename = 0;
24380   }
24381   return zFilename;
24382 }
24383
24384 /*
24385 ** Convert an ansi string to microsoft unicode, based on the
24386 ** current codepage settings for file apis.
24387 ** 
24388 ** Space to hold the returned string is obtained
24389 ** from malloc.
24390 */
24391 static WCHAR *mbcsToUnicode(const char *zFilename){
24392   int nByte;
24393   WCHAR *zMbcsFilename;
24394   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
24395
24396   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
24397   zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
24398   if( zMbcsFilename==0 ){
24399     return 0;
24400   }
24401   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
24402   if( nByte==0 ){
24403     free(zMbcsFilename);
24404     zMbcsFilename = 0;
24405   }
24406   return zMbcsFilename;
24407 }
24408
24409 /*
24410 ** Convert microsoft unicode to multibyte character string, based on the
24411 ** user's Ansi codepage.
24412 **
24413 ** Space to hold the returned string is obtained from
24414 ** malloc().
24415 */
24416 static char *unicodeToMbcs(const WCHAR *zWideFilename){
24417   int nByte;
24418   char *zFilename;
24419   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
24420
24421   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
24422   zFilename = malloc( nByte );
24423   if( zFilename==0 ){
24424     return 0;
24425   }
24426   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
24427                               0, 0);
24428   if( nByte == 0 ){
24429     free(zFilename);
24430     zFilename = 0;
24431   }
24432   return zFilename;
24433 }
24434
24435 /*
24436 ** Convert multibyte character string to UTF-8.  Space to hold the
24437 ** returned string is obtained from malloc().
24438 */
24439 static char *mbcsToUtf8(const char *zFilename){
24440   char *zFilenameUtf8;
24441   WCHAR *zTmpWide;
24442
24443   zTmpWide = mbcsToUnicode(zFilename);
24444   if( zTmpWide==0 ){
24445     return 0;
24446   }
24447   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
24448   free(zTmpWide);
24449   return zFilenameUtf8;
24450 }
24451
24452 /*
24453 ** Convert UTF-8 to multibyte character string.  Space to hold the 
24454 ** returned string is obtained from malloc().
24455 */
24456 static char *utf8ToMbcs(const char *zFilename){
24457   char *zFilenameMbcs;
24458   WCHAR *zTmpWide;
24459
24460   zTmpWide = utf8ToUnicode(zFilename);
24461   if( zTmpWide==0 ){
24462     return 0;
24463   }
24464   zFilenameMbcs = unicodeToMbcs(zTmpWide);
24465   free(zTmpWide);
24466   return zFilenameMbcs;
24467 }
24468
24469 #if SQLITE_OS_WINCE
24470 /*************************************************************************
24471 ** This section contains code for WinCE only.
24472 */
24473 /*
24474 ** WindowsCE does not have a localtime() function.  So create a
24475 ** substitute.
24476 */
24477 struct tm *__cdecl localtime(const time_t *t)
24478 {
24479   static struct tm y;
24480   FILETIME uTm, lTm;
24481   SYSTEMTIME pTm;
24482   sqlite3_int64 t64;
24483   t64 = *t;
24484   t64 = (t64 + 11644473600)*10000000;
24485   uTm.dwLowDateTime = t64 & 0xFFFFFFFF;
24486   uTm.dwHighDateTime= t64 >> 32;
24487   FileTimeToLocalFileTime(&uTm,&lTm);
24488   FileTimeToSystemTime(&lTm,&pTm);
24489   y.tm_year = pTm.wYear - 1900;
24490   y.tm_mon = pTm.wMonth - 1;
24491   y.tm_wday = pTm.wDayOfWeek;
24492   y.tm_mday = pTm.wDay;
24493   y.tm_hour = pTm.wHour;
24494   y.tm_min = pTm.wMinute;
24495   y.tm_sec = pTm.wSecond;
24496   return &y;
24497 }
24498
24499 /* This will never be called, but defined to make the code compile */
24500 #define GetTempPathA(a,b)
24501
24502 #define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
24503 #define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
24504 #define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
24505
24506 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-offsetof(winFile,h)]
24507
24508 /*
24509 ** Acquire a lock on the handle h
24510 */
24511 static void winceMutexAcquire(HANDLE h){
24512    DWORD dwErr;
24513    do {
24514      dwErr = WaitForSingleObject(h, INFINITE);
24515    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
24516 }
24517 /*
24518 ** Release a lock acquired by winceMutexAcquire()
24519 */
24520 #define winceMutexRelease(h) ReleaseMutex(h)
24521
24522 /*
24523 ** Create the mutex and shared memory used for locking in the file
24524 ** descriptor pFile
24525 */
24526 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
24527   WCHAR *zTok;
24528   WCHAR *zName = utf8ToUnicode(zFilename);
24529   BOOL bInit = TRUE;
24530
24531   /* Initialize the local lockdata */
24532   ZeroMemory(&pFile->local, sizeof(pFile->local));
24533
24534   /* Replace the backslashes from the filename and lowercase it
24535   ** to derive a mutex name. */
24536   zTok = CharLowerW(zName);
24537   for (;*zTok;zTok++){
24538     if (*zTok == '\\') *zTok = '_';
24539   }
24540
24541   /* Create/open the named mutex */
24542   pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
24543   if (!pFile->hMutex){
24544     free(zName);
24545     return FALSE;
24546   }
24547
24548   /* Acquire the mutex before continuing */
24549   winceMutexAcquire(pFile->hMutex);
24550   
24551   /* Since the names of named mutexes, semaphores, file mappings etc are 
24552   ** case-sensitive, take advantage of that by uppercasing the mutex name
24553   ** and using that as the shared filemapping name.
24554   */
24555   CharUpperW(zName);
24556   pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
24557                                        PAGE_READWRITE, 0, sizeof(winceLock),
24558                                        zName);  
24559
24560   /* Set a flag that indicates we're the first to create the memory so it 
24561   ** must be zero-initialized */
24562   if (GetLastError() == ERROR_ALREADY_EXISTS){
24563     bInit = FALSE;
24564   }
24565
24566   free(zName);
24567
24568   /* If we succeeded in making the shared memory handle, map it. */
24569   if (pFile->hShared){
24570     pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared, 
24571              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
24572     /* If mapping failed, close the shared memory handle and erase it */
24573     if (!pFile->shared){
24574       CloseHandle(pFile->hShared);
24575       pFile->hShared = NULL;
24576     }
24577   }
24578
24579   /* If shared memory could not be created, then close the mutex and fail */
24580   if (pFile->hShared == NULL){
24581     winceMutexRelease(pFile->hMutex);
24582     CloseHandle(pFile->hMutex);
24583     pFile->hMutex = NULL;
24584     return FALSE;
24585   }
24586   
24587   /* Initialize the shared memory if we're supposed to */
24588   if (bInit) {
24589     ZeroMemory(pFile->shared, sizeof(winceLock));
24590   }
24591
24592   winceMutexRelease(pFile->hMutex);
24593   return TRUE;
24594 }
24595
24596 /*
24597 ** Destroy the part of winFile that deals with wince locks
24598 */
24599 static void winceDestroyLock(winFile *pFile){
24600   if (pFile->hMutex){
24601     /* Acquire the mutex */
24602     winceMutexAcquire(pFile->hMutex);
24603
24604     /* The following blocks should probably assert in debug mode, but they
24605        are to cleanup in case any locks remained open */
24606     if (pFile->local.nReaders){
24607       pFile->shared->nReaders --;
24608     }
24609     if (pFile->local.bReserved){
24610       pFile->shared->bReserved = FALSE;
24611     }
24612     if (pFile->local.bPending){
24613       pFile->shared->bPending = FALSE;
24614     }
24615     if (pFile->local.bExclusive){
24616       pFile->shared->bExclusive = FALSE;
24617     }
24618
24619     /* De-reference and close our copy of the shared memory handle */
24620     UnmapViewOfFile(pFile->shared);
24621     CloseHandle(pFile->hShared);
24622
24623     /* Done with the mutex */
24624     winceMutexRelease(pFile->hMutex);    
24625     CloseHandle(pFile->hMutex);
24626     pFile->hMutex = NULL;
24627   }
24628 }
24629
24630 /* 
24631 ** An implementation of the LockFile() API of windows for wince
24632 */
24633 static BOOL winceLockFile(
24634   HANDLE *phFile,
24635   DWORD dwFileOffsetLow,
24636   DWORD dwFileOffsetHigh,
24637   DWORD nNumberOfBytesToLockLow,
24638   DWORD nNumberOfBytesToLockHigh
24639 ){
24640   winFile *pFile = HANDLE_TO_WINFILE(phFile);
24641   BOOL bReturn = FALSE;
24642
24643   if (!pFile->hMutex) return TRUE;
24644   winceMutexAcquire(pFile->hMutex);
24645
24646   /* Wanting an exclusive lock? */
24647   if (dwFileOffsetLow == SHARED_FIRST
24648        && nNumberOfBytesToLockLow == SHARED_SIZE){
24649     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
24650        pFile->shared->bExclusive = TRUE;
24651        pFile->local.bExclusive = TRUE;
24652        bReturn = TRUE;
24653     }
24654   }
24655
24656   /* Want a read-only lock? */
24657   else if ((dwFileOffsetLow >= SHARED_FIRST &&
24658             dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE) &&
24659             nNumberOfBytesToLockLow == 1){
24660     if (pFile->shared->bExclusive == 0){
24661       pFile->local.nReaders ++;
24662       if (pFile->local.nReaders == 1){
24663         pFile->shared->nReaders ++;
24664       }
24665       bReturn = TRUE;
24666     }
24667   }
24668
24669   /* Want a pending lock? */
24670   else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToLockLow == 1){
24671     /* If no pending lock has been acquired, then acquire it */
24672     if (pFile->shared->bPending == 0) {
24673       pFile->shared->bPending = TRUE;
24674       pFile->local.bPending = TRUE;
24675       bReturn = TRUE;
24676     }
24677   }
24678   /* Want a reserved lock? */
24679   else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
24680     if (pFile->shared->bReserved == 0) {
24681       pFile->shared->bReserved = TRUE;
24682       pFile->local.bReserved = TRUE;
24683       bReturn = TRUE;
24684     }
24685   }
24686
24687   winceMutexRelease(pFile->hMutex);
24688   return bReturn;
24689 }
24690
24691 /*
24692 ** An implementation of the UnlockFile API of windows for wince
24693 */
24694 static BOOL winceUnlockFile(
24695   HANDLE *phFile,
24696   DWORD dwFileOffsetLow,
24697   DWORD dwFileOffsetHigh,
24698   DWORD nNumberOfBytesToUnlockLow,
24699   DWORD nNumberOfBytesToUnlockHigh
24700 ){
24701   winFile *pFile = HANDLE_TO_WINFILE(phFile);
24702   BOOL bReturn = FALSE;
24703
24704   if (!pFile->hMutex) return TRUE;
24705   winceMutexAcquire(pFile->hMutex);
24706
24707   /* Releasing a reader lock or an exclusive lock */
24708   if (dwFileOffsetLow >= SHARED_FIRST &&
24709        dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE){
24710     /* Did we have an exclusive lock? */
24711     if (pFile->local.bExclusive){
24712       pFile->local.bExclusive = FALSE;
24713       pFile->shared->bExclusive = FALSE;
24714       bReturn = TRUE;
24715     }
24716
24717     /* Did we just have a reader lock? */
24718     else if (pFile->local.nReaders){
24719       pFile->local.nReaders --;
24720       if (pFile->local.nReaders == 0)
24721       {
24722         pFile->shared->nReaders --;
24723       }
24724       bReturn = TRUE;
24725     }
24726   }
24727
24728   /* Releasing a pending lock */
24729   else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
24730     if (pFile->local.bPending){
24731       pFile->local.bPending = FALSE;
24732       pFile->shared->bPending = FALSE;
24733       bReturn = TRUE;
24734     }
24735   }
24736   /* Releasing a reserved lock */
24737   else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
24738     if (pFile->local.bReserved) {
24739       pFile->local.bReserved = FALSE;
24740       pFile->shared->bReserved = FALSE;
24741       bReturn = TRUE;
24742     }
24743   }
24744
24745   winceMutexRelease(pFile->hMutex);
24746   return bReturn;
24747 }
24748
24749 /*
24750 ** An implementation of the LockFileEx() API of windows for wince
24751 */
24752 static BOOL winceLockFileEx(
24753   HANDLE *phFile,
24754   DWORD dwFlags,
24755   DWORD dwReserved,
24756   DWORD nNumberOfBytesToLockLow,
24757   DWORD nNumberOfBytesToLockHigh,
24758   LPOVERLAPPED lpOverlapped
24759 ){
24760   /* If the caller wants a shared read lock, forward this call
24761   ** to winceLockFile */
24762   if (lpOverlapped->Offset == SHARED_FIRST &&
24763       dwFlags == 1 &&
24764       nNumberOfBytesToLockLow == SHARED_SIZE){
24765     return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
24766   }
24767   return FALSE;
24768 }
24769 /*
24770 ** End of the special code for wince
24771 *****************************************************************************/
24772 #endif /* SQLITE_OS_WINCE */
24773
24774 /*****************************************************************************
24775 ** The next group of routines implement the I/O methods specified
24776 ** by the sqlite3_io_methods object.
24777 ******************************************************************************/
24778
24779 /*
24780 ** Close a file.
24781 **
24782 ** It is reported that an attempt to close a handle might sometimes
24783 ** fail.  This is a very unreasonable result, but windows is notorious
24784 ** for being unreasonable so I do not doubt that it might happen.  If
24785 ** the close fails, we pause for 100 milliseconds and try again.  As
24786 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
24787 ** giving up and returning an error.
24788 */
24789 #define MX_CLOSE_ATTEMPT 3
24790 static int winClose(sqlite3_file *id){
24791   int rc, cnt = 0;
24792   winFile *pFile = (winFile*)id;
24793   OSTRACE2("CLOSE %d\n", pFile->h);
24794   do{
24795     rc = CloseHandle(pFile->h);
24796   }while( rc==0 && cnt++ < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
24797 #if SQLITE_OS_WINCE
24798 #define WINCE_DELETION_ATTEMPTS 3
24799   winceDestroyLock(pFile);
24800   if( pFile->zDeleteOnClose ){
24801     int cnt = 0;
24802     while(
24803            DeleteFileW(pFile->zDeleteOnClose)==0
24804         && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
24805         && cnt++ < WINCE_DELETION_ATTEMPTS
24806     ){
24807        Sleep(100);  /* Wait a little before trying again */
24808     }
24809     free(pFile->zDeleteOnClose);
24810   }
24811 #endif
24812   OpenCounter(-1);
24813   return rc ? SQLITE_OK : SQLITE_IOERR;
24814 }
24815
24816 /*
24817 ** Some microsoft compilers lack this definition.
24818 */
24819 #ifndef INVALID_SET_FILE_POINTER
24820 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
24821 #endif
24822
24823 /*
24824 ** Read data from a file into a buffer.  Return SQLITE_OK if all
24825 ** bytes were read successfully and SQLITE_IOERR if anything goes
24826 ** wrong.
24827 */
24828 static int winRead(
24829   sqlite3_file *id,          /* File to read from */
24830   void *pBuf,                /* Write content into this buffer */
24831   int amt,                   /* Number of bytes to read */
24832   sqlite3_int64 offset       /* Begin reading at this offset */
24833 ){
24834   LONG upperBits = (offset>>32) & 0x7fffffff;
24835   LONG lowerBits = offset & 0xffffffff;
24836   DWORD rc;
24837   DWORD got;
24838   winFile *pFile = (winFile*)id;
24839   assert( id!=0 );
24840   SimulateIOError(return SQLITE_IOERR_READ);
24841   OSTRACE3("READ %d lock=%d\n", pFile->h, pFile->locktype);
24842   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
24843   if( rc==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR ){
24844     return SQLITE_FULL;
24845   }
24846   if( !ReadFile(pFile->h, pBuf, amt, &got, 0) ){
24847     return SQLITE_IOERR_READ;
24848   }
24849   if( got==(DWORD)amt ){
24850     return SQLITE_OK;
24851   }else{
24852     memset(&((char*)pBuf)[got], 0, amt-got);
24853     return SQLITE_IOERR_SHORT_READ;
24854   }
24855 }
24856
24857 /*
24858 ** Write data from a buffer into a file.  Return SQLITE_OK on success
24859 ** or some other error code on failure.
24860 */
24861 static int winWrite(
24862   sqlite3_file *id,         /* File to write into */
24863   const void *pBuf,         /* The bytes to be written */
24864   int amt,                  /* Number of bytes to write */
24865   sqlite3_int64 offset      /* Offset into the file to begin writing at */
24866 ){
24867   LONG upperBits = (offset>>32) & 0x7fffffff;
24868   LONG lowerBits = offset & 0xffffffff;
24869   DWORD rc;
24870   DWORD wrote;
24871   winFile *pFile = (winFile*)id;
24872   assert( id!=0 );
24873   SimulateIOError(return SQLITE_IOERR_WRITE);
24874   SimulateDiskfullError(return SQLITE_FULL);
24875   OSTRACE3("WRITE %d lock=%d\n", pFile->h, pFile->locktype);
24876   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
24877   if( rc==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR ){
24878     return SQLITE_FULL;
24879   }
24880   assert( amt>0 );
24881   while(
24882      amt>0
24883      && (rc = WriteFile(pFile->h, pBuf, amt, &wrote, 0))!=0
24884      && wrote>0
24885   ){
24886     amt -= wrote;
24887     pBuf = &((char*)pBuf)[wrote];
24888   }
24889   if( !rc || amt>(int)wrote ){
24890     return SQLITE_FULL;
24891   }
24892   return SQLITE_OK;
24893 }
24894
24895 /*
24896 ** Truncate an open file to a specified size
24897 */
24898 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
24899   LONG upperBits = (nByte>>32) & 0x7fffffff;
24900   LONG lowerBits = nByte & 0xffffffff;
24901   winFile *pFile = (winFile*)id;
24902   OSTRACE3("TRUNCATE %d %lld\n", pFile->h, nByte);
24903   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
24904   SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
24905   SetEndOfFile(pFile->h);
24906   return SQLITE_OK;
24907 }
24908
24909 #ifdef SQLITE_TEST
24910 /*
24911 ** Count the number of fullsyncs and normal syncs.  This is used to test
24912 ** that syncs and fullsyncs are occuring at the right times.
24913 */
24914 SQLITE_API int sqlite3_sync_count = 0;
24915 SQLITE_API int sqlite3_fullsync_count = 0;
24916 #endif
24917
24918 /*
24919 ** Make sure all writes to a particular file are committed to disk.
24920 */
24921 static int winSync(sqlite3_file *id, int flags){
24922   winFile *pFile = (winFile*)id;
24923   OSTRACE3("SYNC %d lock=%d\n", pFile->h, pFile->locktype);
24924 #ifdef SQLITE_TEST
24925   if( flags & SQLITE_SYNC_FULL ){
24926     sqlite3_fullsync_count++;
24927   }
24928   sqlite3_sync_count++;
24929 #endif
24930   if( FlushFileBuffers(pFile->h) ){
24931     return SQLITE_OK;
24932   }else{
24933     return SQLITE_IOERR;
24934   }
24935 }
24936
24937 /*
24938 ** Determine the current size of a file in bytes
24939 */
24940 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
24941   winFile *pFile = (winFile*)id;
24942   DWORD upperBits, lowerBits;
24943   SimulateIOError(return SQLITE_IOERR_FSTAT);
24944   lowerBits = GetFileSize(pFile->h, &upperBits);
24945   *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
24946   return SQLITE_OK;
24947 }
24948
24949 /*
24950 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
24951 */
24952 #ifndef LOCKFILE_FAIL_IMMEDIATELY
24953 # define LOCKFILE_FAIL_IMMEDIATELY 1
24954 #endif
24955
24956 /*
24957 ** Acquire a reader lock.
24958 ** Different API routines are called depending on whether or not this
24959 ** is Win95 or WinNT.
24960 */
24961 static int getReadLock(winFile *pFile){
24962   int res;
24963   if( isNT() ){
24964     OVERLAPPED ovlp;
24965     ovlp.Offset = SHARED_FIRST;
24966     ovlp.OffsetHigh = 0;
24967     ovlp.hEvent = 0;
24968     res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
24969                      0, SHARED_SIZE, 0, &ovlp);
24970   }else{
24971     int lk;
24972     sqlite3_randomness(sizeof(lk), &lk);
24973     pFile->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
24974     res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
24975   }
24976   return res;
24977 }
24978
24979 /*
24980 ** Undo a readlock
24981 */
24982 static int unlockReadLock(winFile *pFile){
24983   int res;
24984   if( isNT() ){
24985     res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
24986   }else{
24987     res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
24988   }
24989   return res;
24990 }
24991
24992 /*
24993 ** Lock the file with the lock specified by parameter locktype - one
24994 ** of the following:
24995 **
24996 **     (1) SHARED_LOCK
24997 **     (2) RESERVED_LOCK
24998 **     (3) PENDING_LOCK
24999 **     (4) EXCLUSIVE_LOCK
25000 **
25001 ** Sometimes when requesting one lock state, additional lock states
25002 ** are inserted in between.  The locking might fail on one of the later
25003 ** transitions leaving the lock state different from what it started but
25004 ** still short of its goal.  The following chart shows the allowed
25005 ** transitions and the inserted intermediate states:
25006 **
25007 **    UNLOCKED -> SHARED
25008 **    SHARED -> RESERVED
25009 **    SHARED -> (PENDING) -> EXCLUSIVE
25010 **    RESERVED -> (PENDING) -> EXCLUSIVE
25011 **    PENDING -> EXCLUSIVE
25012 **
25013 ** This routine will only increase a lock.  The winUnlock() routine
25014 ** erases all locks at once and returns us immediately to locking level 0.
25015 ** It is not possible to lower the locking level one step at a time.  You
25016 ** must go straight to locking level 0.
25017 */
25018 static int winLock(sqlite3_file *id, int locktype){
25019   int rc = SQLITE_OK;    /* Return code from subroutines */
25020   int res = 1;           /* Result of a windows lock call */
25021   int newLocktype;       /* Set pFile->locktype to this value before exiting */
25022   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
25023   winFile *pFile = (winFile*)id;
25024
25025   assert( pFile!=0 );
25026   OSTRACE5("LOCK %d %d was %d(%d)\n",
25027           pFile->h, locktype, pFile->locktype, pFile->sharedLockByte);
25028
25029   /* If there is already a lock of this type or more restrictive on the
25030   ** OsFile, do nothing. Don't use the end_lock: exit path, as
25031   ** sqlite3OsEnterMutex() hasn't been called yet.
25032   */
25033   if( pFile->locktype>=locktype ){
25034     return SQLITE_OK;
25035   }
25036
25037   /* Make sure the locking sequence is correct
25038   */
25039   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
25040   assert( locktype!=PENDING_LOCK );
25041   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
25042
25043   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
25044   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
25045   ** the PENDING_LOCK byte is temporary.
25046   */
25047   newLocktype = pFile->locktype;
25048   if( pFile->locktype==NO_LOCK
25049    || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
25050   ){
25051     int cnt = 3;
25052     while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
25053       /* Try 3 times to get the pending lock.  The pending lock might be
25054       ** held by another reader process who will release it momentarily.
25055       */
25056       OSTRACE2("could not get a PENDING lock. cnt=%d\n", cnt);
25057       Sleep(1);
25058     }
25059     gotPendingLock = res;
25060   }
25061
25062   /* Acquire a shared lock
25063   */
25064   if( locktype==SHARED_LOCK && res ){
25065     assert( pFile->locktype==NO_LOCK );
25066     res = getReadLock(pFile);
25067     if( res ){
25068       newLocktype = SHARED_LOCK;
25069     }
25070   }
25071
25072   /* Acquire a RESERVED lock
25073   */
25074   if( locktype==RESERVED_LOCK && res ){
25075     assert( pFile->locktype==SHARED_LOCK );
25076     res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
25077     if( res ){
25078       newLocktype = RESERVED_LOCK;
25079     }
25080   }
25081
25082   /* Acquire a PENDING lock
25083   */
25084   if( locktype==EXCLUSIVE_LOCK && res ){
25085     newLocktype = PENDING_LOCK;
25086     gotPendingLock = 0;
25087   }
25088
25089   /* Acquire an EXCLUSIVE lock
25090   */
25091   if( locktype==EXCLUSIVE_LOCK && res ){
25092     assert( pFile->locktype>=SHARED_LOCK );
25093     res = unlockReadLock(pFile);
25094     OSTRACE2("unreadlock = %d\n", res);
25095     res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
25096     if( res ){
25097       newLocktype = EXCLUSIVE_LOCK;
25098     }else{
25099       OSTRACE2("error-code = %d\n", GetLastError());
25100       getReadLock(pFile);
25101     }
25102   }
25103
25104   /* If we are holding a PENDING lock that ought to be released, then
25105   ** release it now.
25106   */
25107   if( gotPendingLock && locktype==SHARED_LOCK ){
25108     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
25109   }
25110
25111   /* Update the state of the lock has held in the file descriptor then
25112   ** return the appropriate result code.
25113   */
25114   if( res ){
25115     rc = SQLITE_OK;
25116   }else{
25117     OSTRACE4("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
25118            locktype, newLocktype);
25119     rc = SQLITE_BUSY;
25120   }
25121   pFile->locktype = newLocktype;
25122   return rc;
25123 }
25124
25125 /*
25126 ** This routine checks if there is a RESERVED lock held on the specified
25127 ** file by this or any other process. If such a lock is held, return
25128 ** non-zero, otherwise zero.
25129 */
25130 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
25131   int rc;
25132   winFile *pFile = (winFile*)id;
25133   assert( pFile!=0 );
25134   if( pFile->locktype>=RESERVED_LOCK ){
25135     rc = 1;
25136     OSTRACE3("TEST WR-LOCK %d %d (local)\n", pFile->h, rc);
25137   }else{
25138     rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
25139     if( rc ){
25140       UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
25141     }
25142     rc = !rc;
25143     OSTRACE3("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc);
25144   }
25145   *pResOut = rc;
25146   return SQLITE_OK;
25147 }
25148
25149 /*
25150 ** Lower the locking level on file descriptor id to locktype.  locktype
25151 ** must be either NO_LOCK or SHARED_LOCK.
25152 **
25153 ** If the locking level of the file descriptor is already at or below
25154 ** the requested locking level, this routine is a no-op.
25155 **
25156 ** It is not possible for this routine to fail if the second argument
25157 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
25158 ** might return SQLITE_IOERR;
25159 */
25160 static int winUnlock(sqlite3_file *id, int locktype){
25161   int type;
25162   winFile *pFile = (winFile*)id;
25163   int rc = SQLITE_OK;
25164   assert( pFile!=0 );
25165   assert( locktype<=SHARED_LOCK );
25166   OSTRACE5("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
25167           pFile->locktype, pFile->sharedLockByte);
25168   type = pFile->locktype;
25169   if( type>=EXCLUSIVE_LOCK ){
25170     UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
25171     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
25172       /* This should never happen.  We should always be able to
25173       ** reacquire the read lock */
25174       rc = SQLITE_IOERR_UNLOCK;
25175     }
25176   }
25177   if( type>=RESERVED_LOCK ){
25178     UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
25179   }
25180   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
25181     unlockReadLock(pFile);
25182   }
25183   if( type>=PENDING_LOCK ){
25184     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
25185   }
25186   pFile->locktype = locktype;
25187   return rc;
25188 }
25189
25190 /*
25191 ** Control and query of the open file handle.
25192 */
25193 static int winFileControl(sqlite3_file *id, int op, void *pArg){
25194   switch( op ){
25195     case SQLITE_FCNTL_LOCKSTATE: {
25196       *(int*)pArg = ((winFile*)id)->locktype;
25197       return SQLITE_OK;
25198     }
25199   }
25200   return SQLITE_ERROR;
25201 }
25202
25203 /*
25204 ** Return the sector size in bytes of the underlying block device for
25205 ** the specified file. This is almost always 512 bytes, but may be
25206 ** larger for some devices.
25207 **
25208 ** SQLite code assumes this function cannot fail. It also assumes that
25209 ** if two files are created in the same file-system directory (i.e.
25210 ** a database and its journal file) that the sector size will be the
25211 ** same for both.
25212 */
25213 static int winSectorSize(sqlite3_file *id){
25214   return SQLITE_DEFAULT_SECTOR_SIZE;
25215 }
25216
25217 /*
25218 ** Return a vector of device characteristics.
25219 */
25220 static int winDeviceCharacteristics(sqlite3_file *id){
25221   return 0;
25222 }
25223
25224 /*
25225 ** This vector defines all the methods that can operate on an
25226 ** sqlite3_file for win32.
25227 */
25228 static const sqlite3_io_methods winIoMethod = {
25229   1,                        /* iVersion */
25230   winClose,
25231   winRead,
25232   winWrite,
25233   winTruncate,
25234   winSync,
25235   winFileSize,
25236   winLock,
25237   winUnlock,
25238   winCheckReservedLock,
25239   winFileControl,
25240   winSectorSize,
25241   winDeviceCharacteristics
25242 };
25243
25244 /***************************************************************************
25245 ** Here ends the I/O methods that form the sqlite3_io_methods object.
25246 **
25247 ** The next block of code implements the VFS methods.
25248 ****************************************************************************/
25249
25250 /*
25251 ** Convert a UTF-8 filename into whatever form the underlying
25252 ** operating system wants filenames in.  Space to hold the result
25253 ** is obtained from malloc and must be freed by the calling
25254 ** function.
25255 */
25256 static void *convertUtf8Filename(const char *zFilename){
25257   void *zConverted = 0;
25258   if( isNT() ){
25259     zConverted = utf8ToUnicode(zFilename);
25260   }else{
25261     zConverted = utf8ToMbcs(zFilename);
25262   }
25263   /* caller will handle out of memory */
25264   return zConverted;
25265 }
25266
25267 /*
25268 ** Create a temporary file name in zBuf.  zBuf must be big enough to
25269 ** hold at pVfs->mxPathname characters.
25270 */
25271 static int getTempname(int nBuf, char *zBuf){
25272   static char zChars[] =
25273     "abcdefghijklmnopqrstuvwxyz"
25274     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
25275     "0123456789";
25276   size_t i, j;
25277   char zTempPath[MAX_PATH+1];
25278   if( sqlite3_temp_directory ){
25279     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
25280   }else if( isNT() ){
25281     char *zMulti;
25282     WCHAR zWidePath[MAX_PATH];
25283     GetTempPathW(MAX_PATH-30, zWidePath);
25284     zMulti = unicodeToUtf8(zWidePath);
25285     if( zMulti ){
25286       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
25287       free(zMulti);
25288     }else{
25289       return SQLITE_NOMEM;
25290     }
25291   }else{
25292     char *zUtf8;
25293     char zMbcsPath[MAX_PATH];
25294     GetTempPathA(MAX_PATH-30, zMbcsPath);
25295     zUtf8 = mbcsToUtf8(zMbcsPath);
25296     if( zUtf8 ){
25297       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
25298       free(zUtf8);
25299     }else{
25300       return SQLITE_NOMEM;
25301     }
25302   }
25303   for(i=strlen(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
25304   zTempPath[i] = 0;
25305   sqlite3_snprintf(nBuf-30, zBuf,
25306                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
25307   j = strlen(zBuf);
25308   sqlite3_randomness(20, &zBuf[j]);
25309   for(i=0; i<20; i++, j++){
25310     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
25311   }
25312   zBuf[j] = 0;
25313   OSTRACE2("TEMP FILENAME: %s\n", zBuf);
25314   return SQLITE_OK; 
25315 }
25316
25317 /*
25318 ** The return value of getLastErrorMsg
25319 ** is zero if the error message fits in the buffer, or non-zero
25320 ** otherwise (if the message was truncated).
25321 */
25322 static int getLastErrorMsg(int nBuf, char *zBuf){
25323   DWORD error = GetLastError();
25324
25325 #if SQLITE_OS_WINCE
25326   sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
25327 #else
25328   /* FormatMessage returns 0 on failure.  Otherwise it
25329   ** returns the number of TCHARs written to the output
25330   ** buffer, excluding the terminating null char.
25331   */
25332   if (!FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
25333                       NULL,
25334                       error,
25335                       0,
25336                       zBuf,
25337                       nBuf-1,
25338                       0))
25339   {
25340     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
25341   }
25342 #endif
25343
25344   return 0;
25345 }
25346
25347
25348 /*
25349 ** Open a file.
25350 */
25351 static int winOpen(
25352   sqlite3_vfs *pVfs,        /* Not used */
25353   const char *zName,        /* Name of the file (UTF-8) */
25354   sqlite3_file *id,         /* Write the SQLite file handle here */
25355   int flags,                /* Open mode flags */
25356   int *pOutFlags            /* Status return flags */
25357 ){
25358   HANDLE h;
25359   DWORD dwDesiredAccess;
25360   DWORD dwShareMode;
25361   DWORD dwCreationDisposition;
25362   DWORD dwFlagsAndAttributes = 0;
25363   int isTemp;
25364   winFile *pFile = (winFile*)id;
25365   void *zConverted;                 /* Filename in OS encoding */
25366   const char *zUtf8Name = zName;    /* Filename in UTF-8 encoding */
25367   char zTmpname[MAX_PATH+1];        /* Buffer used to create temp filename */
25368
25369   /* If the second argument to this function is NULL, generate a 
25370   ** temporary file name to use 
25371   */
25372   if( !zUtf8Name ){
25373     int rc = getTempname(MAX_PATH+1, zTmpname);
25374     if( rc!=SQLITE_OK ){
25375       return rc;
25376     }
25377     zUtf8Name = zTmpname;
25378   }
25379
25380   /* Convert the filename to the system encoding. */
25381   zConverted = convertUtf8Filename(zUtf8Name);
25382   if( zConverted==0 ){
25383     return SQLITE_NOMEM;
25384   }
25385
25386   if( flags & SQLITE_OPEN_READWRITE ){
25387     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
25388   }else{
25389     dwDesiredAccess = GENERIC_READ;
25390   }
25391   if( flags & SQLITE_OPEN_CREATE ){
25392     dwCreationDisposition = OPEN_ALWAYS;
25393   }else{
25394     dwCreationDisposition = OPEN_EXISTING;
25395   }
25396   if( flags & SQLITE_OPEN_MAIN_DB ){
25397     dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
25398   }else{
25399     dwShareMode = 0;
25400   }
25401   if( flags & SQLITE_OPEN_DELETEONCLOSE ){
25402 #if SQLITE_OS_WINCE
25403     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
25404 #else
25405     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
25406                                | FILE_ATTRIBUTE_HIDDEN
25407                                | FILE_FLAG_DELETE_ON_CLOSE;
25408 #endif
25409     isTemp = 1;
25410   }else{
25411     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
25412     isTemp = 0;
25413   }
25414   /* Reports from the internet are that performance is always
25415   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
25416   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
25417   if( isNT() ){
25418     h = CreateFileW((WCHAR*)zConverted,
25419        dwDesiredAccess,
25420        dwShareMode,
25421        NULL,
25422        dwCreationDisposition,
25423        dwFlagsAndAttributes,
25424        NULL
25425     );
25426   }else{
25427     h = CreateFileA((char*)zConverted,
25428        dwDesiredAccess,
25429        dwShareMode,
25430        NULL,
25431        dwCreationDisposition,
25432        dwFlagsAndAttributes,
25433        NULL
25434     );
25435   }
25436   if( h==INVALID_HANDLE_VALUE ){
25437     free(zConverted);
25438     if( flags & SQLITE_OPEN_READWRITE ){
25439       return winOpen(0, zName, id, 
25440              ((flags|SQLITE_OPEN_READONLY)&~SQLITE_OPEN_READWRITE), pOutFlags);
25441     }else{
25442       return SQLITE_CANTOPEN;
25443     }
25444   }
25445   if( pOutFlags ){
25446     if( flags & SQLITE_OPEN_READWRITE ){
25447       *pOutFlags = SQLITE_OPEN_READWRITE;
25448     }else{
25449       *pOutFlags = SQLITE_OPEN_READONLY;
25450     }
25451   }
25452   memset(pFile, 0, sizeof(*pFile));
25453   pFile->pMethod = &winIoMethod;
25454   pFile->h = h;
25455 #if SQLITE_OS_WINCE
25456   if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
25457                (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)
25458        && !winceCreateLock(zName, pFile)
25459   ){
25460     CloseHandle(h);
25461     free(zConverted);
25462     return SQLITE_CANTOPEN;
25463   }
25464   if( isTemp ){
25465     pFile->zDeleteOnClose = zConverted;
25466   }else
25467 #endif
25468   {
25469     free(zConverted);
25470   }
25471   OpenCounter(+1);
25472   return SQLITE_OK;
25473 }
25474
25475 /*
25476 ** Delete the named file.
25477 **
25478 ** Note that windows does not allow a file to be deleted if some other
25479 ** process has it open.  Sometimes a virus scanner or indexing program
25480 ** will open a journal file shortly after it is created in order to do
25481 ** whatever it does.  While this other process is holding the
25482 ** file open, we will be unable to delete it.  To work around this
25483 ** problem, we delay 100 milliseconds and try to delete again.  Up
25484 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
25485 ** up and returning an error.
25486 */
25487 #define MX_DELETION_ATTEMPTS 5
25488 static int winDelete(
25489   sqlite3_vfs *pVfs,          /* Not used on win32 */
25490   const char *zFilename,      /* Name of file to delete */
25491   int syncDir                 /* Not used on win32 */
25492 ){
25493   int cnt = 0;
25494   int rc;
25495   DWORD error;
25496   void *zConverted = convertUtf8Filename(zFilename);
25497   if( zConverted==0 ){
25498     return SQLITE_NOMEM;
25499   }
25500   SimulateIOError(return SQLITE_IOERR_DELETE);
25501   if( isNT() ){
25502     do{
25503       DeleteFileW(zConverted);
25504     }while(   (   ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
25505                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
25506            && (cnt++ < MX_DELETION_ATTEMPTS)
25507            && (Sleep(100), 1) );
25508   }else{
25509     do{
25510       DeleteFileA(zConverted);
25511     }while(   (   ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
25512                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
25513            && (cnt++ < MX_DELETION_ATTEMPTS)
25514            && (Sleep(100), 1) );
25515   }
25516   free(zConverted);
25517   OSTRACE2("DELETE \"%s\"\n", zFilename);
25518   return (   (rc==INVALID_FILE_ATTRIBUTES) 
25519           && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
25520 }
25521
25522 /*
25523 ** Check the existance and status of a file.
25524 */
25525 static int winAccess(
25526   sqlite3_vfs *pVfs,         /* Not used on win32 */
25527   const char *zFilename,     /* Name of file to check */
25528   int flags,                 /* Type of test to make on this file */
25529   int *pResOut               /* OUT: Result */
25530 ){
25531   DWORD attr;
25532   int rc;
25533   void *zConverted = convertUtf8Filename(zFilename);
25534   if( zConverted==0 ){
25535     return SQLITE_NOMEM;
25536   }
25537   if( isNT() ){
25538     attr = GetFileAttributesW((WCHAR*)zConverted);
25539   }else{
25540     attr = GetFileAttributesA((char*)zConverted);
25541   }
25542   free(zConverted);
25543   switch( flags ){
25544     case SQLITE_ACCESS_READ:
25545     case SQLITE_ACCESS_EXISTS:
25546       rc = attr!=INVALID_FILE_ATTRIBUTES;
25547       break;
25548     case SQLITE_ACCESS_READWRITE:
25549       rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
25550       break;
25551     default:
25552       assert(!"Invalid flags argument");
25553   }
25554   *pResOut = rc;
25555   return SQLITE_OK;
25556 }
25557
25558
25559 /*
25560 ** Turn a relative pathname into a full pathname.  Write the full
25561 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
25562 ** bytes in size.
25563 */
25564 static int winFullPathname(
25565   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
25566   const char *zRelative,        /* Possibly relative input path */
25567   int nFull,                    /* Size of output buffer in bytes */
25568   char *zFull                   /* Output buffer */
25569 ){
25570
25571 #if defined(__CYGWIN__)
25572   cygwin_conv_to_full_win32_path(zRelative, zFull);
25573   return SQLITE_OK;
25574 #endif
25575
25576 #if SQLITE_OS_WINCE
25577   /* WinCE has no concept of a relative pathname, or so I am told. */
25578   sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
25579   return SQLITE_OK;
25580 #endif
25581
25582 #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
25583   int nByte;
25584   void *zConverted;
25585   char *zOut;
25586   zConverted = convertUtf8Filename(zRelative);
25587   if( isNT() ){
25588     WCHAR *zTemp;
25589     nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
25590     zTemp = malloc( nByte*sizeof(zTemp[0]) );
25591     if( zTemp==0 ){
25592       free(zConverted);
25593       return SQLITE_NOMEM;
25594     }
25595     GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
25596     free(zConverted);
25597     zOut = unicodeToUtf8(zTemp);
25598     free(zTemp);
25599   }else{
25600     char *zTemp;
25601     nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
25602     zTemp = malloc( nByte*sizeof(zTemp[0]) );
25603     if( zTemp==0 ){
25604       free(zConverted);
25605       return SQLITE_NOMEM;
25606     }
25607     GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
25608     free(zConverted);
25609     zOut = mbcsToUtf8(zTemp);
25610     free(zTemp);
25611   }
25612   if( zOut ){
25613     sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
25614     free(zOut);
25615     return SQLITE_OK;
25616   }else{
25617     return SQLITE_NOMEM;
25618   }
25619 #endif
25620 }
25621
25622 #ifndef SQLITE_OMIT_LOAD_EXTENSION
25623 /*
25624 ** Interfaces for opening a shared library, finding entry points
25625 ** within the shared library, and closing the shared library.
25626 */
25627 /*
25628 ** Interfaces for opening a shared library, finding entry points
25629 ** within the shared library, and closing the shared library.
25630 */
25631 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
25632   HANDLE h;
25633   void *zConverted = convertUtf8Filename(zFilename);
25634   if( zConverted==0 ){
25635     return 0;
25636   }
25637   if( isNT() ){
25638     h = LoadLibraryW((WCHAR*)zConverted);
25639   }else{
25640     h = LoadLibraryA((char*)zConverted);
25641   }
25642   free(zConverted);
25643   return (void*)h;
25644 }
25645 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
25646   getLastErrorMsg(nBuf, zBufOut);
25647 }
25648 void *winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
25649 #if SQLITE_OS_WINCE
25650   /* The GetProcAddressA() routine is only available on wince. */
25651   return GetProcAddressA((HANDLE)pHandle, zSymbol);
25652 #else
25653   /* All other windows platforms expect GetProcAddress() to take
25654   ** an Ansi string regardless of the _UNICODE setting */
25655   return GetProcAddress((HANDLE)pHandle, zSymbol);
25656 #endif
25657 }
25658 void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
25659   FreeLibrary((HANDLE)pHandle);
25660 }
25661 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
25662   #define winDlOpen  0
25663   #define winDlError 0
25664   #define winDlSym   0
25665   #define winDlClose 0
25666 #endif
25667
25668
25669 /*
25670 ** Write up to nBuf bytes of randomness into zBuf.
25671 */
25672 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
25673   int n = 0;
25674   if( sizeof(SYSTEMTIME)<=nBuf-n ){
25675     SYSTEMTIME x;
25676     GetSystemTime(&x);
25677     memcpy(&zBuf[n], &x, sizeof(x));
25678     n += sizeof(x);
25679   }
25680   if( sizeof(DWORD)<=nBuf-n ){
25681     DWORD pid = GetCurrentProcessId();
25682     memcpy(&zBuf[n], &pid, sizeof(pid));
25683     n += sizeof(pid);
25684   }
25685   if( sizeof(DWORD)<=nBuf-n ){
25686     DWORD cnt = GetTickCount();
25687     memcpy(&zBuf[n], &cnt, sizeof(cnt));
25688     n += sizeof(cnt);
25689   }
25690   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
25691     LARGE_INTEGER i;
25692     QueryPerformanceCounter(&i);
25693     memcpy(&zBuf[n], &i, sizeof(i));
25694     n += sizeof(i);
25695   }
25696   return n;
25697 }
25698
25699
25700 /*
25701 ** Sleep for a little while.  Return the amount of time slept.
25702 */
25703 static int winSleep(sqlite3_vfs *pVfs, int microsec){
25704   Sleep((microsec+999)/1000);
25705   return ((microsec+999)/1000)*1000;
25706 }
25707
25708 /*
25709 ** The following variable, if set to a non-zero value, becomes the result
25710 ** returned from sqlite3OsCurrentTime().  This is used for testing.
25711 */
25712 #ifdef SQLITE_TEST
25713 SQLITE_API int sqlite3_current_time = 0;
25714 #endif
25715
25716 /*
25717 ** Find the current time (in Universal Coordinated Time).  Write the
25718 ** current time and date as a Julian Day number into *prNow and
25719 ** return 0.  Return 1 if the time and date cannot be found.
25720 */
25721 int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
25722   FILETIME ft;
25723   /* FILETIME structure is a 64-bit value representing the number of 
25724      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
25725   */
25726   double now;
25727 #if SQLITE_OS_WINCE
25728   SYSTEMTIME time;
25729   GetSystemTime(&time);
25730   /* if SystemTimeToFileTime() fails, it returns zero. */
25731   if (!SystemTimeToFileTime(&time,&ft)){
25732     return 1;
25733   }
25734 #else
25735   GetSystemTimeAsFileTime( &ft );
25736 #endif
25737   now = ((double)ft.dwHighDateTime) * 4294967296.0; 
25738   *prNow = (now + ft.dwLowDateTime)/864000000000.0 + 2305813.5;
25739 #ifdef SQLITE_TEST
25740   if( sqlite3_current_time ){
25741     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
25742   }
25743 #endif
25744   return 0;
25745 }
25746
25747 /*
25748 ** The idea is that this function works like a combination of
25749 ** GetLastError() and FormatMessage() on windows (or errno and
25750 ** strerror_r() on unix). After an error is returned by an OS
25751 ** function, SQLite calls this function with zBuf pointing to
25752 ** a buffer of nBuf bytes. The OS layer should populate the
25753 ** buffer with a nul-terminated UTF-8 encoded error message
25754 ** describing the last IO error to have occured within the calling
25755 ** thread.
25756 **
25757 ** If the error message is too large for the supplied buffer,
25758 ** it should be truncated. The return value of xGetLastError
25759 ** is zero if the error message fits in the buffer, or non-zero
25760 ** otherwise (if the message was truncated). If non-zero is returned,
25761 ** then it is not necessary to include the nul-terminator character
25762 ** in the output buffer.
25763 **
25764 ** Not supplying an error message will have no adverse effect
25765 ** on SQLite. It is fine to have an implementation that never
25766 ** returns an error message:
25767 **
25768 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
25769 **     assert(zBuf[0]=='\0');
25770 **     return 0;
25771 **   }
25772 **
25773 ** However if an error message is supplied, it will be incorporated
25774 ** by sqlite into the error message available to the user using
25775 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
25776 */
25777 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
25778   return getLastErrorMsg(nBuf, zBuf);
25779 }
25780
25781 /*
25782 ** Initialize and deinitialize the operating system interface.
25783 */
25784 SQLITE_API int sqlite3_os_init(void){
25785   static sqlite3_vfs winVfs = {
25786     1,                 /* iVersion */
25787     sizeof(winFile),   /* szOsFile */
25788     MAX_PATH,          /* mxPathname */
25789     0,                 /* pNext */
25790     "win32",           /* zName */
25791     0,                 /* pAppData */
25792  
25793     winOpen,           /* xOpen */
25794     winDelete,         /* xDelete */
25795     winAccess,         /* xAccess */
25796     winFullPathname,   /* xFullPathname */
25797     winDlOpen,         /* xDlOpen */
25798     winDlError,        /* xDlError */
25799     winDlSym,          /* xDlSym */
25800     winDlClose,        /* xDlClose */
25801     winRandomness,     /* xRandomness */
25802     winSleep,          /* xSleep */
25803     winCurrentTime,    /* xCurrentTime */
25804     winGetLastError    /* xGetLastError */
25805   };
25806   sqlite3_vfs_register(&winVfs, 1);
25807   return SQLITE_OK; 
25808 }
25809 SQLITE_API int sqlite3_os_end(void){ 
25810   return SQLITE_OK;
25811 }
25812
25813 #endif /* SQLITE_OS_WIN */
25814
25815 /************** End of os_win.c **********************************************/
25816 /************** Begin file bitvec.c ******************************************/
25817 /*
25818 ** 2008 February 16
25819 **
25820 ** The author disclaims copyright to this source code.  In place of
25821 ** a legal notice, here is a blessing:
25822 **
25823 **    May you do good and not evil.
25824 **    May you find forgiveness for yourself and forgive others.
25825 **    May you share freely, never taking more than you give.
25826 **
25827 *************************************************************************
25828 ** This file implements an object that represents a fixed-length
25829 ** bitmap.  Bits are numbered starting with 1.
25830 **
25831 ** A bitmap is used to record what pages a database file have been
25832 ** journalled during a transaction.  Usually only a few pages are
25833 ** journalled.  So the bitmap is usually sparse and has low cardinality.
25834 ** But sometimes (for example when during a DROP of a large table) most
25835 ** or all of the pages get journalled.  In those cases, the bitmap becomes
25836 ** dense.  The algorithm needs to handle both cases well.
25837 **
25838 ** The size of the bitmap is fixed when the object is created.
25839 **
25840 ** All bits are clear when the bitmap is created.  Individual bits
25841 ** may be set or cleared one at a time.
25842 **
25843 ** Test operations are about 100 times more common that set operations.
25844 ** Clear operations are exceedingly rare.  There are usually between
25845 ** 5 and 500 set operations per Bitvec object, though the number of sets can
25846 ** sometimes grow into tens of thousands or larger.  The size of the
25847 ** Bitvec object is the number of pages in the database file at the
25848 ** start of a transaction, and is thus usually less than a few thousand,
25849 ** but can be as large as 2 billion for a really big database.
25850 **
25851 ** @(#) $Id: bitvec.c,v 1.6 2008/06/20 14:59:51 danielk1977 Exp $
25852 */
25853
25854 #define BITVEC_SZ        512
25855 /* Round the union size down to the nearest pointer boundary, since that's how 
25856 ** it will be aligned within the Bitvec struct. */
25857 #define BITVEC_USIZE     (((BITVEC_SZ-12)/sizeof(Bitvec*))*sizeof(Bitvec*))
25858 #define BITVEC_NCHAR     BITVEC_USIZE
25859 #define BITVEC_NBIT      (BITVEC_NCHAR*8)
25860 #define BITVEC_NINT      (BITVEC_USIZE/4)
25861 #define BITVEC_MXHASH    (BITVEC_NINT/2)
25862 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
25863
25864 #define BITVEC_HASH(X)   (((X)*37)%BITVEC_NINT)
25865
25866 /*
25867 ** A bitmap is an instance of the following structure.
25868 **
25869 ** This bitmap records the existance of zero or more bits
25870 ** with values between 1 and iSize, inclusive.
25871 **
25872 ** There are three possible representations of the bitmap.
25873 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
25874 ** bitmap.  The least significant bit is bit 1.
25875 **
25876 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
25877 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
25878 **
25879 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
25880 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
25881 ** handles up to iDivisor separate values of i.  apSub[0] holds
25882 ** values between 1 and iDivisor.  apSub[1] holds values between
25883 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
25884 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
25885 ** to hold deal with values between 1 and iDivisor.
25886 */
25887 struct Bitvec {
25888   u32 iSize;      /* Maximum bit index */
25889   u32 nSet;       /* Number of bits that are set */
25890   u32 iDivisor;   /* Number of bits handled by each apSub[] entry */
25891   union {
25892     u8 aBitmap[BITVEC_NCHAR];    /* Bitmap representation */
25893     u32 aHash[BITVEC_NINT];      /* Hash table representation */
25894     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
25895   } u;
25896 };
25897
25898 /*
25899 ** Create a new bitmap object able to handle bits between 0 and iSize,
25900 ** inclusive.  Return a pointer to the new object.  Return NULL if 
25901 ** malloc fails.
25902 */
25903 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
25904   Bitvec *p;
25905   assert( sizeof(*p)==BITVEC_SZ );
25906   p = sqlite3MallocZero( sizeof(*p) );
25907   if( p ){
25908     p->iSize = iSize;
25909   }
25910   return p;
25911 }
25912
25913 /*
25914 ** Check to see if the i-th bit is set.  Return true or false.
25915 ** If p is NULL (if the bitmap has not been created) or if
25916 ** i is out of range, then return false.
25917 */
25918 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
25919   if( p==0 ) return 0;
25920   if( i>p->iSize || i==0 ) return 0;
25921   if( p->iSize<=BITVEC_NBIT ){
25922     i--;
25923     return (p->u.aBitmap[i/8] & (1<<(i&7)))!=0;
25924   }
25925   if( p->iDivisor>0 ){
25926     u32 bin = (i-1)/p->iDivisor;
25927     i = (i-1)%p->iDivisor + 1;
25928     return sqlite3BitvecTest(p->u.apSub[bin], i);
25929   }else{
25930     u32 h = BITVEC_HASH(i);
25931     while( p->u.aHash[h] ){
25932       if( p->u.aHash[h]==i ) return 1;
25933       h++;
25934       if( h>=BITVEC_NINT ) h = 0;
25935     }
25936     return 0;
25937   }
25938 }
25939
25940 /*
25941 ** Set the i-th bit.  Return 0 on success and an error code if
25942 ** anything goes wrong.
25943 */
25944 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
25945   u32 h;
25946   assert( p!=0 );
25947   assert( i>0 );
25948   assert( i<=p->iSize );
25949   if( p->iSize<=BITVEC_NBIT ){
25950     i--;
25951     p->u.aBitmap[i/8] |= 1 << (i&7);
25952     return SQLITE_OK;
25953   }
25954   if( p->iDivisor ){
25955     u32 bin = (i-1)/p->iDivisor;
25956     i = (i-1)%p->iDivisor + 1;
25957     if( p->u.apSub[bin]==0 ){
25958       sqlite3BeginBenignMalloc();
25959       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
25960       sqlite3EndBenignMalloc();
25961       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
25962     }
25963     return sqlite3BitvecSet(p->u.apSub[bin], i);
25964   }
25965   h = BITVEC_HASH(i);
25966   while( p->u.aHash[h] ){
25967     if( p->u.aHash[h]==i ) return SQLITE_OK;
25968     h++;
25969     if( h==BITVEC_NINT ) h = 0;
25970   }
25971   p->nSet++;
25972   if( p->nSet>=BITVEC_MXHASH ){
25973     int j, rc;
25974     u32 aiValues[BITVEC_NINT];
25975     memcpy(aiValues, p->u.aHash, sizeof(aiValues));
25976     memset(p->u.apSub, 0, sizeof(p->u.apSub[0])*BITVEC_NPTR);
25977     p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
25978     rc = sqlite3BitvecSet(p, i);
25979     for(j=0; j<BITVEC_NINT; j++){
25980       if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
25981     }
25982     return rc;
25983   }
25984   p->u.aHash[h] = i;
25985   return SQLITE_OK;
25986 }
25987
25988 /*
25989 ** Clear the i-th bit.  Return 0 on success and an error code if
25990 ** anything goes wrong.
25991 */
25992 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i){
25993   assert( p!=0 );
25994   assert( i>0 );
25995   if( p->iSize<=BITVEC_NBIT ){
25996     i--;
25997     p->u.aBitmap[i/8] &= ~(1 << (i&7));
25998   }else if( p->iDivisor ){
25999     u32 bin = (i-1)/p->iDivisor;
26000     i = (i-1)%p->iDivisor + 1;
26001     if( p->u.apSub[bin] ){
26002       sqlite3BitvecClear(p->u.apSub[bin], i);
26003     }
26004   }else{
26005     int j;
26006     u32 aiValues[BITVEC_NINT];
26007     memcpy(aiValues, p->u.aHash, sizeof(aiValues));
26008     memset(p->u.aHash, 0, sizeof(p->u.aHash[0])*BITVEC_NINT);
26009     p->nSet = 0;
26010     for(j=0; j<BITVEC_NINT; j++){
26011       if( aiValues[j] && aiValues[j]!=i ){
26012         sqlite3BitvecSet(p, aiValues[j]);
26013       }
26014     }
26015   }
26016 }
26017
26018 /*
26019 ** Destroy a bitmap object.  Reclaim all memory used.
26020 */
26021 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
26022   if( p==0 ) return;
26023   if( p->iDivisor ){
26024     int i;
26025     for(i=0; i<BITVEC_NPTR; i++){
26026       sqlite3BitvecDestroy(p->u.apSub[i]);
26027     }
26028   }
26029   sqlite3_free(p);
26030 }
26031
26032 #ifndef SQLITE_OMIT_BUILTIN_TEST
26033 /*
26034 ** Let V[] be an array of unsigned characters sufficient to hold
26035 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
26036 ** Then the following macros can be used to set, clear, or test
26037 ** individual bits within V.
26038 */
26039 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
26040 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
26041 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
26042
26043 /*
26044 ** This routine runs an extensive test of the Bitvec code.
26045 **
26046 ** The input is an array of integers that acts as a program
26047 ** to test the Bitvec.  The integers are opcodes followed
26048 ** by 0, 1, or 3 operands, depending on the opcode.  Another
26049 ** opcode follows immediately after the last operand.
26050 **
26051 ** There are 6 opcodes numbered from 0 through 5.  0 is the
26052 ** "halt" opcode and causes the test to end.
26053 **
26054 **    0          Halt and return the number of errors
26055 **    1 N S X    Set N bits beginning with S and incrementing by X
26056 **    2 N S X    Clear N bits beginning with S and incrementing by X
26057 **    3 N        Set N randomly chosen bits
26058 **    4 N        Clear N randomly chosen bits
26059 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
26060 **
26061 ** The opcodes 1 through 4 perform set and clear operations are performed
26062 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
26063 ** Opcode 5 works on the linear array only, not on the Bitvec.
26064 ** Opcode 5 is used to deliberately induce a fault in order to
26065 ** confirm that error detection works.
26066 **
26067 ** At the conclusion of the test the linear array is compared
26068 ** against the Bitvec object.  If there are any differences,
26069 ** an error is returned.  If they are the same, zero is returned.
26070 **
26071 ** If a memory allocation error occurs, return -1.
26072 */
26073 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
26074   Bitvec *pBitvec = 0;
26075   unsigned char *pV = 0;
26076   int rc = -1;
26077   int i, nx, pc, op;
26078
26079   /* Allocate the Bitvec to be tested and a linear array of
26080   ** bits to act as the reference */
26081   pBitvec = sqlite3BitvecCreate( sz );
26082   pV = sqlite3_malloc( (sz+7)/8 + 1 );
26083   if( pBitvec==0 || pV==0 ) goto bitvec_end;
26084   memset(pV, 0, (sz+7)/8 + 1);
26085
26086   /* Run the program */
26087   pc = 0;
26088   while( (op = aOp[pc])!=0 ){
26089     switch( op ){
26090       case 1:
26091       case 2:
26092       case 5: {
26093         nx = 4;
26094         i = aOp[pc+2] - 1;
26095         aOp[pc+2] += aOp[pc+3];
26096         break;
26097       }
26098       case 3:
26099       case 4: 
26100       default: {
26101         nx = 2;
26102         sqlite3_randomness(sizeof(i), &i);
26103         break;
26104       }
26105     }
26106     if( (--aOp[pc+1]) > 0 ) nx = 0;
26107     pc += nx;
26108     i = (i & 0x7fffffff)%sz;
26109     if( (op & 1)!=0 ){
26110       SETBIT(pV, (i+1));
26111       if( op!=5 ){
26112         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
26113       }
26114     }else{
26115       CLEARBIT(pV, (i+1));
26116       sqlite3BitvecClear(pBitvec, i+1);
26117     }
26118   }
26119
26120   /* Test to make sure the linear array exactly matches the
26121   ** Bitvec object.  Start with the assumption that they do
26122   ** match (rc==0).  Change rc to non-zero if a discrepancy
26123   ** is found.
26124   */
26125   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
26126           + sqlite3BitvecTest(pBitvec, 0);
26127   for(i=1; i<=sz; i++){
26128     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
26129       rc = i;
26130       break;
26131     }
26132   }
26133
26134   /* Free allocated structure */
26135 bitvec_end:
26136   sqlite3_free(pV);
26137   sqlite3BitvecDestroy(pBitvec);
26138   return rc;
26139 }
26140 #endif /* SQLITE_OMIT_BUILTIN_TEST */
26141
26142 /************** End of bitvec.c **********************************************/
26143 /************** Begin file pager.c *******************************************/
26144 /*
26145 ** 2001 September 15
26146 **
26147 ** The author disclaims copyright to this source code.  In place of
26148 ** a legal notice, here is a blessing:
26149 **
26150 **    May you do good and not evil.
26151 **    May you find forgiveness for yourself and forgive others.
26152 **    May you share freely, never taking more than you give.
26153 **
26154 *************************************************************************
26155 ** This is the implementation of the page cache subsystem or "pager".
26156 ** 
26157 ** The pager is used to access a database disk file.  It implements
26158 ** atomic commit and rollback through the use of a journal file that
26159 ** is separate from the database file.  The pager also implements file
26160 ** locking to prevent two processes from writing the same database
26161 ** file simultaneously, or one process from reading the database while
26162 ** another is writing.
26163 **
26164 ** @(#) $Id: pager.c,v 1.469 2008/08/02 03:50:39 drh Exp $
26165 */
26166 #ifndef SQLITE_OMIT_DISKIO
26167
26168 /*
26169 ** Macros for troubleshooting.  Normally turned off
26170 */
26171 #if 0
26172 #define sqlite3DebugPrintf printf
26173 #define PAGERTRACE1(X)       sqlite3DebugPrintf(X)
26174 #define PAGERTRACE2(X,Y)     sqlite3DebugPrintf(X,Y)
26175 #define PAGERTRACE3(X,Y,Z)   sqlite3DebugPrintf(X,Y,Z)
26176 #define PAGERTRACE4(X,Y,Z,W) sqlite3DebugPrintf(X,Y,Z,W)
26177 #define PAGERTRACE5(X,Y,Z,W,V) sqlite3DebugPrintf(X,Y,Z,W,V)
26178 #else
26179 #define PAGERTRACE1(X)
26180 #define PAGERTRACE2(X,Y)
26181 #define PAGERTRACE3(X,Y,Z)
26182 #define PAGERTRACE4(X,Y,Z,W)
26183 #define PAGERTRACE5(X,Y,Z,W,V)
26184 #endif
26185
26186 /*
26187 ** The following two macros are used within the PAGERTRACEX() macros above
26188 ** to print out file-descriptors. 
26189 **
26190 ** PAGERID() takes a pointer to a Pager struct as its argument. The
26191 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
26192 ** struct as its argument.
26193 */
26194 #define PAGERID(p) ((int)(p->fd))
26195 #define FILEHANDLEID(fd) ((int)fd)
26196
26197 /*
26198 ** The page cache as a whole is always in one of the following
26199 ** states:
26200 **
26201 **   PAGER_UNLOCK        The page cache is not currently reading or 
26202 **                       writing the database file.  There is no
26203 **                       data held in memory.  This is the initial
26204 **                       state.
26205 **
26206 **   PAGER_SHARED        The page cache is reading the database.
26207 **                       Writing is not permitted.  There can be
26208 **                       multiple readers accessing the same database
26209 **                       file at the same time.
26210 **
26211 **   PAGER_RESERVED      This process has reserved the database for writing
26212 **                       but has not yet made any changes.  Only one process
26213 **                       at a time can reserve the database.  The original
26214 **                       database file has not been modified so other
26215 **                       processes may still be reading the on-disk
26216 **                       database file.
26217 **
26218 **   PAGER_EXCLUSIVE     The page cache is writing the database.
26219 **                       Access is exclusive.  No other processes or
26220 **                       threads can be reading or writing while one
26221 **                       process is writing.
26222 **
26223 **   PAGER_SYNCED        The pager moves to this state from PAGER_EXCLUSIVE
26224 **                       after all dirty pages have been written to the
26225 **                       database file and the file has been synced to
26226 **                       disk. All that remains to do is to remove or
26227 **                       truncate the journal file and the transaction 
26228 **                       will be committed.
26229 **
26230 ** The page cache comes up in PAGER_UNLOCK.  The first time a
26231 ** sqlite3PagerGet() occurs, the state transitions to PAGER_SHARED.
26232 ** After all pages have been released using sqlite_page_unref(),
26233 ** the state transitions back to PAGER_UNLOCK.  The first time
26234 ** that sqlite3PagerWrite() is called, the state transitions to
26235 ** PAGER_RESERVED.  (Note that sqlite3PagerWrite() can only be
26236 ** called on an outstanding page which means that the pager must
26237 ** be in PAGER_SHARED before it transitions to PAGER_RESERVED.)
26238 ** PAGER_RESERVED means that there is an open rollback journal.
26239 ** The transition to PAGER_EXCLUSIVE occurs before any changes
26240 ** are made to the database file, though writes to the rollback
26241 ** journal occurs with just PAGER_RESERVED.  After an sqlite3PagerRollback()
26242 ** or sqlite3PagerCommitPhaseTwo(), the state can go back to PAGER_SHARED,
26243 ** or it can stay at PAGER_EXCLUSIVE if we are in exclusive access mode.
26244 */
26245 #define PAGER_UNLOCK      0
26246 #define PAGER_SHARED      1   /* same as SHARED_LOCK */
26247 #define PAGER_RESERVED    2   /* same as RESERVED_LOCK */
26248 #define PAGER_EXCLUSIVE   4   /* same as EXCLUSIVE_LOCK */
26249 #define PAGER_SYNCED      5
26250
26251 /*
26252 ** If the SQLITE_BUSY_RESERVED_LOCK macro is set to true at compile-time,
26253 ** then failed attempts to get a reserved lock will invoke the busy callback.
26254 ** This is off by default.  To see why, consider the following scenario:
26255 ** 
26256 ** Suppose thread A already has a shared lock and wants a reserved lock.
26257 ** Thread B already has a reserved lock and wants an exclusive lock.  If
26258 ** both threads are using their busy callbacks, it might be a long time
26259 ** be for one of the threads give up and allows the other to proceed.
26260 ** But if the thread trying to get the reserved lock gives up quickly
26261 ** (if it never invokes its busy callback) then the contention will be
26262 ** resolved quickly.
26263 */
26264 #ifndef SQLITE_BUSY_RESERVED_LOCK
26265 # define SQLITE_BUSY_RESERVED_LOCK 0
26266 #endif
26267
26268 /*
26269 ** This macro rounds values up so that if the value is an address it
26270 ** is guaranteed to be an address that is aligned to an 8-byte boundary.
26271 */
26272 #define FORCE_ALIGNMENT(X)   (((X)+7)&~7)
26273
26274 typedef struct PgHdr PgHdr;
26275
26276 /*
26277 ** Each pager stores all currently unreferenced pages in a list sorted
26278 ** in least-recently-used (LRU) order (i.e. the first item on the list has 
26279 ** not been referenced in a long time, the last item has been recently
26280 ** used). An instance of this structure is included as part of each
26281 ** pager structure for this purpose (variable Pager.lru).
26282 **
26283 ** Additionally, if memory-management is enabled, all unreferenced pages 
26284 ** are stored in a global LRU list (global variable sqlite3LruPageList).
26285 **
26286 ** In both cases, the PagerLruList.pFirstSynced variable points to
26287 ** the first page in the corresponding list that does not require an
26288 ** fsync() operation before its memory can be reclaimed. If no such
26289 ** page exists, PagerLruList.pFirstSynced is set to NULL.
26290 */
26291 typedef struct PagerLruList PagerLruList;
26292 struct PagerLruList {
26293   PgHdr *pFirst;         /* First page in LRU list */
26294   PgHdr *pLast;          /* Last page in LRU list (the most recently used) */
26295   PgHdr *pFirstSynced;   /* First page in list with PgHdr.needSync==0 */
26296 };
26297
26298 /*
26299 ** The following structure contains the next and previous pointers used
26300 ** to link a PgHdr structure into a PagerLruList linked list. 
26301 */
26302 typedef struct PagerLruLink PagerLruLink;
26303 struct PagerLruLink {
26304   PgHdr *pNext;
26305   PgHdr *pPrev;
26306 };
26307
26308 /*
26309 ** Each in-memory image of a page begins with the following header.
26310 ** This header is only visible to this pager module.  The client
26311 ** code that calls pager sees only the data that follows the header.
26312 **
26313 ** Client code should call sqlite3PagerWrite() on a page prior to making
26314 ** any modifications to that page.  The first time sqlite3PagerWrite()
26315 ** is called, the original page contents are written into the rollback
26316 ** journal and PgHdr.inJournal and PgHdr.needSync are set.  Later, once
26317 ** the journal page has made it onto the disk surface, PgHdr.needSync
26318 ** is cleared.  The modified page cannot be written back into the original
26319 ** database file until the journal pages has been synced to disk and the
26320 ** PgHdr.needSync has been cleared.
26321 **
26322 ** The PgHdr.dirty flag is set when sqlite3PagerWrite() is called and
26323 ** is cleared again when the page content is written back to the original
26324 ** database file.
26325 **
26326 ** Details of important structure elements:
26327 **
26328 ** needSync
26329 **
26330 **     If this is true, this means that it is not safe to write the page
26331 **     content to the database because the original content needed
26332 **     for rollback has not by synced to the main rollback journal.
26333 **     The original content may have been written to the rollback journal
26334 **     but it has not yet been synced.  So we cannot write to the database
26335 **     file because power failure might cause the page in the journal file
26336 **     to never reach the disk.  It is as if the write to the journal file
26337 **     does not occur until the journal file is synced.
26338 **     
26339 **     This flag is false if the page content exactly matches what
26340 **     currently exists in the database file.  The needSync flag is also
26341 **     false if the original content has been written to the main rollback
26342 **     journal and synced.  If the page represents a new page that has
26343 **     been added onto the end of the database during the current
26344 **     transaction, the needSync flag is true until the original database
26345 **     size in the journal header has been synced to disk.
26346 **
26347 ** inJournal
26348 **
26349 **     This is true if the original page has been written into the main
26350 **     rollback journal.  This is always false for new pages added to
26351 **     the end of the database file during the current transaction.
26352 **     And this flag says nothing about whether or not the journal
26353 **     has been synced to disk.  For pages that are in the original
26354 **     database file, the following expression should always be true:
26355 **
26356 **       inJournal = sqlite3BitvecTest(pPager->pInJournal, pgno)
26357 **
26358 **     The pPager->pInJournal object is only valid for the original
26359 **     pages of the database, not new pages that are added to the end
26360 **     of the database, so obviously the above expression cannot be
26361 **     valid for new pages.  For new pages inJournal is always 0.
26362 **
26363 ** dirty
26364 **
26365 **     When true, this means that the content of the page has been
26366 **     modified and needs to be written back to the database file.
26367 **     If false, it means that either the content of the page is
26368 **     unchanged or else the content is unimportant and we do not
26369 **     care whether or not it is preserved.
26370 **
26371 ** alwaysRollback
26372 **
26373 **     This means that the sqlite3PagerDontRollback() API should be
26374 **     ignored for this page.  The DontRollback() API attempts to say
26375 **     that the content of the page on disk is unimportant (it is an
26376 **     unused page on the freelist) so that it is unnecessary to 
26377 **     rollback changes to this page because the content of the page
26378 **     can change without changing the meaning of the database.  This
26379 **     flag overrides any DontRollback() attempt.  This flag is set
26380 **     when a page that originally contained valid data is added to
26381 **     the freelist.  Later in the same transaction, this page might
26382 **     be pulled from the freelist and reused for something different
26383 **     and at that point the DontRollback() API will be called because
26384 **     pages taken from the freelist do not need to be protected by
26385 **     the rollback journal.  But this flag says that the page was
26386 **     not originally part of the freelist so that it still needs to
26387 **     be rolled back in spite of any subsequent DontRollback() calls.
26388 **
26389 ** needRead 
26390 **
26391 **     This flag means (when true) that the content of the page has
26392 **     not yet been loaded from disk.  The in-memory content is just
26393 **     garbage.  (Actually, we zero the content, but you should not
26394 **     make any assumptions about the content nevertheless.)  If the
26395 **     content is needed in the future, it should be read from the
26396 **     original database file.
26397 */
26398 struct PgHdr {
26399   Pager *pPager;                 /* The pager to which this page belongs */
26400   Pgno pgno;                     /* The page number for this page */
26401   PgHdr *pNextHash, *pPrevHash;  /* Hash collision chain for PgHdr.pgno */
26402   PagerLruLink free;             /* Next and previous free pages */
26403   PgHdr *pNextAll;               /* A list of all pages */
26404   u8 inJournal;                  /* TRUE if has been written to journal */
26405   u8 dirty;                      /* TRUE if we need to write back changes */
26406   u8 needSync;                   /* Sync journal before writing this page */
26407   u8 alwaysRollback;             /* Disable DontRollback() for this page */
26408   u8 needRead;                   /* Read content if PagerWrite() is called */
26409   short int nRef;                /* Number of users of this page */
26410   PgHdr *pDirty, *pPrevDirty;    /* Dirty pages */
26411 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
26412   PgHdr *pPrevAll;               /* A list of all pages */
26413   PagerLruLink gfree;            /* Global list of nRef==0 pages */
26414 #endif
26415 #ifdef SQLITE_CHECK_PAGES
26416   u32 pageHash;
26417 #endif
26418   void *pData;                   /* Page data */
26419   /* Pager.nExtra bytes of local data appended to this header */
26420 };
26421
26422 /*
26423 ** For an in-memory only database, some extra information is recorded about
26424 ** each page so that changes can be rolled back.  (Journal files are not
26425 ** used for in-memory databases.)  The following information is added to
26426 ** the end of every EXTRA block for in-memory databases.
26427 **
26428 ** This information could have been added directly to the PgHdr structure.
26429 ** But then it would take up an extra 8 bytes of storage on every PgHdr
26430 ** even for disk-based databases.  Splitting it out saves 8 bytes.  This
26431 ** is only a savings of 0.8% but those percentages add up.
26432 */
26433 typedef struct PgHistory PgHistory;
26434 struct PgHistory {
26435   u8 *pOrig;     /* Original page text.  Restore to this on a full rollback */
26436   u8 *pStmt;     /* Text as it was at the beginning of the current statement */
26437   PgHdr *pNextStmt, *pPrevStmt;  /* List of pages in the statement journal */
26438   u8 inStmt;                     /* TRUE if in the statement subjournal */
26439 };
26440
26441 /*
26442 ** A macro used for invoking the codec if there is one
26443 */
26444 #ifdef SQLITE_HAS_CODEC
26445 # define CODEC1(P,D,N,X) if( P->xCodec!=0 ){ P->xCodec(P->pCodecArg,D,N,X); }
26446 # define CODEC2(P,D,N,X) ((char*)(P->xCodec!=0?P->xCodec(P->pCodecArg,D,N,X):D))
26447 #else
26448 # define CODEC1(P,D,N,X) /* NO-OP */
26449 # define CODEC2(P,D,N,X) ((char*)D)
26450 #endif
26451
26452 /*
26453 ** Convert a pointer to a PgHdr into a pointer to its data
26454 ** and back again.
26455 */
26456 #define PGHDR_TO_DATA(P)    ((P)->pData)
26457 #define PGHDR_TO_EXTRA(G,P) ((void*)&((G)[1]))
26458 #define PGHDR_TO_HIST(P,PGR)  \
26459             ((PgHistory*)&((char*)(&(P)[1]))[(PGR)->nExtra])
26460
26461 /*
26462 ** A open page cache is an instance of the following structure.
26463 **
26464 ** Pager.errCode may be set to SQLITE_IOERR, SQLITE_CORRUPT, or
26465 ** or SQLITE_FULL. Once one of the first three errors occurs, it persists
26466 ** and is returned as the result of every major pager API call.  The
26467 ** SQLITE_FULL return code is slightly different. It persists only until the
26468 ** next successful rollback is performed on the pager cache. Also,
26469 ** SQLITE_FULL does not affect the sqlite3PagerGet() and sqlite3PagerLookup()
26470 ** APIs, they may still be used successfully.
26471 */
26472 struct Pager {
26473   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
26474   u8 journalOpen;             /* True if journal file descriptors is valid */
26475   u8 journalStarted;          /* True if header of journal is synced */
26476   u8 useJournal;              /* Use a rollback journal on this file */
26477   u8 noReadlock;              /* Do not bother to obtain readlocks */
26478   u8 stmtOpen;                /* True if the statement subjournal is open */
26479   u8 stmtInUse;               /* True we are in a statement subtransaction */
26480   u8 stmtAutoopen;            /* Open stmt journal when main journal is opened*/
26481   u8 noSync;                  /* Do not sync the journal if true */
26482   u8 fullSync;                /* Do extra syncs of the journal for robustness */
26483   u8 sync_flags;              /* One of SYNC_NORMAL or SYNC_FULL */
26484   u8 state;                   /* PAGER_UNLOCK, _SHARED, _RESERVED, etc. */
26485   u8 tempFile;                /* zFilename is a temporary file */
26486   u8 readOnly;                /* True for a read-only database */
26487   u8 needSync;                /* True if an fsync() is needed on the journal */
26488   u8 dirtyCache;              /* True if cached pages have changed */
26489   u8 alwaysRollback;          /* Disable DontRollback() for all pages */
26490   u8 memDb;                   /* True to inhibit all file I/O */
26491   u8 setMaster;               /* True if a m-j name has been written to jrnl */
26492   u8 doNotSync;               /* Boolean. While true, do not spill the cache */
26493   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
26494   u8 journalMode;             /* On of the PAGER_JOURNALMODE_* values */
26495   u8 dbModified;              /* True if there are any changes to the Db */
26496   u8 changeCountDone;         /* Set after incrementing the change-counter */
26497   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
26498   int errCode;                /* One of several kinds of errors */
26499   int dbSize;                 /* Number of pages in the file */
26500   int origDbSize;             /* dbSize before the current change */
26501   int stmtSize;               /* Size of database (in pages) at stmt_begin() */
26502   int nRec;                   /* Number of pages written to the journal */
26503   u32 cksumInit;              /* Quasi-random value added to every checksum */
26504   int stmtNRec;               /* Number of records in stmt subjournal */
26505   int nExtra;                 /* Add this many bytes to each in-memory page */
26506   int pageSize;               /* Number of bytes in a page */
26507   int nPage;                  /* Total number of in-memory pages */
26508   int nRef;                   /* Number of in-memory pages with PgHdr.nRef>0 */
26509   int mxPage;                 /* Maximum number of pages to hold in cache */
26510   Pgno mxPgno;                /* Maximum allowed size of the database */
26511   Bitvec *pInJournal;         /* One bit for each page in the database file */
26512   Bitvec *pInStmt;            /* One bit for each page in the database */
26513   char *zFilename;            /* Name of the database file */
26514   char *zJournal;             /* Name of the journal file */
26515   char *zDirectory;           /* Directory hold database and journal files */
26516   sqlite3_file *fd, *jfd;     /* File descriptors for database and journal */
26517   sqlite3_file *stfd;         /* File descriptor for the statement subjournal*/
26518   BusyHandler *pBusyHandler;  /* Pointer to sqlite.busyHandler */
26519   PagerLruList lru;           /* LRU list of free pages */
26520   PgHdr *pAll;                /* List of all pages */
26521   PgHdr *pStmt;               /* List of pages in the statement subjournal */
26522   PgHdr *pDirty;              /* List of all dirty pages */
26523   i64 journalOff;             /* Current byte offset in the journal file */
26524   i64 journalHdr;             /* Byte offset to previous journal header */
26525   i64 stmtHdrOff;             /* First journal header written this statement */
26526   i64 stmtCksum;              /* cksumInit when statement was started */
26527   i64 stmtJSize;              /* Size of journal at stmt_begin() */
26528   int sectorSize;             /* Assumed sector size during rollback */
26529 #ifdef SQLITE_TEST
26530   int nHit, nMiss;            /* Cache hits and missing */
26531   int nRead, nWrite;          /* Database pages read/written */
26532 #endif
26533   void (*xDestructor)(DbPage*,int); /* Call this routine when freeing pages */
26534   void (*xReiniter)(DbPage*,int);   /* Call this routine when reloading pages */
26535 #ifdef SQLITE_HAS_CODEC
26536   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
26537   void *pCodecArg;            /* First argument to xCodec() */
26538 #endif
26539   int nHash;                  /* Size of the pager hash table */
26540   PgHdr **aHash;              /* Hash table to map page number to PgHdr */
26541 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
26542   Pager *pNext;               /* Doubly linked list of pagers on which */
26543   Pager *pPrev;               /* sqlite3_release_memory() will work */
26544   volatile int iInUseMM;      /* Non-zero if unavailable to MM */
26545   volatile int iInUseDB;      /* Non-zero if in sqlite3_release_memory() */
26546 #endif
26547   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
26548   char dbFileVers[16];        /* Changes whenever database file changes */
26549   i64 journalSizeLimit;       /* Size limit for persistent journal files */
26550 };
26551
26552 /*
26553 ** The following global variables hold counters used for
26554 ** testing purposes only.  These variables do not exist in
26555 ** a non-testing build.  These variables are not thread-safe.
26556 */
26557 #ifdef SQLITE_TEST
26558 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
26559 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
26560 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
26561 SQLITE_API int sqlite3_pager_pgfree_count = 0;    /* Number of cache pages freed */
26562 # define PAGER_INCR(v)  v++
26563 #else
26564 # define PAGER_INCR(v)
26565 #endif
26566
26567 /*
26568 ** The following variable points to the head of a double-linked list
26569 ** of all pagers that are eligible for page stealing by the
26570 ** sqlite3_release_memory() interface.  Access to this list is
26571 ** protected by the SQLITE_MUTEX_STATIC_MEM2 mutex.
26572 */
26573 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
26574 static Pager *sqlite3PagerList = 0;
26575 static PagerLruList sqlite3LruPageList = {0, 0, 0};
26576 #endif
26577
26578
26579 /*
26580 ** Journal files begin with the following magic string.  The data
26581 ** was obtained from /dev/random.  It is used only as a sanity check.
26582 **
26583 ** Since version 2.8.0, the journal format contains additional sanity
26584 ** checking information.  If the power fails while the journal is begin
26585 ** written, semi-random garbage data might appear in the journal
26586 ** file after power is restored.  If an attempt is then made
26587 ** to roll the journal back, the database could be corrupted.  The additional
26588 ** sanity checking data is an attempt to discover the garbage in the
26589 ** journal and ignore it.
26590 **
26591 ** The sanity checking information for the new journal format consists
26592 ** of a 32-bit checksum on each page of data.  The checksum covers both
26593 ** the page number and the pPager->pageSize bytes of data for the page.
26594 ** This cksum is initialized to a 32-bit random value that appears in the
26595 ** journal file right after the header.  The random initializer is important,
26596 ** because garbage data that appears at the end of a journal is likely
26597 ** data that was once in other files that have now been deleted.  If the
26598 ** garbage data came from an obsolete journal file, the checksums might
26599 ** be correct.  But by initializing the checksum to random value which
26600 ** is different for every journal, we minimize that risk.
26601 */
26602 static const unsigned char aJournalMagic[] = {
26603   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
26604 };
26605
26606 /*
26607 ** The size of the header and of each page in the journal is determined
26608 ** by the following macros.
26609 */
26610 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
26611
26612 /*
26613 ** The journal header size for this pager. In the future, this could be
26614 ** set to some value read from the disk controller. The important
26615 ** characteristic is that it is the same size as a disk sector.
26616 */
26617 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
26618
26619 /*
26620 ** The macro MEMDB is true if we are dealing with an in-memory database.
26621 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
26622 ** the value of MEMDB will be a constant and the compiler will optimize
26623 ** out code that would never execute.
26624 */
26625 #ifdef SQLITE_OMIT_MEMORYDB
26626 # define MEMDB 0
26627 #else
26628 # define MEMDB pPager->memDb
26629 #endif
26630
26631 /*
26632 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
26633 ** reserved for working around a windows/posix incompatibility). It is
26634 ** used in the journal to signify that the remainder of the journal file 
26635 ** is devoted to storing a master journal name - there are no more pages to
26636 ** roll back. See comments for function writeMasterJournal() for details.
26637 */
26638 /* #define PAGER_MJ_PGNO(x) (PENDING_BYTE/((x)->pageSize)) */
26639 #define PAGER_MJ_PGNO(x) ((PENDING_BYTE/((x)->pageSize))+1)
26640
26641 /*
26642 ** The maximum legal page number is (2^31 - 1).
26643 */
26644 #define PAGER_MAX_PGNO 2147483647
26645
26646 /*
26647 ** The pagerEnter() and pagerLeave() routines acquire and release
26648 ** a mutex on each pager.  The mutex is recursive.
26649 **
26650 ** This is a special-purpose mutex.  It only provides mutual exclusion
26651 ** between the Btree and the Memory Management sqlite3_release_memory()
26652 ** function.  It does not prevent, for example, two Btrees from accessing
26653 ** the same pager at the same time.  Other general-purpose mutexes in
26654 ** the btree layer handle that chore.
26655 */
26656 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
26657   static void pagerEnter(Pager *p){
26658     p->iInUseDB++;
26659     if( p->iInUseMM && p->iInUseDB==1 ){
26660 #ifndef SQLITE_MUTEX_NOOP
26661       sqlite3_mutex *mutex;
26662       mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM2);
26663 #endif
26664       p->iInUseDB = 0;
26665       sqlite3_mutex_enter(mutex);
26666       p->iInUseDB = 1;
26667       sqlite3_mutex_leave(mutex);
26668     }
26669     assert( p->iInUseMM==0 );
26670   }
26671   static void pagerLeave(Pager *p){
26672     p->iInUseDB--;
26673     assert( p->iInUseDB>=0 );
26674   }
26675 #else
26676 # define pagerEnter(X)
26677 # define pagerLeave(X)
26678 #endif
26679
26680 /*
26681 ** Add page pPg to the end of the linked list managed by structure
26682 ** pList (pPg becomes the last entry in the list - the most recently 
26683 ** used). Argument pLink should point to either pPg->free or pPg->gfree,
26684 ** depending on whether pPg is being added to the pager-specific or
26685 ** global LRU list.
26686 */
26687 static void listAdd(PagerLruList *pList, PagerLruLink *pLink, PgHdr *pPg){
26688   pLink->pNext = 0;
26689   pLink->pPrev = pList->pLast;
26690
26691 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
26692   assert(pLink==&pPg->free || pLink==&pPg->gfree);
26693   assert(pLink==&pPg->gfree || pList!=&sqlite3LruPageList);
26694 #endif
26695
26696   if( pList->pLast ){
26697     int iOff = (char *)pLink - (char *)pPg;
26698     PagerLruLink *pLastLink = (PagerLruLink *)(&((u8 *)pList->pLast)[iOff]);
26699     pLastLink->pNext = pPg;
26700   }else{
26701     assert(!pList->pFirst);
26702     pList->pFirst = pPg;
26703   }
26704
26705   pList->pLast = pPg;
26706   if( !pList->pFirstSynced && pPg->needSync==0 ){
26707     pList->pFirstSynced = pPg;
26708   }
26709 }
26710
26711 /*
26712 ** Remove pPg from the list managed by the structure pointed to by pList.
26713 **
26714 ** Argument pLink should point to either pPg->free or pPg->gfree, depending 
26715 ** on whether pPg is being added to the pager-specific or global LRU list.
26716 */
26717 static void listRemove(PagerLruList *pList, PagerLruLink *pLink, PgHdr *pPg){
26718   int iOff = (char *)pLink - (char *)pPg;
26719
26720 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
26721   assert(pLink==&pPg->free || pLink==&pPg->gfree);
26722   assert(pLink==&pPg->gfree || pList!=&sqlite3LruPageList);
26723 #endif
26724
26725   if( pPg==pList->pFirst ){
26726     pList->pFirst = pLink->pNext;
26727   }
26728   if( pPg==pList->pLast ){
26729     pList->pLast = pLink->pPrev;
26730   }
26731   if( pLink->pPrev ){
26732     PagerLruLink *pPrevLink = (PagerLruLink *)(&((u8 *)pLink->pPrev)[iOff]);
26733     pPrevLink->pNext = pLink->pNext;
26734   }
26735   if( pLink->pNext ){
26736     PagerLruLink *pNextLink = (PagerLruLink *)(&((u8 *)pLink->pNext)[iOff]);
26737     pNextLink->pPrev = pLink->pPrev;
26738   }
26739   if( pPg==pList->pFirstSynced ){
26740     PgHdr *p = pLink->pNext;
26741     while( p && p->needSync ){
26742       PagerLruLink *pL = (PagerLruLink *)(&((u8 *)p)[iOff]);
26743       p = pL->pNext;
26744     }
26745     pList->pFirstSynced = p;
26746   }
26747
26748   pLink->pNext = pLink->pPrev = 0;
26749 }
26750
26751 /* 
26752 ** Add page pPg to the list of free pages for the pager. If 
26753 ** memory-management is enabled, also add the page to the global 
26754 ** list of free pages.
26755 */
26756 static void lruListAdd(PgHdr *pPg){
26757   listAdd(&pPg->pPager->lru, &pPg->free, pPg);
26758 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
26759   if( !pPg->pPager->memDb ){
26760     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU));
26761     listAdd(&sqlite3LruPageList, &pPg->gfree, pPg);
26762     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU));
26763   }
26764 #endif
26765 }
26766
26767 /* 
26768 ** Remove page pPg from the list of free pages for the associated pager.
26769 ** If memory-management is enabled, also remove pPg from the global list
26770 ** of free pages.
26771 */
26772 static void lruListRemove(PgHdr *pPg){
26773   listRemove(&pPg->pPager->lru, &pPg->free, pPg);
26774 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
26775   if( !pPg->pPager->memDb ){
26776     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU));
26777     listRemove(&sqlite3LruPageList, &pPg->gfree, pPg);
26778     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU));
26779   }
26780 #endif
26781 }
26782
26783 /* 
26784 ** This function is called just after the needSync flag has been cleared
26785 ** from all pages managed by pPager (usually because the journal file
26786 ** has just been synced). It updates the pPager->lru.pFirstSynced variable
26787 ** and, if memory-management is enabled, the sqlite3LruPageList.pFirstSynced
26788 ** variable also.
26789 */
26790 static void lruListSetFirstSynced(Pager *pPager){
26791   pPager->lru.pFirstSynced = pPager->lru.pFirst;
26792 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
26793   if( !pPager->memDb ){
26794     PgHdr *p;
26795     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU));
26796     for(p=sqlite3LruPageList.pFirst; p && p->needSync; p=p->gfree.pNext);
26797     assert(p==pPager->lru.pFirstSynced || p==sqlite3LruPageList.pFirstSynced);
26798     sqlite3LruPageList.pFirstSynced = p;
26799     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU));
26800   }
26801 #endif
26802 }
26803
26804 /*
26805 ** Return true if page *pPg has already been written to the statement
26806 ** journal (or statement snapshot has been created, if *pPg is part
26807 ** of an in-memory database).
26808 */
26809 static int pageInStatement(PgHdr *pPg){
26810   Pager *pPager = pPg->pPager;
26811   if( MEMDB ){
26812     return PGHDR_TO_HIST(pPg, pPager)->inStmt;
26813   }else{
26814     return sqlite3BitvecTest(pPager->pInStmt, pPg->pgno);
26815   }
26816 }
26817
26818 /*
26819 ** Change the size of the pager hash table to N.  N must be a power
26820 ** of two.
26821 */
26822 static void pager_resize_hash_table(Pager *pPager, int N){
26823   PgHdr **aHash, *pPg;
26824   assert( N>0 && (N&(N-1))==0 );
26825 #ifdef SQLITE_MALLOC_SOFT_LIMIT
26826   if( N*sizeof(aHash[0])>SQLITE_MALLOC_SOFT_LIMIT ){
26827     N = SQLITE_MALLOC_SOFT_LIMIT/sizeof(aHash[0]);
26828   }
26829   if( N==pPager->nHash ) return;
26830 #endif
26831   pagerLeave(pPager);
26832   if( pPager->aHash!=0 ) sqlite3BeginBenignMalloc();
26833   aHash = sqlite3MallocZero( sizeof(aHash[0])*N );
26834   if( pPager->aHash!=0 ) sqlite3EndBenignMalloc();
26835   pagerEnter(pPager);
26836   if( aHash==0 ){
26837     /* Failure to rehash is not an error.  It is only a performance hit. */
26838     return;
26839   }
26840   sqlite3_free(pPager->aHash);
26841   pPager->nHash = N;
26842   pPager->aHash = aHash;
26843   for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
26844     int h;
26845     if( pPg->pgno==0 ){
26846       assert( pPg->pNextHash==0 && pPg->pPrevHash==0 );
26847       continue;
26848     }
26849     h = pPg->pgno & (N-1);
26850     pPg->pNextHash = aHash[h];
26851     if( aHash[h] ){
26852       aHash[h]->pPrevHash = pPg;
26853     }
26854     aHash[h] = pPg;
26855     pPg->pPrevHash = 0;
26856   }
26857 }
26858
26859 /*
26860 ** Read a 32-bit integer from the given file descriptor.  Store the integer
26861 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
26862 ** error code is something goes wrong.
26863 **
26864 ** All values are stored on disk as big-endian.
26865 */
26866 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
26867   unsigned char ac[4];
26868   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
26869   if( rc==SQLITE_OK ){
26870     *pRes = sqlite3Get4byte(ac);
26871   }
26872   return rc;
26873 }
26874
26875 /*
26876 ** Write a 32-bit integer into a string buffer in big-endian byte order.
26877 */
26878 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
26879
26880 /*
26881 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
26882 ** on success or an error code is something goes wrong.
26883 */
26884 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
26885   char ac[4];
26886   put32bits(ac, val);
26887   return sqlite3OsWrite(fd, ac, 4, offset);
26888 }
26889
26890 /*
26891 ** If file pFd is open, call sqlite3OsUnlock() on it.
26892 */
26893 static int osUnlock(sqlite3_file *pFd, int eLock){
26894   if( !pFd->pMethods ){
26895     return SQLITE_OK;
26896   }
26897   return sqlite3OsUnlock(pFd, eLock);
26898 }
26899
26900 /*
26901 ** This function determines whether or not the atomic-write optimization
26902 ** can be used with this pager. The optimization can be used if:
26903 **
26904 **  (a) the value returned by OsDeviceCharacteristics() indicates that
26905 **      a database page may be written atomically, and
26906 **  (b) the value returned by OsSectorSize() is less than or equal
26907 **      to the page size.
26908 **
26909 ** If the optimization cannot be used, 0 is returned. If it can be used,
26910 ** then the value returned is the size of the journal file when it
26911 ** contains rollback data for exactly one page.
26912 */
26913 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
26914 static int jrnlBufferSize(Pager *pPager){
26915   int dc;           /* Device characteristics */
26916   int nSector;      /* Sector size */
26917   int szPage;        /* Page size */
26918   sqlite3_file *fd = pPager->fd;
26919
26920   if( fd->pMethods ){
26921     dc = sqlite3OsDeviceCharacteristics(fd);
26922     nSector = sqlite3OsSectorSize(fd);
26923     szPage = pPager->pageSize;
26924   }
26925
26926   assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
26927   assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
26928
26929   if( !fd->pMethods || 
26930        (dc & (SQLITE_IOCAP_ATOMIC|(szPage>>8)) && nSector<=szPage) ){
26931     return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
26932   }
26933   return 0;
26934 }
26935 #endif
26936
26937 /*
26938 ** This function should be called when an error occurs within the pager
26939 ** code. The first argument is a pointer to the pager structure, the
26940 ** second the error-code about to be returned by a pager API function. 
26941 ** The value returned is a copy of the second argument to this function. 
26942 **
26943 ** If the second argument is SQLITE_IOERR, SQLITE_CORRUPT, or SQLITE_FULL
26944 ** the error becomes persistent. Until the persisten error is cleared,
26945 ** subsequent API calls on this Pager will immediately return the same 
26946 ** error code.
26947 **
26948 ** A persistent error indicates that the contents of the pager-cache 
26949 ** cannot be trusted. This state can be cleared by completely discarding 
26950 ** the contents of the pager-cache. If a transaction was active when
26951 ** the persistent error occured, then the rollback journal may need
26952 ** to be replayed.
26953 */
26954 static void pager_unlock(Pager *pPager);
26955 static int pager_error(Pager *pPager, int rc){
26956   int rc2 = rc & 0xff;
26957   assert(
26958        pPager->errCode==SQLITE_FULL ||
26959        pPager->errCode==SQLITE_OK ||
26960        (pPager->errCode & 0xff)==SQLITE_IOERR
26961   );
26962   if(
26963     rc2==SQLITE_FULL ||
26964     rc2==SQLITE_IOERR ||
26965     rc2==SQLITE_CORRUPT
26966   ){
26967     pPager->errCode = rc;
26968     if( pPager->state==PAGER_UNLOCK && pPager->nRef==0 ){
26969       /* If the pager is already unlocked, call pager_unlock() now to
26970       ** clear the error state and ensure that the pager-cache is 
26971       ** completely empty.
26972       */
26973       pager_unlock(pPager);
26974     }
26975   }
26976   return rc;
26977 }
26978
26979 /*
26980 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
26981 ** on the cache using a hash function.  This is used for testing
26982 ** and debugging only.
26983 */
26984 #ifdef SQLITE_CHECK_PAGES
26985 /*
26986 ** Return a 32-bit hash of the page data for pPage.
26987 */
26988 static u32 pager_datahash(int nByte, unsigned char *pData){
26989   u32 hash = 0;
26990   int i;
26991   for(i=0; i<nByte; i++){
26992     hash = (hash*1039) + pData[i];
26993   }
26994   return hash;
26995 }
26996 static u32 pager_pagehash(PgHdr *pPage){
26997   return pager_datahash(pPage->pPager->pageSize, 
26998                         (unsigned char *)PGHDR_TO_DATA(pPage));
26999 }
27000
27001 /*
27002 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
27003 ** is defined, and NDEBUG is not defined, an assert() statement checks
27004 ** that the page is either dirty or still matches the calculated page-hash.
27005 */
27006 #define CHECK_PAGE(x) checkPage(x)
27007 static void checkPage(PgHdr *pPg){
27008   Pager *pPager = pPg->pPager;
27009   assert( !pPg->pageHash || pPager->errCode || MEMDB || pPg->dirty || 
27010       pPg->pageHash==pager_pagehash(pPg) );
27011 }
27012
27013 #else
27014 #define pager_datahash(X,Y)  0
27015 #define pager_pagehash(X)  0
27016 #define CHECK_PAGE(x)
27017 #endif
27018
27019 /*
27020 ** When this is called the journal file for pager pPager must be open.
27021 ** The master journal file name is read from the end of the file and 
27022 ** written into memory supplied by the caller. 
27023 **
27024 ** zMaster must point to a buffer of at least nMaster bytes allocated by
27025 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
27026 ** enough space to write the master journal name). If the master journal
27027 ** name in the journal is longer than nMaster bytes (including a
27028 ** nul-terminator), then this is handled as if no master journal name
27029 ** were present in the journal.
27030 **
27031 ** If no master journal file name is present zMaster[0] is set to 0 and
27032 ** SQLITE_OK returned.
27033 */
27034 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, int nMaster){
27035   int rc;
27036   u32 len;
27037   i64 szJ;
27038   u32 cksum;
27039   u32 u;                   /* Unsigned loop counter */
27040   unsigned char aMagic[8]; /* A buffer to hold the magic header */
27041
27042   zMaster[0] = '\0';
27043
27044   rc = sqlite3OsFileSize(pJrnl, &szJ);
27045   if( rc!=SQLITE_OK || szJ<16 ) return rc;
27046
27047   rc = read32bits(pJrnl, szJ-16, &len);
27048   if( rc!=SQLITE_OK ) return rc;
27049
27050   if( len>=nMaster ){
27051     return SQLITE_OK;
27052   }
27053
27054   rc = read32bits(pJrnl, szJ-12, &cksum);
27055   if( rc!=SQLITE_OK ) return rc;
27056
27057   rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8);
27058   if( rc!=SQLITE_OK || memcmp(aMagic, aJournalMagic, 8) ) return rc;
27059
27060   rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len);
27061   if( rc!=SQLITE_OK ){
27062     return rc;
27063   }
27064   zMaster[len] = '\0';
27065
27066   /* See if the checksum matches the master journal name */
27067   for(u=0; u<len; u++){
27068     cksum -= zMaster[u];
27069    }
27070   if( cksum ){
27071     /* If the checksum doesn't add up, then one or more of the disk sectors
27072     ** containing the master journal filename is corrupted. This means
27073     ** definitely roll back, so just return SQLITE_OK and report a (nul)
27074     ** master-journal filename.
27075     */
27076     zMaster[0] = '\0';
27077   }
27078    
27079   return SQLITE_OK;
27080 }
27081
27082 /*
27083 ** Seek the journal file descriptor to the next sector boundary where a
27084 ** journal header may be read or written. Pager.journalOff is updated with
27085 ** the new seek offset.
27086 **
27087 ** i.e for a sector size of 512:
27088 **
27089 ** Input Offset              Output Offset
27090 ** ---------------------------------------
27091 ** 0                         0
27092 ** 512                       512
27093 ** 100                       512
27094 ** 2000                      2048
27095 ** 
27096 */
27097 static void seekJournalHdr(Pager *pPager){
27098   i64 offset = 0;
27099   i64 c = pPager->journalOff;
27100   if( c ){
27101     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
27102   }
27103   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
27104   assert( offset>=c );
27105   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
27106   pPager->journalOff = offset;
27107 }
27108
27109 /*
27110 ** Write zeros over the header of the journal file.  This has the
27111 ** effect of invalidating the journal file and committing the
27112 ** transaction.
27113 */
27114 static int zeroJournalHdr(Pager *pPager, int doTruncate){
27115   int rc = SQLITE_OK;
27116   static const char zeroHdr[28];
27117
27118   if( pPager->journalOff ){
27119     i64 iLimit = pPager->journalSizeLimit;
27120
27121     IOTRACE(("JZEROHDR %p\n", pPager))
27122     if( doTruncate || iLimit==0 ){
27123       rc = sqlite3OsTruncate(pPager->jfd, 0);
27124     }else{
27125       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
27126     }
27127     if( rc==SQLITE_OK && !pPager->noSync ){
27128       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->sync_flags);
27129     }
27130
27131     /* At this point the transaction is committed but the write lock 
27132     ** is still held on the file. If there is a size limit configured for 
27133     ** the persistent journal and the journal file currently consumes more
27134     ** space than that limit allows for, truncate it now. There is no need
27135     ** to sync the file following this operation.
27136     */
27137     if( rc==SQLITE_OK && iLimit>0 ){
27138       i64 sz;
27139       rc = sqlite3OsFileSize(pPager->jfd, &sz);
27140       if( rc==SQLITE_OK && sz>iLimit ){
27141         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
27142       }
27143     }
27144   }
27145   return rc;
27146 }
27147
27148 /*
27149 ** The journal file must be open when this routine is called. A journal
27150 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
27151 ** current location.
27152 **
27153 ** The format for the journal header is as follows:
27154 ** - 8 bytes: Magic identifying journal format.
27155 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
27156 ** - 4 bytes: Random number used for page hash.
27157 ** - 4 bytes: Initial database page count.
27158 ** - 4 bytes: Sector size used by the process that wrote this journal.
27159 ** - 4 bytes: Database page size.
27160 ** 
27161 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
27162 */
27163 static int writeJournalHdr(Pager *pPager){
27164   int rc = SQLITE_OK;
27165   char *zHeader = pPager->pTmpSpace;
27166   int nHeader = pPager->pageSize;
27167   int nWrite;
27168
27169   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
27170     nHeader = JOURNAL_HDR_SZ(pPager);
27171   }
27172
27173   if( pPager->stmtHdrOff==0 ){
27174     pPager->stmtHdrOff = pPager->journalOff;
27175   }
27176
27177   seekJournalHdr(pPager);
27178   pPager->journalHdr = pPager->journalOff;
27179
27180   memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
27181
27182   /* 
27183   ** Write the nRec Field - the number of page records that follow this
27184   ** journal header. Normally, zero is written to this value at this time.
27185   ** After the records are added to the journal (and the journal synced, 
27186   ** if in full-sync mode), the zero is overwritten with the true number
27187   ** of records (see syncJournal()).
27188   **
27189   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
27190   ** reading the journal this value tells SQLite to assume that the
27191   ** rest of the journal file contains valid page records. This assumption
27192   ** is dangerous, as if a failure occured whilst writing to the journal
27193   ** file it may contain some garbage data. There are two scenarios
27194   ** where this risk can be ignored:
27195   **
27196   **   * When the pager is in no-sync mode. Corruption can follow a
27197   **     power failure in this case anyway.
27198   **
27199   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
27200   **     that garbage data is never appended to the journal file.
27201   */
27202   assert(pPager->fd->pMethods||pPager->noSync);
27203   if( (pPager->noSync) 
27204    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
27205   ){
27206     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
27207   }else{
27208     put32bits(&zHeader[sizeof(aJournalMagic)], 0);
27209   }
27210
27211   /* The random check-hash initialiser */ 
27212   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
27213   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
27214   /* The initial database size */
27215   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbSize);
27216   /* The assumed sector size for this process */
27217   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
27218   if( pPager->journalHdr==0 ){
27219     /* The page size */
27220     put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
27221   }
27222
27223   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
27224     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
27225     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
27226     pPager->journalOff += nHeader;
27227   }
27228
27229   return rc;
27230 }
27231
27232 /*
27233 ** The journal file must be open when this is called. A journal header file
27234 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
27235 ** file. See comments above function writeJournalHdr() for a description of
27236 ** the journal header format.
27237 **
27238 ** If the header is read successfully, *nRec is set to the number of
27239 ** page records following this header and *dbSize is set to the size of the
27240 ** database before the transaction began, in pages. Also, pPager->cksumInit
27241 ** is set to the value read from the journal header. SQLITE_OK is returned
27242 ** in this case.
27243 **
27244 ** If the journal header file appears to be corrupted, SQLITE_DONE is
27245 ** returned and *nRec and *dbSize are not set.  If JOURNAL_HDR_SZ bytes
27246 ** cannot be read from the journal file an error code is returned.
27247 */
27248 static int readJournalHdr(
27249   Pager *pPager, 
27250   i64 journalSize,
27251   u32 *pNRec, 
27252   u32 *pDbSize
27253 ){
27254   int rc;
27255   unsigned char aMagic[8]; /* A buffer to hold the magic header */
27256   i64 jrnlOff;
27257   int iPageSize;
27258
27259   seekJournalHdr(pPager);
27260   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
27261     return SQLITE_DONE;
27262   }
27263   jrnlOff = pPager->journalOff;
27264
27265   rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), jrnlOff);
27266   if( rc ) return rc;
27267   jrnlOff += sizeof(aMagic);
27268
27269   if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
27270     return SQLITE_DONE;
27271   }
27272
27273   rc = read32bits(pPager->jfd, jrnlOff, pNRec);
27274   if( rc ) return rc;
27275
27276   rc = read32bits(pPager->jfd, jrnlOff+4, &pPager->cksumInit);
27277   if( rc ) return rc;
27278
27279   rc = read32bits(pPager->jfd, jrnlOff+8, pDbSize);
27280   if( rc ) return rc;
27281
27282   rc = read32bits(pPager->jfd, jrnlOff+16, (u32 *)&iPageSize);
27283   if( rc==SQLITE_OK 
27284    && iPageSize>=512 
27285    && iPageSize<=SQLITE_MAX_PAGE_SIZE 
27286    && ((iPageSize-1)&iPageSize)==0 
27287   ){
27288     u16 pagesize = iPageSize;
27289     rc = sqlite3PagerSetPagesize(pPager, &pagesize);
27290   }
27291   if( rc ) return rc;
27292
27293   /* Update the assumed sector-size to match the value used by 
27294   ** the process that created this journal. If this journal was
27295   ** created by a process other than this one, then this routine
27296   ** is being called from within pager_playback(). The local value
27297   ** of Pager.sectorSize is restored at the end of that routine.
27298   */
27299   rc = read32bits(pPager->jfd, jrnlOff+12, (u32 *)&pPager->sectorSize);
27300   if( rc ) return rc;
27301
27302   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
27303   return SQLITE_OK;
27304 }
27305
27306
27307 /*
27308 ** Write the supplied master journal name into the journal file for pager
27309 ** pPager at the current location. The master journal name must be the last
27310 ** thing written to a journal file. If the pager is in full-sync mode, the
27311 ** journal file descriptor is advanced to the next sector boundary before
27312 ** anything is written. The format is:
27313 **
27314 ** + 4 bytes: PAGER_MJ_PGNO.
27315 ** + N bytes: length of master journal name.
27316 ** + 4 bytes: N
27317 ** + 4 bytes: Master journal name checksum.
27318 ** + 8 bytes: aJournalMagic[].
27319 **
27320 ** The master journal page checksum is the sum of the bytes in the master
27321 ** journal name.
27322 **
27323 ** If zMaster is a NULL pointer (occurs for a single database transaction), 
27324 ** this call is a no-op.
27325 */
27326 static int writeMasterJournal(Pager *pPager, const char *zMaster){
27327   int rc;
27328   int len; 
27329   int i; 
27330   i64 jrnlOff;
27331   i64 jrnlSize;
27332   u32 cksum = 0;
27333   char zBuf[sizeof(aJournalMagic)+2*4];
27334
27335   if( !zMaster || pPager->setMaster) return SQLITE_OK;
27336   pPager->setMaster = 1;
27337
27338   len = strlen(zMaster);
27339   for(i=0; i<len; i++){
27340     cksum += zMaster[i];
27341   }
27342
27343   /* If in full-sync mode, advance to the next disk sector before writing
27344   ** the master journal name. This is in case the previous page written to
27345   ** the journal has already been synced.
27346   */
27347   if( pPager->fullSync ){
27348     seekJournalHdr(pPager);
27349   }
27350   jrnlOff = pPager->journalOff;
27351   pPager->journalOff += (len+20);
27352
27353   rc = write32bits(pPager->jfd, jrnlOff, PAGER_MJ_PGNO(pPager));
27354   if( rc!=SQLITE_OK ) return rc;
27355   jrnlOff += 4;
27356
27357   rc = sqlite3OsWrite(pPager->jfd, zMaster, len, jrnlOff);
27358   if( rc!=SQLITE_OK ) return rc;
27359   jrnlOff += len;
27360
27361   put32bits(zBuf, len);
27362   put32bits(&zBuf[4], cksum);
27363   memcpy(&zBuf[8], aJournalMagic, sizeof(aJournalMagic));
27364   rc = sqlite3OsWrite(pPager->jfd, zBuf, 8+sizeof(aJournalMagic), jrnlOff);
27365   jrnlOff += 8+sizeof(aJournalMagic);
27366   pPager->needSync = !pPager->noSync;
27367
27368   /* If the pager is in peristent-journal mode, then the physical 
27369   ** journal-file may extend past the end of the master-journal name
27370   ** and 8 bytes of magic data just written to the file. This is 
27371   ** dangerous because the code to rollback a hot-journal file
27372   ** will not be able to find the master-journal name to determine 
27373   ** whether or not the journal is hot. 
27374   **
27375   ** Easiest thing to do in this scenario is to truncate the journal 
27376   ** file to the required size.
27377   */ 
27378   if( (rc==SQLITE_OK)
27379    && (rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))==SQLITE_OK
27380    && jrnlSize>jrnlOff
27381   ){
27382     rc = sqlite3OsTruncate(pPager->jfd, jrnlOff);
27383   }
27384   return rc;
27385 }
27386
27387 /*
27388 ** Add or remove a page from the list of all pages that are in the
27389 ** statement journal.
27390 **
27391 ** The Pager keeps a separate list of pages that are currently in
27392 ** the statement journal.  This helps the sqlite3PagerStmtCommit()
27393 ** routine run MUCH faster for the common case where there are many
27394 ** pages in memory but only a few are in the statement journal.
27395 */
27396 static void page_add_to_stmt_list(PgHdr *pPg){
27397   Pager *pPager = pPg->pPager;
27398   PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
27399   assert( MEMDB );
27400   if( !pHist->inStmt ){
27401     assert( pHist->pPrevStmt==0 && pHist->pNextStmt==0 );
27402     if( pPager->pStmt ){
27403       PGHDR_TO_HIST(pPager->pStmt, pPager)->pPrevStmt = pPg;
27404     }
27405     pHist->pNextStmt = pPager->pStmt;
27406     pPager->pStmt = pPg;
27407     pHist->inStmt = 1;
27408   }
27409 }
27410
27411 /*
27412 ** Find a page in the hash table given its page number.  Return
27413 ** a pointer to the page or NULL if not found.
27414 */
27415 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
27416   PgHdr *p;
27417   if( pPager->aHash==0 ) return 0;
27418   p = pPager->aHash[pgno & (pPager->nHash-1)];
27419   while( p && p->pgno!=pgno ){
27420     p = p->pNextHash;
27421   }
27422   return p;
27423 }
27424
27425 /*
27426 ** Clear the in-memory cache.  This routine
27427 ** sets the state of the pager back to what it was when it was first
27428 ** opened.  Any outstanding pages are invalidated and subsequent attempts
27429 ** to access those pages will likely result in a coredump.
27430 */
27431 static void pager_reset(Pager *pPager){
27432   PgHdr *pPg, *pNext;
27433   if( pPager->errCode ) return;
27434   for(pPg=pPager->pAll; pPg; pPg=pNext){
27435     IOTRACE(("PGFREE %p %d\n", pPager, pPg->pgno));
27436     PAGER_INCR(sqlite3_pager_pgfree_count);
27437     pNext = pPg->pNextAll;
27438     lruListRemove(pPg);
27439     sqlite3PageFree(pPg->pData);
27440     sqlite3_free(pPg);
27441   }
27442   assert(pPager->lru.pFirst==0);
27443   assert(pPager->lru.pFirstSynced==0);
27444   assert(pPager->lru.pLast==0);
27445   pPager->pStmt = 0;
27446   pPager->pAll = 0;
27447   pPager->pDirty = 0;
27448   pPager->nHash = 0;
27449   sqlite3_free(pPager->aHash);
27450   pPager->nPage = 0;
27451   pPager->aHash = 0;
27452   pPager->nRef = 0;
27453 }
27454
27455 /*
27456 ** Unlock the database file. 
27457 **
27458 ** If the pager is currently in error state, discard the contents of 
27459 ** the cache and reset the Pager structure internal state. If there is
27460 ** an open journal-file, then the next time a shared-lock is obtained
27461 ** on the pager file (by this or any other process), it will be
27462 ** treated as a hot-journal and rolled back.
27463 */
27464 static void pager_unlock(Pager *pPager){
27465   if( !pPager->exclusiveMode ){
27466     if( !MEMDB ){
27467       int rc = osUnlock(pPager->fd, NO_LOCK);
27468       if( rc ) pPager->errCode = rc;
27469       pPager->dbSize = -1;
27470       IOTRACE(("UNLOCK %p\n", pPager))
27471
27472       /* Always close the journal file when dropping the database lock.
27473       ** Otherwise, another connection with journal_mode=delete might
27474       ** delete the file out from under us.
27475       */
27476       if( pPager->journalOpen ){
27477         sqlite3OsClose(pPager->jfd);
27478         pPager->journalOpen = 0;
27479         sqlite3BitvecDestroy(pPager->pInJournal);
27480         pPager->pInJournal = 0;
27481       }
27482
27483       /* If Pager.errCode is set, the contents of the pager cache cannot be
27484       ** trusted. Now that the pager file is unlocked, the contents of the
27485       ** cache can be discarded and the error code safely cleared.
27486       */
27487       if( pPager->errCode ){
27488         if( rc==SQLITE_OK ) pPager->errCode = SQLITE_OK;
27489         pager_reset(pPager);
27490         if( pPager->stmtOpen ){
27491           sqlite3OsClose(pPager->stfd);
27492           sqlite3BitvecDestroy(pPager->pInStmt);
27493           pPager->pInStmt = 0;
27494         }
27495         pPager->stmtOpen = 0;
27496         pPager->stmtInUse = 0;
27497         pPager->journalOff = 0;
27498         pPager->journalStarted = 0;
27499         pPager->stmtAutoopen = 0;
27500         pPager->origDbSize = 0;
27501       }
27502     }
27503
27504     if( !MEMDB || pPager->errCode==SQLITE_OK ){
27505       pPager->state = PAGER_UNLOCK;
27506       pPager->changeCountDone = 0;
27507     }
27508   }
27509 }
27510
27511 /*
27512 ** Execute a rollback if a transaction is active and unlock the 
27513 ** database file. If the pager has already entered the error state, 
27514 ** do not attempt the rollback.
27515 */
27516 static void pagerUnlockAndRollback(Pager *p){
27517   /* assert( p->state>=PAGER_RESERVED || p->journalOpen==0 ); */
27518   if( p->errCode==SQLITE_OK && p->state>=PAGER_RESERVED ){
27519     sqlite3BeginBenignMalloc();
27520     sqlite3PagerRollback(p);
27521     sqlite3EndBenignMalloc();
27522   }
27523   pager_unlock(p);
27524 #if 0
27525   assert( p->errCode || !p->journalOpen || (p->exclusiveMode&&!p->journalOff) );
27526   assert( p->errCode || !p->stmtOpen || p->exclusiveMode );
27527 #endif
27528 }
27529
27530 /*
27531 ** This routine ends a transaction.  A transaction is ended by either
27532 ** a COMMIT or a ROLLBACK.
27533 **
27534 ** When this routine is called, the pager has the journal file open and
27535 ** a RESERVED or EXCLUSIVE lock on the database.  This routine will release
27536 ** the database lock and acquires a SHARED lock in its place if that is
27537 ** the appropriate thing to do.  Release locks usually is appropriate,
27538 ** unless we are in exclusive access mode or unless this is a 
27539 ** COMMIT AND BEGIN or ROLLBACK AND BEGIN operation.
27540 **
27541 ** The journal file is either deleted or truncated.
27542 **
27543 ** TODO: Consider keeping the journal file open for temporary databases.
27544 ** This might give a performance improvement on windows where opening
27545 ** a file is an expensive operation.
27546 */
27547 static int pager_end_transaction(Pager *pPager, int hasMaster){
27548   PgHdr *pPg;
27549   int rc = SQLITE_OK;
27550   int rc2 = SQLITE_OK;
27551   assert( !MEMDB );
27552   if( pPager->state<PAGER_RESERVED ){
27553     return SQLITE_OK;
27554   }
27555   sqlite3PagerStmtCommit(pPager);
27556   if( pPager->stmtOpen && !pPager->exclusiveMode ){
27557     sqlite3OsClose(pPager->stfd);
27558     pPager->stmtOpen = 0;
27559   }
27560   if( pPager->journalOpen ){
27561     if( pPager->exclusiveMode 
27562      || pPager->journalMode==PAGER_JOURNALMODE_PERSIST
27563     ){
27564       rc = zeroJournalHdr(pPager, hasMaster);
27565       pager_error(pPager, rc);
27566       pPager->journalOff = 0;
27567       pPager->journalStarted = 0;
27568     }else{
27569       sqlite3OsClose(pPager->jfd);
27570       pPager->journalOpen = 0;
27571       if( rc==SQLITE_OK && !pPager->tempFile ){
27572         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
27573       }
27574     }
27575     sqlite3BitvecDestroy(pPager->pInJournal);
27576     pPager->pInJournal = 0;
27577     for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
27578       pPg->inJournal = 0;
27579       pPg->dirty = 0;
27580       pPg->needSync = 0;
27581       pPg->alwaysRollback = 0;
27582 #ifdef SQLITE_CHECK_PAGES
27583       pPg->pageHash = pager_pagehash(pPg);
27584 #endif
27585     }
27586     pPager->pDirty = 0;
27587     pPager->dirtyCache = 0;
27588     pPager->nRec = 0;
27589   }else{
27590     assert( pPager->pInJournal==0 );
27591   }
27592
27593   if( !pPager->exclusiveMode ){
27594     rc2 = osUnlock(pPager->fd, SHARED_LOCK);
27595     pPager->state = PAGER_SHARED;
27596   }else if( pPager->state==PAGER_SYNCED ){
27597     pPager->state = PAGER_EXCLUSIVE;
27598   }
27599   pPager->origDbSize = 0;
27600   pPager->setMaster = 0;
27601   pPager->needSync = 0;
27602   lruListSetFirstSynced(pPager);
27603   pPager->dbSize = -1;
27604   pPager->dbModified = 0;
27605
27606   return (rc==SQLITE_OK?rc2:rc);
27607 }
27608
27609 /*
27610 ** Compute and return a checksum for the page of data.
27611 **
27612 ** This is not a real checksum.  It is really just the sum of the 
27613 ** random initial value and the page number.  We experimented with
27614 ** a checksum of the entire data, but that was found to be too slow.
27615 **
27616 ** Note that the page number is stored at the beginning of data and
27617 ** the checksum is stored at the end.  This is important.  If journal
27618 ** corruption occurs due to a power failure, the most likely scenario
27619 ** is that one end or the other of the record will be changed.  It is
27620 ** much less likely that the two ends of the journal record will be
27621 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
27622 ** though fast and simple, catches the mostly likely kind of corruption.
27623 **
27624 ** FIX ME:  Consider adding every 200th (or so) byte of the data to the
27625 ** checksum.  That way if a single page spans 3 or more disk sectors and
27626 ** only the middle sector is corrupt, we will still have a reasonable
27627 ** chance of failing the checksum and thus detecting the problem.
27628 */
27629 static u32 pager_cksum(Pager *pPager, const u8 *aData){
27630   u32 cksum = pPager->cksumInit;
27631   int i = pPager->pageSize-200;
27632   while( i>0 ){
27633     cksum += aData[i];
27634     i -= 200;
27635   }
27636   return cksum;
27637 }
27638
27639 /* Forward declaration */
27640 static void makeClean(PgHdr*);
27641
27642 /*
27643 ** Read a single page from the journal file opened on file descriptor
27644 ** jfd.  Playback this one page.
27645 **
27646 ** If useCksum==0 it means this journal does not use checksums.  Checksums
27647 ** are not used in statement journals because statement journals do not
27648 ** need to survive power failures.
27649 */
27650 static int pager_playback_one_page(
27651   Pager *pPager, 
27652   sqlite3_file *jfd,
27653   i64 offset,
27654   int useCksum
27655 ){
27656   int rc;
27657   PgHdr *pPg;                   /* An existing page in the cache */
27658   Pgno pgno;                    /* The page number of a page in journal */
27659   u32 cksum;                    /* Checksum used for sanity checking */
27660   u8 *aData = (u8 *)pPager->pTmpSpace;   /* Temp storage for a page */
27661
27662   /* useCksum should be true for the main journal and false for
27663   ** statement journals.  Verify that this is always the case
27664   */
27665   assert( jfd == (useCksum ? pPager->jfd : pPager->stfd) );
27666   assert( aData );
27667
27668   rc = read32bits(jfd, offset, &pgno);
27669   if( rc!=SQLITE_OK ) return rc;
27670   rc = sqlite3OsRead(jfd, aData, pPager->pageSize, offset+4);
27671   if( rc!=SQLITE_OK ) return rc;
27672   pPager->journalOff += pPager->pageSize + 4;
27673
27674   /* Sanity checking on the page.  This is more important that I originally
27675   ** thought.  If a power failure occurs while the journal is being written,
27676   ** it could cause invalid data to be written into the journal.  We need to
27677   ** detect this invalid data (with high probability) and ignore it.
27678   */
27679   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
27680     return SQLITE_DONE;
27681   }
27682   if( pgno>(unsigned)pPager->dbSize ){
27683     return SQLITE_OK;
27684   }
27685   if( useCksum ){
27686     rc = read32bits(jfd, offset+pPager->pageSize+4, &cksum);
27687     if( rc ) return rc;
27688     pPager->journalOff += 4;
27689     if( pager_cksum(pPager, aData)!=cksum ){
27690       return SQLITE_DONE;
27691     }
27692   }
27693
27694   assert( pPager->state==PAGER_RESERVED || pPager->state>=PAGER_EXCLUSIVE );
27695
27696   /* If the pager is in RESERVED state, then there must be a copy of this
27697   ** page in the pager cache. In this case just update the pager cache,
27698   ** not the database file. The page is left marked dirty in this case.
27699   **
27700   ** An exception to the above rule: If the database is in no-sync mode
27701   ** and a page is moved during an incremental vacuum then the page may
27702   ** not be in the pager cache. Later: if a malloc() or IO error occurs
27703   ** during a Movepage() call, then the page may not be in the cache
27704   ** either. So the condition described in the above paragraph is not
27705   ** assert()able.
27706   **
27707   ** If in EXCLUSIVE state, then we update the pager cache if it exists
27708   ** and the main file. The page is then marked not dirty.
27709   **
27710   ** Ticket #1171:  The statement journal might contain page content that is
27711   ** different from the page content at the start of the transaction.
27712   ** This occurs when a page is changed prior to the start of a statement
27713   ** then changed again within the statement.  When rolling back such a
27714   ** statement we must not write to the original database unless we know
27715   ** for certain that original page contents are synced into the main rollback
27716   ** journal.  Otherwise, a power loss might leave modified data in the
27717   ** database file without an entry in the rollback journal that can
27718   ** restore the database to its original form.  Two conditions must be
27719   ** met before writing to the database files. (1) the database must be
27720   ** locked.  (2) we know that the original page content is fully synced
27721   ** in the main journal either because the page is not in cache or else
27722   ** the page is marked as needSync==0.
27723   **
27724   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
27725   ** is possible to fail a statement on a database that does not yet exist.
27726   ** Do not attempt to write if database file has never been opened.
27727   */
27728   pPg = pager_lookup(pPager, pgno);
27729   PAGERTRACE4("PLAYBACK %d page %d hash(%08x)\n",
27730                PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, aData));
27731   if( pPager->state>=PAGER_EXCLUSIVE && (pPg==0 || pPg->needSync==0)
27732         && pPager->fd->pMethods ){
27733     i64 offset = (pgno-1)*(i64)pPager->pageSize;
27734     rc = sqlite3OsWrite(pPager->fd, aData, pPager->pageSize, offset);
27735     if( pPg ){
27736       makeClean(pPg);
27737     }
27738   }
27739   if( pPg ){
27740     /* No page should ever be explicitly rolled back that is in use, except
27741     ** for page 1 which is held in use in order to keep the lock on the
27742     ** database active. However such a page may be rolled back as a result
27743     ** of an internal error resulting in an automatic call to
27744     ** sqlite3PagerRollback().
27745     */
27746     void *pData;
27747     /* assert( pPg->nRef==0 || pPg->pgno==1 ); */
27748     pData = PGHDR_TO_DATA(pPg);
27749     memcpy(pData, aData, pPager->pageSize);
27750     if( pPager->xReiniter ){
27751       pPager->xReiniter(pPg, pPager->pageSize);
27752     }
27753 #ifdef SQLITE_CHECK_PAGES
27754     pPg->pageHash = pager_pagehash(pPg);
27755 #endif
27756     /* If this was page 1, then restore the value of Pager.dbFileVers.
27757     ** Do this before any decoding. */
27758     if( pgno==1 ){
27759       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
27760     }
27761
27762     /* Decode the page just read from disk */
27763     CODEC1(pPager, pData, pPg->pgno, 3);
27764   }
27765   return rc;
27766 }
27767
27768 /*
27769 ** Parameter zMaster is the name of a master journal file. A single journal
27770 ** file that referred to the master journal file has just been rolled back.
27771 ** This routine checks if it is possible to delete the master journal file,
27772 ** and does so if it is.
27773 **
27774 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
27775 ** available for use within this function.
27776 **
27777 **
27778 ** The master journal file contains the names of all child journals.
27779 ** To tell if a master journal can be deleted, check to each of the
27780 ** children.  If all children are either missing or do not refer to
27781 ** a different master journal, then this master journal can be deleted.
27782 */
27783 static int pager_delmaster(Pager *pPager, const char *zMaster){
27784   sqlite3_vfs *pVfs = pPager->pVfs;
27785   int rc;
27786   int master_open = 0;
27787   sqlite3_file *pMaster;
27788   sqlite3_file *pJournal;
27789   char *zMasterJournal = 0; /* Contents of master journal file */
27790   i64 nMasterJournal;       /* Size of master journal file */
27791
27792   /* Open the master journal file exclusively in case some other process
27793   ** is running this routine also. Not that it makes too much difference.
27794   */
27795   pMaster = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile * 2);
27796   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
27797   if( !pMaster ){
27798     rc = SQLITE_NOMEM;
27799   }else{
27800     int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
27801     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
27802   }
27803   if( rc!=SQLITE_OK ) goto delmaster_out;
27804   master_open = 1;
27805
27806   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
27807   if( rc!=SQLITE_OK ) goto delmaster_out;
27808
27809   if( nMasterJournal>0 ){
27810     char *zJournal;
27811     char *zMasterPtr = 0;
27812     int nMasterPtr = pPager->pVfs->mxPathname+1;
27813
27814     /* Load the entire master journal file into space obtained from
27815     ** sqlite3_malloc() and pointed to by zMasterJournal. 
27816     */
27817     zMasterJournal = (char *)sqlite3Malloc(nMasterJournal + nMasterPtr);
27818     if( !zMasterJournal ){
27819       rc = SQLITE_NOMEM;
27820       goto delmaster_out;
27821     }
27822     zMasterPtr = &zMasterJournal[nMasterJournal];
27823     rc = sqlite3OsRead(pMaster, zMasterJournal, nMasterJournal, 0);
27824     if( rc!=SQLITE_OK ) goto delmaster_out;
27825
27826     zJournal = zMasterJournal;
27827     while( (zJournal-zMasterJournal)<nMasterJournal ){
27828       int exists;
27829       rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
27830       if( rc!=SQLITE_OK ){
27831         goto delmaster_out;
27832       }
27833       if( exists ){
27834         /* One of the journals pointed to by the master journal exists.
27835         ** Open it and check if it points at the master journal. If
27836         ** so, return without deleting the master journal file.
27837         */
27838         int c;
27839         int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
27840         rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
27841         if( rc!=SQLITE_OK ){
27842           goto delmaster_out;
27843         }
27844
27845         rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
27846         sqlite3OsClose(pJournal);
27847         if( rc!=SQLITE_OK ){
27848           goto delmaster_out;
27849         }
27850
27851         c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
27852         if( c ){
27853           /* We have a match. Do not delete the master journal file. */
27854           goto delmaster_out;
27855         }
27856       }
27857       zJournal += (strlen(zJournal)+1);
27858     }
27859   }
27860   
27861   rc = sqlite3OsDelete(pVfs, zMaster, 0);
27862
27863 delmaster_out:
27864   if( zMasterJournal ){
27865     sqlite3_free(zMasterJournal);
27866   }  
27867   if( master_open ){
27868     sqlite3OsClose(pMaster);
27869   }
27870   sqlite3_free(pMaster);
27871   return rc;
27872 }
27873
27874
27875 static void pager_truncate_cache(Pager *pPager);
27876
27877 /*
27878 ** Truncate the main file of the given pager to the number of pages
27879 ** indicated. Also truncate the cached representation of the file.
27880 **
27881 ** Might might be the case that the file on disk is smaller than nPage.
27882 ** This can happen, for example, if we are in the middle of a transaction
27883 ** which has extended the file size and the new pages are still all held
27884 ** in cache, then an INSERT or UPDATE does a statement rollback.  Some
27885 ** operating system implementations can get confused if you try to
27886 ** truncate a file to some size that is larger than it currently is,
27887 ** so detect this case and write a single zero byte to the end of the new
27888 ** file instead.
27889 */
27890 static int pager_truncate(Pager *pPager, int nPage){
27891   int rc = SQLITE_OK;
27892   if( pPager->state>=PAGER_EXCLUSIVE && pPager->fd->pMethods ){
27893     i64 currentSize, newSize;
27894     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
27895     newSize = pPager->pageSize*(i64)nPage;
27896     if( rc==SQLITE_OK && currentSize!=newSize ){
27897       if( currentSize>newSize ){
27898         rc = sqlite3OsTruncate(pPager->fd, newSize);
27899       }else{
27900         rc = sqlite3OsWrite(pPager->fd, "", 1, newSize-1);
27901       }
27902     }
27903   }
27904   if( rc==SQLITE_OK ){
27905     pPager->dbSize = nPage;
27906     pager_truncate_cache(pPager);
27907   }
27908   return rc;
27909 }
27910
27911 /*
27912 ** Set the sectorSize for the given pager.
27913 **
27914 ** The sector size is at least as big as the sector size reported
27915 ** by sqlite3OsSectorSize().  The minimum sector size is 512.
27916 */
27917 static void setSectorSize(Pager *pPager){
27918   assert(pPager->fd->pMethods||pPager->tempFile);
27919   if( !pPager->tempFile ){
27920     /* Sector size doesn't matter for temporary files. Also, the file
27921     ** may not have been opened yet, in whcih case the OsSectorSize()
27922     ** call will segfault.
27923     */
27924     pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
27925   }
27926   if( pPager->sectorSize<512 ){
27927     pPager->sectorSize = 512;
27928   }
27929 }
27930
27931 /*
27932 ** Playback the journal and thus restore the database file to
27933 ** the state it was in before we started making changes.  
27934 **
27935 ** The journal file format is as follows: 
27936 **
27937 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
27938 **  (2)  4 byte big-endian integer which is the number of valid page records
27939 **       in the journal.  If this value is 0xffffffff, then compute the
27940 **       number of page records from the journal size.
27941 **  (3)  4 byte big-endian integer which is the initial value for the 
27942 **       sanity checksum.
27943 **  (4)  4 byte integer which is the number of pages to truncate the
27944 **       database to during a rollback.
27945 **  (5)  4 byte big-endian integer which is the sector size.  The header
27946 **       is this many bytes in size.
27947 **  (6)  4 byte big-endian integer which is the page case.
27948 **  (7)  4 byte integer which is the number of bytes in the master journal
27949 **       name.  The value may be zero (indicate that there is no master
27950 **       journal.)
27951 **  (8)  N bytes of the master journal name.  The name will be nul-terminated
27952 **       and might be shorter than the value read from (5).  If the first byte
27953 **       of the name is \000 then there is no master journal.  The master
27954 **       journal name is stored in UTF-8.
27955 **  (9)  Zero or more pages instances, each as follows:
27956 **        +  4 byte page number.
27957 **        +  pPager->pageSize bytes of data.
27958 **        +  4 byte checksum
27959 **
27960 ** When we speak of the journal header, we mean the first 8 items above.
27961 ** Each entry in the journal is an instance of the 9th item.
27962 **
27963 ** Call the value from the second bullet "nRec".  nRec is the number of
27964 ** valid page entries in the journal.  In most cases, you can compute the
27965 ** value of nRec from the size of the journal file.  But if a power
27966 ** failure occurred while the journal was being written, it could be the
27967 ** case that the size of the journal file had already been increased but
27968 ** the extra entries had not yet made it safely to disk.  In such a case,
27969 ** the value of nRec computed from the file size would be too large.  For
27970 ** that reason, we always use the nRec value in the header.
27971 **
27972 ** If the nRec value is 0xffffffff it means that nRec should be computed
27973 ** from the file size.  This value is used when the user selects the
27974 ** no-sync option for the journal.  A power failure could lead to corruption
27975 ** in this case.  But for things like temporary table (which will be
27976 ** deleted when the power is restored) we don't care.  
27977 **
27978 ** If the file opened as the journal file is not a well-formed
27979 ** journal file then all pages up to the first corrupted page are rolled
27980 ** back (or no pages if the journal header is corrupted). The journal file
27981 ** is then deleted and SQLITE_OK returned, just as if no corruption had
27982 ** been encountered.
27983 **
27984 ** If an I/O or malloc() error occurs, the journal-file is not deleted
27985 ** and an error code is returned.
27986 */
27987 static int pager_playback(Pager *pPager, int isHot){
27988   sqlite3_vfs *pVfs = pPager->pVfs;
27989   i64 szJ;                 /* Size of the journal file in bytes */
27990   u32 nRec;                /* Number of Records in the journal */
27991   u32 u;                   /* Unsigned loop counter */
27992   Pgno mxPg = 0;           /* Size of the original file in pages */
27993   int rc;                  /* Result code of a subroutine */
27994   int res = 1;             /* Value returned by sqlite3OsAccess() */
27995   char *zMaster = 0;       /* Name of master journal file if any */
27996
27997   /* Figure out how many records are in the journal.  Abort early if
27998   ** the journal is empty.
27999   */
28000   assert( pPager->journalOpen );
28001   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
28002   if( rc!=SQLITE_OK || szJ==0 ){
28003     goto end_playback;
28004   }
28005
28006   /* Read the master journal name from the journal, if it is present.
28007   ** If a master journal file name is specified, but the file is not
28008   ** present on disk, then the journal is not hot and does not need to be
28009   ** played back.
28010   */
28011   zMaster = pPager->pTmpSpace;
28012   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
28013   if( rc==SQLITE_OK && zMaster[0] ){
28014     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
28015   }
28016   zMaster = 0;
28017   if( rc!=SQLITE_OK || !res ){
28018     goto end_playback;
28019   }
28020   pPager->journalOff = 0;
28021
28022   /* This loop terminates either when the readJournalHdr() call returns
28023   ** SQLITE_DONE or an IO error occurs. */
28024   while( 1 ){
28025
28026     /* Read the next journal header from the journal file.  If there are
28027     ** not enough bytes left in the journal file for a complete header, or
28028     ** it is corrupted, then a process must of failed while writing it.
28029     ** This indicates nothing more needs to be rolled back.
28030     */
28031     rc = readJournalHdr(pPager, szJ, &nRec, &mxPg);
28032     if( rc!=SQLITE_OK ){ 
28033       if( rc==SQLITE_DONE ){
28034         rc = SQLITE_OK;
28035       }
28036       goto end_playback;
28037     }
28038
28039     /* If nRec is 0xffffffff, then this journal was created by a process
28040     ** working in no-sync mode. This means that the rest of the journal
28041     ** file consists of pages, there are no more journal headers. Compute
28042     ** the value of nRec based on this assumption.
28043     */
28044     if( nRec==0xffffffff ){
28045       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
28046       nRec = (szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager);
28047     }
28048
28049     /* If nRec is 0 and this rollback is of a transaction created by this
28050     ** process and if this is the final header in the journal, then it means
28051     ** that this part of the journal was being filled but has not yet been
28052     ** synced to disk.  Compute the number of pages based on the remaining
28053     ** size of the file.
28054     **
28055     ** The third term of the test was added to fix ticket #2565.
28056     */
28057     if( nRec==0 && !isHot &&
28058         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
28059       nRec = (szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager);
28060     }
28061
28062     /* If this is the first header read from the journal, truncate the
28063     ** database file back to its original size.
28064     */
28065     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
28066       rc = pager_truncate(pPager, mxPg);
28067       if( rc!=SQLITE_OK ){
28068         goto end_playback;
28069       }
28070     }
28071
28072     /* Copy original pages out of the journal and back into the database file.
28073     */
28074     for(u=0; u<nRec; u++){
28075       rc = pager_playback_one_page(pPager, pPager->jfd, pPager->journalOff, 1);
28076       if( rc!=SQLITE_OK ){
28077         if( rc==SQLITE_DONE ){
28078           rc = SQLITE_OK;
28079           pPager->journalOff = szJ;
28080           break;
28081         }else{
28082           goto end_playback;
28083         }
28084       }
28085     }
28086   }
28087   /*NOTREACHED*/
28088   assert( 0 );
28089
28090 end_playback:
28091   if( rc==SQLITE_OK ){
28092     zMaster = pPager->pTmpSpace;
28093     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
28094   }
28095   if( rc==SQLITE_OK ){
28096     rc = pager_end_transaction(pPager, zMaster[0]!='\0');
28097   }
28098   if( rc==SQLITE_OK && zMaster[0] ){
28099     /* If there was a master journal and this routine will return success,
28100     ** see if it is possible to delete the master journal.
28101     */
28102     rc = pager_delmaster(pPager, zMaster);
28103   }
28104
28105   /* The Pager.sectorSize variable may have been updated while rolling
28106   ** back a journal created by a process with a different sector size
28107   ** value. Reset it to the correct value for this process.
28108   */
28109   setSectorSize(pPager);
28110   return rc;
28111 }
28112
28113 /*
28114 ** Playback the statement journal.
28115 **
28116 ** This is similar to playing back the transaction journal but with
28117 ** a few extra twists.
28118 **
28119 **    (1)  The number of pages in the database file at the start of
28120 **         the statement is stored in pPager->stmtSize, not in the
28121 **         journal file itself.
28122 **
28123 **    (2)  In addition to playing back the statement journal, also
28124 **         playback all pages of the transaction journal beginning
28125 **         at offset pPager->stmtJSize.
28126 */
28127 static int pager_stmt_playback(Pager *pPager){
28128   i64 szJ;                 /* Size of the full journal */
28129   i64 hdrOff;
28130   int nRec;                /* Number of Records */
28131   int i;                   /* Loop counter */
28132   int rc;
28133
28134   szJ = pPager->journalOff;
28135
28136   /* Set hdrOff to be the offset just after the end of the last journal
28137   ** page written before the first journal-header for this statement
28138   ** transaction was written, or the end of the file if no journal
28139   ** header was written.
28140   */
28141   hdrOff = pPager->stmtHdrOff;
28142   assert( pPager->fullSync || !hdrOff );
28143   if( !hdrOff ){
28144     hdrOff = szJ;
28145   }
28146   
28147   /* Truncate the database back to its original size.
28148   */
28149   rc = pager_truncate(pPager, pPager->stmtSize);
28150   assert( pPager->state>=PAGER_SHARED );
28151
28152   /* Figure out how many records are in the statement journal.
28153   */
28154   assert( pPager->stmtInUse && pPager->journalOpen );
28155   nRec = pPager->stmtNRec;
28156   
28157   /* Copy original pages out of the statement journal and back into the
28158   ** database file.  Note that the statement journal omits checksums from
28159   ** each record since power-failure recovery is not important to statement
28160   ** journals.
28161   */
28162   for(i=0; i<nRec; i++){
28163     i64 offset = i*(4+pPager->pageSize);
28164     rc = pager_playback_one_page(pPager, pPager->stfd, offset, 0);
28165     assert( rc!=SQLITE_DONE );
28166     if( rc!=SQLITE_OK ) goto end_stmt_playback;
28167   }
28168
28169   /* Now roll some pages back from the transaction journal. Pager.stmtJSize
28170   ** was the size of the journal file when this statement was started, so
28171   ** everything after that needs to be rolled back, either into the
28172   ** database, the memory cache, or both.
28173   **
28174   ** If it is not zero, then Pager.stmtHdrOff is the offset to the start
28175   ** of the first journal header written during this statement transaction.
28176   */
28177   pPager->journalOff = pPager->stmtJSize;
28178   pPager->cksumInit = pPager->stmtCksum;
28179   while( pPager->journalOff < hdrOff ){
28180     rc = pager_playback_one_page(pPager, pPager->jfd, pPager->journalOff, 1);
28181     assert( rc!=SQLITE_DONE );
28182     if( rc!=SQLITE_OK ) goto end_stmt_playback;
28183   }
28184
28185   while( pPager->journalOff < szJ ){
28186     u32 nJRec;         /* Number of Journal Records */
28187     u32 dummy;
28188     rc = readJournalHdr(pPager, szJ, &nJRec, &dummy);
28189     if( rc!=SQLITE_OK ){
28190       assert( rc!=SQLITE_DONE );
28191       goto end_stmt_playback;
28192     }
28193     if( nJRec==0 ){
28194       nJRec = (szJ - pPager->journalOff) / (pPager->pageSize+8);
28195     }
28196     for(i=nJRec-1; i>=0 && pPager->journalOff < szJ; i--){
28197       rc = pager_playback_one_page(pPager, pPager->jfd, pPager->journalOff, 1);
28198       assert( rc!=SQLITE_DONE );
28199       if( rc!=SQLITE_OK ) goto end_stmt_playback;
28200     }
28201   }
28202
28203   pPager->journalOff = szJ;
28204   
28205 end_stmt_playback:
28206   if( rc==SQLITE_OK) {
28207     pPager->journalOff = szJ;
28208     /* pager_reload_cache(pPager); */
28209   }
28210   return rc;
28211 }
28212
28213 /*
28214 ** Change the maximum number of in-memory pages that are allowed.
28215 */
28216 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
28217   if( mxPage>10 ){
28218     pPager->mxPage = mxPage;
28219   }else{
28220     pPager->mxPage = 10;
28221   }
28222 }
28223
28224 /*
28225 ** Adjust the robustness of the database to damage due to OS crashes
28226 ** or power failures by changing the number of syncs()s when writing
28227 ** the rollback journal.  There are three levels:
28228 **
28229 **    OFF       sqlite3OsSync() is never called.  This is the default
28230 **              for temporary and transient files.
28231 **
28232 **    NORMAL    The journal is synced once before writes begin on the
28233 **              database.  This is normally adequate protection, but
28234 **              it is theoretically possible, though very unlikely,
28235 **              that an inopertune power failure could leave the journal
28236 **              in a state which would cause damage to the database
28237 **              when it is rolled back.
28238 **
28239 **    FULL      The journal is synced twice before writes begin on the
28240 **              database (with some additional information - the nRec field
28241 **              of the journal header - being written in between the two
28242 **              syncs).  If we assume that writing a
28243 **              single disk sector is atomic, then this mode provides
28244 **              assurance that the journal will not be corrupted to the
28245 **              point of causing damage to the database during rollback.
28246 **
28247 ** Numeric values associated with these states are OFF==1, NORMAL=2,
28248 ** and FULL=3.
28249 */
28250 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
28251 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager *pPager, int level, int full_fsync){
28252   pPager->noSync =  level==1 || pPager->tempFile;
28253   pPager->fullSync = level==3 && !pPager->tempFile;
28254   pPager->sync_flags = (full_fsync?SQLITE_SYNC_FULL:SQLITE_SYNC_NORMAL);
28255   if( pPager->noSync ) pPager->needSync = 0;
28256 }
28257 #endif
28258
28259 /*
28260 ** The following global variable is incremented whenever the library
28261 ** attempts to open a temporary file.  This information is used for
28262 ** testing and analysis only.  
28263 */
28264 #ifdef SQLITE_TEST
28265 SQLITE_API int sqlite3_opentemp_count = 0;
28266 #endif
28267
28268 /*
28269 ** Open a temporary file. 
28270 **
28271 ** Write the file descriptor into *fd.  Return SQLITE_OK on success or some
28272 ** other error code if we fail. The OS will automatically delete the temporary
28273 ** file when it is closed.
28274 */
28275 static int sqlite3PagerOpentemp(
28276   Pager *pPager,        /* The pager object */
28277   sqlite3_file *pFile,  /* Write the file descriptor here */
28278   int vfsFlags          /* Flags passed through to the VFS */
28279 ){
28280   int rc;
28281
28282 #ifdef SQLITE_TEST
28283   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
28284 #endif
28285
28286   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
28287             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
28288   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
28289   assert( rc!=SQLITE_OK || pFile->pMethods );
28290   return rc;
28291 }
28292
28293 /*
28294 ** Create a new page cache and put a pointer to the page cache in *ppPager.
28295 ** The file to be cached need not exist.  The file is not locked until
28296 ** the first call to sqlite3PagerGet() and is only held open until the
28297 ** last page is released using sqlite3PagerUnref().
28298 **
28299 ** If zFilename is NULL then a randomly-named temporary file is created
28300 ** and used as the file to be cached.  The file will be deleted
28301 ** automatically when it is closed.
28302 **
28303 ** If zFilename is ":memory:" then all information is held in cache.
28304 ** It is never written to disk.  This can be used to implement an
28305 ** in-memory database.
28306 */
28307 SQLITE_PRIVATE int sqlite3PagerOpen(
28308   sqlite3_vfs *pVfs,       /* The virtual file system to use */
28309   Pager **ppPager,         /* Return the Pager structure here */
28310   const char *zFilename,   /* Name of the database file to open */
28311   int nExtra,              /* Extra bytes append to each in-memory page */
28312   int flags,               /* flags controlling this file */
28313   int vfsFlags             /* flags passed through to sqlite3_vfs.xOpen() */
28314 ){
28315   u8 *pPtr;
28316   Pager *pPager = 0;
28317   int rc = SQLITE_OK;
28318   int i;
28319   int tempFile = 0;
28320   int memDb = 0;
28321   int readOnly = 0;
28322   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0;
28323   int noReadlock = (flags & PAGER_NO_READLOCK)!=0;
28324   int journalFileSize = sqlite3JournalSize(pVfs);
28325   int szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;
28326   char *zPathname = 0;
28327   int nPathname = 0;
28328
28329   /* The default return is a NULL pointer */
28330   *ppPager = 0;
28331
28332   /* Compute and store the full pathname in an allocated buffer pointed
28333   ** to by zPathname, length nPathname. Or, if this is a temporary file,
28334   ** leave both nPathname and zPathname set to 0.
28335   */
28336   if( zFilename && zFilename[0] ){
28337     nPathname = pVfs->mxPathname+1;
28338     zPathname = sqlite3Malloc(nPathname*2);
28339     if( zPathname==0 ){
28340       return SQLITE_NOMEM;
28341     }
28342 #ifndef SQLITE_OMIT_MEMORYDB
28343     if( strcmp(zFilename,":memory:")==0 ){
28344       memDb = 1;
28345       zPathname[0] = 0;
28346     }else
28347 #endif
28348     {
28349       rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
28350     }
28351     if( rc!=SQLITE_OK ){
28352       sqlite3_free(zPathname);
28353       return rc;
28354     }
28355     nPathname = strlen(zPathname);
28356   }
28357
28358   /* Allocate memory for the pager structure */
28359   pPager = sqlite3MallocZero(
28360     sizeof(*pPager) +           /* Pager structure */
28361     journalFileSize +           /* The journal file structure */ 
28362     pVfs->szOsFile * 3 +        /* The main db and two journal files */ 
28363     3*nPathname + 40            /* zFilename, zDirectory, zJournal */
28364   );
28365   if( !pPager ){
28366     sqlite3_free(zPathname);
28367     return SQLITE_NOMEM;
28368   }
28369   pPtr = (u8 *)&pPager[1];
28370   pPager->vfsFlags = vfsFlags;
28371   pPager->fd = (sqlite3_file*)&pPtr[pVfs->szOsFile*0];
28372   pPager->stfd = (sqlite3_file*)&pPtr[pVfs->szOsFile*1];
28373   pPager->jfd = (sqlite3_file*)&pPtr[pVfs->szOsFile*2];
28374   pPager->zFilename = (char*)&pPtr[pVfs->szOsFile*2+journalFileSize];
28375   pPager->zDirectory = &pPager->zFilename[nPathname+1];
28376   pPager->zJournal = &pPager->zDirectory[nPathname+1];
28377   pPager->pVfs = pVfs;
28378   if( zPathname ){
28379     memcpy(pPager->zFilename, zPathname, nPathname+1);
28380     sqlite3_free(zPathname);
28381   }
28382
28383   /* Open the pager file.
28384   */
28385   if( zFilename && zFilename[0] && !memDb ){
28386     if( nPathname>(pVfs->mxPathname - sizeof("-journal")) ){
28387       rc = SQLITE_CANTOPEN;
28388     }else{
28389       int fout = 0;
28390       rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd,
28391                          pPager->vfsFlags, &fout);
28392       readOnly = (fout&SQLITE_OPEN_READONLY);
28393
28394       /* If the file was successfully opened for read/write access,
28395       ** choose a default page size in case we have to create the
28396       ** database file. The default page size is the maximum of:
28397       **
28398       **    + SQLITE_DEFAULT_PAGE_SIZE,
28399       **    + The value returned by sqlite3OsSectorSize()
28400       **    + The largest page size that can be written atomically.
28401       */
28402       if( rc==SQLITE_OK && !readOnly ){
28403         int iSectorSize = sqlite3OsSectorSize(pPager->fd);
28404         if( szPageDflt<iSectorSize ){
28405           szPageDflt = iSectorSize;
28406         }
28407 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
28408         {
28409           int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
28410           int ii;
28411           assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
28412           assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
28413           assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
28414           for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
28415             if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ) szPageDflt = ii;
28416           }
28417         }
28418 #endif
28419         if( szPageDflt>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
28420           szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
28421         }
28422       }
28423     }
28424   }else if( !memDb ){
28425     /* If a temporary file is requested, it is not opened immediately.
28426     ** In this case we accept the default page size and delay actually
28427     ** opening the file until the first call to OsWrite().
28428     */ 
28429     tempFile = 1;
28430     pPager->state = PAGER_EXCLUSIVE;
28431   }
28432
28433   if( pPager && rc==SQLITE_OK ){
28434     pPager->pTmpSpace = sqlite3PageMalloc(szPageDflt);
28435   }
28436
28437   /* If an error occured in either of the blocks above.
28438   ** Free the Pager structure and close the file.
28439   ** Since the pager is not allocated there is no need to set 
28440   ** any Pager.errMask variables.
28441   */
28442   if( !pPager || !pPager->pTmpSpace ){
28443     sqlite3OsClose(pPager->fd);
28444     sqlite3_free(pPager);
28445     return ((rc==SQLITE_OK)?SQLITE_NOMEM:rc);
28446   }
28447
28448   PAGERTRACE3("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename);
28449   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
28450
28451   /* Fill in Pager.zDirectory[] */
28452   memcpy(pPager->zDirectory, pPager->zFilename, nPathname+1);
28453   for(i=strlen(pPager->zDirectory); i>0 && pPager->zDirectory[i-1]!='/'; i--){}
28454   if( i>0 ) pPager->zDirectory[i-1] = 0;
28455
28456   /* Fill in Pager.zJournal[] */
28457   if( zPathname ){
28458     memcpy(pPager->zJournal, pPager->zFilename, nPathname);
28459     memcpy(&pPager->zJournal[nPathname], "-journal", 9);
28460   }else{
28461     pPager->zJournal = 0;
28462   }
28463
28464   /* pPager->journalOpen = 0; */
28465   pPager->useJournal = useJournal && !memDb;
28466   pPager->noReadlock = noReadlock && readOnly;
28467   /* pPager->stmtOpen = 0; */
28468   /* pPager->stmtInUse = 0; */
28469   /* pPager->nRef = 0; */
28470   pPager->dbSize = memDb-1;
28471   pPager->pageSize = szPageDflt;
28472   /* pPager->stmtSize = 0; */
28473   /* pPager->stmtJSize = 0; */
28474   /* pPager->nPage = 0; */
28475   pPager->mxPage = 100;
28476   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
28477   /* pPager->state = PAGER_UNLOCK; */
28478   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
28479   /* pPager->errMask = 0; */
28480   pPager->tempFile = tempFile;
28481   assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
28482           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
28483   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
28484   pPager->exclusiveMode = tempFile; 
28485   pPager->memDb = memDb;
28486   pPager->readOnly = readOnly;
28487   /* pPager->needSync = 0; */
28488   pPager->noSync = pPager->tempFile || !useJournal;
28489   pPager->fullSync = (pPager->noSync?0:1);
28490   pPager->sync_flags = SQLITE_SYNC_NORMAL;
28491   /* pPager->pFirst = 0; */
28492   /* pPager->pFirstSynced = 0; */
28493   /* pPager->pLast = 0; */
28494   pPager->nExtra = FORCE_ALIGNMENT(nExtra);
28495   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
28496   assert(pPager->fd->pMethods||memDb||tempFile);
28497   if( !memDb ){
28498     setSectorSize(pPager);
28499   }
28500   /* pPager->pBusyHandler = 0; */
28501   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
28502   *ppPager = pPager;
28503 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
28504   pPager->iInUseMM = 0;
28505   pPager->iInUseDB = 0;
28506   if( !memDb ){
28507 #ifndef SQLITE_MUTEX_NOOP
28508     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM2);
28509 #endif
28510     sqlite3_mutex_enter(mutex);
28511     pPager->pNext = sqlite3PagerList;
28512     if( sqlite3PagerList ){
28513       assert( sqlite3PagerList->pPrev==0 );
28514       sqlite3PagerList->pPrev = pPager;
28515     }
28516     pPager->pPrev = 0;
28517     sqlite3PagerList = pPager;
28518     sqlite3_mutex_leave(mutex);
28519   }
28520 #endif
28521   return SQLITE_OK;
28522 }
28523
28524 /*
28525 ** Set the busy handler function.
28526 */
28527 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager *pPager, BusyHandler *pBusyHandler){
28528   pPager->pBusyHandler = pBusyHandler;
28529 }
28530
28531 /*
28532 ** Set the destructor for this pager.  If not NULL, the destructor is called
28533 ** when the reference count on each page reaches zero.  The destructor can
28534 ** be used to clean up information in the extra segment appended to each page.
28535 **
28536 ** The destructor is not called as a result sqlite3PagerClose().  
28537 ** Destructors are only called by sqlite3PagerUnref().
28538 */
28539 SQLITE_PRIVATE void sqlite3PagerSetDestructor(Pager *pPager, void (*xDesc)(DbPage*,int)){
28540   pPager->xDestructor = xDesc;
28541 }
28542
28543 /*
28544 ** Set the reinitializer for this pager.  If not NULL, the reinitializer
28545 ** is called when the content of a page in cache is restored to its original
28546 ** value as a result of a rollback.  The callback gives higher-level code
28547 ** an opportunity to restore the EXTRA section to agree with the restored
28548 ** page data.
28549 */
28550 SQLITE_PRIVATE void sqlite3PagerSetReiniter(Pager *pPager, void (*xReinit)(DbPage*,int)){
28551   pPager->xReiniter = xReinit;
28552 }
28553
28554 /*
28555 ** Set the page size to *pPageSize. If the suggest new page size is
28556 ** inappropriate, then an alternative page size is set to that
28557 ** value before returning.
28558 */
28559 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u16 *pPageSize){
28560   int rc = SQLITE_OK;
28561   u16 pageSize = *pPageSize;
28562   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
28563   if( pageSize && pageSize!=pPager->pageSize 
28564    && !pPager->memDb && pPager->nRef==0 
28565   ){
28566     char *pNew = (char *)sqlite3PageMalloc(pageSize);
28567     if( !pNew ){
28568       rc = SQLITE_NOMEM;
28569     }else{
28570       pagerEnter(pPager);
28571       pager_reset(pPager);
28572       pPager->pageSize = pageSize;
28573       setSectorSize(pPager);
28574       sqlite3PageFree(pPager->pTmpSpace);
28575       pPager->pTmpSpace = pNew;
28576       pagerLeave(pPager);
28577     }
28578   }
28579   *pPageSize = pPager->pageSize;
28580   return rc;
28581 }
28582
28583 /*
28584 ** Return a pointer to the "temporary page" buffer held internally
28585 ** by the pager.  This is a buffer that is big enough to hold the
28586 ** entire content of a database page.  This buffer is used internally
28587 ** during rollback and will be overwritten whenever a rollback
28588 ** occurs.  But other modules are free to use it too, as long as
28589 ** no rollbacks are happening.
28590 */
28591 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
28592   return pPager->pTmpSpace;
28593 }
28594
28595 /*
28596 ** Attempt to set the maximum database page count if mxPage is positive. 
28597 ** Make no changes if mxPage is zero or negative.  And never reduce the
28598 ** maximum page count below the current size of the database.
28599 **
28600 ** Regardless of mxPage, return the current maximum page count.
28601 */
28602 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
28603   if( mxPage>0 ){
28604     pPager->mxPgno = mxPage;
28605   }
28606   sqlite3PagerPagecount(pPager, 0);
28607   return pPager->mxPgno;
28608 }
28609
28610 /*
28611 ** The following set of routines are used to disable the simulated
28612 ** I/O error mechanism.  These routines are used to avoid simulated
28613 ** errors in places where we do not care about errors.
28614 **
28615 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
28616 ** and generate no code.
28617 */
28618 #ifdef SQLITE_TEST
28619 SQLITE_API extern int sqlite3_io_error_pending;
28620 SQLITE_API extern int sqlite3_io_error_hit;
28621 static int saved_cnt;
28622 void disable_simulated_io_errors(void){
28623   saved_cnt = sqlite3_io_error_pending;
28624   sqlite3_io_error_pending = -1;
28625 }
28626 void enable_simulated_io_errors(void){
28627   sqlite3_io_error_pending = saved_cnt;
28628 }
28629 #else
28630 # define disable_simulated_io_errors()
28631 # define enable_simulated_io_errors()
28632 #endif
28633
28634 /*
28635 ** Read the first N bytes from the beginning of the file into memory
28636 ** that pDest points to. 
28637 **
28638 ** No error checking is done. The rational for this is that this function 
28639 ** may be called even if the file does not exist or contain a header. In 
28640 ** these cases sqlite3OsRead() will return an error, to which the correct 
28641 ** response is to zero the memory at pDest and continue.  A real IO error 
28642 ** will presumably recur and be picked up later (Todo: Think about this).
28643 */
28644 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
28645   int rc = SQLITE_OK;
28646   memset(pDest, 0, N);
28647   assert(MEMDB||pPager->fd->pMethods||pPager->tempFile);
28648   if( pPager->fd->pMethods ){
28649     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
28650     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
28651     if( rc==SQLITE_IOERR_SHORT_READ ){
28652       rc = SQLITE_OK;
28653     }
28654   }
28655   return rc;
28656 }
28657
28658 /*
28659 ** Return the total number of pages in the disk file associated with
28660 ** pPager. 
28661 **
28662 ** If the PENDING_BYTE lies on the page directly after the end of the
28663 ** file, then consider this page part of the file too. For example, if
28664 ** PENDING_BYTE is byte 4096 (the first byte of page 5) and the size of the
28665 ** file is 4096 bytes, 5 is returned instead of 4.
28666 */
28667 SQLITE_PRIVATE int sqlite3PagerPagecount(Pager *pPager, int *pnPage){
28668   i64 n = 0;
28669   int rc;
28670   assert( pPager!=0 );
28671   if( pPager->errCode ){
28672     return pPager->errCode;
28673   }
28674   if( pPager->dbSize>=0 ){
28675     n = pPager->dbSize;
28676   } else {
28677     assert(pPager->fd->pMethods||pPager->tempFile);
28678     if( (pPager->fd->pMethods)
28679      && (rc = sqlite3OsFileSize(pPager->fd, &n))!=SQLITE_OK ){
28680       pPager->nRef++;
28681       pager_error(pPager, rc);
28682       pPager->nRef--;
28683       return rc;
28684     }
28685     if( n>0 && n<pPager->pageSize ){
28686       n = 1;
28687     }else{
28688       n /= pPager->pageSize;
28689     }
28690     if( pPager->state!=PAGER_UNLOCK ){
28691       pPager->dbSize = n;
28692     }
28693   }
28694   if( n==(PENDING_BYTE/pPager->pageSize) ){
28695     n++;
28696   }
28697   if( n>pPager->mxPgno ){
28698     pPager->mxPgno = n;
28699   }
28700   if( pnPage ){
28701     *pnPage = n;
28702   }
28703   return SQLITE_OK;
28704 }
28705
28706
28707 #ifndef SQLITE_OMIT_MEMORYDB
28708 /*
28709 ** Clear a PgHistory block
28710 */
28711 static void clearHistory(PgHistory *pHist){
28712   sqlite3PageFree(pHist->pOrig);
28713   sqlite3PageFree(pHist->pStmt);
28714   pHist->pOrig = 0;
28715   pHist->pStmt = 0;
28716 }
28717 #else
28718 #define clearHistory(x)
28719 #endif
28720
28721 /*
28722 ** Forward declaration
28723 */
28724 static int syncJournal(Pager*);
28725
28726 /*
28727 ** Unlink pPg from its hash chain. Also set the page number to 0 to indicate
28728 ** that the page is not part of any hash chain. This is required because the
28729 ** sqlite3PagerMovepage() routine can leave a page in the 
28730 ** pNextFree/pPrevFree list that is not a part of any hash-chain.
28731 */
28732 static void unlinkHashChain(Pager *pPager, PgHdr *pPg){
28733   if( pPg->pgno==0 ){
28734     assert( pPg->pNextHash==0 && pPg->pPrevHash==0 );
28735     return;
28736   }
28737   if( pPg->pNextHash ){
28738     pPg->pNextHash->pPrevHash = pPg->pPrevHash;
28739   }
28740   if( pPg->pPrevHash ){
28741     assert( pPager->aHash[pPg->pgno & (pPager->nHash-1)]!=pPg );
28742     pPg->pPrevHash->pNextHash = pPg->pNextHash;
28743   }else{
28744     int h = pPg->pgno & (pPager->nHash-1);
28745     pPager->aHash[h] = pPg->pNextHash;
28746   }
28747   if( MEMDB ){
28748     clearHistory(PGHDR_TO_HIST(pPg, pPager));
28749   }
28750   pPg->pgno = 0;
28751   pPg->pNextHash = pPg->pPrevHash = 0;
28752 }
28753
28754 /*
28755 ** Unlink a page from the free list (the list of all pages where nRef==0)
28756 ** and from its hash collision chain.
28757 */
28758 static void unlinkPage(PgHdr *pPg){
28759   Pager *pPager = pPg->pPager;
28760
28761   /* Unlink from free page list */
28762   lruListRemove(pPg);
28763
28764   /* Unlink from the pgno hash table */
28765   unlinkHashChain(pPager, pPg);
28766 }
28767
28768 /*
28769 ** This routine is used to truncate the cache when a database
28770 ** is truncated.  Drop from the cache all pages whose pgno is
28771 ** larger than pPager->dbSize and is unreferenced.
28772 **
28773 ** Referenced pages larger than pPager->dbSize are zeroed.
28774 **
28775 ** Actually, at the point this routine is called, it would be
28776 ** an error to have a referenced page.  But rather than delete
28777 ** that page and guarantee a subsequent segfault, it seems better
28778 ** to zero it and hope that we error out sanely.
28779 */
28780 static void pager_truncate_cache(Pager *pPager){
28781   PgHdr *pPg;
28782   PgHdr **ppPg;
28783   int dbSize = pPager->dbSize;
28784
28785   ppPg = &pPager->pAll;
28786   while( (pPg = *ppPg)!=0 ){
28787     if( pPg->pgno<=dbSize ){
28788       ppPg = &pPg->pNextAll;
28789     }else if( pPg->nRef>0 ){
28790       memset(PGHDR_TO_DATA(pPg), 0, pPager->pageSize);
28791       ppPg = &pPg->pNextAll;
28792     }else{
28793       *ppPg = pPg->pNextAll;
28794 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
28795       if( *ppPg ){
28796         (*ppPg)->pPrevAll = pPg->pPrevAll;
28797       }
28798 #endif
28799       IOTRACE(("PGFREE %p %d\n", pPager, pPg->pgno));
28800       PAGER_INCR(sqlite3_pager_pgfree_count);
28801       unlinkPage(pPg);
28802       makeClean(pPg);
28803       sqlite3PageFree(pPg->pData);
28804       sqlite3_free(pPg);
28805       pPager->nPage--;
28806     }
28807   }
28808 }
28809
28810 /*
28811 ** Try to obtain a lock on a file.  Invoke the busy callback if the lock
28812 ** is currently not available.  Repeat until the busy callback returns
28813 ** false or until the lock succeeds.
28814 **
28815 ** Return SQLITE_OK on success and an error code if we cannot obtain
28816 ** the lock.
28817 */
28818 static int pager_wait_on_lock(Pager *pPager, int locktype){
28819   int rc;
28820
28821   /* The OS lock values must be the same as the Pager lock values */
28822   assert( PAGER_SHARED==SHARED_LOCK );
28823   assert( PAGER_RESERVED==RESERVED_LOCK );
28824   assert( PAGER_EXCLUSIVE==EXCLUSIVE_LOCK );
28825
28826   /* If the file is currently unlocked then the size must be unknown */
28827   assert( pPager->state>=PAGER_SHARED || pPager->dbSize<0 || MEMDB );
28828
28829   if( pPager->state>=locktype ){
28830     rc = SQLITE_OK;
28831   }else{
28832     if( pPager->pBusyHandler ) pPager->pBusyHandler->nBusy = 0;
28833     do {
28834       rc = sqlite3OsLock(pPager->fd, locktype);
28835     }while( rc==SQLITE_BUSY && sqlite3InvokeBusyHandler(pPager->pBusyHandler) );
28836     if( rc==SQLITE_OK ){
28837       pPager->state = locktype;
28838       IOTRACE(("LOCK %p %d\n", pPager, locktype))
28839     }
28840   }
28841   return rc;
28842 }
28843
28844 /*
28845 ** Truncate the file to the number of pages specified.
28846 */
28847 SQLITE_PRIVATE int sqlite3PagerTruncate(Pager *pPager, Pgno nPage){
28848   int rc;
28849   assert( pPager->state>=PAGER_SHARED || MEMDB );
28850   sqlite3PagerPagecount(pPager, 0);
28851   if( pPager->errCode ){
28852     rc = pPager->errCode;
28853     return rc;
28854   }
28855   if( nPage>=(unsigned)pPager->dbSize ){
28856     return SQLITE_OK;
28857   }
28858   if( MEMDB ){
28859     pPager->dbSize = nPage;
28860     pager_truncate_cache(pPager);
28861     return SQLITE_OK;
28862   }
28863   pagerEnter(pPager);
28864   rc = syncJournal(pPager);
28865   pagerLeave(pPager);
28866   if( rc!=SQLITE_OK ){
28867     return rc;
28868   }
28869
28870   /* Get an exclusive lock on the database before truncating. */
28871   pagerEnter(pPager);
28872   rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
28873   pagerLeave(pPager);
28874   if( rc!=SQLITE_OK ){
28875     return rc;
28876   }
28877
28878   rc = pager_truncate(pPager, nPage);
28879   return rc;
28880 }
28881
28882 /*
28883 ** Shutdown the page cache.  Free all memory and close all files.
28884 **
28885 ** If a transaction was in progress when this routine is called, that
28886 ** transaction is rolled back.  All outstanding pages are invalidated
28887 ** and their memory is freed.  Any attempt to use a page associated
28888 ** with this page cache after this function returns will likely
28889 ** result in a coredump.
28890 **
28891 ** This function always succeeds. If a transaction is active an attempt
28892 ** is made to roll it back. If an error occurs during the rollback 
28893 ** a hot journal may be left in the filesystem but no error is returned
28894 ** to the caller.
28895 */
28896 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
28897 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
28898   if( !MEMDB ){
28899 #ifndef SQLITE_MUTEX_NOOP
28900     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM2);
28901 #endif
28902     sqlite3_mutex_enter(mutex);
28903     if( pPager->pPrev ){
28904       pPager->pPrev->pNext = pPager->pNext;
28905     }else{
28906       sqlite3PagerList = pPager->pNext;
28907     }
28908     if( pPager->pNext ){
28909       pPager->pNext->pPrev = pPager->pPrev;
28910     }
28911     sqlite3_mutex_leave(mutex);
28912   }
28913 #endif
28914
28915   disable_simulated_io_errors();
28916   sqlite3BeginBenignMalloc();
28917   pPager->errCode = 0;
28918   pPager->exclusiveMode = 0;
28919   pager_reset(pPager);
28920   pagerUnlockAndRollback(pPager);
28921   enable_simulated_io_errors();
28922   sqlite3EndBenignMalloc();
28923   PAGERTRACE2("CLOSE %d\n", PAGERID(pPager));
28924   IOTRACE(("CLOSE %p\n", pPager))
28925   if( pPager->journalOpen ){
28926     sqlite3OsClose(pPager->jfd);
28927   }
28928   sqlite3BitvecDestroy(pPager->pInJournal);
28929   if( pPager->stmtOpen ){
28930     sqlite3OsClose(pPager->stfd);
28931   }
28932   sqlite3OsClose(pPager->fd);
28933   /* Temp files are automatically deleted by the OS
28934   ** if( pPager->tempFile ){
28935   **   sqlite3OsDelete(pPager->zFilename);
28936   ** }
28937   */
28938
28939   sqlite3_free(pPager->aHash);
28940   sqlite3PageFree(pPager->pTmpSpace);
28941   sqlite3_free(pPager);
28942   return SQLITE_OK;
28943 }
28944
28945 #if !defined(NDEBUG) || defined(SQLITE_TEST)
28946 /*
28947 ** Return the page number for the given page data.
28948 */
28949 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *p){
28950   return p->pgno;
28951 }
28952 #endif
28953
28954 /*
28955 ** The page_ref() function increments the reference count for a page.
28956 ** If the page is currently on the freelist (the reference count is zero) then
28957 ** remove it from the freelist.
28958 **
28959 ** For non-test systems, page_ref() is a macro that calls _page_ref()
28960 ** online of the reference count is zero.  For test systems, page_ref()
28961 ** is a real function so that we can set breakpoints and trace it.
28962 */
28963 static void _page_ref(PgHdr *pPg){
28964   if( pPg->nRef==0 ){
28965     /* The page is currently on the freelist.  Remove it. */
28966     lruListRemove(pPg);
28967     pPg->pPager->nRef++;
28968   }
28969   pPg->nRef++;
28970 }
28971 #ifdef SQLITE_DEBUG
28972   static void page_ref(PgHdr *pPg){
28973     if( pPg->nRef==0 ){
28974       _page_ref(pPg);
28975     }else{
28976       pPg->nRef++;
28977     }
28978   }
28979 #else
28980 # define page_ref(P)   ((P)->nRef==0?_page_ref(P):(void)(P)->nRef++)
28981 #endif
28982
28983 /*
28984 ** Increment the reference count for a page.  The input pointer is
28985 ** a reference to the page data.
28986 */
28987 SQLITE_PRIVATE int sqlite3PagerRef(DbPage *pPg){
28988   pagerEnter(pPg->pPager);
28989   page_ref(pPg);
28990   pagerLeave(pPg->pPager);
28991   return SQLITE_OK;
28992 }
28993
28994 /*
28995 ** Sync the journal.  In other words, make sure all the pages that have
28996 ** been written to the journal have actually reached the surface of the
28997 ** disk.  It is not safe to modify the original database file until after
28998 ** the journal has been synced.  If the original database is modified before
28999 ** the journal is synced and a power failure occurs, the unsynced journal
29000 ** data would be lost and we would be unable to completely rollback the
29001 ** database changes.  Database corruption would occur.
29002 ** 
29003 ** This routine also updates the nRec field in the header of the journal.
29004 ** (See comments on the pager_playback() routine for additional information.)
29005 ** If the sync mode is FULL, two syncs will occur.  First the whole journal
29006 ** is synced, then the nRec field is updated, then a second sync occurs.
29007 **
29008 ** For temporary databases, we do not care if we are able to rollback
29009 ** after a power failure, so no sync occurs.
29010 **
29011 ** If the IOCAP_SEQUENTIAL flag is set for the persistent media on which
29012 ** the database is stored, then OsSync() is never called on the journal
29013 ** file. In this case all that is required is to update the nRec field in
29014 ** the journal header.
29015 **
29016 ** This routine clears the needSync field of every page current held in
29017 ** memory.
29018 */
29019 static int syncJournal(Pager *pPager){
29020   PgHdr *pPg;
29021   int rc = SQLITE_OK;
29022
29023   /* Sync the journal before modifying the main database
29024   ** (assuming there is a journal and it needs to be synced.)
29025   */
29026   if( pPager->needSync ){
29027     if( !pPager->tempFile ){
29028       int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
29029       assert( pPager->journalOpen );
29030
29031       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
29032         /* Write the nRec value into the journal file header. If in
29033         ** full-synchronous mode, sync the journal first. This ensures that
29034         ** all data has really hit the disk before nRec is updated to mark
29035         ** it as a candidate for rollback.
29036         **
29037         ** This is not required if the persistent media supports the
29038         ** SAFE_APPEND property. Because in this case it is not possible 
29039         ** for garbage data to be appended to the file, the nRec field
29040         ** is populated with 0xFFFFFFFF when the journal header is written
29041         ** and never needs to be updated.
29042         */
29043         i64 jrnlOff;
29044         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
29045           PAGERTRACE2("SYNC journal of %d\n", PAGERID(pPager));
29046           IOTRACE(("JSYNC %p\n", pPager))
29047           rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags);
29048           if( rc!=0 ) return rc;
29049         }
29050
29051         jrnlOff = pPager->journalHdr + sizeof(aJournalMagic);
29052         IOTRACE(("JHDR %p %lld %d\n", pPager, jrnlOff, 4));
29053         rc = write32bits(pPager->jfd, jrnlOff, pPager->nRec);
29054         if( rc ) return rc;
29055       }
29056       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
29057         PAGERTRACE2("SYNC journal of %d\n", PAGERID(pPager));
29058         IOTRACE(("JSYNC %p\n", pPager))
29059         rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags| 
29060           (pPager->sync_flags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
29061         );
29062         if( rc!=0 ) return rc;
29063       }
29064       pPager->journalStarted = 1;
29065     }
29066     pPager->needSync = 0;
29067
29068     /* Erase the needSync flag from every page.
29069     */
29070     for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
29071       pPg->needSync = 0;
29072     }
29073     lruListSetFirstSynced(pPager);
29074   }
29075
29076 #ifndef NDEBUG
29077   /* If the Pager.needSync flag is clear then the PgHdr.needSync
29078   ** flag must also be clear for all pages.  Verify that this
29079   ** invariant is true.
29080   */
29081   else{
29082     for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
29083       assert( pPg->needSync==0 );
29084     }
29085     assert( pPager->lru.pFirstSynced==pPager->lru.pFirst );
29086   }
29087 #endif
29088
29089   return rc;
29090 }
29091
29092 /*
29093 ** Merge two lists of pages connected by pDirty and in pgno order.
29094 ** Do not both fixing the pPrevDirty pointers.
29095 */
29096 static PgHdr *merge_pagelist(PgHdr *pA, PgHdr *pB){
29097   PgHdr result, *pTail;
29098   pTail = &result;
29099   while( pA && pB ){
29100     if( pA->pgno<pB->pgno ){
29101       pTail->pDirty = pA;
29102       pTail = pA;
29103       pA = pA->pDirty;
29104     }else{
29105       pTail->pDirty = pB;
29106       pTail = pB;
29107       pB = pB->pDirty;
29108     }
29109   }
29110   if( pA ){
29111     pTail->pDirty = pA;
29112   }else if( pB ){
29113     pTail->pDirty = pB;
29114   }else{
29115     pTail->pDirty = 0;
29116   }
29117   return result.pDirty;
29118 }
29119
29120 /*
29121 ** Sort the list of pages in accending order by pgno.  Pages are
29122 ** connected by pDirty pointers.  The pPrevDirty pointers are
29123 ** corrupted by this sort.
29124 */
29125 #define N_SORT_BUCKET_ALLOC 25
29126 #define N_SORT_BUCKET       25
29127 #ifdef SQLITE_TEST
29128   int sqlite3_pager_n_sort_bucket = 0;
29129   #undef N_SORT_BUCKET
29130   #define N_SORT_BUCKET \
29131    (sqlite3_pager_n_sort_bucket?sqlite3_pager_n_sort_bucket:N_SORT_BUCKET_ALLOC)
29132 #endif
29133 static PgHdr *sort_pagelist(PgHdr *pIn){
29134   PgHdr *a[N_SORT_BUCKET_ALLOC], *p;
29135   int i;
29136   memset(a, 0, sizeof(a));
29137   while( pIn ){
29138     p = pIn;
29139     pIn = p->pDirty;
29140     p->pDirty = 0;
29141     for(i=0; i<N_SORT_BUCKET-1; i++){
29142       if( a[i]==0 ){
29143         a[i] = p;
29144         break;
29145       }else{
29146         p = merge_pagelist(a[i], p);
29147         a[i] = 0;
29148       }
29149     }
29150     if( i==N_SORT_BUCKET-1 ){
29151       /* Coverage: To get here, there need to be 2^(N_SORT_BUCKET) 
29152       ** elements in the input list. This is possible, but impractical.
29153       ** Testing this line is the point of global variable
29154       ** sqlite3_pager_n_sort_bucket.
29155       */
29156       a[i] = merge_pagelist(a[i], p);
29157     }
29158   }
29159   p = a[0];
29160   for(i=1; i<N_SORT_BUCKET; i++){
29161     p = merge_pagelist(p, a[i]);
29162   }
29163   return p;
29164 }
29165
29166 /*
29167 ** Given a list of pages (connected by the PgHdr.pDirty pointer) write
29168 ** every one of those pages out to the database file and mark them all
29169 ** as clean.
29170 */
29171 static int pager_write_pagelist(PgHdr *pList){
29172   Pager *pPager;
29173   PgHdr *p;
29174   int rc;
29175
29176   if( pList==0 ) return SQLITE_OK;
29177   pPager = pList->pPager;
29178
29179   /* At this point there may be either a RESERVED or EXCLUSIVE lock on the
29180   ** database file. If there is already an EXCLUSIVE lock, the following
29181   ** calls to sqlite3OsLock() are no-ops.
29182   **
29183   ** Moving the lock from RESERVED to EXCLUSIVE actually involves going
29184   ** through an intermediate state PENDING.   A PENDING lock prevents new
29185   ** readers from attaching to the database but is unsufficient for us to
29186   ** write.  The idea of a PENDING lock is to prevent new readers from
29187   ** coming in while we wait for existing readers to clear.
29188   **
29189   ** While the pager is in the RESERVED state, the original database file
29190   ** is unchanged and we can rollback without having to playback the
29191   ** journal into the original database file.  Once we transition to
29192   ** EXCLUSIVE, it means the database file has been changed and any rollback
29193   ** will require a journal playback.
29194   */
29195   rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
29196   if( rc!=SQLITE_OK ){
29197     return rc;
29198   }
29199
29200   pList = sort_pagelist(pList);
29201   for(p=pList; p; p=p->pDirty){
29202     assert( p->dirty );
29203     p->dirty = 0;
29204   }
29205   while( pList ){
29206
29207     /* If the file has not yet been opened, open it now. */
29208     if( !pPager->fd->pMethods ){
29209       assert(pPager->tempFile);
29210       rc = sqlite3PagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
29211       if( rc ) return rc;
29212     }
29213
29214     /* If there are dirty pages in the page cache with page numbers greater
29215     ** than Pager.dbSize, this means sqlite3PagerTruncate() was called to
29216     ** make the file smaller (presumably by auto-vacuum code). Do not write
29217     ** any such pages to the file.
29218     */
29219     if( pList->pgno<=pPager->dbSize ){
29220       i64 offset = (pList->pgno-1)*(i64)pPager->pageSize;
29221       char *pData = CODEC2(pPager, PGHDR_TO_DATA(pList), pList->pgno, 6);
29222       PAGERTRACE4("STORE %d page %d hash(%08x)\n",
29223                    PAGERID(pPager), pList->pgno, pager_pagehash(pList));
29224       IOTRACE(("PGOUT %p %d\n", pPager, pList->pgno));
29225       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
29226       PAGER_INCR(sqlite3_pager_writedb_count);
29227       PAGER_INCR(pPager->nWrite);
29228       if( pList->pgno==1 ){
29229         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
29230       }
29231     }
29232 #ifndef NDEBUG
29233     else{
29234       PAGERTRACE3("NOSTORE %d page %d\n", PAGERID(pPager), pList->pgno);
29235     }
29236 #endif
29237     if( rc ) return rc;
29238 #ifdef SQLITE_CHECK_PAGES
29239     pList->pageHash = pager_pagehash(pList);
29240 #endif
29241     pList = pList->pDirty;
29242   }
29243   return SQLITE_OK;
29244 }
29245
29246 /*
29247 ** Collect every dirty page into a dirty list and
29248 ** return a pointer to the head of that list.  All pages are
29249 ** collected even if they are still in use.
29250 */
29251 static PgHdr *pager_get_all_dirty_pages(Pager *pPager){
29252
29253 #ifndef NDEBUG
29254   /* Verify the sanity of the dirty list when we are running
29255   ** in debugging mode.  This is expensive, so do not
29256   ** do this on a normal build. */
29257   int n1 = 0;
29258   int n2 = 0;
29259   PgHdr *p;
29260   for(p=pPager->pAll; p; p=p->pNextAll){ if( p->dirty ) n1++; }
29261   for(p=pPager->pDirty; p; p=p->pDirty){ n2++; }
29262   assert( n1==n2 );
29263 #endif
29264
29265   return pPager->pDirty;
29266 }
29267
29268 /*
29269 ** Return 1 if there is a hot journal on the given pager.
29270 ** A hot journal is one that needs to be played back.
29271 **
29272 ** If the current size of the database file is 0 but a journal file
29273 ** exists, that is probably an old journal left over from a prior
29274 ** database with the same name.  Just delete the journal.
29275 **
29276 ** Return negative if unable to determine the status of the journal.
29277 **
29278 ** This routine does not open the journal file to examine its
29279 ** content.  Hence, the journal might contain the name of a master
29280 ** journal file that has been deleted, and hence not be hot.  Or
29281 ** the header of the journal might be zeroed out.  This routine
29282 ** does not discover these cases of a non-hot journal - if the
29283 ** journal file exists and is not empty this routine assumes it
29284 ** is hot.  The pager_playback() routine will discover that the
29285 ** journal file is not really hot and will no-op.
29286 */
29287 static int hasHotJournal(Pager *pPager, int *pExists){
29288   sqlite3_vfs *pVfs = pPager->pVfs;
29289   int rc = SQLITE_OK;
29290   *pExists = 0;
29291   if( pPager->useJournal && pPager->fd->pMethods ){
29292     int exists;
29293     int locked;
29294
29295     rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
29296     if( rc==SQLITE_OK && exists ){
29297       rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
29298     }
29299
29300     if( rc==SQLITE_OK && exists && !locked ){
29301       int nPage;
29302       rc = sqlite3PagerPagecount(pPager, &nPage);
29303       if( rc==SQLITE_OK ){
29304         if( nPage==0 ){
29305           sqlite3OsDelete(pVfs, pPager->zJournal, 0);
29306         }else{
29307           *pExists = 1;
29308         }
29309       }
29310     }
29311   }
29312
29313   return rc;
29314 }
29315
29316 /*
29317 ** Try to find a page in the cache that can be recycled. 
29318 **
29319 ** This routine may return SQLITE_IOERR, SQLITE_FULL or SQLITE_OK. It 
29320 ** does not set the pPager->errCode variable.
29321 */
29322 static int pager_recycle(Pager *pPager, PgHdr **ppPg){
29323   PgHdr *pPg;
29324   *ppPg = 0;
29325
29326   /* It is illegal to call this function unless the pager object
29327   ** pointed to by pPager has at least one free page (page with nRef==0).
29328   */ 
29329   assert(!MEMDB);
29330   assert(pPager->lru.pFirst);
29331
29332   /* Find a page to recycle.  Try to locate a page that does not
29333   ** require us to do an fsync() on the journal.
29334   */
29335   pPg = pPager->lru.pFirstSynced;
29336
29337   /* If we could not find a page that does not require an fsync()
29338   ** on the journal file then fsync the journal file.  This is a
29339   ** very slow operation, so we work hard to avoid it.  But sometimes
29340   ** it can't be helped.
29341   */
29342   if( pPg==0 && pPager->lru.pFirst ){
29343     if( !pPager->errCode ){
29344       int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
29345       int rc = syncJournal(pPager);
29346       if( rc!=0 ){
29347         return rc;
29348       }
29349       if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
29350         /* If in full-sync mode, write a new journal header into the
29351         ** journal file. This is done to avoid ever modifying a journal
29352         ** header that is involved in the rollback of pages that have
29353         ** already been written to the database (in case the header is
29354         ** trashed when the nRec field is updated).
29355         */
29356         pPager->nRec = 0;
29357         assert( pPager->journalOff > 0 );
29358         assert( pPager->doNotSync==0 );
29359         rc = writeJournalHdr(pPager);
29360         if( rc!=0 ){
29361           return rc;
29362         }
29363       }
29364     }
29365     pPg = pPager->lru.pFirst;
29366   }
29367
29368   assert( pPg->nRef==0 );
29369
29370   /* Write the page to the database file if it is dirty.
29371   */
29372   if( pPg->dirty && !pPager->errCode ){
29373     int rc;
29374     assert( pPg->needSync==0 );
29375     makeClean(pPg);
29376     pPg->dirty = 1;
29377     pPg->pDirty = 0;
29378     rc = pager_write_pagelist( pPg );
29379     pPg->dirty = 0;
29380     if( rc!=SQLITE_OK ){
29381       return rc;
29382     }
29383   }
29384   assert( pPg->dirty==0 || pPager->errCode );
29385
29386   /* If the page we are recycling is marked as alwaysRollback, then
29387   ** set the global alwaysRollback flag, thus disabling the
29388   ** sqlite3PagerDontRollback() optimization for the rest of this transaction.
29389   ** It is necessary to do this because the page marked alwaysRollback
29390   ** might be reloaded at a later time but at that point we won't remember
29391   ** that is was marked alwaysRollback.  This means that all pages must
29392   ** be marked as alwaysRollback from here on out.
29393   */
29394   if( pPg->alwaysRollback ){
29395     IOTRACE(("ALWAYS_ROLLBACK %p\n", pPager))
29396     pPager->alwaysRollback = 1;
29397   }
29398
29399   /* Unlink the old page from the free list and the hash table
29400   */
29401   unlinkPage(pPg);
29402   assert( pPg->pgno==0 );
29403
29404   *ppPg = pPg;
29405   return SQLITE_OK;
29406 }
29407
29408 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
29409 /*
29410 ** This function is called to free superfluous dynamically allocated memory
29411 ** held by the pager system. Memory in use by any SQLite pager allocated
29412 ** by the current thread may be sqlite3_free()ed.
29413 **
29414 ** nReq is the number of bytes of memory required. Once this much has
29415 ** been released, the function returns. The return value is the total number 
29416 ** of bytes of memory released.
29417 */
29418 SQLITE_PRIVATE int sqlite3PagerReleaseMemory(int nReq){
29419   int nReleased = 0;          /* Bytes of memory released so far */
29420   Pager *pPager;              /* For looping over pagers */
29421   BusyHandler *savedBusy;     /* Saved copy of the busy handler */
29422   int rc = SQLITE_OK;
29423
29424   /* Acquire the memory-management mutex
29425   */
29426 #ifndef SQLITE_MUTEX_NOOP
29427   sqlite3_mutex *mutex;       /* The MEM2 mutex */
29428   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM2);
29429 #endif
29430   sqlite3_mutex_enter(mutex);
29431
29432   /* Signal all database connections that memory management wants
29433   ** to have access to the pagers.
29434   */
29435   for(pPager=sqlite3PagerList; pPager; pPager=pPager->pNext){
29436      pPager->iInUseMM = 1;
29437   }
29438
29439   while( rc==SQLITE_OK && (nReq<0 || nReleased<nReq) ){
29440     PgHdr *pPg;
29441     PgHdr *pRecycled;
29442  
29443     /* Try to find a page to recycle that does not require a sync(). If
29444     ** this is not possible, find one that does require a sync().
29445     */
29446     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU));
29447     pPg = sqlite3LruPageList.pFirstSynced;
29448     while( pPg && (pPg->needSync || pPg->pPager->iInUseDB) ){
29449       pPg = pPg->gfree.pNext;
29450     }
29451     if( !pPg ){
29452       pPg = sqlite3LruPageList.pFirst;
29453       while( pPg && pPg->pPager->iInUseDB ){
29454         pPg = pPg->gfree.pNext;
29455       }
29456     }
29457     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU));
29458
29459     /* If pPg==0, then the block above has failed to find a page to
29460     ** recycle. In this case return early - no further memory will
29461     ** be released.
29462     */
29463     if( !pPg ) break;
29464
29465     pPager = pPg->pPager;
29466     assert(!pPg->needSync || pPg==pPager->lru.pFirst);
29467     assert(pPg->needSync || pPg==pPager->lru.pFirstSynced);
29468   
29469     savedBusy = pPager->pBusyHandler;
29470     pPager->pBusyHandler = 0;
29471     rc = pager_recycle(pPager, &pRecycled);
29472     pPager->pBusyHandler = savedBusy;
29473     assert(pRecycled==pPg || rc!=SQLITE_OK);
29474     if( rc==SQLITE_OK ){
29475       /* We've found a page to free. At this point the page has been 
29476       ** removed from the page hash-table, free-list and synced-list 
29477       ** (pFirstSynced). It is still in the all pages (pAll) list. 
29478       ** Remove it from this list before freeing.
29479       **
29480       ** Todo: Check the Pager.pStmt list to make sure this is Ok. It 
29481       ** probably is though.
29482       */
29483       PgHdr *pTmp;
29484       assert( pPg );
29485       if( pPg==pPager->pAll ){
29486          assert(pPg->pPrevAll==0);
29487          assert(pPg->pNextAll==0 || pPg->pNextAll->pPrevAll==pPg);
29488          pPager->pAll = pPg->pNextAll;
29489          if( pPager->pAll ){
29490            pPager->pAll->pPrevAll = 0;
29491          }
29492       }else{
29493          assert(pPg->pPrevAll);
29494          assert(pPg->pPrevAll->pNextAll==pPg);
29495          pTmp = pPg->pPrevAll;
29496          pTmp->pNextAll = pPg->pNextAll;
29497          if( pTmp->pNextAll ){
29498            pTmp->pNextAll->pPrevAll = pTmp;
29499          }
29500       }
29501       nReleased += (
29502           sizeof(*pPg) + pPager->pageSize
29503           + sizeof(u32) + pPager->nExtra
29504           + MEMDB*sizeof(PgHistory) 
29505       );
29506       IOTRACE(("PGFREE %p %d *\n", pPager, pPg->pgno));
29507       PAGER_INCR(sqlite3_pager_pgfree_count);
29508       sqlite3PageFree(pPg->pData);
29509       sqlite3_free(pPg);
29510       pPager->nPage--;
29511     }else{
29512       /* An error occured whilst writing to the database file or 
29513       ** journal in pager_recycle(). The error is not returned to the 
29514       ** caller of this function. Instead, set the Pager.errCode variable.
29515       ** The error will be returned to the user (or users, in the case 
29516       ** of a shared pager cache) of the pager for which the error occured.
29517       */
29518       assert(
29519           (rc&0xff)==SQLITE_IOERR ||
29520           rc==SQLITE_FULL ||
29521           rc==SQLITE_BUSY
29522       );
29523       assert( pPager->state>=PAGER_RESERVED );
29524       pager_error(pPager, rc);
29525     }
29526   }
29527
29528   /* Clear the memory management flags and release the mutex
29529   */
29530   for(pPager=sqlite3PagerList; pPager; pPager=pPager->pNext){
29531      pPager->iInUseMM = 0;
29532   }
29533   sqlite3_mutex_leave(mutex);
29534
29535   /* Return the number of bytes released
29536   */
29537   return nReleased;
29538 }
29539 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
29540
29541 /*
29542 ** Read the content of page pPg out of the database file.
29543 */
29544 static int readDbPage(Pager *pPager, PgHdr *pPg, Pgno pgno){
29545   int rc;
29546   i64 offset;
29547   assert( MEMDB==0 );
29548   assert(pPager->fd->pMethods||pPager->tempFile);
29549   if( !pPager->fd->pMethods ){
29550     return SQLITE_IOERR_SHORT_READ;
29551   }
29552   offset = (pgno-1)*(i64)pPager->pageSize;
29553   rc = sqlite3OsRead(pPager->fd, PGHDR_TO_DATA(pPg), pPager->pageSize, offset);
29554   PAGER_INCR(sqlite3_pager_readdb_count);
29555   PAGER_INCR(pPager->nRead);
29556   IOTRACE(("PGIN %p %d\n", pPager, pgno));
29557   if( pgno==1 ){
29558     memcpy(&pPager->dbFileVers, &((u8*)PGHDR_TO_DATA(pPg))[24],
29559                                               sizeof(pPager->dbFileVers));
29560   }
29561   CODEC1(pPager, PGHDR_TO_DATA(pPg), pPg->pgno, 3);
29562   PAGERTRACE4("FETCH %d page %d hash(%08x)\n",
29563                PAGERID(pPager), pPg->pgno, pager_pagehash(pPg));
29564   return rc;
29565 }
29566
29567
29568 /*
29569 ** This function is called to obtain the shared lock required before
29570 ** data may be read from the pager cache. If the shared lock has already
29571 ** been obtained, this function is a no-op.
29572 **
29573 ** Immediately after obtaining the shared lock (if required), this function
29574 ** checks for a hot-journal file. If one is found, an emergency rollback
29575 ** is performed immediately.
29576 */
29577 static int pagerSharedLock(Pager *pPager){
29578   int rc = SQLITE_OK;
29579   int isErrorReset = 0;
29580
29581   /* If this database is opened for exclusive access, has no outstanding 
29582   ** page references and is in an error-state, now is the chance to clear
29583   ** the error. Discard the contents of the pager-cache and treat any
29584   ** open journal file as a hot-journal.
29585   */
29586   if( !MEMDB && pPager->exclusiveMode && pPager->nRef==0 && pPager->errCode ){
29587     if( pPager->journalOpen ){
29588       isErrorReset = 1;
29589     }
29590     pPager->errCode = SQLITE_OK;
29591     pager_reset(pPager);
29592   }
29593
29594   /* If the pager is still in an error state, do not proceed. The error 
29595   ** state will be cleared at some point in the future when all page 
29596   ** references are dropped and the cache can be discarded.
29597   */
29598   if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
29599     return pPager->errCode;
29600   }
29601
29602   if( pPager->state==PAGER_UNLOCK || isErrorReset ){
29603     sqlite3_vfs *pVfs = pPager->pVfs;
29604     if( !MEMDB ){
29605       int isHotJournal;
29606       assert( pPager->nRef==0 );
29607       if( !pPager->noReadlock ){
29608         rc = pager_wait_on_lock(pPager, SHARED_LOCK);
29609         if( rc!=SQLITE_OK ){
29610           assert( pPager->state==PAGER_UNLOCK );
29611           return pager_error(pPager, rc);
29612         }
29613         assert( pPager->state>=SHARED_LOCK );
29614       }
29615   
29616       /* If a journal file exists, and there is no RESERVED lock on the
29617       ** database file, then it either needs to be played back or deleted.
29618       */
29619       if( !isErrorReset ){
29620         rc = hasHotJournal(pPager, &isHotJournal);
29621         if( rc!=SQLITE_OK ){
29622           goto failed;
29623         }
29624       }
29625       if( isErrorReset || isHotJournal ){
29626         /* Get an EXCLUSIVE lock on the database file. At this point it is
29627         ** important that a RESERVED lock is not obtained on the way to the
29628         ** EXCLUSIVE lock. If it were, another process might open the
29629         ** database file, detect the RESERVED lock, and conclude that the
29630         ** database is safe to read while this process is still rolling it 
29631         ** back.
29632         ** 
29633         ** Because the intermediate RESERVED lock is not requested, the
29634         ** second process will get to this point in the code and fail to
29635         ** obtain its own EXCLUSIVE lock on the database file.
29636         */
29637         if( pPager->state<EXCLUSIVE_LOCK ){
29638           rc = sqlite3OsLock(pPager->fd, EXCLUSIVE_LOCK);
29639           if( rc!=SQLITE_OK ){
29640             rc = pager_error(pPager, rc);
29641             goto failed;
29642           }
29643           pPager->state = PAGER_EXCLUSIVE;
29644         }
29645  
29646         /* Open the journal for read/write access. This is because in 
29647         ** exclusive-access mode the file descriptor will be kept open and
29648         ** possibly used for a transaction later on. On some systems, the
29649         ** OsTruncate() call used in exclusive-access mode also requires
29650         ** a read/write file handle.
29651         */
29652         if( !isErrorReset && pPager->journalOpen==0 ){
29653           int res;
29654           rc = sqlite3OsAccess(pVfs,pPager->zJournal,SQLITE_ACCESS_EXISTS,&res);
29655           if( rc==SQLITE_OK ){
29656             if( res ){
29657               int fout = 0;
29658               int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
29659               assert( !pPager->tempFile );
29660               rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
29661               assert( rc!=SQLITE_OK || pPager->jfd->pMethods );
29662               if( fout&SQLITE_OPEN_READONLY ){
29663                 rc = SQLITE_BUSY;
29664                 sqlite3OsClose(pPager->jfd);
29665               }
29666             }else{
29667               /* If the journal does not exist, that means some other process
29668               ** has already rolled it back */
29669               rc = SQLITE_BUSY;
29670             }
29671           }
29672         }
29673         if( rc!=SQLITE_OK ){
29674           if( rc!=SQLITE_NOMEM && rc!=SQLITE_IOERR_UNLOCK 
29675            && rc!=SQLITE_IOERR_NOMEM 
29676           ){
29677             rc = SQLITE_BUSY;
29678           }
29679           goto failed;
29680         }
29681         pPager->journalOpen = 1;
29682         pPager->journalStarted = 0;
29683         pPager->journalOff = 0;
29684         pPager->setMaster = 0;
29685         pPager->journalHdr = 0;
29686  
29687         /* Playback and delete the journal.  Drop the database write
29688         ** lock and reacquire the read lock.
29689         */
29690         rc = pager_playback(pPager, 1);
29691         if( rc!=SQLITE_OK ){
29692           rc = pager_error(pPager, rc);
29693           goto failed;
29694         }
29695         assert(pPager->state==PAGER_SHARED || 
29696             (pPager->exclusiveMode && pPager->state>PAGER_SHARED)
29697         );
29698       }
29699
29700       if( pPager->pAll ){
29701         /* The shared-lock has just been acquired on the database file
29702         ** and there are already pages in the cache (from a previous
29703         ** read or write transaction).  Check to see if the database
29704         ** has been modified.  If the database has changed, flush the
29705         ** cache.
29706         **
29707         ** Database changes is detected by looking at 15 bytes beginning
29708         ** at offset 24 into the file.  The first 4 of these 16 bytes are
29709         ** a 32-bit counter that is incremented with each change.  The
29710         ** other bytes change randomly with each file change when
29711         ** a codec is in use.
29712         ** 
29713         ** There is a vanishingly small chance that a change will not be 
29714         ** detected.  The chance of an undetected change is so small that
29715         ** it can be neglected.
29716         */
29717         char dbFileVers[sizeof(pPager->dbFileVers)];
29718         sqlite3PagerPagecount(pPager, 0);
29719
29720         if( pPager->errCode ){
29721           rc = pPager->errCode;
29722           goto failed;
29723         }
29724
29725         if( pPager->dbSize>0 ){
29726           IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
29727           rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
29728           if( rc!=SQLITE_OK ){
29729             goto failed;
29730           }
29731         }else{
29732           memset(dbFileVers, 0, sizeof(dbFileVers));
29733         }
29734
29735         if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
29736           pager_reset(pPager);
29737         }
29738       }
29739     }
29740     assert( pPager->exclusiveMode || pPager->state<=PAGER_SHARED );
29741     if( pPager->state==PAGER_UNLOCK ){
29742       pPager->state = PAGER_SHARED;
29743     }
29744   }
29745
29746  failed:
29747   if( rc!=SQLITE_OK ){
29748     /* pager_unlock() is a no-op for exclusive mode and in-memory databases. */
29749     pager_unlock(pPager);
29750   }
29751   return rc;
29752 }
29753
29754 /*
29755 ** Allocate a PgHdr object.   Either create a new one or reuse
29756 ** an existing one that is not otherwise in use.
29757 **
29758 ** A new PgHdr structure is created if any of the following are
29759 ** true:
29760 **
29761 **     (1)  We have not exceeded our maximum allocated cache size
29762 **          as set by the "PRAGMA cache_size" command.
29763 **
29764 **     (2)  There are no unused PgHdr objects available at this time.
29765 **
29766 **     (3)  This is an in-memory database.
29767 **
29768 **     (4)  There are no PgHdr objects that do not require a journal
29769 **          file sync and a sync of the journal file is currently
29770 **          prohibited.
29771 **
29772 ** Otherwise, reuse an existing PgHdr.  In other words, reuse an
29773 ** existing PgHdr if all of the following are true:
29774 **
29775 **     (1)  We have reached or exceeded the maximum cache size
29776 **          allowed by "PRAGMA cache_size".
29777 **
29778 **     (2)  There is a PgHdr available with PgHdr->nRef==0
29779 **
29780 **     (3)  We are not in an in-memory database
29781 **
29782 **     (4)  Either there is an available PgHdr that does not need
29783 **          to be synced to disk or else disk syncing is currently
29784 **          allowed.
29785 */
29786 static int pagerAllocatePage(Pager *pPager, PgHdr **ppPg){
29787   int rc = SQLITE_OK;
29788   PgHdr *pPg;
29789   int nByteHdr;
29790
29791   /* Create a new PgHdr if any of the four conditions defined 
29792   ** above are met: */
29793   if( pPager->nPage<pPager->mxPage
29794    || pPager->lru.pFirst==0 
29795    || MEMDB
29796    || (pPager->lru.pFirstSynced==0 && pPager->doNotSync)
29797   ){
29798     void *pData;
29799     if( pPager->nPage>=pPager->nHash ){
29800       pager_resize_hash_table(pPager,
29801          pPager->nHash<256 ? 256 : pPager->nHash*2);
29802       if( pPager->nHash==0 ){
29803         rc = SQLITE_NOMEM;
29804         goto pager_allocate_out;
29805       }
29806     }
29807     pagerLeave(pPager);
29808     nByteHdr = sizeof(*pPg) + sizeof(u32) + pPager->nExtra
29809               + MEMDB*sizeof(PgHistory);
29810     pPg = sqlite3Malloc( nByteHdr );
29811     if( pPg ){
29812       pData = sqlite3PageMalloc( pPager->pageSize );
29813       if( pData==0 ){
29814         sqlite3_free(pPg);
29815         pPg = 0;
29816       }
29817     }
29818     pagerEnter(pPager);
29819     if( pPg==0 ){
29820       rc = SQLITE_NOMEM;
29821       goto pager_allocate_out;
29822     }
29823     memset(pPg, 0, nByteHdr);
29824     pPg->pData = pData;
29825     pPg->pPager = pPager;
29826     pPg->pNextAll = pPager->pAll;
29827 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
29828     if( pPg->pNextAll ){
29829       pPg->pNextAll->pPrevAll = pPg;
29830     }
29831 #endif
29832     pPager->pAll = pPg;
29833     pPager->nPage++;
29834   }else{
29835     /* Recycle an existing page with a zero ref-count. */
29836     rc = pager_recycle(pPager, &pPg);
29837     if( rc==SQLITE_BUSY ){
29838       rc = SQLITE_IOERR_BLOCKED;
29839     }
29840     if( rc!=SQLITE_OK ){
29841       goto pager_allocate_out;
29842     }
29843     assert( pPager->state>=SHARED_LOCK );
29844     assert(pPg);
29845   }
29846   *ppPg = pPg;
29847
29848 pager_allocate_out:
29849   return rc;
29850 }
29851
29852 /*
29853 ** Make sure we have the content for a page.  If the page was
29854 ** previously acquired with noContent==1, then the content was
29855 ** just initialized to zeros instead of being read from disk.
29856 ** But now we need the real data off of disk.  So make sure we
29857 ** have it.  Read it in if we do not have it already.
29858 */
29859 static int pager_get_content(PgHdr *pPg){
29860   if( pPg->needRead ){
29861     int rc = readDbPage(pPg->pPager, pPg, pPg->pgno);
29862     if( rc==SQLITE_OK ){
29863       pPg->needRead = 0;
29864     }else{
29865       return rc;
29866     }
29867   }
29868   return SQLITE_OK;
29869 }
29870
29871 /*
29872 ** Acquire a page.
29873 **
29874 ** A read lock on the disk file is obtained when the first page is acquired. 
29875 ** This read lock is dropped when the last page is released.
29876 **
29877 ** This routine works for any page number greater than 0.  If the database
29878 ** file is smaller than the requested page, then no actual disk
29879 ** read occurs and the memory image of the page is initialized to
29880 ** all zeros.  The extra data appended to a page is always initialized
29881 ** to zeros the first time a page is loaded into memory.
29882 **
29883 ** The acquisition might fail for several reasons.  In all cases,
29884 ** an appropriate error code is returned and *ppPage is set to NULL.
29885 **
29886 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
29887 ** to find a page in the in-memory cache first.  If the page is not already
29888 ** in memory, this routine goes to disk to read it in whereas Lookup()
29889 ** just returns 0.  This routine acquires a read-lock the first time it
29890 ** has to go to disk, and could also playback an old journal if necessary.
29891 ** Since Lookup() never goes to disk, it never has to deal with locks
29892 ** or journal files.
29893 **
29894 ** If noContent is false, the page contents are actually read from disk.
29895 ** If noContent is true, it means that we do not care about the contents
29896 ** of the page at this time, so do not do a disk read.  Just fill in the
29897 ** page content with zeros.  But mark the fact that we have not read the
29898 ** content by setting the PgHdr.needRead flag.  Later on, if 
29899 ** sqlite3PagerWrite() is called on this page or if this routine is
29900 ** called again with noContent==0, that means that the content is needed
29901 ** and the disk read should occur at that point.
29902 */
29903 static int pagerAcquire(
29904   Pager *pPager,      /* The pager open on the database file */
29905   Pgno pgno,          /* Page number to fetch */
29906   DbPage **ppPage,    /* Write a pointer to the page here */
29907   int noContent       /* Do not bother reading content from disk if true */
29908 ){
29909   PgHdr *pPg;
29910   int rc;
29911
29912   assert( pPager->state==PAGER_UNLOCK || pPager->nRef>0 || pgno==1 );
29913
29914   /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
29915   ** number greater than this, or zero, is requested.
29916   */
29917   if( pgno>PAGER_MAX_PGNO || pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
29918     return SQLITE_CORRUPT_BKPT;
29919   }
29920
29921   /* Make sure we have not hit any critical errors.
29922   */ 
29923   assert( pPager!=0 );
29924   *ppPage = 0;
29925
29926   /* If this is the first page accessed, then get a SHARED lock
29927   ** on the database file. pagerSharedLock() is a no-op if 
29928   ** a database lock is already held.
29929   */
29930   rc = pagerSharedLock(pPager);
29931   if( rc!=SQLITE_OK ){
29932     return rc;
29933   }
29934   assert( pPager->state!=PAGER_UNLOCK );
29935
29936   pPg = pager_lookup(pPager, pgno);
29937   if( pPg==0 ){
29938     /* The requested page is not in the page cache. */
29939     int nMax;
29940     int h;
29941     PAGER_INCR(pPager->nMiss);
29942     rc = pagerAllocatePage(pPager, &pPg);
29943     if( rc!=SQLITE_OK ){
29944       return rc;
29945     }
29946
29947     pPg->pgno = pgno;
29948     assert( !MEMDB || pgno>pPager->stmtSize );
29949     pPg->inJournal = sqlite3BitvecTest(pPager->pInJournal, pgno);
29950     pPg->needSync = 0;
29951
29952     makeClean(pPg);
29953     pPg->nRef = 1;
29954
29955     pPager->nRef++;
29956     if( pPager->nExtra>0 ){
29957       memset(PGHDR_TO_EXTRA(pPg, pPager), 0, pPager->nExtra);
29958     }
29959     rc = sqlite3PagerPagecount(pPager, &nMax);
29960     if( rc!=SQLITE_OK ){
29961       sqlite3PagerUnref(pPg);
29962       return rc;
29963     }
29964
29965     /* Populate the page with data, either by reading from the database
29966     ** file, or by setting the entire page to zero.
29967     */
29968     if( nMax<(int)pgno || MEMDB || (noContent && !pPager->alwaysRollback) ){
29969       if( pgno>pPager->mxPgno ){
29970         sqlite3PagerUnref(pPg);
29971         return SQLITE_FULL;
29972       }
29973       memset(PGHDR_TO_DATA(pPg), 0, pPager->pageSize);
29974       pPg->needRead = noContent && !pPager->alwaysRollback;
29975       IOTRACE(("ZERO %p %d\n", pPager, pgno));
29976     }else{
29977       rc = readDbPage(pPager, pPg, pgno);
29978       if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
29979         pPg->pgno = 0;
29980         sqlite3PagerUnref(pPg);
29981         return rc;
29982       }
29983       pPg->needRead = 0;
29984     }
29985
29986     /* Link the page into the page hash table */
29987     h = pgno & (pPager->nHash-1);
29988     assert( pgno!=0 );
29989     pPg->pNextHash = pPager->aHash[h];
29990     pPager->aHash[h] = pPg;
29991     if( pPg->pNextHash ){
29992       assert( pPg->pNextHash->pPrevHash==0 );
29993       pPg->pNextHash->pPrevHash = pPg;
29994     }
29995
29996 #ifdef SQLITE_CHECK_PAGES
29997     pPg->pageHash = pager_pagehash(pPg);
29998 #endif
29999   }else{
30000     /* The requested page is in the page cache. */
30001     assert(pPager->nRef>0 || pgno==1);
30002     PAGER_INCR(pPager->nHit);
30003     if( !noContent ){
30004       rc = pager_get_content(pPg);
30005       if( rc ){
30006         return rc;
30007       }
30008     }
30009     page_ref(pPg);
30010   }
30011   *ppPage = pPg;
30012   return SQLITE_OK;
30013 }
30014 SQLITE_PRIVATE int sqlite3PagerAcquire(
30015   Pager *pPager,      /* The pager open on the database file */
30016   Pgno pgno,          /* Page number to fetch */
30017   DbPage **ppPage,    /* Write a pointer to the page here */
30018   int noContent       /* Do not bother reading content from disk if true */
30019 ){
30020   int rc;
30021   pagerEnter(pPager);
30022   rc = pagerAcquire(pPager, pgno, ppPage, noContent);
30023   pagerLeave(pPager);
30024   return rc;
30025 }
30026
30027
30028 /*
30029 ** Acquire a page if it is already in the in-memory cache.  Do
30030 ** not read the page from disk.  Return a pointer to the page,
30031 ** or 0 if the page is not in cache.
30032 **
30033 ** See also sqlite3PagerGet().  The difference between this routine
30034 ** and sqlite3PagerGet() is that _get() will go to the disk and read
30035 ** in the page if the page is not already in cache.  This routine
30036 ** returns NULL if the page is not in cache or if a disk I/O error 
30037 ** has ever happened.
30038 */
30039 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
30040   PgHdr *pPg = 0;
30041
30042   assert( pPager!=0 );
30043   assert( pgno!=0 );
30044
30045   pagerEnter(pPager);
30046   if( pPager->state==PAGER_UNLOCK ){
30047     assert( !pPager->pAll || pPager->exclusiveMode );
30048   }else if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
30049     /* Do nothing */
30050   }else if( (pPg = pager_lookup(pPager, pgno))!=0 ){
30051     page_ref(pPg);
30052   }
30053   pagerLeave(pPager);
30054   return pPg;
30055 }
30056
30057 /*
30058 ** Release a page.
30059 **
30060 ** If the number of references to the page drop to zero, then the
30061 ** page is added to the LRU list.  When all references to all pages
30062 ** are released, a rollback occurs and the lock on the database is
30063 ** removed.
30064 */
30065 SQLITE_PRIVATE int sqlite3PagerUnref(DbPage *pPg){
30066   Pager *pPager;
30067
30068   if( pPg==0 ) return SQLITE_OK;
30069   pPager = pPg->pPager;
30070
30071   /* Decrement the reference count for this page
30072   */
30073   assert( pPg->nRef>0 );
30074   pagerEnter(pPg->pPager);
30075   pPg->nRef--;
30076
30077   CHECK_PAGE(pPg);
30078
30079   /* When the number of references to a page reach 0, call the
30080   ** destructor and add the page to the freelist.
30081   */
30082   if( pPg->nRef==0 ){
30083
30084     lruListAdd(pPg);
30085     if( pPager->xDestructor ){
30086       pPager->xDestructor(pPg, pPager->pageSize);
30087     }
30088   
30089     /* When all pages reach the freelist, drop the read lock from
30090     ** the database file.
30091     */
30092     pPager->nRef--;
30093     assert( pPager->nRef>=0 );
30094     if( pPager->nRef==0 && (!pPager->exclusiveMode || pPager->journalOff>0) ){
30095       pagerUnlockAndRollback(pPager);
30096     }
30097   }
30098   pagerLeave(pPager);
30099   return SQLITE_OK;
30100 }
30101
30102 /*
30103 ** Create a journal file for pPager.  There should already be a RESERVED
30104 ** or EXCLUSIVE lock on the database file when this routine is called.
30105 **
30106 ** Return SQLITE_OK if everything.  Return an error code and release the
30107 ** write lock if anything goes wrong.
30108 */
30109 static int pager_open_journal(Pager *pPager){
30110   sqlite3_vfs *pVfs = pPager->pVfs;
30111   int flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_CREATE);
30112
30113   int rc;
30114   assert( !MEMDB );
30115   assert( pPager->state>=PAGER_RESERVED );
30116   assert( pPager->useJournal );
30117   assert( pPager->pInJournal==0 );
30118   sqlite3PagerPagecount(pPager, 0);
30119   pagerLeave(pPager);
30120   pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
30121   pagerEnter(pPager);
30122   if( pPager->pInJournal==0 ){
30123     rc = SQLITE_NOMEM;
30124     goto failed_to_open_journal;
30125   }
30126
30127   if( pPager->journalOpen==0 ){
30128     if( pPager->tempFile ){
30129       flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
30130     }else{
30131       flags |= (SQLITE_OPEN_MAIN_JOURNAL);
30132     }
30133 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
30134     rc = sqlite3JournalOpen(
30135         pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
30136     );
30137 #else
30138     rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
30139 #endif
30140     assert( rc!=SQLITE_OK || pPager->jfd->pMethods );
30141     pPager->journalOff = 0;
30142     pPager->setMaster = 0;
30143     pPager->journalHdr = 0;
30144     if( rc!=SQLITE_OK ){
30145       if( rc==SQLITE_NOMEM ){
30146         sqlite3OsDelete(pVfs, pPager->zJournal, 0);
30147       }
30148       goto failed_to_open_journal;
30149     }
30150   }
30151   pPager->journalOpen = 1;
30152   pPager->journalStarted = 0;
30153   pPager->needSync = 0;
30154   pPager->alwaysRollback = 0;
30155   pPager->nRec = 0;
30156   if( pPager->errCode ){
30157     rc = pPager->errCode;
30158     goto failed_to_open_journal;
30159   }
30160   pPager->origDbSize = pPager->dbSize;
30161
30162   rc = writeJournalHdr(pPager);
30163
30164   if( pPager->stmtAutoopen && rc==SQLITE_OK ){
30165     rc = sqlite3PagerStmtBegin(pPager);
30166   }
30167   if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && rc!=SQLITE_IOERR_NOMEM ){
30168     rc = pager_end_transaction(pPager, 0);
30169     if( rc==SQLITE_OK ){
30170       rc = SQLITE_FULL;
30171     }
30172   }
30173   return rc;
30174
30175 failed_to_open_journal:
30176   sqlite3BitvecDestroy(pPager->pInJournal);
30177   pPager->pInJournal = 0;
30178   return rc;
30179 }
30180
30181 /*
30182 ** Acquire a write-lock on the database.  The lock is removed when
30183 ** the any of the following happen:
30184 **
30185 **   *  sqlite3PagerCommitPhaseTwo() is called.
30186 **   *  sqlite3PagerRollback() is called.
30187 **   *  sqlite3PagerClose() is called.
30188 **   *  sqlite3PagerUnref() is called to on every outstanding page.
30189 **
30190 ** The first parameter to this routine is a pointer to any open page of the
30191 ** database file.  Nothing changes about the page - it is used merely to
30192 ** acquire a pointer to the Pager structure and as proof that there is
30193 ** already a read-lock on the database.
30194 **
30195 ** The second parameter indicates how much space in bytes to reserve for a
30196 ** master journal file-name at the start of the journal when it is created.
30197 **
30198 ** A journal file is opened if this is not a temporary file.  For temporary
30199 ** files, the opening of the journal file is deferred until there is an
30200 ** actual need to write to the journal.
30201 **
30202 ** If the database is already reserved for writing, this routine is a no-op.
30203 **
30204 ** If exFlag is true, go ahead and get an EXCLUSIVE lock on the file
30205 ** immediately instead of waiting until we try to flush the cache.  The
30206 ** exFlag is ignored if a transaction is already active.
30207 */
30208 SQLITE_PRIVATE int sqlite3PagerBegin(DbPage *pPg, int exFlag){
30209   Pager *pPager = pPg->pPager;
30210   int rc = SQLITE_OK;
30211   pagerEnter(pPager);
30212   assert( pPg->nRef>0 );
30213   assert( pPager->state!=PAGER_UNLOCK );
30214   if( pPager->state==PAGER_SHARED ){
30215     assert( pPager->pInJournal==0 );
30216     if( MEMDB ){
30217       pPager->state = PAGER_EXCLUSIVE;
30218       pPager->origDbSize = pPager->dbSize;
30219     }else{
30220       rc = sqlite3OsLock(pPager->fd, RESERVED_LOCK);
30221       if( rc==SQLITE_OK ){
30222         pPager->state = PAGER_RESERVED;
30223         if( exFlag ){
30224           rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
30225         }
30226       }
30227       if( rc!=SQLITE_OK ){
30228         pagerLeave(pPager);
30229         return rc;
30230       }
30231       pPager->dirtyCache = 0;
30232       PAGERTRACE2("TRANSACTION %d\n", PAGERID(pPager));
30233       if( pPager->useJournal && !pPager->tempFile
30234              && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
30235         rc = pager_open_journal(pPager);
30236       }
30237     }
30238   }else if( pPager->journalOpen && pPager->journalOff==0 ){
30239     /* This happens when the pager was in exclusive-access mode the last
30240     ** time a (read or write) transaction was successfully concluded
30241     ** by this connection. Instead of deleting the journal file it was 
30242     ** kept open and either was truncated to 0 bytes or its header was
30243     ** overwritten with zeros.
30244     */
30245     assert( pPager->nRec==0 );
30246     assert( pPager->origDbSize==0 );
30247     assert( pPager->pInJournal==0 );
30248     sqlite3PagerPagecount(pPager, 0);
30249     pagerLeave(pPager);
30250     pPager->pInJournal = sqlite3BitvecCreate( pPager->dbSize );
30251     pagerEnter(pPager);
30252     if( !pPager->pInJournal ){
30253       rc = SQLITE_NOMEM;
30254     }else{
30255       pPager->origDbSize = pPager->dbSize;
30256       rc = writeJournalHdr(pPager);
30257     }
30258   }
30259   assert( !pPager->journalOpen || pPager->journalOff>0 || rc!=SQLITE_OK );
30260   pagerLeave(pPager);
30261   return rc;
30262 }
30263
30264 /*
30265 ** Make a page dirty.  Set its dirty flag and add it to the dirty
30266 ** page list.
30267 */
30268 static void makeDirty(PgHdr *pPg){
30269   if( pPg->dirty==0 ){
30270     Pager *pPager = pPg->pPager;
30271     pPg->dirty = 1;
30272     pPg->pDirty = pPager->pDirty;
30273     if( pPager->pDirty ){
30274       pPager->pDirty->pPrevDirty = pPg;
30275     }
30276     pPg->pPrevDirty = 0;
30277     pPager->pDirty = pPg;
30278   }
30279 }
30280
30281 /*
30282 ** Make a page clean.  Clear its dirty bit and remove it from the
30283 ** dirty page list.
30284 */
30285 static void makeClean(PgHdr *pPg){
30286   if( pPg->dirty ){
30287     pPg->dirty = 0;
30288     if( pPg->pDirty ){
30289       assert( pPg->pDirty->pPrevDirty==pPg );
30290       pPg->pDirty->pPrevDirty = pPg->pPrevDirty;
30291     }
30292     if( pPg->pPrevDirty ){
30293       assert( pPg->pPrevDirty->pDirty==pPg );
30294       pPg->pPrevDirty->pDirty = pPg->pDirty;
30295     }else{
30296       assert( pPg->pPager->pDirty==pPg );
30297       pPg->pPager->pDirty = pPg->pDirty;
30298     }
30299   }
30300 }
30301
30302
30303 /*
30304 ** Mark a data page as writeable.  The page is written into the journal 
30305 ** if it is not there already.  This routine must be called before making
30306 ** changes to a page.
30307 **
30308 ** The first time this routine is called, the pager creates a new
30309 ** journal and acquires a RESERVED lock on the database.  If the RESERVED
30310 ** lock could not be acquired, this routine returns SQLITE_BUSY.  The
30311 ** calling routine must check for that return value and be careful not to
30312 ** change any page data until this routine returns SQLITE_OK.
30313 **
30314 ** If the journal file could not be written because the disk is full,
30315 ** then this routine returns SQLITE_FULL and does an immediate rollback.
30316 ** All subsequent write attempts also return SQLITE_FULL until there
30317 ** is a call to sqlite3PagerCommit() or sqlite3PagerRollback() to
30318 ** reset.
30319 */
30320 static int pager_write(PgHdr *pPg){
30321   void *pData = PGHDR_TO_DATA(pPg);
30322   Pager *pPager = pPg->pPager;
30323   int rc = SQLITE_OK;
30324
30325   /* Check for errors
30326   */
30327   if( pPager->errCode ){ 
30328     return pPager->errCode;
30329   }
30330   if( pPager->readOnly ){
30331     return SQLITE_PERM;
30332   }
30333
30334   assert( !pPager->setMaster );
30335
30336   CHECK_PAGE(pPg);
30337
30338   /* If this page was previously acquired with noContent==1, that means
30339   ** we didn't really read in the content of the page.  This can happen
30340   ** (for example) when the page is being moved to the freelist.  But
30341   ** now we are (perhaps) moving the page off of the freelist for
30342   ** reuse and we need to know its original content so that content
30343   ** can be stored in the rollback journal.  So do the read at this
30344   ** time.
30345   */
30346   rc = pager_get_content(pPg);
30347   if( rc ){
30348     return rc;
30349   }
30350
30351   /* Mark the page as dirty.  If the page has already been written
30352   ** to the journal then we can return right away.
30353   */
30354   makeDirty(pPg);
30355   if( pPg->inJournal && (pageInStatement(pPg) || pPager->stmtInUse==0) ){
30356     pPager->dirtyCache = 1;
30357     pPager->dbModified = 1;
30358   }else{
30359
30360     /* If we get this far, it means that the page needs to be
30361     ** written to the transaction journal or the ckeckpoint journal
30362     ** or both.
30363     **
30364     ** First check to see that the transaction journal exists and
30365     ** create it if it does not.
30366     */
30367     assert( pPager->state!=PAGER_UNLOCK );
30368     rc = sqlite3PagerBegin(pPg, 0);
30369     if( rc!=SQLITE_OK ){
30370       return rc;
30371     }
30372     assert( pPager->state>=PAGER_RESERVED );
30373     if( !pPager->journalOpen && pPager->useJournal
30374           && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
30375       rc = pager_open_journal(pPager);
30376       if( rc!=SQLITE_OK ) return rc;
30377     }
30378     pPager->dirtyCache = 1;
30379     pPager->dbModified = 1;
30380   
30381     /* The transaction journal now exists and we have a RESERVED or an
30382     ** EXCLUSIVE lock on the main database file.  Write the current page to
30383     ** the transaction journal if it is not there already.
30384     */
30385     if( !pPg->inJournal && (pPager->journalOpen || MEMDB) ){
30386       if( (int)pPg->pgno <= pPager->origDbSize ){
30387         if( MEMDB ){
30388           PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
30389           PAGERTRACE3("JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno);
30390           assert( pHist->pOrig==0 );
30391           pHist->pOrig = sqlite3PageMalloc( pPager->pageSize );
30392           if( !pHist->pOrig ){
30393             return SQLITE_NOMEM;
30394           }
30395           memcpy(pHist->pOrig, PGHDR_TO_DATA(pPg), pPager->pageSize);
30396         }else{
30397           u32 cksum;
30398           char *pData2;
30399
30400           /* We should never write to the journal file the page that
30401           ** contains the database locks.  The following assert verifies
30402           ** that we do not. */
30403           assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
30404           pData2 = CODEC2(pPager, pData, pPg->pgno, 7);
30405           cksum = pager_cksum(pPager, (u8*)pData2);
30406           rc = write32bits(pPager->jfd, pPager->journalOff, pPg->pgno);
30407           if( rc==SQLITE_OK ){
30408             rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize,
30409                                 pPager->journalOff + 4);
30410             pPager->journalOff += pPager->pageSize+4;
30411           }
30412           if( rc==SQLITE_OK ){
30413             rc = write32bits(pPager->jfd, pPager->journalOff, cksum);
30414             pPager->journalOff += 4;
30415           }
30416           IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
30417                    pPager->journalOff, pPager->pageSize));
30418           PAGER_INCR(sqlite3_pager_writej_count);
30419           PAGERTRACE5("JOURNAL %d page %d needSync=%d hash(%08x)\n",
30420                PAGERID(pPager), pPg->pgno, pPg->needSync, pager_pagehash(pPg));
30421
30422           /* An error has occured writing to the journal file. The 
30423           ** transaction will be rolled back by the layer above.
30424           */
30425           if( rc!=SQLITE_OK ){
30426             return rc;
30427           }
30428
30429           pPager->nRec++;
30430           assert( pPager->pInJournal!=0 );
30431           sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
30432           pPg->needSync = !pPager->noSync;
30433           if( pPager->stmtInUse ){
30434             sqlite3BitvecSet(pPager->pInStmt, pPg->pgno);
30435           }
30436         }
30437       }else{
30438         pPg->needSync = !pPager->journalStarted && !pPager->noSync;
30439         PAGERTRACE4("APPEND %d page %d needSync=%d\n",
30440                 PAGERID(pPager), pPg->pgno, pPg->needSync);
30441       }
30442       if( pPg->needSync ){
30443         pPager->needSync = 1;
30444       }
30445       pPg->inJournal = 1;
30446     }
30447   
30448     /* If the statement journal is open and the page is not in it,
30449     ** then write the current page to the statement journal.  Note that
30450     ** the statement journal format differs from the standard journal format
30451     ** in that it omits the checksums and the header.
30452     */
30453     if( pPager->stmtInUse 
30454      && !pageInStatement(pPg) 
30455      && (int)pPg->pgno<=pPager->stmtSize 
30456     ){
30457       assert( pPg->inJournal || (int)pPg->pgno>pPager->origDbSize );
30458       if( MEMDB ){
30459         PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
30460         assert( pHist->pStmt==0 );
30461         pHist->pStmt = sqlite3PageMalloc( pPager->pageSize );
30462         if( pHist->pStmt ){
30463           memcpy(pHist->pStmt, PGHDR_TO_DATA(pPg), pPager->pageSize);
30464         }
30465         PAGERTRACE3("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno);
30466         page_add_to_stmt_list(pPg);
30467       }else{
30468         i64 offset = pPager->stmtNRec*(4+pPager->pageSize);
30469         char *pData2 = CODEC2(pPager, pData, pPg->pgno, 7);
30470         rc = write32bits(pPager->stfd, offset, pPg->pgno);
30471         if( rc==SQLITE_OK ){
30472           rc = sqlite3OsWrite(pPager->stfd, pData2, pPager->pageSize, offset+4);
30473         }
30474         PAGERTRACE3("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno);
30475         if( rc!=SQLITE_OK ){
30476           return rc;
30477         }
30478         pPager->stmtNRec++;
30479         assert( pPager->pInStmt!=0 );
30480         sqlite3BitvecSet(pPager->pInStmt, pPg->pgno);
30481       }
30482     }
30483   }
30484
30485   /* Update the database size and return.
30486   */
30487   assert( pPager->state>=PAGER_SHARED );
30488   if( pPager->dbSize<(int)pPg->pgno ){
30489     pPager->dbSize = pPg->pgno;
30490     if( !MEMDB && pPager->dbSize==PENDING_BYTE/pPager->pageSize ){
30491       pPager->dbSize++;
30492     }
30493   }
30494   return rc;
30495 }
30496
30497 /*
30498 ** This function is used to mark a data-page as writable. It uses 
30499 ** pager_write() to open a journal file (if it is not already open)
30500 ** and write the page *pData to the journal.
30501 **
30502 ** The difference between this function and pager_write() is that this
30503 ** function also deals with the special case where 2 or more pages
30504 ** fit on a single disk sector. In this case all co-resident pages
30505 ** must have been written to the journal file before returning.
30506 */
30507 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
30508   int rc = SQLITE_OK;
30509
30510   PgHdr *pPg = pDbPage;
30511   Pager *pPager = pPg->pPager;
30512   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
30513
30514   pagerEnter(pPager);
30515   if( !MEMDB && nPagePerSector>1 ){
30516     Pgno nPageCount;          /* Total number of pages in database file */
30517     Pgno pg1;                 /* First page of the sector pPg is located on. */
30518     int nPage;                /* Number of pages starting at pg1 to journal */
30519     int ii;
30520     int needSync = 0;
30521
30522     /* Set the doNotSync flag to 1. This is because we cannot allow a journal
30523     ** header to be written between the pages journaled by this function.
30524     */
30525     assert( pPager->doNotSync==0 );
30526     pPager->doNotSync = 1;
30527
30528     /* This trick assumes that both the page-size and sector-size are
30529     ** an integer power of 2. It sets variable pg1 to the identifier
30530     ** of the first page of the sector pPg is located on.
30531     */
30532     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
30533
30534     sqlite3PagerPagecount(pPager, (int *)&nPageCount);
30535     if( pPg->pgno>nPageCount ){
30536       nPage = (pPg->pgno - pg1)+1;
30537     }else if( (pg1+nPagePerSector-1)>nPageCount ){
30538       nPage = nPageCount+1-pg1;
30539     }else{
30540       nPage = nPagePerSector;
30541     }
30542     assert(nPage>0);
30543     assert(pg1<=pPg->pgno);
30544     assert((pg1+nPage)>pPg->pgno);
30545
30546     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
30547       Pgno pg = pg1+ii;
30548       PgHdr *pPage;
30549       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
30550         if( pg!=PAGER_MJ_PGNO(pPager) ){
30551           rc = sqlite3PagerGet(pPager, pg, &pPage);
30552           if( rc==SQLITE_OK ){
30553             rc = pager_write(pPage);
30554             if( pPage->needSync ){
30555               needSync = 1;
30556             }
30557             sqlite3PagerUnref(pPage);
30558           }
30559         }
30560       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
30561         if( pPage->needSync ){
30562           needSync = 1;
30563         }
30564       }
30565     }
30566
30567     /* If the PgHdr.needSync flag is set for any of the nPage pages 
30568     ** starting at pg1, then it needs to be set for all of them. Because
30569     ** writing to any of these nPage pages may damage the others, the
30570     ** journal file must contain sync()ed copies of all of them
30571     ** before any of them can be written out to the database file.
30572     */
30573     if( needSync ){
30574       for(ii=0; ii<nPage && needSync; ii++){
30575         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
30576         if( pPage ) pPage->needSync = 1;
30577       }
30578       assert(pPager->needSync);
30579     }
30580
30581     assert( pPager->doNotSync==1 );
30582     pPager->doNotSync = 0;
30583   }else{
30584     rc = pager_write(pDbPage);
30585   }
30586   pagerLeave(pPager);
30587   return rc;
30588 }
30589
30590 /*
30591 ** Return TRUE if the page given in the argument was previously passed
30592 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
30593 ** to change the content of the page.
30594 */
30595 #ifndef NDEBUG
30596 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
30597   return pPg->dirty;
30598 }
30599 #endif
30600
30601 /*
30602 ** A call to this routine tells the pager that it is not necessary to
30603 ** write the information on page pPg back to the disk, even though
30604 ** that page might be marked as dirty.
30605 **
30606 ** The overlying software layer calls this routine when all of the data
30607 ** on the given page is unused.  The pager marks the page as clean so
30608 ** that it does not get written to disk.
30609 **
30610 ** Tests show that this optimization, together with the
30611 ** sqlite3PagerDontRollback() below, more than double the speed
30612 ** of large INSERT operations and quadruple the speed of large DELETEs.
30613 **
30614 ** When this routine is called, set the alwaysRollback flag to true.
30615 ** Subsequent calls to sqlite3PagerDontRollback() for the same page
30616 ** will thereafter be ignored.  This is necessary to avoid a problem
30617 ** where a page with data is added to the freelist during one part of
30618 ** a transaction then removed from the freelist during a later part
30619 ** of the same transaction and reused for some other purpose.  When it
30620 ** is first added to the freelist, this routine is called.  When reused,
30621 ** the sqlite3PagerDontRollback() routine is called.  But because the
30622 ** page contains critical data, we still need to be sure it gets
30623 ** rolled back in spite of the sqlite3PagerDontRollback() call.
30624 */
30625 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage *pDbPage){
30626   PgHdr *pPg = pDbPage;
30627   Pager *pPager = pPg->pPager;
30628
30629   if( MEMDB ) return;
30630   pagerEnter(pPager);
30631   pPg->alwaysRollback = 1;
30632   if( pPg->dirty && !pPager->stmtInUse ){
30633     assert( pPager->state>=PAGER_SHARED );
30634     if( pPager->dbSize==(int)pPg->pgno && pPager->origDbSize<pPager->dbSize ){
30635       /* If this pages is the last page in the file and the file has grown
30636       ** during the current transaction, then do NOT mark the page as clean.
30637       ** When the database file grows, we must make sure that the last page
30638       ** gets written at least once so that the disk file will be the correct
30639       ** size. If you do not write this page and the size of the file
30640       ** on the disk ends up being too small, that can lead to database
30641       ** corruption during the next transaction.
30642       */
30643     }else{
30644       PAGERTRACE3("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager));
30645       IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
30646       makeClean(pPg);
30647 #ifdef SQLITE_CHECK_PAGES
30648       pPg->pageHash = pager_pagehash(pPg);
30649 #endif
30650     }
30651   }
30652   pagerLeave(pPager);
30653 }
30654
30655 /*
30656 ** A call to this routine tells the pager that if a rollback occurs,
30657 ** it is not necessary to restore the data on the given page.  This
30658 ** means that the pager does not have to record the given page in the
30659 ** rollback journal.
30660 **
30661 ** If we have not yet actually read the content of this page (if
30662 ** the PgHdr.needRead flag is set) then this routine acts as a promise
30663 ** that we will never need to read the page content in the future.
30664 ** so the needRead flag can be cleared at this point.
30665 */
30666 SQLITE_PRIVATE void sqlite3PagerDontRollback(DbPage *pPg){
30667   Pager *pPager = pPg->pPager;
30668
30669   pagerEnter(pPager);
30670   assert( pPager->state>=PAGER_RESERVED );
30671
30672   /* If the journal file is not open, or DontWrite() has been called on
30673   ** this page (DontWrite() sets the alwaysRollback flag), then this
30674   ** function is a no-op.
30675   */
30676   if( pPager->journalOpen==0 || pPg->alwaysRollback || pPager->alwaysRollback ){
30677     pagerLeave(pPager);
30678     return;
30679   }
30680   assert( !MEMDB );    /* For a memdb, pPager->journalOpen is always 0 */
30681
30682 #ifdef SQLITE_SECURE_DELETE
30683   if( pPg->inJournal || (int)pPg->pgno > pPager->origDbSize ){
30684     return;
30685   }
30686 #endif
30687
30688   /* If SECURE_DELETE is disabled, then there is no way that this
30689   ** routine can be called on a page for which sqlite3PagerDontWrite()
30690   ** has not been previously called during the same transaction.
30691   ** And if DontWrite() has previously been called, the following
30692   ** conditions must be met.
30693   **
30694   ** (Later:)  Not true.  If the database is corrupted by having duplicate
30695   ** pages on the freelist (ex: corrupt9.test) then the following is not
30696   ** necessarily true:
30697   */
30698   /* assert( !pPg->inJournal && (int)pPg->pgno <= pPager->origDbSize ); */
30699
30700   assert( pPager->pInJournal!=0 );
30701   sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
30702   pPg->inJournal = 1;
30703   pPg->needRead = 0;
30704   if( pPager->stmtInUse ){
30705     assert( pPager->stmtSize >= pPager->origDbSize );
30706     sqlite3BitvecSet(pPager->pInStmt, pPg->pgno);
30707   }
30708   PAGERTRACE3("DONT_ROLLBACK page %d of %d\n", pPg->pgno, PAGERID(pPager));
30709   IOTRACE(("GARBAGE %p %d\n", pPager, pPg->pgno))
30710   pagerLeave(pPager);
30711 }
30712
30713
30714 /*
30715 ** This routine is called to increment the database file change-counter,
30716 ** stored at byte 24 of the pager file.
30717 */
30718 static int pager_incr_changecounter(Pager *pPager, int isDirect){
30719   PgHdr *pPgHdr;
30720   u32 change_counter;
30721   int rc = SQLITE_OK;
30722
30723 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
30724   assert( isDirect==0 );  /* isDirect is only true for atomic writes */
30725 #endif
30726   if( !pPager->changeCountDone ){
30727     /* Open page 1 of the file for writing. */
30728     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
30729     if( rc!=SQLITE_OK ) return rc;
30730
30731     if( !isDirect ){
30732       rc = sqlite3PagerWrite(pPgHdr);
30733       if( rc!=SQLITE_OK ){
30734         sqlite3PagerUnref(pPgHdr);
30735         return rc;
30736       }
30737     }
30738
30739     /* Increment the value just read and write it back to byte 24. */
30740     change_counter = sqlite3Get4byte((u8*)pPager->dbFileVers);
30741     change_counter++;
30742     put32bits(((char*)PGHDR_TO_DATA(pPgHdr))+24, change_counter);
30743
30744 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
30745     if( isDirect && pPager->fd->pMethods ){
30746       const void *zBuf = PGHDR_TO_DATA(pPgHdr);
30747       rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
30748     }
30749 #endif
30750
30751     /* Release the page reference. */
30752     sqlite3PagerUnref(pPgHdr);
30753     pPager->changeCountDone = 1;
30754   }
30755   return rc;
30756 }
30757
30758 /*
30759 ** Sync the pager file to disk.
30760 */
30761 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
30762   int rc;
30763   pagerEnter(pPager);
30764   rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
30765   pagerLeave(pPager);
30766   return rc;
30767 }
30768
30769 /*
30770 ** Sync the database file for the pager pPager. zMaster points to the name
30771 ** of a master journal file that should be written into the individual
30772 ** journal file. zMaster may be NULL, which is interpreted as no master
30773 ** journal (a single database transaction).
30774 **
30775 ** This routine ensures that the journal is synced, all dirty pages written
30776 ** to the database file and the database file synced. The only thing that
30777 ** remains to commit the transaction is to delete the journal file (or
30778 ** master journal file if specified).
30779 **
30780 ** Note that if zMaster==NULL, this does not overwrite a previous value
30781 ** passed to an sqlite3PagerCommitPhaseOne() call.
30782 **
30783 ** If parameter nTrunc is non-zero, then the pager file is truncated to
30784 ** nTrunc pages (this is used by auto-vacuum databases).
30785 **
30786 ** If the final parameter - noSync - is true, then the database file itself
30787 ** is not synced. The caller must call sqlite3PagerSync() directly to
30788 ** sync the database file before calling CommitPhaseTwo() to delete the
30789 ** journal file in this case.
30790 */
30791 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
30792   Pager *pPager, 
30793   const char *zMaster, 
30794   Pgno nTrunc,
30795   int noSync
30796 ){
30797   int rc = SQLITE_OK;
30798
30799   if( pPager->errCode ){
30800     return pPager->errCode;
30801   }
30802
30803   /* If no changes have been made, we can leave the transaction early.
30804   */
30805   if( pPager->dbModified==0 &&
30806         (pPager->journalMode!=PAGER_JOURNALMODE_DELETE ||
30807           pPager->exclusiveMode!=0) ){
30808     assert( pPager->dirtyCache==0 || pPager->journalOpen==0 );
30809     return SQLITE_OK;
30810   }
30811
30812   PAGERTRACE4("DATABASE SYNC: File=%s zMaster=%s nTrunc=%d\n", 
30813       pPager->zFilename, zMaster, nTrunc);
30814   pagerEnter(pPager);
30815
30816   /* If this is an in-memory db, or no pages have been written to, or this
30817   ** function has already been called, it is a no-op.
30818   */
30819   if( pPager->state!=PAGER_SYNCED && !MEMDB && pPager->dirtyCache ){
30820     PgHdr *pPg;
30821
30822 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
30823     /* The atomic-write optimization can be used if all of the
30824     ** following are true:
30825     **
30826     **    + The file-system supports the atomic-write property for
30827     **      blocks of size page-size, and
30828     **    + This commit is not part of a multi-file transaction, and
30829     **    + Exactly one page has been modified and store in the journal file.
30830     **
30831     ** If the optimization can be used, then the journal file will never
30832     ** be created for this transaction.
30833     */
30834     int useAtomicWrite = (
30835         !zMaster && 
30836         pPager->journalOpen &&
30837         pPager->journalOff==jrnlBufferSize(pPager) && 
30838         nTrunc==0 && 
30839         (0==pPager->pDirty || 0==pPager->pDirty->pDirty)
30840     );
30841     assert( pPager->journalOpen || pPager->journalMode==PAGER_JOURNALMODE_OFF );
30842     if( useAtomicWrite ){
30843       /* Update the nRec field in the journal file. */
30844       int offset = pPager->journalHdr + sizeof(aJournalMagic);
30845       assert(pPager->nRec==1);
30846       rc = write32bits(pPager->jfd, offset, pPager->nRec);
30847
30848       /* Update the db file change counter. The following call will modify
30849       ** the in-memory representation of page 1 to include the updated
30850       ** change counter and then write page 1 directly to the database
30851       ** file. Because of the atomic-write property of the host file-system, 
30852       ** this is safe.
30853       */
30854       if( rc==SQLITE_OK ){
30855         rc = pager_incr_changecounter(pPager, 1);
30856       }
30857     }else{
30858       rc = sqlite3JournalCreate(pPager->jfd);
30859     }
30860
30861     if( !useAtomicWrite && rc==SQLITE_OK )
30862 #endif
30863
30864     /* If a master journal file name has already been written to the
30865     ** journal file, then no sync is required. This happens when it is
30866     ** written, then the process fails to upgrade from a RESERVED to an
30867     ** EXCLUSIVE lock. The next time the process tries to commit the
30868     ** transaction the m-j name will have already been written.
30869     */
30870     if( !pPager->setMaster ){
30871       rc = pager_incr_changecounter(pPager, 0);
30872       if( rc!=SQLITE_OK ) goto sync_exit;
30873       if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
30874 #ifndef SQLITE_OMIT_AUTOVACUUM
30875         if( nTrunc!=0 ){
30876           /* If this transaction has made the database smaller, then all pages
30877           ** being discarded by the truncation must be written to the journal
30878           ** file.
30879           */
30880           Pgno i;
30881           int iSkip = PAGER_MJ_PGNO(pPager);
30882           for( i=nTrunc+1; i<=pPager->origDbSize; i++ ){
30883             if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
30884               rc = sqlite3PagerGet(pPager, i, &pPg);
30885               if( rc!=SQLITE_OK ) goto sync_exit;
30886               rc = sqlite3PagerWrite(pPg);
30887               sqlite3PagerUnref(pPg);
30888               if( rc!=SQLITE_OK ) goto sync_exit;
30889             }
30890           } 
30891         }
30892 #endif
30893         rc = writeMasterJournal(pPager, zMaster);
30894         if( rc!=SQLITE_OK ) goto sync_exit;
30895         rc = syncJournal(pPager);
30896       }
30897     }
30898     if( rc!=SQLITE_OK ) goto sync_exit;
30899
30900 #ifndef SQLITE_OMIT_AUTOVACUUM
30901     if( nTrunc!=0 ){
30902       rc = sqlite3PagerTruncate(pPager, nTrunc);
30903       if( rc!=SQLITE_OK ) goto sync_exit;
30904     }
30905 #endif
30906
30907     /* Write all dirty pages to the database file */
30908     pPg = pager_get_all_dirty_pages(pPager);
30909     rc = pager_write_pagelist(pPg);
30910     if( rc!=SQLITE_OK ){
30911       assert( rc!=SQLITE_IOERR_BLOCKED );
30912       /* The error might have left the dirty list all fouled up here,
30913       ** but that does not matter because if the if the dirty list did
30914       ** get corrupted, then the transaction will roll back and
30915       ** discard the dirty list.  There is an assert in
30916       ** pager_get_all_dirty_pages() that verifies that no attempt
30917       ** is made to use an invalid dirty list.
30918       */
30919       goto sync_exit;
30920     }
30921     pPager->pDirty = 0;
30922
30923     /* Sync the database file. */
30924     if( !pPager->noSync && !noSync ){
30925       rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
30926     }
30927     IOTRACE(("DBSYNC %p\n", pPager))
30928
30929     pPager->state = PAGER_SYNCED;
30930   }else if( MEMDB && nTrunc!=0 ){
30931     rc = sqlite3PagerTruncate(pPager, nTrunc);
30932   }
30933
30934 sync_exit:
30935   if( rc==SQLITE_IOERR_BLOCKED ){
30936     /* pager_incr_changecounter() may attempt to obtain an exclusive
30937      * lock to spill the cache and return IOERR_BLOCKED. But since 
30938      * there is no chance the cache is inconsistent, it is
30939      * better to return SQLITE_BUSY.
30940      */
30941     rc = SQLITE_BUSY;
30942   }
30943   pagerLeave(pPager);
30944   return rc;
30945 }
30946
30947
30948 /*
30949 ** Commit all changes to the database and release the write lock.
30950 **
30951 ** If the commit fails for any reason, a rollback attempt is made
30952 ** and an error code is returned.  If the commit worked, SQLITE_OK
30953 ** is returned.
30954 */
30955 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
30956   int rc;
30957   PgHdr *pPg;
30958
30959   if( pPager->errCode ){
30960     return pPager->errCode;
30961   }
30962   if( pPager->state<PAGER_RESERVED ){
30963     return SQLITE_ERROR;
30964   }
30965   if( pPager->dbModified==0 &&
30966         (pPager->journalMode!=PAGER_JOURNALMODE_DELETE ||
30967           pPager->exclusiveMode!=0) ){
30968     assert( pPager->dirtyCache==0 || pPager->journalOpen==0 );
30969     return SQLITE_OK;
30970   }
30971   pagerEnter(pPager);
30972   PAGERTRACE2("COMMIT %d\n", PAGERID(pPager));
30973   if( MEMDB ){
30974     pPg = pager_get_all_dirty_pages(pPager);
30975     while( pPg ){
30976       PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
30977       clearHistory(pHist);
30978       pPg->dirty = 0;
30979       pPg->inJournal = 0;
30980       pHist->inStmt = 0;
30981       pPg->needSync = 0;
30982       pHist->pPrevStmt = pHist->pNextStmt = 0;
30983       pPg = pPg->pDirty;
30984     }
30985     pPager->pDirty = 0;
30986 #ifndef NDEBUG
30987     for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
30988       PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
30989       assert( !pPg->alwaysRollback );
30990       assert( !pHist->pOrig );
30991       assert( !pHist->pStmt );
30992     }
30993 #endif
30994     pPager->pStmt = 0;
30995     pPager->state = PAGER_SHARED;
30996     pagerLeave(pPager);
30997     return SQLITE_OK;
30998   }
30999   assert( pPager->state==PAGER_SYNCED || !pPager->dirtyCache );
31000   rc = pager_end_transaction(pPager, pPager->setMaster);
31001   rc = pager_error(pPager, rc);
31002   pagerLeave(pPager);
31003   return rc;
31004 }
31005
31006 /*
31007 ** Rollback all changes.  The database falls back to PAGER_SHARED mode.
31008 ** All in-memory cache pages revert to their original data contents.
31009 ** The journal is deleted.
31010 **
31011 ** This routine cannot fail unless some other process is not following
31012 ** the correct locking protocol or unless some other
31013 ** process is writing trash into the journal file (SQLITE_CORRUPT) or
31014 ** unless a prior malloc() failed (SQLITE_NOMEM).  Appropriate error
31015 ** codes are returned for all these occasions.  Otherwise,
31016 ** SQLITE_OK is returned.
31017 */
31018 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
31019   int rc;
31020   PAGERTRACE2("ROLLBACK %d\n", PAGERID(pPager));
31021   if( MEMDB ){
31022     PgHdr *p;
31023     for(p=pPager->pAll; p; p=p->pNextAll){
31024       PgHistory *pHist;
31025       assert( !p->alwaysRollback );
31026       if( !p->dirty ){
31027         assert( !((PgHistory *)PGHDR_TO_HIST(p, pPager))->pOrig );
31028         assert( !((PgHistory *)PGHDR_TO_HIST(p, pPager))->pStmt );
31029         continue;
31030       }
31031
31032       pHist = PGHDR_TO_HIST(p, pPager);
31033       if( pHist->pOrig ){
31034         memcpy(PGHDR_TO_DATA(p), pHist->pOrig, pPager->pageSize);
31035         PAGERTRACE3("ROLLBACK-PAGE %d of %d\n", p->pgno, PAGERID(pPager));
31036       }else{
31037         PAGERTRACE3("PAGE %d is clean on %d\n", p->pgno, PAGERID(pPager));
31038       }
31039       clearHistory(pHist);
31040       p->dirty = 0;
31041       p->inJournal = 0;
31042       pHist->inStmt = 0;
31043       pHist->pPrevStmt = pHist->pNextStmt = 0;
31044       if( pPager->xReiniter ){
31045         pPager->xReiniter(p, pPager->pageSize);
31046       }
31047     }
31048     pPager->pDirty = 0;
31049     pPager->pStmt = 0;
31050     pPager->dbSize = pPager->origDbSize;
31051     pager_truncate_cache(pPager);
31052     pPager->stmtInUse = 0;
31053     pPager->state = PAGER_SHARED;
31054     return SQLITE_OK;
31055   }
31056
31057   pagerEnter(pPager);
31058   if( !pPager->dirtyCache || !pPager->journalOpen ){
31059     rc = pager_end_transaction(pPager, pPager->setMaster);
31060     pagerLeave(pPager);
31061     return rc;
31062   }
31063
31064   if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
31065     if( pPager->state>=PAGER_EXCLUSIVE ){
31066       pager_playback(pPager, 0);
31067     }
31068     pagerLeave(pPager);
31069     return pPager->errCode;
31070   }
31071   if( pPager->state==PAGER_RESERVED ){
31072     int rc2;
31073     rc = pager_playback(pPager, 0);
31074     rc2 = pager_end_transaction(pPager, pPager->setMaster);
31075     if( rc==SQLITE_OK ){
31076       rc = rc2;
31077     }
31078   }else{
31079     rc = pager_playback(pPager, 0);
31080   }
31081   /* pager_reset(pPager); */
31082   pPager->dbSize = -1;
31083
31084   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
31085   ** cache. So call pager_error() on the way out to make any error 
31086   ** persistent.
31087   */
31088   rc = pager_error(pPager, rc);
31089   pagerLeave(pPager);
31090   return rc;
31091 }
31092
31093 /*
31094 ** Return TRUE if the database file is opened read-only.  Return FALSE
31095 ** if the database is (in theory) writable.
31096 */
31097 SQLITE_PRIVATE int sqlite3PagerIsreadonly(Pager *pPager){
31098   return pPager->readOnly;
31099 }
31100
31101 /*
31102 ** Return the number of references to the pager.
31103 */
31104 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
31105   return pPager->nRef;
31106 }
31107
31108 #ifdef SQLITE_TEST
31109 /*
31110 ** This routine is used for testing and analysis only.
31111 */
31112 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
31113   static int a[11];
31114   a[0] = pPager->nRef;
31115   a[1] = pPager->nPage;
31116   a[2] = pPager->mxPage;
31117   a[3] = pPager->dbSize;
31118   a[4] = pPager->state;
31119   a[5] = pPager->errCode;
31120   a[6] = pPager->nHit;
31121   a[7] = pPager->nMiss;
31122   a[8] = 0;  /* Used to be pPager->nOvfl */
31123   a[9] = pPager->nRead;
31124   a[10] = pPager->nWrite;
31125   return a;
31126 }
31127 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
31128   return MEMDB;
31129 }
31130 #endif
31131
31132 /*
31133 ** Set the statement rollback point.
31134 **
31135 ** This routine should be called with the transaction journal already
31136 ** open.  A new statement journal is created that can be used to rollback
31137 ** changes of a single SQL command within a larger transaction.
31138 */
31139 static int pagerStmtBegin(Pager *pPager){
31140   int rc;
31141   assert( !pPager->stmtInUse );
31142   assert( pPager->state>=PAGER_SHARED );
31143   assert( pPager->dbSize>=0 );
31144   PAGERTRACE2("STMT-BEGIN %d\n", PAGERID(pPager));
31145   if( MEMDB ){
31146     pPager->stmtInUse = 1;
31147     pPager->stmtSize = pPager->dbSize;
31148     return SQLITE_OK;
31149   }
31150   if( !pPager->journalOpen ){
31151     pPager->stmtAutoopen = 1;
31152     return SQLITE_OK;
31153   }
31154   assert( pPager->journalOpen );
31155   pagerLeave(pPager);
31156   assert( pPager->pInStmt==0 );
31157   pPager->pInStmt = sqlite3BitvecCreate(pPager->dbSize);
31158   pagerEnter(pPager);
31159   if( pPager->pInStmt==0 ){
31160     /* sqlite3OsLock(pPager->fd, SHARED_LOCK); */
31161     return SQLITE_NOMEM;
31162   }
31163   pPager->stmtJSize = pPager->journalOff;
31164   pPager->stmtSize = pPager->dbSize;
31165   pPager->stmtHdrOff = 0;
31166   pPager->stmtCksum = pPager->cksumInit;
31167   if( !pPager->stmtOpen ){
31168     rc = sqlite3PagerOpentemp(pPager, pPager->stfd, SQLITE_OPEN_SUBJOURNAL);
31169     if( rc ){
31170       goto stmt_begin_failed;
31171     }
31172     pPager->stmtOpen = 1;
31173     pPager->stmtNRec = 0;
31174   }
31175   pPager->stmtInUse = 1;
31176   return SQLITE_OK;
31177  
31178 stmt_begin_failed:
31179   if( pPager->pInStmt ){
31180     sqlite3BitvecDestroy(pPager->pInStmt);
31181     pPager->pInStmt = 0;
31182   }
31183   return rc;
31184 }
31185 SQLITE_PRIVATE int sqlite3PagerStmtBegin(Pager *pPager){
31186   int rc;
31187   pagerEnter(pPager);
31188   rc = pagerStmtBegin(pPager);
31189   pagerLeave(pPager);
31190   return rc;
31191 }
31192
31193 /*
31194 ** Commit a statement.
31195 */
31196 SQLITE_PRIVATE int sqlite3PagerStmtCommit(Pager *pPager){
31197   pagerEnter(pPager);
31198   if( pPager->stmtInUse ){
31199     PgHdr *pPg, *pNext;
31200     PAGERTRACE2("STMT-COMMIT %d\n", PAGERID(pPager));
31201     if( !MEMDB ){
31202       /* sqlite3OsTruncate(pPager->stfd, 0); */
31203       sqlite3BitvecDestroy(pPager->pInStmt);
31204       pPager->pInStmt = 0;
31205     }else{
31206       for(pPg=pPager->pStmt; pPg; pPg=pNext){
31207         PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
31208         pNext = pHist->pNextStmt;
31209         assert( pHist->inStmt );
31210         pHist->inStmt = 0;
31211         pHist->pPrevStmt = pHist->pNextStmt = 0;
31212         sqlite3PageFree(pHist->pStmt);
31213         pHist->pStmt = 0;
31214       }
31215     }
31216     pPager->stmtNRec = 0;
31217     pPager->stmtInUse = 0;
31218     pPager->pStmt = 0;
31219   }
31220   pPager->stmtAutoopen = 0;
31221   pagerLeave(pPager);
31222   return SQLITE_OK;
31223 }
31224
31225 /*
31226 ** Rollback a statement.
31227 */
31228 SQLITE_PRIVATE int sqlite3PagerStmtRollback(Pager *pPager){
31229   int rc;
31230   pagerEnter(pPager);
31231   if( pPager->stmtInUse ){
31232     PAGERTRACE2("STMT-ROLLBACK %d\n", PAGERID(pPager));
31233     if( MEMDB ){
31234       PgHdr *pPg;
31235       PgHistory *pHist;
31236       for(pPg=pPager->pStmt; pPg; pPg=pHist->pNextStmt){
31237         pHist = PGHDR_TO_HIST(pPg, pPager);
31238         if( pHist->pStmt ){
31239           memcpy(PGHDR_TO_DATA(pPg), pHist->pStmt, pPager->pageSize);
31240           sqlite3PageFree(pHist->pStmt);
31241           pHist->pStmt = 0;
31242         }
31243       }
31244       pPager->dbSize = pPager->stmtSize;
31245       pager_truncate_cache(pPager);
31246       rc = SQLITE_OK;
31247     }else{
31248       rc = pager_stmt_playback(pPager);
31249     }
31250     sqlite3PagerStmtCommit(pPager);
31251   }else{
31252     rc = SQLITE_OK;
31253   }
31254   pPager->stmtAutoopen = 0;
31255   pagerLeave(pPager);
31256   return rc;
31257 }
31258
31259 /*
31260 ** Return the full pathname of the database file.
31261 */
31262 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
31263   return pPager->zFilename;
31264 }
31265
31266 /*
31267 ** Return the VFS structure for the pager.
31268 */
31269 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
31270   return pPager->pVfs;
31271 }
31272
31273 /*
31274 ** Return the file handle for the database file associated
31275 ** with the pager.  This might return NULL if the file has
31276 ** not yet been opened.
31277 */
31278 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
31279   return pPager->fd;
31280 }
31281
31282 /*
31283 ** Return the directory of the database file.
31284 */
31285 SQLITE_PRIVATE const char *sqlite3PagerDirname(Pager *pPager){
31286   return pPager->zDirectory;
31287 }
31288
31289 /*
31290 ** Return the full pathname of the journal file.
31291 */
31292 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
31293   return pPager->zJournal;
31294 }
31295
31296 /*
31297 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
31298 ** if fsync()s are executed normally.
31299 */
31300 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
31301   return pPager->noSync;
31302 }
31303
31304 #ifdef SQLITE_HAS_CODEC
31305 /*
31306 ** Set the codec for this pager
31307 */
31308 SQLITE_PRIVATE void sqlite3PagerSetCodec(
31309   Pager *pPager,
31310   void *(*xCodec)(void*,void*,Pgno,int),
31311   void *pCodecArg
31312 ){
31313   pPager->xCodec = xCodec;
31314   pPager->pCodecArg = pCodecArg;
31315 }
31316 #endif
31317
31318 #ifndef SQLITE_OMIT_AUTOVACUUM
31319 /*
31320 ** Move the page pPg to location pgno in the file.
31321 **
31322 ** There must be no references to the page previously located at
31323 ** pgno (which we call pPgOld) though that page is allowed to be
31324 ** in cache.  If the page previous located at pgno is not already
31325 ** in the rollback journal, it is not put there by by this routine.
31326 **
31327 ** References to the page pPg remain valid. Updating any
31328 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
31329 ** allocated along with the page) is the responsibility of the caller.
31330 **
31331 ** A transaction must be active when this routine is called. It used to be
31332 ** required that a statement transaction was not active, but this restriction
31333 ** has been removed (CREATE INDEX needs to move a page when a statement
31334 ** transaction is active).
31335 **
31336 ** If the fourth argument, isCommit, is non-zero, then this page is being
31337 ** moved as part of a database reorganization just before the transaction 
31338 ** is being committed. In this case, it is guaranteed that the database page 
31339 ** pPg refers to will not be written to again within this transaction.
31340 */
31341 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
31342   PgHdr *pPgOld;  /* The page being overwritten. */
31343   int h;
31344   Pgno needSyncPgno = 0;
31345
31346   pagerEnter(pPager);
31347   assert( pPg->nRef>0 );
31348
31349   PAGERTRACE5("MOVE %d page %d (needSync=%d) moves to %d\n", 
31350       PAGERID(pPager), pPg->pgno, pPg->needSync, pgno);
31351   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
31352
31353   pager_get_content(pPg);
31354
31355   /* If the journal needs to be sync()ed before page pPg->pgno can
31356   ** be written to, store pPg->pgno in local variable needSyncPgno.
31357   **
31358   ** If the isCommit flag is set, there is no need to remember that
31359   ** the journal needs to be sync()ed before database page pPg->pgno 
31360   ** can be written to. The caller has already promised not to write to it.
31361   */
31362   if( pPg->needSync && !isCommit ){
31363     needSyncPgno = pPg->pgno;
31364     assert( pPg->inJournal || (int)pgno>pPager->origDbSize );
31365     assert( pPg->dirty );
31366     assert( pPager->needSync );
31367   }
31368
31369   /* Unlink pPg from its hash-chain */
31370   unlinkHashChain(pPager, pPg);
31371
31372   /* If the cache contains a page with page-number pgno, remove it
31373   ** from its hash chain. Also, if the PgHdr.needSync was set for 
31374   ** page pgno before the 'move' operation, it needs to be retained 
31375   ** for the page moved there.
31376   */
31377   pPg->needSync = 0;
31378   pPgOld = pager_lookup(pPager, pgno);
31379   if( pPgOld ){
31380     assert( pPgOld->nRef==0 );
31381     unlinkHashChain(pPager, pPgOld);
31382     makeClean(pPgOld);
31383     pPg->needSync = pPgOld->needSync;
31384   }else{
31385     pPg->needSync = 0;
31386   }
31387   pPg->inJournal = sqlite3BitvecTest(pPager->pInJournal, pgno);
31388
31389   /* Change the page number for pPg and insert it into the new hash-chain. */
31390   assert( pgno!=0 );
31391   pPg->pgno = pgno;
31392   h = pgno & (pPager->nHash-1);
31393   if( pPager->aHash[h] ){
31394     assert( pPager->aHash[h]->pPrevHash==0 );
31395     pPager->aHash[h]->pPrevHash = pPg;
31396   }
31397   pPg->pNextHash = pPager->aHash[h];
31398   pPager->aHash[h] = pPg;
31399   pPg->pPrevHash = 0;
31400
31401   makeDirty(pPg);
31402   pPager->dirtyCache = 1;
31403   pPager->dbModified = 1;
31404
31405   if( needSyncPgno ){
31406     /* If needSyncPgno is non-zero, then the journal file needs to be 
31407     ** sync()ed before any data is written to database file page needSyncPgno.
31408     ** Currently, no such page exists in the page-cache and the 
31409     ** "is journaled" bitvec flag has been set. This needs to be remedied by
31410     ** loading the page into the pager-cache and setting the PgHdr.needSync 
31411     ** flag.
31412     **
31413     ** If the attempt to load the page into the page-cache fails, (due
31414     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
31415     ** array. Otherwise, if the page is loaded and written again in
31416     ** this transaction, it may be written to the database file before
31417     ** it is synced into the journal file. This way, it may end up in
31418     ** the journal file twice, but that is not a problem.
31419     **
31420     ** The sqlite3PagerGet() call may cause the journal to sync. So make
31421     ** sure the Pager.needSync flag is set too.
31422     */
31423     int rc;
31424     PgHdr *pPgHdr;
31425     assert( pPager->needSync );
31426     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
31427     if( rc!=SQLITE_OK ){
31428       if( pPager->pInJournal && (int)needSyncPgno<=pPager->origDbSize ){
31429         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno);
31430       }
31431       pagerLeave(pPager);
31432       return rc;
31433     }
31434     pPager->needSync = 1;
31435     pPgHdr->needSync = 1;
31436     pPgHdr->inJournal = 1;
31437     makeDirty(pPgHdr);
31438     sqlite3PagerUnref(pPgHdr);
31439   }
31440
31441   pagerLeave(pPager);
31442   return SQLITE_OK;
31443 }
31444 #endif
31445
31446 /*
31447 ** Return a pointer to the data for the specified page.
31448 */
31449 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
31450   return PGHDR_TO_DATA(pPg);
31451 }
31452
31453 /*
31454 ** Return a pointer to the Pager.nExtra bytes of "extra" space 
31455 ** allocated along with the specified page.
31456 */
31457 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
31458   Pager *pPager = pPg->pPager;
31459   return (pPager?PGHDR_TO_EXTRA(pPg, pPager):0);
31460 }
31461
31462 /*
31463 ** Get/set the locking-mode for this pager. Parameter eMode must be one
31464 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
31465 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
31466 ** the locking-mode is set to the value specified.
31467 **
31468 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
31469 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
31470 ** locking-mode.
31471 */
31472 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
31473   assert( eMode==PAGER_LOCKINGMODE_QUERY
31474             || eMode==PAGER_LOCKINGMODE_NORMAL
31475             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
31476   assert( PAGER_LOCKINGMODE_QUERY<0 );
31477   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
31478   if( eMode>=0 && !pPager->tempFile ){
31479     pPager->exclusiveMode = eMode;
31480   }
31481   return (int)pPager->exclusiveMode;
31482 }
31483
31484 /*
31485 ** Get/set the journal-mode for this pager. Parameter eMode must be one
31486 ** of PAGER_JOURNALMODE_QUERY, PAGER_JOURNALMODE_DELETE or 
31487 ** PAGER_JOURNALMODE_PERSIST. If the parameter is not _QUERY, then
31488 ** the journal-mode is set to the value specified.
31489 **
31490 ** The returned value is either PAGER_JOURNALMODE_DELETE or
31491 ** PAGER_JOURNALMODE_PERSIST, indicating the current (possibly updated)
31492 ** journal-mode.
31493 */
31494 SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *pPager, int eMode){
31495   assert( eMode==PAGER_JOURNALMODE_QUERY
31496             || eMode==PAGER_JOURNALMODE_DELETE
31497             || eMode==PAGER_JOURNALMODE_PERSIST
31498             || eMode==PAGER_JOURNALMODE_OFF );
31499   assert( PAGER_JOURNALMODE_QUERY<0 );
31500   assert( PAGER_JOURNALMODE_DELETE>=0 && PAGER_JOURNALMODE_PERSIST>=0 );
31501   if( eMode>=0 ){
31502     pPager->journalMode = eMode;
31503   }
31504   return (int)pPager->journalMode;
31505 }
31506
31507 /*
31508 ** Get/set the size-limit used for persistent journal files.
31509 */
31510 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
31511   if( iLimit>=-1 ){
31512     pPager->journalSizeLimit = iLimit;
31513   }
31514   return pPager->journalSizeLimit;
31515 }
31516
31517 #endif /* SQLITE_OMIT_DISKIO */
31518
31519 /************** End of pager.c ***********************************************/
31520 /************** Begin file btmutex.c *****************************************/
31521 /*
31522 ** 2007 August 27
31523 **
31524 ** The author disclaims copyright to this source code.  In place of
31525 ** a legal notice, here is a blessing:
31526 **
31527 **    May you do good and not evil.
31528 **    May you find forgiveness for yourself and forgive others.
31529 **    May you share freely, never taking more than you give.
31530 **
31531 *************************************************************************
31532 **
31533 ** $Id: btmutex.c,v 1.10 2008/07/14 19:39:17 drh Exp $
31534 **
31535 ** This file contains code used to implement mutexes on Btree objects.
31536 ** This code really belongs in btree.c.  But btree.c is getting too
31537 ** big and we want to break it down some.  This packaged seemed like
31538 ** a good breakout.
31539 */
31540 /************** Include btreeInt.h in the middle of btmutex.c ****************/
31541 /************** Begin file btreeInt.h ****************************************/
31542 /*
31543 ** 2004 April 6
31544 **
31545 ** The author disclaims copyright to this source code.  In place of
31546 ** a legal notice, here is a blessing:
31547 **
31548 **    May you do good and not evil.
31549 **    May you find forgiveness for yourself and forgive others.
31550 **    May you share freely, never taking more than you give.
31551 **
31552 *************************************************************************
31553 ** $Id: btreeInt.h,v 1.30 2008/08/01 20:10:08 drh Exp $
31554 **
31555 ** This file implements a external (disk-based) database using BTrees.
31556 ** For a detailed discussion of BTrees, refer to
31557 **
31558 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
31559 **     "Sorting And Searching", pages 473-480. Addison-Wesley
31560 **     Publishing Company, Reading, Massachusetts.
31561 **
31562 ** The basic idea is that each page of the file contains N database
31563 ** entries and N+1 pointers to subpages.
31564 **
31565 **   ----------------------------------------------------------------
31566 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
31567 **   ----------------------------------------------------------------
31568 **
31569 ** All of the keys on the page that Ptr(0) points to have values less
31570 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
31571 ** values greater than Key(0) and less than Key(1).  All of the keys
31572 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
31573 ** so forth.
31574 **
31575 ** Finding a particular key requires reading O(log(M)) pages from the 
31576 ** disk where M is the number of entries in the tree.
31577 **
31578 ** In this implementation, a single file can hold one or more separate 
31579 ** BTrees.  Each BTree is identified by the index of its root page.  The
31580 ** key and data for any entry are combined to form the "payload".  A
31581 ** fixed amount of payload can be carried directly on the database
31582 ** page.  If the payload is larger than the preset amount then surplus
31583 ** bytes are stored on overflow pages.  The payload for an entry
31584 ** and the preceding pointer are combined to form a "Cell".  Each 
31585 ** page has a small header which contains the Ptr(N) pointer and other
31586 ** information such as the size of key and data.
31587 **
31588 ** FORMAT DETAILS
31589 **
31590 ** The file is divided into pages.  The first page is called page 1,
31591 ** the second is page 2, and so forth.  A page number of zero indicates
31592 ** "no such page".  The page size can be anything between 512 and 65536.
31593 ** Each page can be either a btree page, a freelist page or an overflow
31594 ** page.
31595 **
31596 ** The first page is always a btree page.  The first 100 bytes of the first
31597 ** page contain a special header (the "file header") that describes the file.
31598 ** The format of the file header is as follows:
31599 **
31600 **   OFFSET   SIZE    DESCRIPTION
31601 **      0      16     Header string: "SQLite format 3\000"
31602 **     16       2     Page size in bytes.  
31603 **     18       1     File format write version
31604 **     19       1     File format read version
31605 **     20       1     Bytes of unused space at the end of each page
31606 **     21       1     Max embedded payload fraction
31607 **     22       1     Min embedded payload fraction
31608 **     23       1     Min leaf payload fraction
31609 **     24       4     File change counter
31610 **     28       4     Reserved for future use
31611 **     32       4     First freelist page
31612 **     36       4     Number of freelist pages in the file
31613 **     40      60     15 4-byte meta values passed to higher layers
31614 **
31615 ** All of the integer values are big-endian (most significant byte first).
31616 **
31617 ** The file change counter is incremented when the database is changed
31618 ** This counter allows other processes to know when the file has changed
31619 ** and thus when they need to flush their cache.
31620 **
31621 ** The max embedded payload fraction is the amount of the total usable
31622 ** space in a page that can be consumed by a single cell for standard
31623 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
31624 ** is to limit the maximum cell size so that at least 4 cells will fit
31625 ** on one page.  Thus the default max embedded payload fraction is 64.
31626 **
31627 ** If the payload for a cell is larger than the max payload, then extra
31628 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
31629 ** as many bytes as possible are moved into the overflow pages without letting
31630 ** the cell size drop below the min embedded payload fraction.
31631 **
31632 ** The min leaf payload fraction is like the min embedded payload fraction
31633 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
31634 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
31635 ** not specified in the header.
31636 **
31637 ** Each btree pages is divided into three sections:  The header, the
31638 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
31639 ** file header that occurs before the page header.
31640 **
31641 **      |----------------|
31642 **      | file header    |   100 bytes.  Page 1 only.
31643 **      |----------------|
31644 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
31645 **      |----------------|
31646 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
31647 **      | array          |   |  Grows downward
31648 **      |                |   v
31649 **      |----------------|
31650 **      | unallocated    |
31651 **      | space          |
31652 **      |----------------|   ^  Grows upwards
31653 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
31654 **      | area           |   |  and free space fragments.
31655 **      |----------------|
31656 **
31657 ** The page headers looks like this:
31658 **
31659 **   OFFSET   SIZE     DESCRIPTION
31660 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
31661 **      1       2      byte offset to the first freeblock
31662 **      3       2      number of cells on this page
31663 **      5       2      first byte of the cell content area
31664 **      7       1      number of fragmented free bytes
31665 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
31666 **
31667 ** The flags define the format of this btree page.  The leaf flag means that
31668 ** this page has no children.  The zerodata flag means that this page carries
31669 ** only keys and no data.  The intkey flag means that the key is a integer
31670 ** which is stored in the key size entry of the cell header rather than in
31671 ** the payload area.
31672 **
31673 ** The cell pointer array begins on the first byte after the page header.
31674 ** The cell pointer array contains zero or more 2-byte numbers which are
31675 ** offsets from the beginning of the page to the cell content in the cell
31676 ** content area.  The cell pointers occur in sorted order.  The system strives
31677 ** to keep free space after the last cell pointer so that new cells can
31678 ** be easily added without having to defragment the page.
31679 **
31680 ** Cell content is stored at the very end of the page and grows toward the
31681 ** beginning of the page.
31682 **
31683 ** Unused space within the cell content area is collected into a linked list of
31684 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
31685 ** to the first freeblock is given in the header.  Freeblocks occur in
31686 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
31687 ** any group of 3 or fewer unused bytes in the cell content area cannot
31688 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
31689 ** a fragment.  The total number of bytes in all fragments is recorded.
31690 ** in the page header at offset 7.
31691 **
31692 **    SIZE    DESCRIPTION
31693 **      2     Byte offset of the next freeblock
31694 **      2     Bytes in this freeblock
31695 **
31696 ** Cells are of variable length.  Cells are stored in the cell content area at
31697 ** the end of the page.  Pointers to the cells are in the cell pointer array
31698 ** that immediately follows the page header.  Cells is not necessarily
31699 ** contiguous or in order, but cell pointers are contiguous and in order.
31700 **
31701 ** Cell content makes use of variable length integers.  A variable
31702 ** length integer is 1 to 9 bytes where the lower 7 bits of each 
31703 ** byte are used.  The integer consists of all bytes that have bit 8 set and
31704 ** the first byte with bit 8 clear.  The most significant byte of the integer
31705 ** appears first.  A variable-length integer may not be more than 9 bytes long.
31706 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
31707 ** allows a 64-bit integer to be encoded in 9 bytes.
31708 **
31709 **    0x00                      becomes  0x00000000
31710 **    0x7f                      becomes  0x0000007f
31711 **    0x81 0x00                 becomes  0x00000080
31712 **    0x82 0x00                 becomes  0x00000100
31713 **    0x80 0x7f                 becomes  0x0000007f
31714 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
31715 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
31716 **
31717 ** Variable length integers are used for rowids and to hold the number of
31718 ** bytes of key and data in a btree cell.
31719 **
31720 ** The content of a cell looks like this:
31721 **
31722 **    SIZE    DESCRIPTION
31723 **      4     Page number of the left child. Omitted if leaf flag is set.
31724 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
31725 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
31726 **      *     Payload
31727 **      4     First page of the overflow chain.  Omitted if no overflow
31728 **
31729 ** Overflow pages form a linked list.  Each page except the last is completely
31730 ** filled with data (pagesize - 4 bytes).  The last page can have as little
31731 ** as 1 byte of data.
31732 **
31733 **    SIZE    DESCRIPTION
31734 **      4     Page number of next overflow page
31735 **      *     Data
31736 **
31737 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
31738 ** file header points to the first in a linked list of trunk page.  Each trunk
31739 ** page points to multiple leaf pages.  The content of a leaf page is
31740 ** unspecified.  A trunk page looks like this:
31741 **
31742 **    SIZE    DESCRIPTION
31743 **      4     Page number of next trunk page
31744 **      4     Number of leaf pointers on this page
31745 **      *     zero or more pages numbers of leaves
31746 */
31747
31748 /* Round up a number to the next larger multiple of 8.  This is used
31749 ** to force 8-byte alignment on 64-bit architectures.
31750 */
31751 #define ROUND8(x)   ((x+7)&~7)
31752
31753
31754 /* The following value is the maximum cell size assuming a maximum page
31755 ** size give above.
31756 */
31757 #define MX_CELL_SIZE(pBt)  (pBt->pageSize-8)
31758
31759 /* The maximum number of cells on a single page of the database.  This
31760 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
31761 ** plus 2 bytes for the index to the cell in the page header).  Such
31762 ** small cells will be rare, but they are possible.
31763 */
31764 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
31765
31766 /* Forward declarations */
31767 typedef struct MemPage MemPage;
31768 typedef struct BtLock BtLock;
31769
31770 /*
31771 ** This is a magic string that appears at the beginning of every
31772 ** SQLite database in order to identify the file as a real database.
31773 **
31774 ** You can change this value at compile-time by specifying a
31775 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
31776 ** header must be exactly 16 bytes including the zero-terminator so
31777 ** the string itself should be 15 characters long.  If you change
31778 ** the header, then your custom library will not be able to read 
31779 ** databases generated by the standard tools and the standard tools
31780 ** will not be able to read databases created by your custom library.
31781 */
31782 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
31783 #  define SQLITE_FILE_HEADER "SQLite format 3"
31784 #endif
31785
31786 /*
31787 ** Page type flags.  An ORed combination of these flags appear as the
31788 ** first byte of on-disk image of every BTree page.
31789 */
31790 #define PTF_INTKEY    0x01
31791 #define PTF_ZERODATA  0x02
31792 #define PTF_LEAFDATA  0x04
31793 #define PTF_LEAF      0x08
31794
31795 /*
31796 ** As each page of the file is loaded into memory, an instance of the following
31797 ** structure is appended and initialized to zero.  This structure stores
31798 ** information about the page that is decoded from the raw file page.
31799 **
31800 ** The pParent field points back to the parent page.  This allows us to
31801 ** walk up the BTree from any leaf to the root.  Care must be taken to
31802 ** unref() the parent page pointer when this page is no longer referenced.
31803 ** The pageDestructor() routine handles that chore.
31804 **
31805 ** Access to all fields of this structure is controlled by the mutex
31806 ** stored in MemPage.pBt->mutex.
31807 */
31808 struct MemPage {
31809   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
31810   u8 idxShift;         /* True if Cell indices have changed */
31811   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
31812   u8 intKey;           /* True if intkey flag is set */
31813   u8 leaf;             /* True if leaf flag is set */
31814   u8 hasData;          /* True if this page stores data */
31815   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
31816   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
31817   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
31818   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
31819   u16 cellOffset;      /* Index in aData of first cell pointer */
31820   u16 idxParent;       /* Index in parent of this node */
31821   u16 nFree;           /* Number of free bytes on the page */
31822   u16 nCell;           /* Number of cells on this page, local and ovfl */
31823   u16 maskPage;        /* Mask for page offset */
31824   struct _OvflCell {   /* Cells that will not fit on aData[] */
31825     u8 *pCell;          /* Pointers to the body of the overflow cell */
31826     u16 idx;            /* Insert this cell before idx-th non-overflow cell */
31827   } aOvfl[5];
31828   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
31829   u8 *aData;           /* Pointer to disk image of the page data */
31830   DbPage *pDbPage;     /* Pager page handle */
31831   Pgno pgno;           /* Page number for this page */
31832   MemPage *pParent;    /* The parent of this page.  NULL for root */
31833 };
31834
31835 /*
31836 ** The in-memory image of a disk page has the auxiliary information appended
31837 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
31838 ** that extra information.
31839 */
31840 #define EXTRA_SIZE sizeof(MemPage)
31841
31842 /* A Btree handle
31843 **
31844 ** A database connection contains a pointer to an instance of
31845 ** this object for every database file that it has open.  This structure
31846 ** is opaque to the database connection.  The database connection cannot
31847 ** see the internals of this structure and only deals with pointers to
31848 ** this structure.
31849 **
31850 ** For some database files, the same underlying database cache might be 
31851 ** shared between multiple connections.  In that case, each contection
31852 ** has it own pointer to this object.  But each instance of this object
31853 ** points to the same BtShared object.  The database cache and the
31854 ** schema associated with the database file are all contained within
31855 ** the BtShared object.
31856 **
31857 ** All fields in this structure are accessed under sqlite3.mutex.
31858 ** The pBt pointer itself may not be changed while there exists cursors 
31859 ** in the referenced BtShared that point back to this Btree since those
31860 ** cursors have to do go through this Btree to find their BtShared and
31861 ** they often do so without holding sqlite3.mutex.
31862 */
31863 struct Btree {
31864   sqlite3 *db;       /* The database connection holding this btree */
31865   BtShared *pBt;     /* Sharable content of this btree */
31866   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
31867   u8 sharable;       /* True if we can share pBt with another db */
31868   u8 locked;         /* True if db currently has pBt locked */
31869   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
31870   Btree *pNext;      /* List of other sharable Btrees from the same db */
31871   Btree *pPrev;      /* Back pointer of the same list */
31872 };
31873
31874 /*
31875 ** Btree.inTrans may take one of the following values.
31876 **
31877 ** If the shared-data extension is enabled, there may be multiple users
31878 ** of the Btree structure. At most one of these may open a write transaction,
31879 ** but any number may have active read transactions.
31880 */
31881 #define TRANS_NONE  0
31882 #define TRANS_READ  1
31883 #define TRANS_WRITE 2
31884
31885 /*
31886 ** An instance of this object represents a single database file.
31887 ** 
31888 ** A single database file can be in use as the same time by two
31889 ** or more database connections.  When two or more connections are
31890 ** sharing the same database file, each connection has it own
31891 ** private Btree object for the file and each of those Btrees points
31892 ** to this one BtShared object.  BtShared.nRef is the number of
31893 ** connections currently sharing this database file.
31894 **
31895 ** Fields in this structure are accessed under the BtShared.mutex
31896 ** mutex, except for nRef and pNext which are accessed under the
31897 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
31898 ** may not be modified once it is initially set as long as nRef>0.
31899 ** The pSchema field may be set once under BtShared.mutex and
31900 ** thereafter is unchanged as long as nRef>0.
31901 */
31902 struct BtShared {
31903   Pager *pPager;        /* The page cache */
31904   sqlite3 *db;          /* Database connection currently using this Btree */
31905   BtCursor *pCursor;    /* A list of all open cursors */
31906   MemPage *pPage1;      /* First page of the database */
31907   u8 inStmt;            /* True if we are in a statement subtransaction */
31908   u8 readOnly;          /* True if the underlying file is readonly */
31909   u8 pageSizeFixed;     /* True if the page size can no longer be changed */
31910 #ifndef SQLITE_OMIT_AUTOVACUUM
31911   u8 autoVacuum;        /* True if auto-vacuum is enabled */
31912   u8 incrVacuum;        /* True if incr-vacuum is enabled */
31913   Pgno nTrunc;          /* Non-zero if the db will be truncated (incr vacuum) */
31914 #endif
31915   u16 pageSize;         /* Total number of bytes on a page */
31916   u16 usableSize;       /* Number of usable bytes on each page */
31917   int maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
31918   int minLocal;         /* Minimum local payload in non-LEAFDATA tables */
31919   int maxLeaf;          /* Maximum local payload in a LEAFDATA table */
31920   int minLeaf;          /* Minimum local payload in a LEAFDATA table */
31921   u8 inTransaction;     /* Transaction state */
31922   int nTransaction;     /* Number of open transactions (read + write) */
31923   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
31924   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
31925   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */
31926   BusyHandler busyHdr;  /* The busy handler for this btree */
31927 #ifndef SQLITE_OMIT_SHARED_CACHE
31928   int nRef;             /* Number of references to this structure */
31929   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
31930   BtLock *pLock;        /* List of locks held on this shared-btree struct */
31931   Btree *pExclusive;    /* Btree with an EXCLUSIVE lock on the whole db */
31932 #endif
31933   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
31934 };
31935
31936 /*
31937 ** An instance of the following structure is used to hold information
31938 ** about a cell.  The parseCellPtr() function fills in this structure
31939 ** based on information extract from the raw disk page.
31940 */
31941 typedef struct CellInfo CellInfo;
31942 struct CellInfo {
31943   u8 *pCell;     /* Pointer to the start of cell content */
31944   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
31945   u32 nData;     /* Number of bytes of data */
31946   u32 nPayload;  /* Total amount of payload */
31947   u16 nHeader;   /* Size of the cell content header in bytes */
31948   u16 nLocal;    /* Amount of payload held locally */
31949   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
31950   u16 nSize;     /* Size of the cell content on the main b-tree page */
31951 };
31952
31953 /*
31954 ** A cursor is a pointer to a particular entry within a particular
31955 ** b-tree within a database file.
31956 **
31957 ** The entry is identified by its MemPage and the index in
31958 ** MemPage.aCell[] of the entry.
31959 **
31960 ** When a single database file can shared by two more database connections,
31961 ** but cursors cannot be shared.  Each cursor is associated with a
31962 ** particular database connection identified BtCursor.pBtree.db.
31963 **
31964 ** Fields in this structure are accessed under the BtShared.mutex
31965 ** found at self->pBt->mutex. 
31966 */
31967 struct BtCursor {
31968   Btree *pBtree;            /* The Btree to which this cursor belongs */
31969   BtShared *pBt;            /* The BtShared this cursor points to */
31970   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
31971   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
31972   Pgno pgnoRoot;            /* The root page of this tree */
31973   MemPage *pPage;           /* Page that contains the entry */
31974   int idx;                  /* Index of the entry in pPage->aCell[] */
31975   CellInfo info;            /* A parse of the cell we are pointing at */
31976   u8 wrFlag;                /* True if writable */
31977   u8 atLast;                /* Cursor pointing to the last entry */
31978   u8 validNKey;             /* True if info.nKey is valid */
31979   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
31980   void *pKey;      /* Saved key that was cursor's last known position */
31981   i64 nKey;        /* Size of pKey, or last integer key */
31982   int skip;        /* (skip<0) -> Prev() is a no-op. (skip>0) -> Next() is */
31983 #ifndef SQLITE_OMIT_INCRBLOB
31984   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
31985   Pgno *aOverflow;          /* Cache of overflow page locations */
31986 #endif
31987 };
31988
31989 /*
31990 ** Potential values for BtCursor.eState.
31991 **
31992 ** CURSOR_VALID:
31993 **   Cursor points to a valid entry. getPayload() etc. may be called.
31994 **
31995 ** CURSOR_INVALID:
31996 **   Cursor does not point to a valid entry. This can happen (for example) 
31997 **   because the table is empty or because BtreeCursorFirst() has not been
31998 **   called.
31999 **
32000 ** CURSOR_REQUIRESEEK:
32001 **   The table that this cursor was opened on still exists, but has been 
32002 **   modified since the cursor was last used. The cursor position is saved
32003 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
32004 **   this state, restoreCursorPosition() can be called to attempt to
32005 **   seek the cursor to the saved position.
32006 **
32007 ** CURSOR_FAULT:
32008 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
32009 **   on a different connection that shares the BtShared cache with this
32010 **   cursor.  The error has left the cache in an inconsistent state.
32011 **   Do nothing else with this cursor.  Any attempt to use the cursor
32012 **   should return the error code stored in BtCursor.skip
32013 */
32014 #define CURSOR_INVALID           0
32015 #define CURSOR_VALID             1
32016 #define CURSOR_REQUIRESEEK       2
32017 #define CURSOR_FAULT             3
32018
32019 /* The database page the PENDING_BYTE occupies. This page is never used.
32020 ** TODO: This macro is very similary to PAGER_MJ_PGNO() in pager.c. They
32021 ** should possibly be consolidated (presumably in pager.h).
32022 **
32023 ** If disk I/O is omitted (meaning that the database is stored purely
32024 ** in memory) then there is no pending byte.
32025 */
32026 #ifdef SQLITE_OMIT_DISKIO
32027 # define PENDING_BYTE_PAGE(pBt)  0x7fffffff
32028 #else
32029 # define PENDING_BYTE_PAGE(pBt) ((PENDING_BYTE/(pBt)->pageSize)+1)
32030 #endif
32031
32032 /*
32033 ** A linked list of the following structures is stored at BtShared.pLock.
32034 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
32035 ** is opened on the table with root page BtShared.iTable. Locks are removed
32036 ** from this list when a transaction is committed or rolled back, or when
32037 ** a btree handle is closed.
32038 */
32039 struct BtLock {
32040   Btree *pBtree;        /* Btree handle holding this lock */
32041   Pgno iTable;          /* Root page of table */
32042   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
32043   BtLock *pNext;        /* Next in BtShared.pLock list */
32044 };
32045
32046 /* Candidate values for BtLock.eLock */
32047 #define READ_LOCK     1
32048 #define WRITE_LOCK    2
32049
32050 /*
32051 ** These macros define the location of the pointer-map entry for a 
32052 ** database page. The first argument to each is the number of usable
32053 ** bytes on each page of the database (often 1024). The second is the
32054 ** page number to look up in the pointer map.
32055 **
32056 ** PTRMAP_PAGENO returns the database page number of the pointer-map
32057 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
32058 ** the offset of the requested map entry.
32059 **
32060 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
32061 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
32062 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
32063 ** this test.
32064 */
32065 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
32066 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
32067 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
32068
32069 /*
32070 ** The pointer map is a lookup table that identifies the parent page for
32071 ** each child page in the database file.  The parent page is the page that
32072 ** contains a pointer to the child.  Every page in the database contains
32073 ** 0 or 1 parent pages.  (In this context 'database page' refers
32074 ** to any page that is not part of the pointer map itself.)  Each pointer map
32075 ** entry consists of a single byte 'type' and a 4 byte parent page number.
32076 ** The PTRMAP_XXX identifiers below are the valid types.
32077 **
32078 ** The purpose of the pointer map is to facility moving pages from one
32079 ** position in the file to another as part of autovacuum.  When a page
32080 ** is moved, the pointer in its parent must be updated to point to the
32081 ** new location.  The pointer map is used to locate the parent page quickly.
32082 **
32083 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
32084 **                  used in this case.
32085 **
32086 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
32087 **                  is not used in this case.
32088 **
32089 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
32090 **                   overflow pages. The page number identifies the page that
32091 **                   contains the cell with a pointer to this overflow page.
32092 **
32093 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
32094 **                   overflow pages. The page-number identifies the previous
32095 **                   page in the overflow page list.
32096 **
32097 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
32098 **               identifies the parent page in the btree.
32099 */
32100 #define PTRMAP_ROOTPAGE 1
32101 #define PTRMAP_FREEPAGE 2
32102 #define PTRMAP_OVERFLOW1 3
32103 #define PTRMAP_OVERFLOW2 4
32104 #define PTRMAP_BTREE 5
32105
32106 /* A bunch of assert() statements to check the transaction state variables
32107 ** of handle p (type Btree*) are internally consistent.
32108 */
32109 #define btreeIntegrity(p) \
32110   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
32111   assert( p->pBt->inTransaction>=p->inTrans ); 
32112
32113
32114 /*
32115 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
32116 ** if the database supports auto-vacuum or not. Because it is used
32117 ** within an expression that is an argument to another macro 
32118 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
32119 ** So, this macro is defined instead.
32120 */
32121 #ifndef SQLITE_OMIT_AUTOVACUUM
32122 #define ISAUTOVACUUM (pBt->autoVacuum)
32123 #else
32124 #define ISAUTOVACUUM 0
32125 #endif
32126
32127
32128 /*
32129 ** This structure is passed around through all the sanity checking routines
32130 ** in order to keep track of some global state information.
32131 */
32132 typedef struct IntegrityCk IntegrityCk;
32133 struct IntegrityCk {
32134   BtShared *pBt;    /* The tree being checked out */
32135   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
32136   int nPage;        /* Number of pages in the database */
32137   int *anRef;       /* Number of times each page is referenced */
32138   int mxErr;        /* Stop accumulating errors when this reaches zero */
32139   int nErr;         /* Number of messages written to zErrMsg so far */
32140   int mallocFailed; /* A memory allocation error has occurred */
32141   StrAccum errMsg;  /* Accumulate the error message text here */
32142 };
32143
32144 /*
32145 ** Read or write a two- and four-byte big-endian integer values.
32146 */
32147 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
32148 #define put2byte(p,v) ((p)[0] = (v)>>8, (p)[1] = (v))
32149 #define get4byte sqlite3Get4byte
32150 #define put4byte sqlite3Put4byte
32151
32152 /*
32153 ** Internal routines that should be accessed by the btree layer only.
32154 */
32155 SQLITE_PRIVATE int sqlite3BtreeGetPage(BtShared*, Pgno, MemPage**, int);
32156 SQLITE_PRIVATE int sqlite3BtreeInitPage(MemPage *pPage, MemPage *pParent);
32157 SQLITE_PRIVATE void sqlite3BtreeParseCellPtr(MemPage*, u8*, CellInfo*);
32158 SQLITE_PRIVATE void sqlite3BtreeParseCell(MemPage*, int, CellInfo*);
32159 SQLITE_PRIVATE int sqlite3BtreeRestoreCursorPosition(BtCursor *pCur);
32160 SQLITE_PRIVATE void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur);
32161 SQLITE_PRIVATE void sqlite3BtreeReleaseTempCursor(BtCursor *pCur);
32162 SQLITE_PRIVATE int sqlite3BtreeIsRootPage(MemPage *pPage);
32163 SQLITE_PRIVATE void sqlite3BtreeMoveToParent(BtCursor *pCur);
32164
32165 /************** End of btreeInt.h ********************************************/
32166 /************** Continuing where we left off in btmutex.c ********************/
32167 #if SQLITE_THREADSAFE && !defined(SQLITE_OMIT_SHARED_CACHE)
32168
32169
32170 /*
32171 ** Enter a mutex on the given BTree object.
32172 **
32173 ** If the object is not sharable, then no mutex is ever required
32174 ** and this routine is a no-op.  The underlying mutex is non-recursive.
32175 ** But we keep a reference count in Btree.wantToLock so the behavior
32176 ** of this interface is recursive.
32177 **
32178 ** To avoid deadlocks, multiple Btrees are locked in the same order
32179 ** by all database connections.  The p->pNext is a list of other
32180 ** Btrees belonging to the same database connection as the p Btree
32181 ** which need to be locked after p.  If we cannot get a lock on
32182 ** p, then first unlock all of the others on p->pNext, then wait
32183 ** for the lock to become available on p, then relock all of the
32184 ** subsequent Btrees that desire a lock.
32185 */
32186 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
32187   Btree *pLater;
32188
32189   /* Some basic sanity checking on the Btree.  The list of Btrees
32190   ** connected by pNext and pPrev should be in sorted order by
32191   ** Btree.pBt value. All elements of the list should belong to
32192   ** the same connection. Only shared Btrees are on the list. */
32193   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
32194   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
32195   assert( p->pNext==0 || p->pNext->db==p->db );
32196   assert( p->pPrev==0 || p->pPrev->db==p->db );
32197   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
32198
32199   /* Check for locking consistency */
32200   assert( !p->locked || p->wantToLock>0 );
32201   assert( p->sharable || p->wantToLock==0 );
32202
32203   /* We should already hold a lock on the database connection */
32204   assert( sqlite3_mutex_held(p->db->mutex) );
32205
32206   if( !p->sharable ) return;
32207   p->wantToLock++;
32208   if( p->locked ) return;
32209
32210 #ifndef SQLITE_MUTEX_NOOP
32211   /* In most cases, we should be able to acquire the lock we
32212   ** want without having to go throught the ascending lock
32213   ** procedure that follows.  Just be sure not to block.
32214   */
32215   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
32216     p->locked = 1;
32217     return;
32218   }
32219
32220   /* To avoid deadlock, first release all locks with a larger
32221   ** BtShared address.  Then acquire our lock.  Then reacquire
32222   ** the other BtShared locks that we used to hold in ascending
32223   ** order.
32224   */
32225   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
32226     assert( pLater->sharable );
32227     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
32228     assert( !pLater->locked || pLater->wantToLock>0 );
32229     if( pLater->locked ){
32230       sqlite3_mutex_leave(pLater->pBt->mutex);
32231       pLater->locked = 0;
32232     }
32233   }
32234   sqlite3_mutex_enter(p->pBt->mutex);
32235   p->locked = 1;
32236   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
32237     if( pLater->wantToLock ){
32238       sqlite3_mutex_enter(pLater->pBt->mutex);
32239       pLater->locked = 1;
32240     }
32241   }
32242 #endif /* SQLITE_MUTEX_NOOP */
32243 }
32244
32245 /*
32246 ** Exit the recursive mutex on a Btree.
32247 */
32248 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
32249   if( p->sharable ){
32250     assert( p->wantToLock>0 );
32251     p->wantToLock--;
32252     if( p->wantToLock==0 ){
32253       assert( p->locked );
32254       sqlite3_mutex_leave(p->pBt->mutex);
32255       p->locked = 0;
32256     }
32257   }
32258 }
32259
32260 #ifndef NDEBUG
32261 /*
32262 ** Return true if the BtShared mutex is held on the btree.  
32263 **
32264 ** This routine makes no determination one why or another if the
32265 ** database connection mutex is held.
32266 **
32267 ** This routine is used only from within assert() statements.
32268 */
32269 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
32270   return (p->sharable==0 ||
32271              (p->locked && p->wantToLock && sqlite3_mutex_held(p->pBt->mutex)));
32272 }
32273 #endif
32274
32275
32276 #ifndef SQLITE_OMIT_INCRBLOB
32277 /*
32278 ** Enter and leave a mutex on a Btree given a cursor owned by that
32279 ** Btree.  These entry points are used by incremental I/O and can be
32280 ** omitted if that module is not used.
32281 */
32282 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
32283   sqlite3BtreeEnter(pCur->pBtree);
32284 }
32285 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
32286   sqlite3BtreeLeave(pCur->pBtree);
32287 }
32288 #endif /* SQLITE_OMIT_INCRBLOB */
32289
32290
32291 /*
32292 ** Enter the mutex on every Btree associated with a database
32293 ** connection.  This is needed (for example) prior to parsing
32294 ** a statement since we will be comparing table and column names
32295 ** against all schemas and we do not want those schemas being
32296 ** reset out from under us.
32297 **
32298 ** There is a corresponding leave-all procedures.
32299 **
32300 ** Enter the mutexes in accending order by BtShared pointer address
32301 ** to avoid the possibility of deadlock when two threads with
32302 ** two or more btrees in common both try to lock all their btrees
32303 ** at the same instant.
32304 */
32305 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
32306   int i;
32307   Btree *p, *pLater;
32308   assert( sqlite3_mutex_held(db->mutex) );
32309   for(i=0; i<db->nDb; i++){
32310     p = db->aDb[i].pBt;
32311     if( p && p->sharable ){
32312       p->wantToLock++;
32313       if( !p->locked ){
32314         assert( p->wantToLock==1 );
32315         while( p->pPrev ) p = p->pPrev;
32316         while( p->locked && p->pNext ) p = p->pNext;
32317         for(pLater = p->pNext; pLater; pLater=pLater->pNext){
32318           if( pLater->locked ){
32319             sqlite3_mutex_leave(pLater->pBt->mutex);
32320             pLater->locked = 0;
32321           }
32322         }
32323         while( p ){
32324           sqlite3_mutex_enter(p->pBt->mutex);
32325           p->locked++;
32326           p = p->pNext;
32327         }
32328       }
32329     }
32330   }
32331 }
32332 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
32333   int i;
32334   Btree *p;
32335   assert( sqlite3_mutex_held(db->mutex) );
32336   for(i=0; i<db->nDb; i++){
32337     p = db->aDb[i].pBt;
32338     if( p && p->sharable ){
32339       assert( p->wantToLock>0 );
32340       p->wantToLock--;
32341       if( p->wantToLock==0 ){
32342         assert( p->locked );
32343         sqlite3_mutex_leave(p->pBt->mutex);
32344         p->locked = 0;
32345       }
32346     }
32347   }
32348 }
32349
32350 #ifndef NDEBUG
32351 /*
32352 ** Return true if the current thread holds the database connection
32353 ** mutex and all required BtShared mutexes.
32354 **
32355 ** This routine is used inside assert() statements only.
32356 */
32357 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
32358   int i;
32359   if( !sqlite3_mutex_held(db->mutex) ){
32360     return 0;
32361   }
32362   for(i=0; i<db->nDb; i++){
32363     Btree *p;
32364     p = db->aDb[i].pBt;
32365     if( p && p->sharable &&
32366          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
32367       return 0;
32368     }
32369   }
32370   return 1;
32371 }
32372 #endif /* NDEBUG */
32373
32374 /*
32375 ** Add a new Btree pointer to a BtreeMutexArray. 
32376 ** if the pointer can possibly be shared with
32377 ** another database connection.
32378 **
32379 ** The pointers are kept in sorted order by pBtree->pBt.  That
32380 ** way when we go to enter all the mutexes, we can enter them
32381 ** in order without every having to backup and retry and without
32382 ** worrying about deadlock.
32383 **
32384 ** The number of shared btrees will always be small (usually 0 or 1)
32385 ** so an insertion sort is an adequate algorithm here.
32386 */
32387 SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray *pArray, Btree *pBtree){
32388   int i, j;
32389   BtShared *pBt;
32390   if( pBtree==0 || pBtree->sharable==0 ) return;
32391 #ifndef NDEBUG
32392   {
32393     for(i=0; i<pArray->nMutex; i++){
32394       assert( pArray->aBtree[i]!=pBtree );
32395     }
32396   }
32397 #endif
32398   assert( pArray->nMutex>=0 );
32399   assert( pArray->nMutex<sizeof(pArray->aBtree)/sizeof(pArray->aBtree[0])-1 );
32400   pBt = pBtree->pBt;
32401   for(i=0; i<pArray->nMutex; i++){
32402     assert( pArray->aBtree[i]!=pBtree );
32403     if( pArray->aBtree[i]->pBt>pBt ){
32404       for(j=pArray->nMutex; j>i; j--){
32405         pArray->aBtree[j] = pArray->aBtree[j-1];
32406       }
32407       pArray->aBtree[i] = pBtree;
32408       pArray->nMutex++;
32409       return;
32410     }
32411   }
32412   pArray->aBtree[pArray->nMutex++] = pBtree;
32413 }
32414
32415 /*
32416 ** Enter the mutex of every btree in the array.  This routine is
32417 ** called at the beginning of sqlite3VdbeExec().  The mutexes are
32418 ** exited at the end of the same function.
32419 */
32420 SQLITE_PRIVATE void sqlite3BtreeMutexArrayEnter(BtreeMutexArray *pArray){
32421   int i;
32422   for(i=0; i<pArray->nMutex; i++){
32423     Btree *p = pArray->aBtree[i];
32424     /* Some basic sanity checking */
32425     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
32426     assert( !p->locked || p->wantToLock>0 );
32427
32428     /* We should already hold a lock on the database connection */
32429     assert( sqlite3_mutex_held(p->db->mutex) );
32430
32431     p->wantToLock++;
32432     if( !p->locked && p->sharable ){
32433       sqlite3_mutex_enter(p->pBt->mutex);
32434       p->locked = 1;
32435     }
32436   }
32437 }
32438
32439 /*
32440 ** Leave the mutex of every btree in the group.
32441 */
32442 SQLITE_PRIVATE void sqlite3BtreeMutexArrayLeave(BtreeMutexArray *pArray){
32443   int i;
32444   for(i=0; i<pArray->nMutex; i++){
32445     Btree *p = pArray->aBtree[i];
32446     /* Some basic sanity checking */
32447     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
32448     assert( p->locked || !p->sharable );
32449     assert( p->wantToLock>0 );
32450
32451     /* We should already hold a lock on the database connection */
32452     assert( sqlite3_mutex_held(p->db->mutex) );
32453
32454     p->wantToLock--;
32455     if( p->wantToLock==0 && p->locked ){
32456       sqlite3_mutex_leave(p->pBt->mutex);
32457       p->locked = 0;
32458     }
32459   }
32460 }
32461
32462
32463 #endif  /* SQLITE_THREADSAFE && !SQLITE_OMIT_SHARED_CACHE */
32464
32465 /************** End of btmutex.c *********************************************/
32466 /************** Begin file btree.c *******************************************/
32467 /*
32468 ** 2004 April 6
32469 **
32470 ** The author disclaims copyright to this source code.  In place of
32471 ** a legal notice, here is a blessing:
32472 **
32473 **    May you do good and not evil.
32474 **    May you find forgiveness for yourself and forgive others.
32475 **    May you share freely, never taking more than you give.
32476 **
32477 *************************************************************************
32478 ** $Id: btree.c,v 1.495 2008/08/02 17:36:46 danielk1977 Exp $
32479 **
32480 ** This file implements a external (disk-based) database using BTrees.
32481 ** See the header comment on "btreeInt.h" for additional information.
32482 ** Including a description of file format and an overview of operation.
32483 */
32484
32485 /*
32486 ** The header string that appears at the beginning of every
32487 ** SQLite database.
32488 */
32489 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
32490
32491 /*
32492 ** Set this global variable to 1 to enable tracing using the TRACE
32493 ** macro.
32494 */
32495 #if 0
32496 int sqlite3BtreeTrace=0;  /* True to enable tracing */
32497 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
32498 #else
32499 # define TRACE(X)
32500 #endif
32501
32502
32503
32504 #ifndef SQLITE_OMIT_SHARED_CACHE
32505 /*
32506 ** A flag to indicate whether or not shared cache is enabled.  Also,
32507 ** a list of BtShared objects that are eligible for participation
32508 ** in shared cache.  The variables have file scope during normal builds,
32509 ** but the test harness needs to access these variables so we make them
32510 ** global for test builds.
32511 */
32512 #ifdef SQLITE_TEST
32513 SQLITE_PRIVATE BtShared *sqlite3SharedCacheList = 0;
32514 SQLITE_PRIVATE int sqlite3SharedCacheEnabled = 0;
32515 #else
32516 static BtShared *sqlite3SharedCacheList = 0;
32517 static int sqlite3SharedCacheEnabled = 0;
32518 #endif
32519 #endif /* SQLITE_OMIT_SHARED_CACHE */
32520
32521 #ifndef SQLITE_OMIT_SHARED_CACHE
32522 /*
32523 ** Enable or disable the shared pager and schema features.
32524 **
32525 ** This routine has no effect on existing database connections.
32526 ** The shared cache setting effects only future calls to
32527 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
32528 */
32529 SQLITE_API int sqlite3_enable_shared_cache(int enable){
32530   sqlite3SharedCacheEnabled = enable;
32531   return SQLITE_OK;
32532 }
32533 #endif
32534
32535
32536 /*
32537 ** Forward declaration
32538 */
32539 static int checkReadLocks(Btree*, Pgno, BtCursor*, i64);
32540
32541
32542 #ifdef SQLITE_OMIT_SHARED_CACHE
32543   /*
32544   ** The functions queryTableLock(), lockTable() and unlockAllTables()
32545   ** manipulate entries in the BtShared.pLock linked list used to store
32546   ** shared-cache table level locks. If the library is compiled with the
32547   ** shared-cache feature disabled, then there is only ever one user
32548   ** of each BtShared structure and so this locking is not necessary. 
32549   ** So define the lock related functions as no-ops.
32550   */
32551   #define queryTableLock(a,b,c) SQLITE_OK
32552   #define lockTable(a,b,c) SQLITE_OK
32553   #define unlockAllTables(a)
32554 #endif
32555
32556 #ifndef SQLITE_OMIT_SHARED_CACHE
32557 /*
32558 ** Query to see if btree handle p may obtain a lock of type eLock 
32559 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
32560 ** SQLITE_OK if the lock may be obtained (by calling lockTable()), or
32561 ** SQLITE_LOCKED if not.
32562 */
32563 static int queryTableLock(Btree *p, Pgno iTab, u8 eLock){
32564   BtShared *pBt = p->pBt;
32565   BtLock *pIter;
32566
32567   assert( sqlite3BtreeHoldsMutex(p) );
32568   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
32569   assert( p->db!=0 );
32570   
32571   /* This is a no-op if the shared-cache is not enabled */
32572   if( !p->sharable ){
32573     return SQLITE_OK;
32574   }
32575
32576   /* If some other connection is holding an exclusive lock, the
32577   ** requested lock may not be obtained.
32578   */
32579   if( pBt->pExclusive && pBt->pExclusive!=p ){
32580     return SQLITE_LOCKED;
32581   }
32582
32583   /* This (along with lockTable()) is where the ReadUncommitted flag is
32584   ** dealt with. If the caller is querying for a read-lock and the flag is
32585   ** set, it is unconditionally granted - even if there are write-locks
32586   ** on the table. If a write-lock is requested, the ReadUncommitted flag
32587   ** is not considered.
32588   **
32589   ** In function lockTable(), if a read-lock is demanded and the 
32590   ** ReadUncommitted flag is set, no entry is added to the locks list 
32591   ** (BtShared.pLock).
32592   **
32593   ** To summarize: If the ReadUncommitted flag is set, then read cursors do
32594   ** not create or respect table locks. The locking procedure for a 
32595   ** write-cursor does not change.
32596   */
32597   if( 
32598     0==(p->db->flags&SQLITE_ReadUncommitted) || 
32599     eLock==WRITE_LOCK ||
32600     iTab==MASTER_ROOT
32601   ){
32602     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
32603       if( pIter->pBtree!=p && pIter->iTable==iTab && 
32604           (pIter->eLock!=eLock || eLock!=READ_LOCK) ){
32605         return SQLITE_LOCKED;
32606       }
32607     }
32608   }
32609   return SQLITE_OK;
32610 }
32611 #endif /* !SQLITE_OMIT_SHARED_CACHE */
32612
32613 #ifndef SQLITE_OMIT_SHARED_CACHE
32614 /*
32615 ** Add a lock on the table with root-page iTable to the shared-btree used
32616 ** by Btree handle p. Parameter eLock must be either READ_LOCK or 
32617 ** WRITE_LOCK.
32618 **
32619 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_BUSY and
32620 ** SQLITE_NOMEM may also be returned.
32621 */
32622 static int lockTable(Btree *p, Pgno iTable, u8 eLock){
32623   BtShared *pBt = p->pBt;
32624   BtLock *pLock = 0;
32625   BtLock *pIter;
32626
32627   assert( sqlite3BtreeHoldsMutex(p) );
32628   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
32629   assert( p->db!=0 );
32630
32631   /* This is a no-op if the shared-cache is not enabled */
32632   if( !p->sharable ){
32633     return SQLITE_OK;
32634   }
32635
32636   assert( SQLITE_OK==queryTableLock(p, iTable, eLock) );
32637
32638   /* If the read-uncommitted flag is set and a read-lock is requested,
32639   ** return early without adding an entry to the BtShared.pLock list. See
32640   ** comment in function queryTableLock() for more info on handling 
32641   ** the ReadUncommitted flag.
32642   */
32643   if( 
32644     (p->db->flags&SQLITE_ReadUncommitted) && 
32645     (eLock==READ_LOCK) &&
32646     iTable!=MASTER_ROOT
32647   ){
32648     return SQLITE_OK;
32649   }
32650
32651   /* First search the list for an existing lock on this table. */
32652   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
32653     if( pIter->iTable==iTable && pIter->pBtree==p ){
32654       pLock = pIter;
32655       break;
32656     }
32657   }
32658
32659   /* If the above search did not find a BtLock struct associating Btree p
32660   ** with table iTable, allocate one and link it into the list.
32661   */
32662   if( !pLock ){
32663     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
32664     if( !pLock ){
32665       return SQLITE_NOMEM;
32666     }
32667     pLock->iTable = iTable;
32668     pLock->pBtree = p;
32669     pLock->pNext = pBt->pLock;
32670     pBt->pLock = pLock;
32671   }
32672
32673   /* Set the BtLock.eLock variable to the maximum of the current lock
32674   ** and the requested lock. This means if a write-lock was already held
32675   ** and a read-lock requested, we don't incorrectly downgrade the lock.
32676   */
32677   assert( WRITE_LOCK>READ_LOCK );
32678   if( eLock>pLock->eLock ){
32679     pLock->eLock = eLock;
32680   }
32681
32682   return SQLITE_OK;
32683 }
32684 #endif /* !SQLITE_OMIT_SHARED_CACHE */
32685
32686 #ifndef SQLITE_OMIT_SHARED_CACHE
32687 /*
32688 ** Release all the table locks (locks obtained via calls to the lockTable()
32689 ** procedure) held by Btree handle p.
32690 */
32691 static void unlockAllTables(Btree *p){
32692   BtShared *pBt = p->pBt;
32693   BtLock **ppIter = &pBt->pLock;
32694
32695   assert( sqlite3BtreeHoldsMutex(p) );
32696   assert( p->sharable || 0==*ppIter );
32697
32698   while( *ppIter ){
32699     BtLock *pLock = *ppIter;
32700     assert( pBt->pExclusive==0 || pBt->pExclusive==pLock->pBtree );
32701     if( pLock->pBtree==p ){
32702       *ppIter = pLock->pNext;
32703       sqlite3_free(pLock);
32704     }else{
32705       ppIter = &pLock->pNext;
32706     }
32707   }
32708
32709   if( pBt->pExclusive==p ){
32710     pBt->pExclusive = 0;
32711   }
32712 }
32713 #endif /* SQLITE_OMIT_SHARED_CACHE */
32714
32715 static void releasePage(MemPage *pPage);  /* Forward reference */
32716
32717 /*
32718 ** Verify that the cursor holds a mutex on the BtShared
32719 */
32720 #ifndef NDEBUG
32721 static int cursorHoldsMutex(BtCursor *p){
32722   return sqlite3_mutex_held(p->pBt->mutex);
32723 }
32724 #endif
32725
32726
32727 #ifndef SQLITE_OMIT_INCRBLOB
32728 /*
32729 ** Invalidate the overflow page-list cache for cursor pCur, if any.
32730 */
32731 static void invalidateOverflowCache(BtCursor *pCur){
32732   assert( cursorHoldsMutex(pCur) );
32733   sqlite3_free(pCur->aOverflow);
32734   pCur->aOverflow = 0;
32735 }
32736
32737 /*
32738 ** Invalidate the overflow page-list cache for all cursors opened
32739 ** on the shared btree structure pBt.
32740 */
32741 static void invalidateAllOverflowCache(BtShared *pBt){
32742   BtCursor *p;
32743   assert( sqlite3_mutex_held(pBt->mutex) );
32744   for(p=pBt->pCursor; p; p=p->pNext){
32745     invalidateOverflowCache(p);
32746   }
32747 }
32748 #else
32749   #define invalidateOverflowCache(x)
32750   #define invalidateAllOverflowCache(x)
32751 #endif
32752
32753 /*
32754 ** Save the current cursor position in the variables BtCursor.nKey 
32755 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
32756 */
32757 static int saveCursorPosition(BtCursor *pCur){
32758   int rc;
32759
32760   assert( CURSOR_VALID==pCur->eState );
32761   assert( 0==pCur->pKey );
32762   assert( cursorHoldsMutex(pCur) );
32763
32764   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
32765
32766   /* If this is an intKey table, then the above call to BtreeKeySize()
32767   ** stores the integer key in pCur->nKey. In this case this value is
32768   ** all that is required. Otherwise, if pCur is not open on an intKey
32769   ** table, then malloc space for and store the pCur->nKey bytes of key 
32770   ** data.
32771   */
32772   if( rc==SQLITE_OK && 0==pCur->pPage->intKey){
32773     void *pKey = sqlite3Malloc(pCur->nKey);
32774     if( pKey ){
32775       rc = sqlite3BtreeKey(pCur, 0, pCur->nKey, pKey);
32776       if( rc==SQLITE_OK ){
32777         pCur->pKey = pKey;
32778       }else{
32779         sqlite3_free(pKey);
32780       }
32781     }else{
32782       rc = SQLITE_NOMEM;
32783     }
32784   }
32785   assert( !pCur->pPage->intKey || !pCur->pKey );
32786
32787   if( rc==SQLITE_OK ){
32788     releasePage(pCur->pPage);
32789     pCur->pPage = 0;
32790     pCur->eState = CURSOR_REQUIRESEEK;
32791   }
32792
32793   invalidateOverflowCache(pCur);
32794   return rc;
32795 }
32796
32797 /*
32798 ** Save the positions of all cursors except pExcept open on the table 
32799 ** with root-page iRoot. Usually, this is called just before cursor
32800 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
32801 */
32802 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
32803   BtCursor *p;
32804   assert( sqlite3_mutex_held(pBt->mutex) );
32805   assert( pExcept==0 || pExcept->pBt==pBt );
32806   for(p=pBt->pCursor; p; p=p->pNext){
32807     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) && 
32808         p->eState==CURSOR_VALID ){
32809       int rc = saveCursorPosition(p);
32810       if( SQLITE_OK!=rc ){
32811         return rc;
32812       }
32813     }
32814   }
32815   return SQLITE_OK;
32816 }
32817
32818 /*
32819 ** Clear the current cursor position.
32820 */
32821 static void clearCursorPosition(BtCursor *pCur){
32822   assert( cursorHoldsMutex(pCur) );
32823   sqlite3_free(pCur->pKey);
32824   pCur->pKey = 0;
32825   pCur->eState = CURSOR_INVALID;
32826 }
32827
32828 /*
32829 ** Restore the cursor to the position it was in (or as close to as possible)
32830 ** when saveCursorPosition() was called. Note that this call deletes the 
32831 ** saved position info stored by saveCursorPosition(), so there can be
32832 ** at most one effective restoreCursorPosition() call after each 
32833 ** saveCursorPosition().
32834 */
32835 SQLITE_PRIVATE int sqlite3BtreeRestoreCursorPosition(BtCursor *pCur){
32836   int rc;
32837   assert( cursorHoldsMutex(pCur) );
32838   assert( pCur->eState>=CURSOR_REQUIRESEEK );
32839   if( pCur->eState==CURSOR_FAULT ){
32840     return pCur->skip;
32841   }
32842   pCur->eState = CURSOR_INVALID;
32843   rc = sqlite3BtreeMoveto(pCur, pCur->pKey, 0, pCur->nKey, 0, &pCur->skip);
32844   if( rc==SQLITE_OK ){
32845     sqlite3_free(pCur->pKey);
32846     pCur->pKey = 0;
32847     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
32848   }
32849   return rc;
32850 }
32851
32852 #define restoreCursorPosition(p) \
32853   (p->eState>=CURSOR_REQUIRESEEK ? \
32854          sqlite3BtreeRestoreCursorPosition(p) : \
32855          SQLITE_OK)
32856
32857 /*
32858 ** Determine whether or not a cursor has moved from the position it
32859 ** was last placed at.  Cursor can move when the row they are pointing
32860 ** at is deleted out from under them.
32861 **
32862 ** This routine returns an error code if something goes wrong.  The
32863 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
32864 */
32865 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
32866   int rc;
32867
32868   rc = restoreCursorPosition(pCur);
32869   if( rc ){
32870     *pHasMoved = 1;
32871     return rc;
32872   }
32873   if( pCur->eState!=CURSOR_VALID || pCur->skip!=0 ){
32874     *pHasMoved = 1;
32875   }else{
32876     *pHasMoved = 0;
32877   }
32878   return SQLITE_OK;
32879 }
32880
32881 #ifndef SQLITE_OMIT_AUTOVACUUM
32882 /*
32883 ** Given a page number of a regular database page, return the page
32884 ** number for the pointer-map page that contains the entry for the
32885 ** input page number.
32886 */
32887 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
32888   int nPagesPerMapPage, iPtrMap, ret;
32889   assert( sqlite3_mutex_held(pBt->mutex) );
32890   nPagesPerMapPage = (pBt->usableSize/5)+1;
32891   iPtrMap = (pgno-2)/nPagesPerMapPage;
32892   ret = (iPtrMap*nPagesPerMapPage) + 2; 
32893   if( ret==PENDING_BYTE_PAGE(pBt) ){
32894     ret++;
32895   }
32896   return ret;
32897 }
32898
32899 /*
32900 ** Write an entry into the pointer map.
32901 **
32902 ** This routine updates the pointer map entry for page number 'key'
32903 ** so that it maps to type 'eType' and parent page number 'pgno'.
32904 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
32905 */
32906 static int ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent){
32907   DbPage *pDbPage;  /* The pointer map page */
32908   u8 *pPtrmap;      /* The pointer map data */
32909   Pgno iPtrmap;     /* The pointer map page number */
32910   int offset;       /* Offset in pointer map page */
32911   int rc;
32912
32913   assert( sqlite3_mutex_held(pBt->mutex) );
32914   /* The master-journal page number must never be used as a pointer map page */
32915   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
32916
32917   assert( pBt->autoVacuum );
32918   if( key==0 ){
32919     return SQLITE_CORRUPT_BKPT;
32920   }
32921   iPtrmap = PTRMAP_PAGENO(pBt, key);
32922   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
32923   if( rc!=SQLITE_OK ){
32924     return rc;
32925   }
32926   offset = PTRMAP_PTROFFSET(iPtrmap, key);
32927   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
32928
32929   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
32930     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
32931     rc = sqlite3PagerWrite(pDbPage);
32932     if( rc==SQLITE_OK ){
32933       pPtrmap[offset] = eType;
32934       put4byte(&pPtrmap[offset+1], parent);
32935     }
32936   }
32937
32938   sqlite3PagerUnref(pDbPage);
32939   return rc;
32940 }
32941
32942 /*
32943 ** Read an entry from the pointer map.
32944 **
32945 ** This routine retrieves the pointer map entry for page 'key', writing
32946 ** the type and parent page number to *pEType and *pPgno respectively.
32947 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
32948 */
32949 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
32950   DbPage *pDbPage;   /* The pointer map page */
32951   int iPtrmap;       /* Pointer map page index */
32952   u8 *pPtrmap;       /* Pointer map page data */
32953   int offset;        /* Offset of entry in pointer map */
32954   int rc;
32955
32956   assert( sqlite3_mutex_held(pBt->mutex) );
32957
32958   iPtrmap = PTRMAP_PAGENO(pBt, key);
32959   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
32960   if( rc!=0 ){
32961     return rc;
32962   }
32963   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
32964
32965   offset = PTRMAP_PTROFFSET(iPtrmap, key);
32966   assert( pEType!=0 );
32967   *pEType = pPtrmap[offset];
32968   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
32969
32970   sqlite3PagerUnref(pDbPage);
32971   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
32972   return SQLITE_OK;
32973 }
32974
32975 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
32976   #define ptrmapPut(w,x,y,z) SQLITE_OK
32977   #define ptrmapGet(w,x,y,z) SQLITE_OK
32978   #define ptrmapPutOvfl(y,z) SQLITE_OK
32979 #endif
32980
32981 /*
32982 ** Given a btree page and a cell index (0 means the first cell on
32983 ** the page, 1 means the second cell, and so forth) return a pointer
32984 ** to the cell content.
32985 **
32986 ** This routine works only for pages that do not contain overflow cells.
32987 */
32988 #define findCell(P,I) \
32989   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
32990
32991 /*
32992 ** This a more complex version of findCell() that works for
32993 ** pages that do contain overflow cells.  See insert
32994 */
32995 static u8 *findOverflowCell(MemPage *pPage, int iCell){
32996   int i;
32997   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
32998   for(i=pPage->nOverflow-1; i>=0; i--){
32999     int k;
33000     struct _OvflCell *pOvfl;
33001     pOvfl = &pPage->aOvfl[i];
33002     k = pOvfl->idx;
33003     if( k<=iCell ){
33004       if( k==iCell ){
33005         return pOvfl->pCell;
33006       }
33007       iCell--;
33008     }
33009   }
33010   return findCell(pPage, iCell);
33011 }
33012
33013 /*
33014 ** Parse a cell content block and fill in the CellInfo structure.  There
33015 ** are two versions of this function.  sqlite3BtreeParseCell() takes a 
33016 ** cell index as the second argument and sqlite3BtreeParseCellPtr() 
33017 ** takes a pointer to the body of the cell as its second argument.
33018 **
33019 ** Within this file, the parseCell() macro can be called instead of
33020 ** sqlite3BtreeParseCellPtr(). Using some compilers, this will be faster.
33021 */
33022 SQLITE_PRIVATE void sqlite3BtreeParseCellPtr(
33023   MemPage *pPage,         /* Page containing the cell */
33024   u8 *pCell,              /* Pointer to the cell text. */
33025   CellInfo *pInfo         /* Fill in this structure */
33026 ){
33027   int n;                  /* Number bytes in cell content header */
33028   u32 nPayload;           /* Number of bytes of cell payload */
33029
33030   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
33031
33032   pInfo->pCell = pCell;
33033   assert( pPage->leaf==0 || pPage->leaf==1 );
33034   n = pPage->childPtrSize;
33035   assert( n==4-4*pPage->leaf );
33036   if( pPage->intKey ){
33037     if( pPage->hasData ){
33038       n += getVarint32(&pCell[n], nPayload);
33039     }else{
33040       nPayload = 0;
33041     }
33042     n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
33043     pInfo->nData = nPayload;
33044   }else{
33045     pInfo->nData = 0;
33046     n += getVarint32(&pCell[n], nPayload);
33047     pInfo->nKey = nPayload;
33048   }
33049   pInfo->nPayload = nPayload;
33050   pInfo->nHeader = n;
33051   if( likely(nPayload<=pPage->maxLocal) ){
33052     /* This is the (easy) common case where the entire payload fits
33053     ** on the local page.  No overflow is required.
33054     */
33055     int nSize;          /* Total size of cell content in bytes */
33056     nSize = nPayload + n;
33057     pInfo->nLocal = nPayload;
33058     pInfo->iOverflow = 0;
33059     if( (nSize & ~3)==0 ){
33060       nSize = 4;        /* Minimum cell size is 4 */
33061     }
33062     pInfo->nSize = nSize;
33063   }else{
33064     /* If the payload will not fit completely on the local page, we have
33065     ** to decide how much to store locally and how much to spill onto
33066     ** overflow pages.  The strategy is to minimize the amount of unused
33067     ** space on overflow pages while keeping the amount of local storage
33068     ** in between minLocal and maxLocal.
33069     **
33070     ** Warning:  changing the way overflow payload is distributed in any
33071     ** way will result in an incompatible file format.
33072     */
33073     int minLocal;  /* Minimum amount of payload held locally */
33074     int maxLocal;  /* Maximum amount of payload held locally */
33075     int surplus;   /* Overflow payload available for local storage */
33076
33077     minLocal = pPage->minLocal;
33078     maxLocal = pPage->maxLocal;
33079     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
33080     if( surplus <= maxLocal ){
33081       pInfo->nLocal = surplus;
33082     }else{
33083       pInfo->nLocal = minLocal;
33084     }
33085     pInfo->iOverflow = pInfo->nLocal + n;
33086     pInfo->nSize = pInfo->iOverflow + 4;
33087   }
33088 }
33089 #define parseCell(pPage, iCell, pInfo) \
33090   sqlite3BtreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
33091 SQLITE_PRIVATE void sqlite3BtreeParseCell(
33092   MemPage *pPage,         /* Page containing the cell */
33093   int iCell,              /* The cell index.  First cell is 0 */
33094   CellInfo *pInfo         /* Fill in this structure */
33095 ){
33096   parseCell(pPage, iCell, pInfo);
33097 }
33098
33099 /*
33100 ** Compute the total number of bytes that a Cell needs in the cell
33101 ** data area of the btree-page.  The return number includes the cell
33102 ** data header and the local payload, but not any overflow page or
33103 ** the space used by the cell pointer.
33104 */
33105 #ifndef NDEBUG
33106 static u16 cellSize(MemPage *pPage, int iCell){
33107   CellInfo info;
33108   sqlite3BtreeParseCell(pPage, iCell, &info);
33109   return info.nSize;
33110 }
33111 #endif
33112 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
33113   CellInfo info;
33114   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
33115   return info.nSize;
33116 }
33117
33118 #ifndef SQLITE_OMIT_AUTOVACUUM
33119 /*
33120 ** If the cell pCell, part of page pPage contains a pointer
33121 ** to an overflow page, insert an entry into the pointer-map
33122 ** for the overflow page.
33123 */
33124 static int ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell){
33125   CellInfo info;
33126   assert( pCell!=0 );
33127   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
33128   assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
33129   if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
33130     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
33131     return ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno);
33132   }
33133   return SQLITE_OK;
33134 }
33135 /*
33136 ** If the cell with index iCell on page pPage contains a pointer
33137 ** to an overflow page, insert an entry into the pointer-map
33138 ** for the overflow page.
33139 */
33140 static int ptrmapPutOvfl(MemPage *pPage, int iCell){
33141   u8 *pCell;
33142   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
33143   pCell = findOverflowCell(pPage, iCell);
33144   return ptrmapPutOvflPtr(pPage, pCell);
33145 }
33146 #endif
33147
33148
33149 /*
33150 ** Defragment the page given.  All Cells are moved to the
33151 ** end of the page and all free space is collected into one
33152 ** big FreeBlk that occurs in between the header and cell
33153 ** pointer array and the cell content area.
33154 */
33155 static void defragmentPage(MemPage *pPage){
33156   int i;                     /* Loop counter */
33157   int pc;                    /* Address of a i-th cell */
33158   int addr;                  /* Offset of first byte after cell pointer array */
33159   int hdr;                   /* Offset to the page header */
33160   int size;                  /* Size of a cell */
33161   int usableSize;            /* Number of usable bytes on a page */
33162   int cellOffset;            /* Offset to the cell pointer array */
33163   int brk;                   /* Offset to the cell content area */
33164   int nCell;                 /* Number of cells on the page */
33165   unsigned char *data;       /* The page data */
33166   unsigned char *temp;       /* Temp area for cell content */
33167
33168   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
33169   assert( pPage->pBt!=0 );
33170   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
33171   assert( pPage->nOverflow==0 );
33172   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
33173   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
33174   data = pPage->aData;
33175   hdr = pPage->hdrOffset;
33176   cellOffset = pPage->cellOffset;
33177   nCell = pPage->nCell;
33178   assert( nCell==get2byte(&data[hdr+3]) );
33179   usableSize = pPage->pBt->usableSize;
33180   brk = get2byte(&data[hdr+5]);
33181   memcpy(&temp[brk], &data[brk], usableSize - brk);
33182   brk = usableSize;
33183   for(i=0; i<nCell; i++){
33184     u8 *pAddr;     /* The i-th cell pointer */
33185     pAddr = &data[cellOffset + i*2];
33186     pc = get2byte(pAddr);
33187     assert( pc<pPage->pBt->usableSize );
33188     size = cellSizePtr(pPage, &temp[pc]);
33189     brk -= size;
33190     memcpy(&data[brk], &temp[pc], size);
33191     put2byte(pAddr, brk);
33192   }
33193   assert( brk>=cellOffset+2*nCell );
33194   put2byte(&data[hdr+5], brk);
33195   data[hdr+1] = 0;
33196   data[hdr+2] = 0;
33197   data[hdr+7] = 0;
33198   addr = cellOffset+2*nCell;
33199   memset(&data[addr], 0, brk-addr);
33200 }
33201
33202 /*
33203 ** Allocate nByte bytes of space on a page.
33204 **
33205 ** Return the index into pPage->aData[] of the first byte of
33206 ** the new allocation.  The caller guarantees that there is enough
33207 ** space.  This routine will never fail.
33208 **
33209 ** If the page contains nBytes of free space but does not contain
33210 ** nBytes of contiguous free space, then this routine automatically
33211 ** calls defragementPage() to consolidate all free space before 
33212 ** allocating the new chunk.
33213 */
33214 static int allocateSpace(MemPage *pPage, int nByte){
33215   int addr, pc, hdr;
33216   int size;
33217   int nFrag;
33218   int top;
33219   int nCell;
33220   int cellOffset;
33221   unsigned char *data;
33222   
33223   data = pPage->aData;
33224   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
33225   assert( pPage->pBt );
33226   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
33227   assert( nByte>=0 );  /* Minimum cell size is 4 */
33228   assert( pPage->nFree>=nByte );
33229   assert( pPage->nOverflow==0 );
33230   pPage->nFree -= nByte;
33231   hdr = pPage->hdrOffset;
33232
33233   nFrag = data[hdr+7];
33234   if( nFrag<60 ){
33235     /* Search the freelist looking for a slot big enough to satisfy the
33236     ** space request. */
33237     addr = hdr+1;
33238     while( (pc = get2byte(&data[addr]))>0 ){
33239       size = get2byte(&data[pc+2]);
33240       if( size>=nByte ){
33241         if( size<nByte+4 ){
33242           memcpy(&data[addr], &data[pc], 2);
33243           data[hdr+7] = nFrag + size - nByte;
33244           return pc;
33245         }else{
33246           put2byte(&data[pc+2], size-nByte);
33247           return pc + size - nByte;
33248         }
33249       }
33250       addr = pc;
33251     }
33252   }
33253
33254   /* Allocate memory from the gap in between the cell pointer array
33255   ** and the cell content area.
33256   */
33257   top = get2byte(&data[hdr+5]);
33258   nCell = get2byte(&data[hdr+3]);
33259   cellOffset = pPage->cellOffset;
33260   if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
33261     defragmentPage(pPage);
33262     top = get2byte(&data[hdr+5]);
33263   }
33264   top -= nByte;
33265   assert( cellOffset + 2*nCell <= top );
33266   put2byte(&data[hdr+5], top);
33267   return top;
33268 }
33269
33270 /*
33271 ** Return a section of the pPage->aData to the freelist.
33272 ** The first byte of the new free block is pPage->aDisk[start]
33273 ** and the size of the block is "size" bytes.
33274 **
33275 ** Most of the effort here is involved in coalesing adjacent
33276 ** free blocks into a single big free block.
33277 */
33278 static void freeSpace(MemPage *pPage, int start, int size){
33279   int addr, pbegin, hdr;
33280   unsigned char *data = pPage->aData;
33281
33282   assert( pPage->pBt!=0 );
33283   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
33284   assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
33285   assert( (start + size)<=pPage->pBt->usableSize );
33286   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
33287   assert( size>=0 );   /* Minimum cell size is 4 */
33288
33289 #ifdef SQLITE_SECURE_DELETE
33290   /* Overwrite deleted information with zeros when the SECURE_DELETE 
33291   ** option is enabled at compile-time */
33292   memset(&data[start], 0, size);
33293 #endif
33294
33295   /* Add the space back into the linked list of freeblocks */
33296   hdr = pPage->hdrOffset;
33297   addr = hdr + 1;
33298   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
33299     assert( pbegin<=pPage->pBt->usableSize-4 );
33300     assert( pbegin>addr );
33301     addr = pbegin;
33302   }
33303   assert( pbegin<=pPage->pBt->usableSize-4 );
33304   assert( pbegin>addr || pbegin==0 );
33305   put2byte(&data[addr], start);
33306   put2byte(&data[start], pbegin);
33307   put2byte(&data[start+2], size);
33308   pPage->nFree += size;
33309
33310   /* Coalesce adjacent free blocks */
33311   addr = pPage->hdrOffset + 1;
33312   while( (pbegin = get2byte(&data[addr]))>0 ){
33313     int pnext, psize;
33314     assert( pbegin>addr );
33315     assert( pbegin<=pPage->pBt->usableSize-4 );
33316     pnext = get2byte(&data[pbegin]);
33317     psize = get2byte(&data[pbegin+2]);
33318     if( pbegin + psize + 3 >= pnext && pnext>0 ){
33319       int frag = pnext - (pbegin+psize);
33320       assert( frag<=data[pPage->hdrOffset+7] );
33321       data[pPage->hdrOffset+7] -= frag;
33322       put2byte(&data[pbegin], get2byte(&data[pnext]));
33323       put2byte(&data[pbegin+2], pnext+get2byte(&data[pnext+2])-pbegin);
33324     }else{
33325       addr = pbegin;
33326     }
33327   }
33328
33329   /* If the cell content area begins with a freeblock, remove it. */
33330   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
33331     int top;
33332     pbegin = get2byte(&data[hdr+1]);
33333     memcpy(&data[hdr+1], &data[pbegin], 2);
33334     top = get2byte(&data[hdr+5]);
33335     put2byte(&data[hdr+5], top + get2byte(&data[pbegin+2]));
33336   }
33337 }
33338
33339 /*
33340 ** Decode the flags byte (the first byte of the header) for a page
33341 ** and initialize fields of the MemPage structure accordingly.
33342 **
33343 ** Only the following combinations are supported.  Anything different
33344 ** indicates a corrupt database files:
33345 **
33346 **         PTF_ZERODATA
33347 **         PTF_ZERODATA | PTF_LEAF
33348 **         PTF_LEAFDATA | PTF_INTKEY
33349 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
33350 */
33351 static int decodeFlags(MemPage *pPage, int flagByte){
33352   BtShared *pBt;     /* A copy of pPage->pBt */
33353
33354   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
33355   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
33356   pPage->leaf = flagByte>>3;  assert( PTF_LEAF == 1<<3 );
33357   flagByte &= ~PTF_LEAF;
33358   pPage->childPtrSize = 4-4*pPage->leaf;
33359   pBt = pPage->pBt;
33360   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
33361     pPage->intKey = 1;
33362     pPage->hasData = pPage->leaf;
33363     pPage->maxLocal = pBt->maxLeaf;
33364     pPage->minLocal = pBt->minLeaf;
33365   }else if( flagByte==PTF_ZERODATA ){
33366     pPage->intKey = 0;
33367     pPage->hasData = 0;
33368     pPage->maxLocal = pBt->maxLocal;
33369     pPage->minLocal = pBt->minLocal;
33370   }else{
33371     return SQLITE_CORRUPT_BKPT;
33372   }
33373   return SQLITE_OK;
33374 }
33375
33376 /*
33377 ** Initialize the auxiliary information for a disk block.
33378 **
33379 ** The pParent parameter must be a pointer to the MemPage which
33380 ** is the parent of the page being initialized.  The root of a
33381 ** BTree has no parent and so for that page, pParent==NULL.
33382 **
33383 ** Return SQLITE_OK on success.  If we see that the page does
33384 ** not contain a well-formed database page, then return 
33385 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
33386 ** guarantee that the page is well-formed.  It only shows that
33387 ** we failed to detect any corruption.
33388 */
33389 SQLITE_PRIVATE int sqlite3BtreeInitPage(
33390   MemPage *pPage,        /* The page to be initialized */
33391   MemPage *pParent       /* The parent.  Might be NULL */
33392 ){
33393   int pc;            /* Address of a freeblock within pPage->aData[] */
33394   int hdr;           /* Offset to beginning of page header */
33395   u8 *data;          /* Equal to pPage->aData */
33396   BtShared *pBt;        /* The main btree structure */
33397   int usableSize;    /* Amount of usable space on each page */
33398   int cellOffset;    /* Offset from start of page to first cell pointer */
33399   int nFree;         /* Number of unused bytes on the page */
33400   int top;           /* First byte of the cell content area */
33401
33402   pBt = pPage->pBt;
33403   assert( pBt!=0 );
33404   assert( pParent==0 || pParent->pBt==pBt );
33405   assert( sqlite3_mutex_held(pBt->mutex) );
33406   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
33407   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
33408   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
33409   if( pPage->pParent!=pParent && (pPage->pParent!=0 || pPage->isInit) ){
33410     /* The parent page should never change unless the file is corrupt */
33411     return SQLITE_CORRUPT_BKPT;
33412   }
33413   if( pPage->isInit ) return SQLITE_OK;
33414   if( pPage->pParent==0 && pParent!=0 ){
33415     pPage->pParent = pParent;
33416     sqlite3PagerRef(pParent->pDbPage);
33417   }
33418   hdr = pPage->hdrOffset;
33419   data = pPage->aData;
33420   if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
33421   assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
33422   pPage->maskPage = pBt->pageSize - 1;
33423   pPage->nOverflow = 0;
33424   pPage->idxShift = 0;
33425   usableSize = pBt->usableSize;
33426   pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
33427   top = get2byte(&data[hdr+5]);
33428   pPage->nCell = get2byte(&data[hdr+3]);
33429   if( pPage->nCell>MX_CELL(pBt) ){
33430     /* To many cells for a single page.  The page must be corrupt */
33431     return SQLITE_CORRUPT_BKPT;
33432   }
33433   if( pPage->nCell==0 && pParent!=0 && pParent->pgno!=1 ){
33434     /* All pages must have at least one cell, except for root pages */
33435     return SQLITE_CORRUPT_BKPT;
33436   }
33437
33438   /* Compute the total free space on the page */
33439   pc = get2byte(&data[hdr+1]);
33440   nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
33441   while( pc>0 ){
33442     int next, size;
33443     if( pc>usableSize-4 ){
33444       /* Free block is off the page */
33445       return SQLITE_CORRUPT_BKPT; 
33446     }
33447     next = get2byte(&data[pc]);
33448     size = get2byte(&data[pc+2]);
33449     if( next>0 && next<=pc+size+3 ){
33450       /* Free blocks must be in accending order */
33451       return SQLITE_CORRUPT_BKPT; 
33452     }
33453     nFree += size;
33454     pc = next;
33455   }
33456   pPage->nFree = nFree;
33457   if( nFree>=usableSize ){
33458     /* Free space cannot exceed total page size */
33459     return SQLITE_CORRUPT_BKPT; 
33460   }
33461
33462 #if 0
33463   /* Check that all the offsets in the cell offset array are within range. 
33464   ** 
33465   ** Omitting this consistency check and using the pPage->maskPage mask
33466   ** to prevent overrunning the page buffer in findCell() results in a
33467   ** 2.5% performance gain.
33468   */
33469   {
33470     u8 *pOff;        /* Iterator used to check all cell offsets are in range */
33471     u8 *pEnd;        /* Pointer to end of cell offset array */
33472     u8 mask;         /* Mask of bits that must be zero in MSB of cell offsets */
33473     mask = ~(((u8)(pBt->pageSize>>8))-1);
33474     pEnd = &data[cellOffset + pPage->nCell*2];
33475     for(pOff=&data[cellOffset]; pOff!=pEnd && !((*pOff)&mask); pOff+=2);
33476     if( pOff!=pEnd ){
33477       return SQLITE_CORRUPT_BKPT;
33478     }
33479   }
33480 #endif
33481
33482   pPage->isInit = 1;
33483   return SQLITE_OK;
33484 }
33485
33486 /*
33487 ** Set up a raw page so that it looks like a database page holding
33488 ** no entries.
33489 */
33490 static void zeroPage(MemPage *pPage, int flags){
33491   unsigned char *data = pPage->aData;
33492   BtShared *pBt = pPage->pBt;
33493   int hdr = pPage->hdrOffset;
33494   int first;
33495
33496   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
33497   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
33498   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
33499   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
33500   assert( sqlite3_mutex_held(pBt->mutex) );
33501   /*memset(&data[hdr], 0, pBt->usableSize - hdr);*/
33502   data[hdr] = flags;
33503   first = hdr + 8 + 4*((flags&PTF_LEAF)==0);
33504   memset(&data[hdr+1], 0, 4);
33505   data[hdr+7] = 0;
33506   put2byte(&data[hdr+5], pBt->usableSize);
33507   pPage->nFree = pBt->usableSize - first;
33508   decodeFlags(pPage, flags);
33509   pPage->hdrOffset = hdr;
33510   pPage->cellOffset = first;
33511   pPage->nOverflow = 0;
33512   assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
33513   pPage->maskPage = pBt->pageSize - 1;
33514   pPage->idxShift = 0;
33515   pPage->nCell = 0;
33516   pPage->isInit = 1;
33517 }
33518
33519 /*
33520 ** Get a page from the pager.  Initialize the MemPage.pBt and
33521 ** MemPage.aData elements if needed.
33522 **
33523 ** If the noContent flag is set, it means that we do not care about
33524 ** the content of the page at this time.  So do not go to the disk
33525 ** to fetch the content.  Just fill in the content with zeros for now.
33526 ** If in the future we call sqlite3PagerWrite() on this page, that
33527 ** means we have started to be concerned about content and the disk
33528 ** read should occur at that point.
33529 */
33530 SQLITE_PRIVATE int sqlite3BtreeGetPage(
33531   BtShared *pBt,       /* The btree */
33532   Pgno pgno,           /* Number of the page to fetch */
33533   MemPage **ppPage,    /* Return the page in this parameter */
33534   int noContent        /* Do not load page content if true */
33535 ){
33536   int rc;
33537   MemPage *pPage;
33538   DbPage *pDbPage;
33539
33540   assert( sqlite3_mutex_held(pBt->mutex) );
33541   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
33542   if( rc ) return rc;
33543   pPage = (MemPage *)sqlite3PagerGetExtra(pDbPage);
33544   pPage->aData = sqlite3PagerGetData(pDbPage);
33545   pPage->pDbPage = pDbPage;
33546   pPage->pBt = pBt;
33547   pPage->pgno = pgno;
33548   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
33549   *ppPage = pPage;
33550   return SQLITE_OK;
33551 }
33552
33553 /*
33554 ** Get a page from the pager and initialize it.  This routine
33555 ** is just a convenience wrapper around separate calls to
33556 ** sqlite3BtreeGetPage() and sqlite3BtreeInitPage().
33557 */
33558 static int getAndInitPage(
33559   BtShared *pBt,          /* The database file */
33560   Pgno pgno,           /* Number of the page to get */
33561   MemPage **ppPage,    /* Write the page pointer here */
33562   MemPage *pParent     /* Parent of the page */
33563 ){
33564   int rc;
33565   assert( sqlite3_mutex_held(pBt->mutex) );
33566   if( pgno==0 ){
33567     return SQLITE_CORRUPT_BKPT; 
33568   }
33569   rc = sqlite3BtreeGetPage(pBt, pgno, ppPage, 0);
33570   if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
33571     rc = sqlite3BtreeInitPage(*ppPage, pParent);
33572     if( rc!=SQLITE_OK ){
33573       releasePage(*ppPage);
33574       *ppPage = 0;
33575     }
33576   }
33577   return rc;
33578 }
33579
33580 /*
33581 ** Release a MemPage.  This should be called once for each prior
33582 ** call to sqlite3BtreeGetPage.
33583 */
33584 static void releasePage(MemPage *pPage){
33585   if( pPage ){
33586     assert( pPage->aData );
33587     assert( pPage->pBt );
33588     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
33589     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
33590     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
33591     sqlite3PagerUnref(pPage->pDbPage);
33592   }
33593 }
33594
33595 /*
33596 ** This routine is called when the reference count for a page
33597 ** reaches zero.  We need to unref the pParent pointer when that
33598 ** happens.
33599 */
33600 static void pageDestructor(DbPage *pData, int pageSize){
33601   MemPage *pPage;
33602   assert( (pageSize & 7)==0 );
33603   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
33604   assert( pPage->isInit==0 || sqlite3_mutex_held(pPage->pBt->mutex) );
33605   if( pPage->pParent ){
33606     MemPage *pParent = pPage->pParent;
33607     assert( pParent->pBt==pPage->pBt );
33608     pPage->pParent = 0;
33609     releasePage(pParent);
33610   }
33611   pPage->isInit = 0;
33612 }
33613
33614 /*
33615 ** During a rollback, when the pager reloads information into the cache
33616 ** so that the cache is restored to its original state at the start of
33617 ** the transaction, for each page restored this routine is called.
33618 **
33619 ** This routine needs to reset the extra data section at the end of the
33620 ** page to agree with the restored data.
33621 */
33622 static void pageReinit(DbPage *pData, int pageSize){
33623   MemPage *pPage;
33624   assert( (pageSize & 7)==0 );
33625   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
33626   if( pPage->isInit ){
33627     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
33628     pPage->isInit = 0;
33629     sqlite3BtreeInitPage(pPage, pPage->pParent);
33630   }
33631 }
33632
33633 /*
33634 ** Invoke the busy handler for a btree.
33635 */
33636 static int sqlite3BtreeInvokeBusyHandler(void *pArg, int n){
33637   BtShared *pBt = (BtShared*)pArg;
33638   assert( pBt->db );
33639   assert( sqlite3_mutex_held(pBt->db->mutex) );
33640   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
33641 }
33642
33643 /*
33644 ** Open a database file.
33645 ** 
33646 ** zFilename is the name of the database file.  If zFilename is NULL
33647 ** a new database with a random name is created.  This randomly named
33648 ** database file will be deleted when sqlite3BtreeClose() is called.
33649 ** If zFilename is ":memory:" then an in-memory database is created
33650 ** that is automatically destroyed when it is closed.
33651 */
33652 SQLITE_PRIVATE int sqlite3BtreeOpen(
33653   const char *zFilename,  /* Name of the file containing the BTree database */
33654   sqlite3 *db,            /* Associated database handle */
33655   Btree **ppBtree,        /* Pointer to new Btree object written here */
33656   int flags,              /* Options */
33657   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
33658 ){
33659   sqlite3_vfs *pVfs;      /* The VFS to use for this btree */
33660   BtShared *pBt = 0;      /* Shared part of btree structure */
33661   Btree *p;               /* Handle to return */
33662   int rc = SQLITE_OK;
33663   int nReserve;
33664   unsigned char zDbHeader[100];
33665
33666   /* Set the variable isMemdb to true for an in-memory database, or 
33667   ** false for a file-based database. This symbol is only required if
33668   ** either of the shared-data or autovacuum features are compiled 
33669   ** into the library.
33670   */
33671 #if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
33672   #ifdef SQLITE_OMIT_MEMORYDB
33673     const int isMemdb = 0;
33674   #else
33675     const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
33676   #endif
33677 #endif
33678
33679   assert( db!=0 );
33680   assert( sqlite3_mutex_held(db->mutex) );
33681
33682   pVfs = db->pVfs;
33683   p = sqlite3MallocZero(sizeof(Btree));
33684   if( !p ){
33685     return SQLITE_NOMEM;
33686   }
33687   p->inTrans = TRANS_NONE;
33688   p->db = db;
33689
33690 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
33691   /*
33692   ** If this Btree is a candidate for shared cache, try to find an
33693   ** existing BtShared object that we can share with
33694   */
33695   if( isMemdb==0
33696    && (db->flags & SQLITE_Vtab)==0
33697    && zFilename && zFilename[0]
33698   ){
33699     if( sqlite3SharedCacheEnabled ){
33700       int nFullPathname = pVfs->mxPathname+1;
33701       char *zFullPathname = sqlite3Malloc(nFullPathname);
33702       sqlite3_mutex *mutexShared;
33703       p->sharable = 1;
33704       db->flags |= SQLITE_SharedCache;
33705       if( !zFullPathname ){
33706         sqlite3_free(p);
33707         return SQLITE_NOMEM;
33708       }
33709       sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
33710       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
33711       sqlite3_mutex_enter(mutexShared);
33712       for(pBt=sqlite3SharedCacheList; pBt; pBt=pBt->pNext){
33713         assert( pBt->nRef>0 );
33714         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
33715                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
33716           p->pBt = pBt;
33717           pBt->nRef++;
33718           break;
33719         }
33720       }
33721       sqlite3_mutex_leave(mutexShared);
33722       sqlite3_free(zFullPathname);
33723     }
33724 #ifdef SQLITE_DEBUG
33725     else{
33726       /* In debug mode, we mark all persistent databases as sharable
33727       ** even when they are not.  This exercises the locking code and
33728       ** gives more opportunity for asserts(sqlite3_mutex_held())
33729       ** statements to find locking problems.
33730       */
33731       p->sharable = 1;
33732     }
33733 #endif
33734   }
33735 #endif
33736   if( pBt==0 ){
33737     /*
33738     ** The following asserts make sure that structures used by the btree are
33739     ** the right size.  This is to guard against size changes that result
33740     ** when compiling on a different architecture.
33741     */
33742     assert( sizeof(i64)==8 || sizeof(i64)==4 );
33743     assert( sizeof(u64)==8 || sizeof(u64)==4 );
33744     assert( sizeof(u32)==4 );
33745     assert( sizeof(u16)==2 );
33746     assert( sizeof(Pgno)==4 );
33747   
33748     pBt = sqlite3MallocZero( sizeof(*pBt) );
33749     if( pBt==0 ){
33750       rc = SQLITE_NOMEM;
33751       goto btree_open_out;
33752     }
33753     pBt->busyHdr.xFunc = sqlite3BtreeInvokeBusyHandler;
33754     pBt->busyHdr.pArg = pBt;
33755     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
33756                           EXTRA_SIZE, flags, vfsFlags);
33757     if( rc==SQLITE_OK ){
33758       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
33759     }
33760     if( rc!=SQLITE_OK ){
33761       goto btree_open_out;
33762     }
33763     sqlite3PagerSetBusyhandler(pBt->pPager, &pBt->busyHdr);
33764     p->pBt = pBt;
33765   
33766     sqlite3PagerSetDestructor(pBt->pPager, pageDestructor);
33767     sqlite3PagerSetReiniter(pBt->pPager, pageReinit);
33768     pBt->pCursor = 0;
33769     pBt->pPage1 = 0;
33770     pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
33771     pBt->pageSize = get2byte(&zDbHeader[16]);
33772     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
33773          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
33774       pBt->pageSize = 0;
33775       sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
33776 #ifndef SQLITE_OMIT_AUTOVACUUM
33777       /* If the magic name ":memory:" will create an in-memory database, then
33778       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
33779       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
33780       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
33781       ** regular file-name. In this case the auto-vacuum applies as per normal.
33782       */
33783       if( zFilename && !isMemdb ){
33784         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
33785         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
33786       }
33787 #endif
33788       nReserve = 0;
33789     }else{
33790       nReserve = zDbHeader[20];
33791       pBt->pageSizeFixed = 1;
33792 #ifndef SQLITE_OMIT_AUTOVACUUM
33793       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
33794       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
33795 #endif
33796     }
33797     pBt->usableSize = pBt->pageSize - nReserve;
33798     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
33799     sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
33800    
33801 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
33802     /* Add the new BtShared object to the linked list sharable BtShareds.
33803     */
33804     if( p->sharable ){
33805       sqlite3_mutex *mutexShared;
33806       pBt->nRef = 1;
33807       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
33808       if( SQLITE_THREADSAFE && sqlite3Config.bCoreMutex ){
33809         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
33810         if( pBt->mutex==0 ){
33811           rc = SQLITE_NOMEM;
33812           db->mallocFailed = 0;
33813           goto btree_open_out;
33814         }
33815       }
33816       sqlite3_mutex_enter(mutexShared);
33817       pBt->pNext = sqlite3SharedCacheList;
33818       sqlite3SharedCacheList = pBt;
33819       sqlite3_mutex_leave(mutexShared);
33820     }
33821 #endif
33822   }
33823
33824 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
33825   /* If the new Btree uses a sharable pBtShared, then link the new
33826   ** Btree into the list of all sharable Btrees for the same connection.
33827   ** The list is kept in ascending order by pBt address.
33828   */
33829   if( p->sharable ){
33830     int i;
33831     Btree *pSib;
33832     for(i=0; i<db->nDb; i++){
33833       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
33834         while( pSib->pPrev ){ pSib = pSib->pPrev; }
33835         if( p->pBt<pSib->pBt ){
33836           p->pNext = pSib;
33837           p->pPrev = 0;
33838           pSib->pPrev = p;
33839         }else{
33840           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
33841             pSib = pSib->pNext;
33842           }
33843           p->pNext = pSib->pNext;
33844           p->pPrev = pSib;
33845           if( p->pNext ){
33846             p->pNext->pPrev = p;
33847           }
33848           pSib->pNext = p;
33849         }
33850         break;
33851       }
33852     }
33853   }
33854 #endif
33855   *ppBtree = p;
33856
33857 btree_open_out:
33858   if( rc!=SQLITE_OK ){
33859     if( pBt && pBt->pPager ){
33860       sqlite3PagerClose(pBt->pPager);
33861     }
33862     sqlite3_free(pBt);
33863     sqlite3_free(p);
33864     *ppBtree = 0;
33865   }
33866   return rc;
33867 }
33868
33869 /*
33870 ** Decrement the BtShared.nRef counter.  When it reaches zero,
33871 ** remove the BtShared structure from the sharing list.  Return
33872 ** true if the BtShared.nRef counter reaches zero and return
33873 ** false if it is still positive.
33874 */
33875 static int removeFromSharingList(BtShared *pBt){
33876 #ifndef SQLITE_OMIT_SHARED_CACHE
33877   sqlite3_mutex *pMaster;
33878   BtShared *pList;
33879   int removed = 0;
33880
33881   assert( sqlite3_mutex_notheld(pBt->mutex) );
33882   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
33883   sqlite3_mutex_enter(pMaster);
33884   pBt->nRef--;
33885   if( pBt->nRef<=0 ){
33886     if( sqlite3SharedCacheList==pBt ){
33887       sqlite3SharedCacheList = pBt->pNext;
33888     }else{
33889       pList = sqlite3SharedCacheList;
33890       while( ALWAYS(pList) && pList->pNext!=pBt ){
33891         pList=pList->pNext;
33892       }
33893       if( ALWAYS(pList) ){
33894         pList->pNext = pBt->pNext;
33895       }
33896     }
33897     if( SQLITE_THREADSAFE ){
33898       sqlite3_mutex_free(pBt->mutex);
33899     }
33900     removed = 1;
33901   }
33902   sqlite3_mutex_leave(pMaster);
33903   return removed;
33904 #else
33905   return 1;
33906 #endif
33907 }
33908
33909 /*
33910 ** Make sure pBt->pTmpSpace points to an allocation of 
33911 ** MX_CELL_SIZE(pBt) bytes.
33912 */
33913 static void allocateTempSpace(BtShared *pBt){
33914   if( !pBt->pTmpSpace ){
33915     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
33916   }
33917 }
33918
33919 /*
33920 ** Free the pBt->pTmpSpace allocation
33921 */
33922 static void freeTempSpace(BtShared *pBt){
33923   sqlite3PageFree( pBt->pTmpSpace);
33924   pBt->pTmpSpace = 0;
33925 }
33926
33927 /*
33928 ** Close an open database and invalidate all cursors.
33929 */
33930 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
33931   BtShared *pBt = p->pBt;
33932   BtCursor *pCur;
33933
33934   /* Close all cursors opened via this handle.  */
33935   assert( sqlite3_mutex_held(p->db->mutex) );
33936   sqlite3BtreeEnter(p);
33937   pBt->db = p->db;
33938   pCur = pBt->pCursor;
33939   while( pCur ){
33940     BtCursor *pTmp = pCur;
33941     pCur = pCur->pNext;
33942     if( pTmp->pBtree==p ){
33943       sqlite3BtreeCloseCursor(pTmp);
33944     }
33945   }
33946
33947   /* Rollback any active transaction and free the handle structure.
33948   ** The call to sqlite3BtreeRollback() drops any table-locks held by
33949   ** this handle.
33950   */
33951   sqlite3BtreeRollback(p);
33952   sqlite3BtreeLeave(p);
33953
33954   /* If there are still other outstanding references to the shared-btree
33955   ** structure, return now. The remainder of this procedure cleans 
33956   ** up the shared-btree.
33957   */
33958   assert( p->wantToLock==0 && p->locked==0 );
33959   if( !p->sharable || removeFromSharingList(pBt) ){
33960     /* The pBt is no longer on the sharing list, so we can access
33961     ** it without having to hold the mutex.
33962     **
33963     ** Clean out and delete the BtShared object.
33964     */
33965     assert( !pBt->pCursor );
33966     sqlite3PagerClose(pBt->pPager);
33967     if( pBt->xFreeSchema && pBt->pSchema ){
33968       pBt->xFreeSchema(pBt->pSchema);
33969     }
33970     sqlite3_free(pBt->pSchema);
33971     freeTempSpace(pBt);
33972     sqlite3_free(pBt);
33973   }
33974
33975 #ifndef SQLITE_OMIT_SHARED_CACHE
33976   assert( p->wantToLock==0 );
33977   assert( p->locked==0 );
33978   if( p->pPrev ) p->pPrev->pNext = p->pNext;
33979   if( p->pNext ) p->pNext->pPrev = p->pPrev;
33980 #endif
33981
33982   sqlite3_free(p);
33983   return SQLITE_OK;
33984 }
33985
33986 /*
33987 ** Change the limit on the number of pages allowed in the cache.
33988 **
33989 ** The maximum number of cache pages is set to the absolute
33990 ** value of mxPage.  If mxPage is negative, the pager will
33991 ** operate asynchronously - it will not stop to do fsync()s
33992 ** to insure data is written to the disk surface before
33993 ** continuing.  Transactions still work if synchronous is off,
33994 ** and the database cannot be corrupted if this program
33995 ** crashes.  But if the operating system crashes or there is
33996 ** an abrupt power failure when synchronous is off, the database
33997 ** could be left in an inconsistent and unrecoverable state.
33998 ** Synchronous is on by default so database corruption is not
33999 ** normally a worry.
34000 */
34001 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
34002   BtShared *pBt = p->pBt;
34003   assert( sqlite3_mutex_held(p->db->mutex) );
34004   sqlite3BtreeEnter(p);
34005   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
34006   sqlite3BtreeLeave(p);
34007   return SQLITE_OK;
34008 }
34009
34010 /*
34011 ** Change the way data is synced to disk in order to increase or decrease
34012 ** how well the database resists damage due to OS crashes and power
34013 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
34014 ** there is a high probability of damage)  Level 2 is the default.  There
34015 ** is a very low but non-zero probability of damage.  Level 3 reduces the
34016 ** probability of damage to near zero but with a write performance reduction.
34017 */
34018 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
34019 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
34020   BtShared *pBt = p->pBt;
34021   assert( sqlite3_mutex_held(p->db->mutex) );
34022   sqlite3BtreeEnter(p);
34023   sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
34024   sqlite3BtreeLeave(p);
34025   return SQLITE_OK;
34026 }
34027 #endif
34028
34029 /*
34030 ** Return TRUE if the given btree is set to safety level 1.  In other
34031 ** words, return TRUE if no sync() occurs on the disk files.
34032 */
34033 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
34034   BtShared *pBt = p->pBt;
34035   int rc;
34036   assert( sqlite3_mutex_held(p->db->mutex) );  
34037   sqlite3BtreeEnter(p);
34038   assert( pBt && pBt->pPager );
34039   rc = sqlite3PagerNosync(pBt->pPager);
34040   sqlite3BtreeLeave(p);
34041   return rc;
34042 }
34043
34044 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
34045 /*
34046 ** Change the default pages size and the number of reserved bytes per page.
34047 **
34048 ** The page size must be a power of 2 between 512 and 65536.  If the page
34049 ** size supplied does not meet this constraint then the page size is not
34050 ** changed.
34051 **
34052 ** Page sizes are constrained to be a power of two so that the region
34053 ** of the database file used for locking (beginning at PENDING_BYTE,
34054 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
34055 ** at the beginning of a page.
34056 **
34057 ** If parameter nReserve is less than zero, then the number of reserved
34058 ** bytes per page is left unchanged.
34059 */
34060 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve){
34061   int rc = SQLITE_OK;
34062   BtShared *pBt = p->pBt;
34063   sqlite3BtreeEnter(p);
34064   if( pBt->pageSizeFixed ){
34065     sqlite3BtreeLeave(p);
34066     return SQLITE_READONLY;
34067   }
34068   if( nReserve<0 ){
34069     nReserve = pBt->pageSize - pBt->usableSize;
34070   }
34071   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
34072         ((pageSize-1)&pageSize)==0 ){
34073     assert( (pageSize & 7)==0 );
34074     assert( !pBt->pPage1 && !pBt->pCursor );
34075     pBt->pageSize = pageSize;
34076     freeTempSpace(pBt);
34077     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
34078   }
34079   pBt->usableSize = pBt->pageSize - nReserve;
34080   sqlite3BtreeLeave(p);
34081   return rc;
34082 }
34083
34084 /*
34085 ** Return the currently defined page size
34086 */
34087 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
34088   return p->pBt->pageSize;
34089 }
34090 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
34091   int n;
34092   sqlite3BtreeEnter(p);
34093   n = p->pBt->pageSize - p->pBt->usableSize;
34094   sqlite3BtreeLeave(p);
34095   return n;
34096 }
34097
34098 /*
34099 ** Set the maximum page count for a database if mxPage is positive.
34100 ** No changes are made if mxPage is 0 or negative.
34101 ** Regardless of the value of mxPage, return the maximum page count.
34102 */
34103 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
34104   int n;
34105   sqlite3BtreeEnter(p);
34106   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
34107   sqlite3BtreeLeave(p);
34108   return n;
34109 }
34110 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
34111
34112 /*
34113 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
34114 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
34115 ** is disabled. The default value for the auto-vacuum property is 
34116 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
34117 */
34118 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
34119 #ifdef SQLITE_OMIT_AUTOVACUUM
34120   return SQLITE_READONLY;
34121 #else
34122   BtShared *pBt = p->pBt;
34123   int rc = SQLITE_OK;
34124   int av = (autoVacuum?1:0);
34125
34126   sqlite3BtreeEnter(p);
34127   if( pBt->pageSizeFixed && av!=pBt->autoVacuum ){
34128     rc = SQLITE_READONLY;
34129   }else{
34130     pBt->autoVacuum = av;
34131   }
34132   sqlite3BtreeLeave(p);
34133   return rc;
34134 #endif
34135 }
34136
34137 /*
34138 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
34139 ** enabled 1 is returned. Otherwise 0.
34140 */
34141 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
34142 #ifdef SQLITE_OMIT_AUTOVACUUM
34143   return BTREE_AUTOVACUUM_NONE;
34144 #else
34145   int rc;
34146   sqlite3BtreeEnter(p);
34147   rc = (
34148     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
34149     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
34150     BTREE_AUTOVACUUM_INCR
34151   );
34152   sqlite3BtreeLeave(p);
34153   return rc;
34154 #endif
34155 }
34156
34157
34158 /*
34159 ** Get a reference to pPage1 of the database file.  This will
34160 ** also acquire a readlock on that file.
34161 **
34162 ** SQLITE_OK is returned on success.  If the file is not a
34163 ** well-formed database file, then SQLITE_CORRUPT is returned.
34164 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
34165 ** is returned if we run out of memory. 
34166 */
34167 static int lockBtree(BtShared *pBt){
34168   int rc;
34169   MemPage *pPage1;
34170   int nPage;
34171
34172   assert( sqlite3_mutex_held(pBt->mutex) );
34173   if( pBt->pPage1 ) return SQLITE_OK;
34174   rc = sqlite3BtreeGetPage(pBt, 1, &pPage1, 0);
34175   if( rc!=SQLITE_OK ) return rc;
34176
34177   /* Do some checking to help insure the file we opened really is
34178   ** a valid database file. 
34179   */
34180   rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
34181   if( rc!=SQLITE_OK ){
34182     goto page1_init_failed;
34183   }else if( nPage>0 ){
34184     int pageSize;
34185     int usableSize;
34186     u8 *page1 = pPage1->aData;
34187     rc = SQLITE_NOTADB;
34188     if( memcmp(page1, zMagicHeader, 16)!=0 ){
34189       goto page1_init_failed;
34190     }
34191     if( page1[18]>1 ){
34192       pBt->readOnly = 1;
34193     }
34194     if( page1[19]>1 ){
34195       goto page1_init_failed;
34196     }
34197
34198     /* The maximum embedded fraction must be exactly 25%.  And the minimum
34199     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
34200     ** The original design allowed these amounts to vary, but as of
34201     ** version 3.6.0, we require them to be fixed.
34202     */
34203     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
34204       goto page1_init_failed;
34205     }
34206     pageSize = get2byte(&page1[16]);
34207     if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
34208         (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
34209     ){
34210       goto page1_init_failed;
34211     }
34212     assert( (pageSize & 7)==0 );
34213     usableSize = pageSize - page1[20];
34214     if( pageSize!=pBt->pageSize ){
34215       /* After reading the first page of the database assuming a page size
34216       ** of BtShared.pageSize, we have discovered that the page-size is
34217       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
34218       ** zero and return SQLITE_OK. The caller will call this function
34219       ** again with the correct page-size.
34220       */
34221       releasePage(pPage1);
34222       pBt->usableSize = usableSize;
34223       pBt->pageSize = pageSize;
34224       freeTempSpace(pBt);
34225       sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
34226       return SQLITE_OK;
34227     }
34228     if( usableSize<500 ){
34229       goto page1_init_failed;
34230     }
34231     pBt->pageSize = pageSize;
34232     pBt->usableSize = usableSize;
34233 #ifndef SQLITE_OMIT_AUTOVACUUM
34234     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
34235     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
34236 #endif
34237   }
34238
34239   /* maxLocal is the maximum amount of payload to store locally for
34240   ** a cell.  Make sure it is small enough so that at least minFanout
34241   ** cells can will fit on one page.  We assume a 10-byte page header.
34242   ** Besides the payload, the cell must store:
34243   **     2-byte pointer to the cell
34244   **     4-byte child pointer
34245   **     9-byte nKey value
34246   **     4-byte nData value
34247   **     4-byte overflow page pointer
34248   ** So a cell consists of a 2-byte poiner, a header which is as much as
34249   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
34250   ** page pointer.
34251   */
34252   pBt->maxLocal = (pBt->usableSize-12)*64/255 - 23;
34253   pBt->minLocal = (pBt->usableSize-12)*32/255 - 23;
34254   pBt->maxLeaf = pBt->usableSize - 35;
34255   pBt->minLeaf = (pBt->usableSize-12)*32/255 - 23;
34256   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
34257   pBt->pPage1 = pPage1;
34258   return SQLITE_OK;
34259
34260 page1_init_failed:
34261   releasePage(pPage1);
34262   pBt->pPage1 = 0;
34263   return rc;
34264 }
34265
34266 /*
34267 ** This routine works like lockBtree() except that it also invokes the
34268 ** busy callback if there is lock contention.
34269 */
34270 static int lockBtreeWithRetry(Btree *pRef){
34271   int rc = SQLITE_OK;
34272
34273   assert( sqlite3BtreeHoldsMutex(pRef) );
34274   if( pRef->inTrans==TRANS_NONE ){
34275     u8 inTransaction = pRef->pBt->inTransaction;
34276     btreeIntegrity(pRef);
34277     rc = sqlite3BtreeBeginTrans(pRef, 0);
34278     pRef->pBt->inTransaction = inTransaction;
34279     pRef->inTrans = TRANS_NONE;
34280     if( rc==SQLITE_OK ){
34281       pRef->pBt->nTransaction--;
34282     }
34283     btreeIntegrity(pRef);
34284   }
34285   return rc;
34286 }
34287        
34288
34289 /*
34290 ** If there are no outstanding cursors and we are not in the middle
34291 ** of a transaction but there is a read lock on the database, then
34292 ** this routine unrefs the first page of the database file which 
34293 ** has the effect of releasing the read lock.
34294 **
34295 ** If there are any outstanding cursors, this routine is a no-op.
34296 **
34297 ** If there is a transaction in progress, this routine is a no-op.
34298 */
34299 static void unlockBtreeIfUnused(BtShared *pBt){
34300   assert( sqlite3_mutex_held(pBt->mutex) );
34301   if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
34302     if( sqlite3PagerRefcount(pBt->pPager)>=1 ){
34303       assert( pBt->pPage1->aData );
34304 #if 0
34305       if( pBt->pPage1->aData==0 ){
34306         MemPage *pPage = pBt->pPage1;
34307         pPage->aData = sqlite3PagerGetData(pPage->pDbPage);
34308         pPage->pBt = pBt;
34309         pPage->pgno = 1;
34310       }
34311 #endif
34312       releasePage(pBt->pPage1);
34313     }
34314     pBt->pPage1 = 0;
34315     pBt->inStmt = 0;
34316   }
34317 }
34318
34319 /*
34320 ** Create a new database by initializing the first page of the
34321 ** file.
34322 */
34323 static int newDatabase(BtShared *pBt){
34324   MemPage *pP1;
34325   unsigned char *data;
34326   int rc;
34327   int nPage;
34328
34329   assert( sqlite3_mutex_held(pBt->mutex) );
34330   rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
34331   if( rc!=SQLITE_OK || nPage>0 ){
34332     return rc;
34333   }
34334   pP1 = pBt->pPage1;
34335   assert( pP1!=0 );
34336   data = pP1->aData;
34337   rc = sqlite3PagerWrite(pP1->pDbPage);
34338   if( rc ) return rc;
34339   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
34340   assert( sizeof(zMagicHeader)==16 );
34341   put2byte(&data[16], pBt->pageSize);
34342   data[18] = 1;
34343   data[19] = 1;
34344   data[20] = pBt->pageSize - pBt->usableSize;
34345   data[21] = 64;
34346   data[22] = 32;
34347   data[23] = 32;
34348   memset(&data[24], 0, 100-24);
34349   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
34350   pBt->pageSizeFixed = 1;
34351 #ifndef SQLITE_OMIT_AUTOVACUUM
34352   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
34353   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
34354   put4byte(&data[36 + 4*4], pBt->autoVacuum);
34355   put4byte(&data[36 + 7*4], pBt->incrVacuum);
34356 #endif
34357   return SQLITE_OK;
34358 }
34359
34360 /*
34361 ** Attempt to start a new transaction. A write-transaction
34362 ** is started if the second argument is nonzero, otherwise a read-
34363 ** transaction.  If the second argument is 2 or more and exclusive
34364 ** transaction is started, meaning that no other process is allowed
34365 ** to access the database.  A preexisting transaction may not be
34366 ** upgraded to exclusive by calling this routine a second time - the
34367 ** exclusivity flag only works for a new transaction.
34368 **
34369 ** A write-transaction must be started before attempting any 
34370 ** changes to the database.  None of the following routines 
34371 ** will work unless a transaction is started first:
34372 **
34373 **      sqlite3BtreeCreateTable()
34374 **      sqlite3BtreeCreateIndex()
34375 **      sqlite3BtreeClearTable()
34376 **      sqlite3BtreeDropTable()
34377 **      sqlite3BtreeInsert()
34378 **      sqlite3BtreeDelete()
34379 **      sqlite3BtreeUpdateMeta()
34380 **
34381 ** If an initial attempt to acquire the lock fails because of lock contention
34382 ** and the database was previously unlocked, then invoke the busy handler
34383 ** if there is one.  But if there was previously a read-lock, do not
34384 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
34385 ** returned when there is already a read-lock in order to avoid a deadlock.
34386 **
34387 ** Suppose there are two processes A and B.  A has a read lock and B has
34388 ** a reserved lock.  B tries to promote to exclusive but is blocked because
34389 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
34390 ** One or the other of the two processes must give way or there can be
34391 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
34392 ** when A already has a read lock, we encourage A to give up and let B
34393 ** proceed.
34394 */
34395 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
34396   BtShared *pBt = p->pBt;
34397   int rc = SQLITE_OK;
34398
34399   sqlite3BtreeEnter(p);
34400   pBt->db = p->db;
34401   btreeIntegrity(p);
34402
34403   /* If the btree is already in a write-transaction, or it
34404   ** is already in a read-transaction and a read-transaction
34405   ** is requested, this is a no-op.
34406   */
34407   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
34408     goto trans_begun;
34409   }
34410
34411   /* Write transactions are not possible on a read-only database */
34412   if( pBt->readOnly && wrflag ){
34413     rc = SQLITE_READONLY;
34414     goto trans_begun;
34415   }
34416
34417   /* If another database handle has already opened a write transaction 
34418   ** on this shared-btree structure and a second write transaction is
34419   ** requested, return SQLITE_BUSY.
34420   */
34421   if( pBt->inTransaction==TRANS_WRITE && wrflag ){
34422     rc = SQLITE_BUSY;
34423     goto trans_begun;
34424   }
34425
34426 #ifndef SQLITE_OMIT_SHARED_CACHE
34427   if( wrflag>1 ){
34428     BtLock *pIter;
34429     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
34430       if( pIter->pBtree!=p ){
34431         rc = SQLITE_BUSY;
34432         goto trans_begun;
34433       }
34434     }
34435   }
34436 #endif
34437
34438   do {
34439     if( pBt->pPage1==0 ){
34440       do{
34441         rc = lockBtree(pBt);
34442       }while( pBt->pPage1==0 && rc==SQLITE_OK );
34443     }
34444
34445     if( rc==SQLITE_OK && wrflag ){
34446       if( pBt->readOnly ){
34447         rc = SQLITE_READONLY;
34448       }else{
34449         rc = sqlite3PagerBegin(pBt->pPage1->pDbPage, wrflag>1);
34450         if( rc==SQLITE_OK ){
34451           rc = newDatabase(pBt);
34452         }
34453       }
34454     }
34455   
34456     if( rc==SQLITE_OK ){
34457       if( wrflag ) pBt->inStmt = 0;
34458     }else{
34459       unlockBtreeIfUnused(pBt);
34460     }
34461   }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
34462           sqlite3BtreeInvokeBusyHandler(pBt, 0) );
34463
34464   if( rc==SQLITE_OK ){
34465     if( p->inTrans==TRANS_NONE ){
34466       pBt->nTransaction++;
34467     }
34468     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
34469     if( p->inTrans>pBt->inTransaction ){
34470       pBt->inTransaction = p->inTrans;
34471     }
34472 #ifndef SQLITE_OMIT_SHARED_CACHE
34473     if( wrflag>1 ){
34474       assert( !pBt->pExclusive );
34475       pBt->pExclusive = p;
34476     }
34477 #endif
34478   }
34479
34480
34481 trans_begun:
34482   btreeIntegrity(p);
34483   sqlite3BtreeLeave(p);
34484   return rc;
34485 }
34486
34487 /*
34488 ** Return the size of the database file in pages.  Or return -1 if
34489 ** there is any kind of error.
34490 */
34491 static int pagerPagecount(Pager *pPager){
34492   int rc;
34493   int nPage;
34494   rc = sqlite3PagerPagecount(pPager, &nPage);
34495   return (rc==SQLITE_OK?nPage:-1);
34496 }
34497
34498
34499 #ifndef SQLITE_OMIT_AUTOVACUUM
34500
34501 /*
34502 ** Set the pointer-map entries for all children of page pPage. Also, if
34503 ** pPage contains cells that point to overflow pages, set the pointer
34504 ** map entries for the overflow pages as well.
34505 */
34506 static int setChildPtrmaps(MemPage *pPage){
34507   int i;                             /* Counter variable */
34508   int nCell;                         /* Number of cells in page pPage */
34509   int rc;                            /* Return code */
34510   BtShared *pBt = pPage->pBt;
34511   int isInitOrig = pPage->isInit;
34512   Pgno pgno = pPage->pgno;
34513
34514   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34515   rc = sqlite3BtreeInitPage(pPage, pPage->pParent);
34516   if( rc!=SQLITE_OK ){
34517     goto set_child_ptrmaps_out;
34518   }
34519   nCell = pPage->nCell;
34520
34521   for(i=0; i<nCell; i++){
34522     u8 *pCell = findCell(pPage, i);
34523
34524     rc = ptrmapPutOvflPtr(pPage, pCell);
34525     if( rc!=SQLITE_OK ){
34526       goto set_child_ptrmaps_out;
34527     }
34528
34529     if( !pPage->leaf ){
34530       Pgno childPgno = get4byte(pCell);
34531       rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
34532        if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
34533     }
34534   }
34535
34536   if( !pPage->leaf ){
34537     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
34538     rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
34539   }
34540
34541 set_child_ptrmaps_out:
34542   pPage->isInit = isInitOrig;
34543   return rc;
34544 }
34545
34546 /*
34547 ** Somewhere on pPage, which is guarenteed to be a btree page, not an overflow
34548 ** page, is a pointer to page iFrom. Modify this pointer so that it points to
34549 ** iTo. Parameter eType describes the type of pointer to be modified, as 
34550 ** follows:
34551 **
34552 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
34553 **                   page of pPage.
34554 **
34555 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
34556 **                   page pointed to by one of the cells on pPage.
34557 **
34558 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
34559 **                   overflow page in the list.
34560 */
34561 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
34562   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34563   if( eType==PTRMAP_OVERFLOW2 ){
34564     /* The pointer is always the first 4 bytes of the page in this case.  */
34565     if( get4byte(pPage->aData)!=iFrom ){
34566       return SQLITE_CORRUPT_BKPT;
34567     }
34568     put4byte(pPage->aData, iTo);
34569   }else{
34570     int isInitOrig = pPage->isInit;
34571     int i;
34572     int nCell;
34573
34574     sqlite3BtreeInitPage(pPage, 0);
34575     nCell = pPage->nCell;
34576
34577     for(i=0; i<nCell; i++){
34578       u8 *pCell = findCell(pPage, i);
34579       if( eType==PTRMAP_OVERFLOW1 ){
34580         CellInfo info;
34581         sqlite3BtreeParseCellPtr(pPage, pCell, &info);
34582         if( info.iOverflow ){
34583           if( iFrom==get4byte(&pCell[info.iOverflow]) ){
34584             put4byte(&pCell[info.iOverflow], iTo);
34585             break;
34586           }
34587         }
34588       }else{
34589         if( get4byte(pCell)==iFrom ){
34590           put4byte(pCell, iTo);
34591           break;
34592         }
34593       }
34594     }
34595   
34596     if( i==nCell ){
34597       if( eType!=PTRMAP_BTREE || 
34598           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
34599         return SQLITE_CORRUPT_BKPT;
34600       }
34601       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
34602     }
34603
34604     pPage->isInit = isInitOrig;
34605   }
34606   return SQLITE_OK;
34607 }
34608
34609
34610 /*
34611 ** Move the open database page pDbPage to location iFreePage in the 
34612 ** database. The pDbPage reference remains valid.
34613 */
34614 static int relocatePage(
34615   BtShared *pBt,           /* Btree */
34616   MemPage *pDbPage,        /* Open page to move */
34617   u8 eType,                /* Pointer map 'type' entry for pDbPage */
34618   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
34619   Pgno iFreePage,          /* The location to move pDbPage to */
34620   int isCommit
34621 ){
34622   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
34623   Pgno iDbPage = pDbPage->pgno;
34624   Pager *pPager = pBt->pPager;
34625   int rc;
34626
34627   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
34628       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
34629   assert( sqlite3_mutex_held(pBt->mutex) );
34630   assert( pDbPage->pBt==pBt );
34631
34632   /* Move page iDbPage from its current location to page number iFreePage */
34633   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
34634       iDbPage, iFreePage, iPtrPage, eType));
34635   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
34636   if( rc!=SQLITE_OK ){
34637     return rc;
34638   }
34639   pDbPage->pgno = iFreePage;
34640
34641   /* If pDbPage was a btree-page, then it may have child pages and/or cells
34642   ** that point to overflow pages. The pointer map entries for all these
34643   ** pages need to be changed.
34644   **
34645   ** If pDbPage is an overflow page, then the first 4 bytes may store a
34646   ** pointer to a subsequent overflow page. If this is the case, then
34647   ** the pointer map needs to be updated for the subsequent overflow page.
34648   */
34649   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
34650     rc = setChildPtrmaps(pDbPage);
34651     if( rc!=SQLITE_OK ){
34652       return rc;
34653     }
34654   }else{
34655     Pgno nextOvfl = get4byte(pDbPage->aData);
34656     if( nextOvfl!=0 ){
34657       rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
34658       if( rc!=SQLITE_OK ){
34659         return rc;
34660       }
34661     }
34662   }
34663
34664   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
34665   ** that it points at iFreePage. Also fix the pointer map entry for
34666   ** iPtrPage.
34667   */
34668   if( eType!=PTRMAP_ROOTPAGE ){
34669     rc = sqlite3BtreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
34670     if( rc!=SQLITE_OK ){
34671       return rc;
34672     }
34673     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
34674     if( rc!=SQLITE_OK ){
34675       releasePage(pPtrPage);
34676       return rc;
34677     }
34678     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
34679     releasePage(pPtrPage);
34680     if( rc==SQLITE_OK ){
34681       rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
34682     }
34683   }
34684   return rc;
34685 }
34686
34687 /* Forward declaration required by incrVacuumStep(). */
34688 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
34689
34690 /*
34691 ** Perform a single step of an incremental-vacuum. If successful,
34692 ** return SQLITE_OK. If there is no work to do (and therefore no
34693 ** point in calling this function again), return SQLITE_DONE.
34694 **
34695 ** More specificly, this function attempts to re-organize the 
34696 ** database so that the last page of the file currently in use
34697 ** is no longer in use.
34698 **
34699 ** If the nFin parameter is non-zero, the implementation assumes
34700 ** that the caller will keep calling incrVacuumStep() until
34701 ** it returns SQLITE_DONE or an error, and that nFin is the
34702 ** number of pages the database file will contain after this 
34703 ** process is complete.
34704 */
34705 static int incrVacuumStep(BtShared *pBt, Pgno nFin){
34706   Pgno iLastPg;             /* Last page in the database */
34707   Pgno nFreeList;           /* Number of pages still on the free-list */
34708
34709   assert( sqlite3_mutex_held(pBt->mutex) );
34710   iLastPg = pBt->nTrunc;
34711   if( iLastPg==0 ){
34712     iLastPg = pagerPagecount(pBt->pPager);
34713   }
34714
34715   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
34716     int rc;
34717     u8 eType;
34718     Pgno iPtrPage;
34719
34720     nFreeList = get4byte(&pBt->pPage1->aData[36]);
34721     if( nFreeList==0 || nFin==iLastPg ){
34722       return SQLITE_DONE;
34723     }
34724
34725     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
34726     if( rc!=SQLITE_OK ){
34727       return rc;
34728     }
34729     if( eType==PTRMAP_ROOTPAGE ){
34730       return SQLITE_CORRUPT_BKPT;
34731     }
34732
34733     if( eType==PTRMAP_FREEPAGE ){
34734       if( nFin==0 ){
34735         /* Remove the page from the files free-list. This is not required
34736         ** if nFin is non-zero. In that case, the free-list will be
34737         ** truncated to zero after this function returns, so it doesn't 
34738         ** matter if it still contains some garbage entries.
34739         */
34740         Pgno iFreePg;
34741         MemPage *pFreePg;
34742         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
34743         if( rc!=SQLITE_OK ){
34744           return rc;
34745         }
34746         assert( iFreePg==iLastPg );
34747         releasePage(pFreePg);
34748       }
34749     } else {
34750       Pgno iFreePg;             /* Index of free page to move pLastPg to */
34751       MemPage *pLastPg;
34752
34753       rc = sqlite3BtreeGetPage(pBt, iLastPg, &pLastPg, 0);
34754       if( rc!=SQLITE_OK ){
34755         return rc;
34756       }
34757
34758       /* If nFin is zero, this loop runs exactly once and page pLastPg
34759       ** is swapped with the first free page pulled off the free list.
34760       **
34761       ** On the other hand, if nFin is greater than zero, then keep
34762       ** looping until a free-page located within the first nFin pages
34763       ** of the file is found.
34764       */
34765       do {
34766         MemPage *pFreePg;
34767         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
34768         if( rc!=SQLITE_OK ){
34769           releasePage(pLastPg);
34770           return rc;
34771         }
34772         releasePage(pFreePg);
34773       }while( nFin!=0 && iFreePg>nFin );
34774       assert( iFreePg<iLastPg );
34775       
34776       rc = sqlite3PagerWrite(pLastPg->pDbPage);
34777       if( rc==SQLITE_OK ){
34778         rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
34779       }
34780       releasePage(pLastPg);
34781       if( rc!=SQLITE_OK ){
34782         return rc;
34783       }
34784     }
34785   }
34786
34787   pBt->nTrunc = iLastPg - 1;
34788   while( pBt->nTrunc==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, pBt->nTrunc) ){
34789     pBt->nTrunc--;
34790   }
34791   return SQLITE_OK;
34792 }
34793
34794 /*
34795 ** A write-transaction must be opened before calling this function.
34796 ** It performs a single unit of work towards an incremental vacuum.
34797 **
34798 ** If the incremental vacuum is finished after this function has run,
34799 ** SQLITE_DONE is returned. If it is not finished, but no error occured,
34800 ** SQLITE_OK is returned. Otherwise an SQLite error code. 
34801 */
34802 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
34803   int rc;
34804   BtShared *pBt = p->pBt;
34805
34806   sqlite3BtreeEnter(p);
34807   pBt->db = p->db;
34808   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
34809   if( !pBt->autoVacuum ){
34810     rc = SQLITE_DONE;
34811   }else{
34812     invalidateAllOverflowCache(pBt);
34813     rc = incrVacuumStep(pBt, 0);
34814   }
34815   sqlite3BtreeLeave(p);
34816   return rc;
34817 }
34818
34819 /*
34820 ** This routine is called prior to sqlite3PagerCommit when a transaction
34821 ** is commited for an auto-vacuum database.
34822 **
34823 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
34824 ** the database file should be truncated to during the commit process. 
34825 ** i.e. the database has been reorganized so that only the first *pnTrunc
34826 ** pages are in use.
34827 */
34828 static int autoVacuumCommit(BtShared *pBt, Pgno *pnTrunc){
34829   int rc = SQLITE_OK;
34830   Pager *pPager = pBt->pPager;
34831 #ifndef NDEBUG
34832   int nRef = sqlite3PagerRefcount(pPager);
34833 #endif
34834
34835   assert( sqlite3_mutex_held(pBt->mutex) );
34836   invalidateAllOverflowCache(pBt);
34837   assert(pBt->autoVacuum);
34838   if( !pBt->incrVacuum ){
34839     Pgno nFin = 0;
34840
34841     if( pBt->nTrunc==0 ){
34842       Pgno nFree;
34843       Pgno nPtrmap;
34844       const int pgsz = pBt->pageSize;
34845       int nOrig = pagerPagecount(pBt->pPager);
34846
34847       if( PTRMAP_ISPAGE(pBt, nOrig) ){
34848         return SQLITE_CORRUPT_BKPT;
34849       }
34850       if( nOrig==PENDING_BYTE_PAGE(pBt) ){
34851         nOrig--;
34852       }
34853       nFree = get4byte(&pBt->pPage1->aData[36]);
34854       nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+pgsz/5)/(pgsz/5);
34855       nFin = nOrig - nFree - nPtrmap;
34856       if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<=PENDING_BYTE_PAGE(pBt) ){
34857         nFin--;
34858       }
34859       while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
34860         nFin--;
34861       }
34862     }
34863
34864     while( rc==SQLITE_OK ){
34865       rc = incrVacuumStep(pBt, nFin);
34866     }
34867     if( rc==SQLITE_DONE ){
34868       assert(nFin==0 || pBt->nTrunc==0 || nFin<=pBt->nTrunc);
34869       rc = SQLITE_OK;
34870       if( pBt->nTrunc && nFin ){
34871         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
34872         put4byte(&pBt->pPage1->aData[32], 0);
34873         put4byte(&pBt->pPage1->aData[36], 0);
34874         pBt->nTrunc = nFin;
34875       }
34876     }
34877     if( rc!=SQLITE_OK ){
34878       sqlite3PagerRollback(pPager);
34879     }
34880   }
34881
34882   if( rc==SQLITE_OK ){
34883     *pnTrunc = pBt->nTrunc;
34884     pBt->nTrunc = 0;
34885   }
34886   assert( nRef==sqlite3PagerRefcount(pPager) );
34887   return rc;
34888 }
34889
34890 #endif
34891
34892 /*
34893 ** This routine does the first phase of a two-phase commit.  This routine
34894 ** causes a rollback journal to be created (if it does not already exist)
34895 ** and populated with enough information so that if a power loss occurs
34896 ** the database can be restored to its original state by playing back
34897 ** the journal.  Then the contents of the journal are flushed out to
34898 ** the disk.  After the journal is safely on oxide, the changes to the
34899 ** database are written into the database file and flushed to oxide.
34900 ** At the end of this call, the rollback journal still exists on the
34901 ** disk and we are still holding all locks, so the transaction has not
34902 ** committed.  See sqlite3BtreeCommit() for the second phase of the
34903 ** commit process.
34904 **
34905 ** This call is a no-op if no write-transaction is currently active on pBt.
34906 **
34907 ** Otherwise, sync the database file for the btree pBt. zMaster points to
34908 ** the name of a master journal file that should be written into the
34909 ** individual journal file, or is NULL, indicating no master journal file 
34910 ** (single database transaction).
34911 **
34912 ** When this is called, the master journal should already have been
34913 ** created, populated with this journal pointer and synced to disk.
34914 **
34915 ** Once this is routine has returned, the only thing required to commit
34916 ** the write-transaction for this database file is to delete the journal.
34917 */
34918 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
34919   int rc = SQLITE_OK;
34920   if( p->inTrans==TRANS_WRITE ){
34921     BtShared *pBt = p->pBt;
34922     Pgno nTrunc = 0;
34923     sqlite3BtreeEnter(p);
34924     pBt->db = p->db;
34925 #ifndef SQLITE_OMIT_AUTOVACUUM
34926     if( pBt->autoVacuum ){
34927       rc = autoVacuumCommit(pBt, &nTrunc); 
34928       if( rc!=SQLITE_OK ){
34929         sqlite3BtreeLeave(p);
34930         return rc;
34931       }
34932     }
34933 #endif
34934     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, nTrunc, 0);
34935     sqlite3BtreeLeave(p);
34936   }
34937   return rc;
34938 }
34939
34940 /*
34941 ** Commit the transaction currently in progress.
34942 **
34943 ** This routine implements the second phase of a 2-phase commit.  The
34944 ** sqlite3BtreeSync() routine does the first phase and should be invoked
34945 ** prior to calling this routine.  The sqlite3BtreeSync() routine did
34946 ** all the work of writing information out to disk and flushing the
34947 ** contents so that they are written onto the disk platter.  All this
34948 ** routine has to do is delete or truncate the rollback journal
34949 ** (which causes the transaction to commit) and drop locks.
34950 **
34951 ** This will release the write lock on the database file.  If there
34952 ** are no active cursors, it also releases the read lock.
34953 */
34954 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p){
34955   BtShared *pBt = p->pBt;
34956
34957   sqlite3BtreeEnter(p);
34958   pBt->db = p->db;
34959   btreeIntegrity(p);
34960
34961   /* If the handle has a write-transaction open, commit the shared-btrees 
34962   ** transaction and set the shared state to TRANS_READ.
34963   */
34964   if( p->inTrans==TRANS_WRITE ){
34965     int rc;
34966     assert( pBt->inTransaction==TRANS_WRITE );
34967     assert( pBt->nTransaction>0 );
34968     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
34969     if( rc!=SQLITE_OK ){
34970       sqlite3BtreeLeave(p);
34971       return rc;
34972     }
34973     pBt->inTransaction = TRANS_READ;
34974     pBt->inStmt = 0;
34975   }
34976   unlockAllTables(p);
34977
34978   /* If the handle has any kind of transaction open, decrement the transaction
34979   ** count of the shared btree. If the transaction count reaches 0, set
34980   ** the shared state to TRANS_NONE. The unlockBtreeIfUnused() call below
34981   ** will unlock the pager.
34982   */
34983   if( p->inTrans!=TRANS_NONE ){
34984     pBt->nTransaction--;
34985     if( 0==pBt->nTransaction ){
34986       pBt->inTransaction = TRANS_NONE;
34987     }
34988   }
34989
34990   /* Set the handles current transaction state to TRANS_NONE and unlock
34991   ** the pager if this call closed the only read or write transaction.
34992   */
34993   p->inTrans = TRANS_NONE;
34994   unlockBtreeIfUnused(pBt);
34995
34996   btreeIntegrity(p);
34997   sqlite3BtreeLeave(p);
34998   return SQLITE_OK;
34999 }
35000
35001 /*
35002 ** Do both phases of a commit.
35003 */
35004 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
35005   int rc;
35006   sqlite3BtreeEnter(p);
35007   rc = sqlite3BtreeCommitPhaseOne(p, 0);
35008   if( rc==SQLITE_OK ){
35009     rc = sqlite3BtreeCommitPhaseTwo(p);
35010   }
35011   sqlite3BtreeLeave(p);
35012   return rc;
35013 }
35014
35015 #ifndef NDEBUG
35016 /*
35017 ** Return the number of write-cursors open on this handle. This is for use
35018 ** in assert() expressions, so it is only compiled if NDEBUG is not
35019 ** defined.
35020 **
35021 ** For the purposes of this routine, a write-cursor is any cursor that
35022 ** is capable of writing to the databse.  That means the cursor was
35023 ** originally opened for writing and the cursor has not be disabled
35024 ** by having its state changed to CURSOR_FAULT.
35025 */
35026 static int countWriteCursors(BtShared *pBt){
35027   BtCursor *pCur;
35028   int r = 0;
35029   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
35030     if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++; 
35031   }
35032   return r;
35033 }
35034 #endif
35035
35036 /*
35037 ** This routine sets the state to CURSOR_FAULT and the error
35038 ** code to errCode for every cursor on BtShared that pBtree
35039 ** references.
35040 **
35041 ** Every cursor is tripped, including cursors that belong
35042 ** to other database connections that happen to be sharing
35043 ** the cache with pBtree.
35044 **
35045 ** This routine gets called when a rollback occurs.
35046 ** All cursors using the same cache must be tripped
35047 ** to prevent them from trying to use the btree after
35048 ** the rollback.  The rollback may have deleted tables
35049 ** or moved root pages, so it is not sufficient to
35050 ** save the state of the cursor.  The cursor must be
35051 ** invalidated.
35052 */
35053 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
35054   BtCursor *p;
35055   sqlite3BtreeEnter(pBtree);
35056   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
35057     clearCursorPosition(p);
35058     p->eState = CURSOR_FAULT;
35059     p->skip = errCode;
35060   }
35061   sqlite3BtreeLeave(pBtree);
35062 }
35063
35064 /*
35065 ** Rollback the transaction in progress.  All cursors will be
35066 ** invalided by this operation.  Any attempt to use a cursor
35067 ** that was open at the beginning of this operation will result
35068 ** in an error.
35069 **
35070 ** This will release the write lock on the database file.  If there
35071 ** are no active cursors, it also releases the read lock.
35072 */
35073 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
35074   int rc;
35075   BtShared *pBt = p->pBt;
35076   MemPage *pPage1;
35077
35078   sqlite3BtreeEnter(p);
35079   pBt->db = p->db;
35080   rc = saveAllCursors(pBt, 0, 0);
35081 #ifndef SQLITE_OMIT_SHARED_CACHE
35082   if( rc!=SQLITE_OK ){
35083     /* This is a horrible situation. An IO or malloc() error occured whilst
35084     ** trying to save cursor positions. If this is an automatic rollback (as
35085     ** the result of a constraint, malloc() failure or IO error) then 
35086     ** the cache may be internally inconsistent (not contain valid trees) so
35087     ** we cannot simply return the error to the caller. Instead, abort 
35088     ** all queries that may be using any of the cursors that failed to save.
35089     */
35090     sqlite3BtreeTripAllCursors(p, rc);
35091   }
35092 #endif
35093   btreeIntegrity(p);
35094   unlockAllTables(p);
35095
35096   if( p->inTrans==TRANS_WRITE ){
35097     int rc2;
35098
35099 #ifndef SQLITE_OMIT_AUTOVACUUM
35100     pBt->nTrunc = 0;
35101 #endif
35102
35103     assert( TRANS_WRITE==pBt->inTransaction );
35104     rc2 = sqlite3PagerRollback(pBt->pPager);
35105     if( rc2!=SQLITE_OK ){
35106       rc = rc2;
35107     }
35108
35109     /* The rollback may have destroyed the pPage1->aData value.  So
35110     ** call sqlite3BtreeGetPage() on page 1 again to make
35111     ** sure pPage1->aData is set correctly. */
35112     if( sqlite3BtreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
35113       releasePage(pPage1);
35114     }
35115     assert( countWriteCursors(pBt)==0 );
35116     pBt->inTransaction = TRANS_READ;
35117   }
35118
35119   if( p->inTrans!=TRANS_NONE ){
35120     assert( pBt->nTransaction>0 );
35121     pBt->nTransaction--;
35122     if( 0==pBt->nTransaction ){
35123       pBt->inTransaction = TRANS_NONE;
35124     }
35125   }
35126
35127   p->inTrans = TRANS_NONE;
35128   pBt->inStmt = 0;
35129   unlockBtreeIfUnused(pBt);
35130
35131   btreeIntegrity(p);
35132   sqlite3BtreeLeave(p);
35133   return rc;
35134 }
35135
35136 /*
35137 ** Start a statement subtransaction.  The subtransaction can
35138 ** can be rolled back independently of the main transaction.
35139 ** You must start a transaction before starting a subtransaction.
35140 ** The subtransaction is ended automatically if the main transaction
35141 ** commits or rolls back.
35142 **
35143 ** Only one subtransaction may be active at a time.  It is an error to try
35144 ** to start a new subtransaction if another subtransaction is already active.
35145 **
35146 ** Statement subtransactions are used around individual SQL statements
35147 ** that are contained within a BEGIN...COMMIT block.  If a constraint
35148 ** error occurs within the statement, the effect of that one statement
35149 ** can be rolled back without having to rollback the entire transaction.
35150 */
35151 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p){
35152   int rc;
35153   BtShared *pBt = p->pBt;
35154   sqlite3BtreeEnter(p);
35155   pBt->db = p->db;
35156   if( (p->inTrans!=TRANS_WRITE) || pBt->inStmt ){
35157     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
35158   }else{
35159     assert( pBt->inTransaction==TRANS_WRITE );
35160     rc = pBt->readOnly ? SQLITE_OK : sqlite3PagerStmtBegin(pBt->pPager);
35161     pBt->inStmt = 1;
35162   }
35163   sqlite3BtreeLeave(p);
35164   return rc;
35165 }
35166
35167
35168 /*
35169 ** Commit the statment subtransaction currently in progress.  If no
35170 ** subtransaction is active, this is a no-op.
35171 */
35172 SQLITE_PRIVATE int sqlite3BtreeCommitStmt(Btree *p){
35173   int rc;
35174   BtShared *pBt = p->pBt;
35175   sqlite3BtreeEnter(p);
35176   pBt->db = p->db;
35177   if( pBt->inStmt && !pBt->readOnly ){
35178     rc = sqlite3PagerStmtCommit(pBt->pPager);
35179   }else{
35180     rc = SQLITE_OK;
35181   }
35182   pBt->inStmt = 0;
35183   sqlite3BtreeLeave(p);
35184   return rc;
35185 }
35186
35187 /*
35188 ** Rollback the active statement subtransaction.  If no subtransaction
35189 ** is active this routine is a no-op.
35190 **
35191 ** All cursors will be invalidated by this operation.  Any attempt
35192 ** to use a cursor that was open at the beginning of this operation
35193 ** will result in an error.
35194 */
35195 SQLITE_PRIVATE int sqlite3BtreeRollbackStmt(Btree *p){
35196   int rc = SQLITE_OK;
35197   BtShared *pBt = p->pBt;
35198   sqlite3BtreeEnter(p);
35199   pBt->db = p->db;
35200   if( pBt->inStmt && !pBt->readOnly ){
35201     rc = sqlite3PagerStmtRollback(pBt->pPager);
35202     pBt->inStmt = 0;
35203   }
35204   sqlite3BtreeLeave(p);
35205   return rc;
35206 }
35207
35208 /*
35209 ** Create a new cursor for the BTree whose root is on the page
35210 ** iTable.  The act of acquiring a cursor gets a read lock on 
35211 ** the database file.
35212 **
35213 ** If wrFlag==0, then the cursor can only be used for reading.
35214 ** If wrFlag==1, then the cursor can be used for reading or for
35215 ** writing if other conditions for writing are also met.  These
35216 ** are the conditions that must be met in order for writing to
35217 ** be allowed:
35218 **
35219 ** 1:  The cursor must have been opened with wrFlag==1
35220 **
35221 ** 2:  Other database connections that share the same pager cache
35222 **     but which are not in the READ_UNCOMMITTED state may not have
35223 **     cursors open with wrFlag==0 on the same table.  Otherwise
35224 **     the changes made by this write cursor would be visible to
35225 **     the read cursors in the other database connection.
35226 **
35227 ** 3:  The database must be writable (not on read-only media)
35228 **
35229 ** 4:  There must be an active transaction.
35230 **
35231 ** No checking is done to make sure that page iTable really is the
35232 ** root page of a b-tree.  If it is not, then the cursor acquired
35233 ** will not work correctly.
35234 */
35235 static int btreeCursor(
35236   Btree *p,                              /* The btree */
35237   int iTable,                            /* Root page of table to open */
35238   int wrFlag,                            /* 1 to write. 0 read-only */
35239   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
35240   BtCursor *pCur                         /* Space for new cursor */
35241 ){
35242   int rc;
35243   BtShared *pBt = p->pBt;
35244
35245   assert( sqlite3BtreeHoldsMutex(p) );
35246   if( wrFlag ){
35247     if( pBt->readOnly ){
35248       return SQLITE_READONLY;
35249     }
35250     if( checkReadLocks(p, iTable, 0, 0) ){
35251       return SQLITE_LOCKED;
35252     }
35253   }
35254
35255   if( pBt->pPage1==0 ){
35256     rc = lockBtreeWithRetry(p);
35257     if( rc!=SQLITE_OK ){
35258       return rc;
35259     }
35260     if( pBt->readOnly && wrFlag ){
35261       return SQLITE_READONLY;
35262     }
35263   }
35264   pCur->pgnoRoot = (Pgno)iTable;
35265   if( iTable==1 && pagerPagecount(pBt->pPager)==0 ){
35266     rc = SQLITE_EMPTY;
35267     goto create_cursor_exception;
35268   }
35269   rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->pPage, 0);
35270   if( rc!=SQLITE_OK ){
35271     goto create_cursor_exception;
35272   }
35273
35274   /* Now that no other errors can occur, finish filling in the BtCursor
35275   ** variables, link the cursor into the BtShared list and set *ppCur (the
35276   ** output argument to this function).
35277   */
35278   pCur->pKeyInfo = pKeyInfo;
35279   pCur->pBtree = p;
35280   pCur->pBt = pBt;
35281   pCur->wrFlag = wrFlag;
35282   pCur->pNext = pBt->pCursor;
35283   if( pCur->pNext ){
35284     pCur->pNext->pPrev = pCur;
35285   }
35286   pBt->pCursor = pCur;
35287   pCur->eState = CURSOR_INVALID;
35288
35289   return SQLITE_OK;
35290
35291 create_cursor_exception:
35292   releasePage(pCur->pPage);
35293   unlockBtreeIfUnused(pBt);
35294   return rc;
35295 }
35296 SQLITE_PRIVATE int sqlite3BtreeCursor(
35297   Btree *p,                                   /* The btree */
35298   int iTable,                                 /* Root page of table to open */
35299   int wrFlag,                                 /* 1 to write. 0 read-only */
35300   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
35301   BtCursor *pCur                              /* Write new cursor here */
35302 ){
35303   int rc;
35304   sqlite3BtreeEnter(p);
35305   p->pBt->db = p->db;
35306   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
35307   sqlite3BtreeLeave(p);
35308   return rc;
35309 }
35310 SQLITE_PRIVATE int sqlite3BtreeCursorSize(){
35311   return sizeof(BtCursor);
35312 }
35313
35314
35315
35316 /*
35317 ** Close a cursor.  The read lock on the database file is released
35318 ** when the last cursor is closed.
35319 */
35320 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
35321   Btree *pBtree = pCur->pBtree;
35322   if( pBtree ){
35323     BtShared *pBt = pCur->pBt;
35324     sqlite3BtreeEnter(pBtree);
35325     pBt->db = pBtree->db;
35326     clearCursorPosition(pCur);
35327     if( pCur->pPrev ){
35328       pCur->pPrev->pNext = pCur->pNext;
35329     }else{
35330       pBt->pCursor = pCur->pNext;
35331     }
35332     if( pCur->pNext ){
35333       pCur->pNext->pPrev = pCur->pPrev;
35334     }
35335     releasePage(pCur->pPage);
35336     unlockBtreeIfUnused(pBt);
35337     invalidateOverflowCache(pCur);
35338     /* sqlite3_free(pCur); */
35339     sqlite3BtreeLeave(pBtree);
35340   }
35341   return SQLITE_OK;
35342 }
35343
35344 /*
35345 ** Make a temporary cursor by filling in the fields of pTempCur.
35346 ** The temporary cursor is not on the cursor list for the Btree.
35347 */
35348 SQLITE_PRIVATE void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur){
35349   assert( cursorHoldsMutex(pCur) );
35350   memcpy(pTempCur, pCur, sizeof(*pCur));
35351   pTempCur->pNext = 0;
35352   pTempCur->pPrev = 0;
35353   if( pTempCur->pPage ){
35354     sqlite3PagerRef(pTempCur->pPage->pDbPage);
35355   }
35356 }
35357
35358 /*
35359 ** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
35360 ** function above.
35361 */
35362 SQLITE_PRIVATE void sqlite3BtreeReleaseTempCursor(BtCursor *pCur){
35363   assert( cursorHoldsMutex(pCur) );
35364   if( pCur->pPage ){
35365     sqlite3PagerUnref(pCur->pPage->pDbPage);
35366   }
35367 }
35368
35369 /*
35370 ** Make sure the BtCursor* given in the argument has a valid
35371 ** BtCursor.info structure.  If it is not already valid, call
35372 ** sqlite3BtreeParseCell() to fill it in.
35373 **
35374 ** BtCursor.info is a cache of the information in the current cell.
35375 ** Using this cache reduces the number of calls to sqlite3BtreeParseCell().
35376 **
35377 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
35378 ** compiler to crash when getCellInfo() is implemented as a macro.
35379 ** But there is a measureable speed advantage to using the macro on gcc
35380 ** (when less compiler optimizations like -Os or -O0 are used and the
35381 ** compiler is not doing agressive inlining.)  So we use a real function
35382 ** for MSVC and a macro for everything else.  Ticket #2457.
35383 */
35384 #ifndef NDEBUG
35385   static void assertCellInfo(BtCursor *pCur){
35386     CellInfo info;
35387     memset(&info, 0, sizeof(info));
35388     sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &info);
35389     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
35390   }
35391 #else
35392   #define assertCellInfo(x)
35393 #endif
35394 #ifdef _MSC_VER
35395   /* Use a real function in MSVC to work around bugs in that compiler. */
35396   static void getCellInfo(BtCursor *pCur){
35397     if( pCur->info.nSize==0 ){
35398       sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &pCur->info);
35399       pCur->validNKey = 1;
35400     }else{
35401       assertCellInfo(pCur);
35402     }
35403   }
35404 #else /* if not _MSC_VER */
35405   /* Use a macro in all other compilers so that the function is inlined */
35406 #define getCellInfo(pCur)                                               \
35407   if( pCur->info.nSize==0 ){                                            \
35408     sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &pCur->info);         \
35409     pCur->validNKey = 1;                                                \
35410   }else{                                                                \
35411     assertCellInfo(pCur);                                               \
35412   }
35413 #endif /* _MSC_VER */
35414
35415 /*
35416 ** Set *pSize to the size of the buffer needed to hold the value of
35417 ** the key for the current entry.  If the cursor is not pointing
35418 ** to a valid entry, *pSize is set to 0. 
35419 **
35420 ** For a table with the INTKEY flag set, this routine returns the key
35421 ** itself, not the number of bytes in the key.
35422 */
35423 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
35424   int rc;
35425
35426   assert( cursorHoldsMutex(pCur) );
35427   rc = restoreCursorPosition(pCur);
35428   if( rc==SQLITE_OK ){
35429     assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
35430     if( pCur->eState==CURSOR_INVALID ){
35431       *pSize = 0;
35432     }else{
35433       getCellInfo(pCur);
35434       *pSize = pCur->info.nKey;
35435     }
35436   }
35437   return rc;
35438 }
35439
35440 /*
35441 ** Set *pSize to the number of bytes of data in the entry the
35442 ** cursor currently points to.  Always return SQLITE_OK.
35443 ** Failure is not possible.  If the cursor is not currently
35444 ** pointing to an entry (which can happen, for example, if
35445 ** the database is empty) then *pSize is set to 0.
35446 */
35447 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
35448   int rc;
35449
35450   assert( cursorHoldsMutex(pCur) );
35451   rc = restoreCursorPosition(pCur);
35452   if( rc==SQLITE_OK ){
35453     assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
35454     if( pCur->eState==CURSOR_INVALID ){
35455       /* Not pointing at a valid entry - set *pSize to 0. */
35456       *pSize = 0;
35457     }else{
35458       getCellInfo(pCur);
35459       *pSize = pCur->info.nData;
35460     }
35461   }
35462   return rc;
35463 }
35464
35465 /*
35466 ** Given the page number of an overflow page in the database (parameter
35467 ** ovfl), this function finds the page number of the next page in the 
35468 ** linked list of overflow pages. If possible, it uses the auto-vacuum
35469 ** pointer-map data instead of reading the content of page ovfl to do so. 
35470 **
35471 ** If an error occurs an SQLite error code is returned. Otherwise:
35472 **
35473 ** Unless pPgnoNext is NULL, the page number of the next overflow 
35474 ** page in the linked list is written to *pPgnoNext. If page ovfl
35475 ** is the last page in its linked list, *pPgnoNext is set to zero. 
35476 **
35477 ** If ppPage is not NULL, *ppPage is set to the MemPage* handle
35478 ** for page ovfl. The underlying pager page may have been requested
35479 ** with the noContent flag set, so the page data accessable via
35480 ** this handle may not be trusted.
35481 */
35482 static int getOverflowPage(
35483   BtShared *pBt, 
35484   Pgno ovfl,                   /* Overflow page */
35485   MemPage **ppPage,            /* OUT: MemPage handle */
35486   Pgno *pPgnoNext              /* OUT: Next overflow page number */
35487 ){
35488   Pgno next = 0;
35489   int rc;
35490
35491   assert( sqlite3_mutex_held(pBt->mutex) );
35492   /* One of these must not be NULL. Otherwise, why call this function? */
35493   assert(ppPage || pPgnoNext);
35494
35495   /* If pPgnoNext is NULL, then this function is being called to obtain
35496   ** a MemPage* reference only. No page-data is required in this case.
35497   */
35498   if( !pPgnoNext ){
35499     return sqlite3BtreeGetPage(pBt, ovfl, ppPage, 1);
35500   }
35501
35502 #ifndef SQLITE_OMIT_AUTOVACUUM
35503   /* Try to find the next page in the overflow list using the
35504   ** autovacuum pointer-map pages. Guess that the next page in 
35505   ** the overflow list is page number (ovfl+1). If that guess turns 
35506   ** out to be wrong, fall back to loading the data of page 
35507   ** number ovfl to determine the next page number.
35508   */
35509   if( pBt->autoVacuum ){
35510     Pgno pgno;
35511     Pgno iGuess = ovfl+1;
35512     u8 eType;
35513
35514     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
35515       iGuess++;
35516     }
35517
35518     if( iGuess<=pagerPagecount(pBt->pPager) ){
35519       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
35520       if( rc!=SQLITE_OK ){
35521         return rc;
35522       }
35523       if( eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
35524         next = iGuess;
35525       }
35526     }
35527   }
35528 #endif
35529
35530   if( next==0 || ppPage ){
35531     MemPage *pPage = 0;
35532
35533     rc = sqlite3BtreeGetPage(pBt, ovfl, &pPage, next!=0);
35534     assert(rc==SQLITE_OK || pPage==0);
35535     if( next==0 && rc==SQLITE_OK ){
35536       next = get4byte(pPage->aData);
35537     }
35538
35539     if( ppPage ){
35540       *ppPage = pPage;
35541     }else{
35542       releasePage(pPage);
35543     }
35544   }
35545   *pPgnoNext = next;
35546
35547   return rc;
35548 }
35549
35550 /*
35551 ** Copy data from a buffer to a page, or from a page to a buffer.
35552 **
35553 ** pPayload is a pointer to data stored on database page pDbPage.
35554 ** If argument eOp is false, then nByte bytes of data are copied
35555 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
35556 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
35557 ** of data are copied from the buffer pBuf to pPayload.
35558 **
35559 ** SQLITE_OK is returned on success, otherwise an error code.
35560 */
35561 static int copyPayload(
35562   void *pPayload,           /* Pointer to page data */
35563   void *pBuf,               /* Pointer to buffer */
35564   int nByte,                /* Number of bytes to copy */
35565   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
35566   DbPage *pDbPage           /* Page containing pPayload */
35567 ){
35568   if( eOp ){
35569     /* Copy data from buffer to page (a write operation) */
35570     int rc = sqlite3PagerWrite(pDbPage);
35571     if( rc!=SQLITE_OK ){
35572       return rc;
35573     }
35574     memcpy(pPayload, pBuf, nByte);
35575   }else{
35576     /* Copy data from page to buffer (a read operation) */
35577     memcpy(pBuf, pPayload, nByte);
35578   }
35579   return SQLITE_OK;
35580 }
35581
35582 /*
35583 ** This function is used to read or overwrite payload information
35584 ** for the entry that the pCur cursor is pointing to. If the eOp
35585 ** parameter is 0, this is a read operation (data copied into
35586 ** buffer pBuf). If it is non-zero, a write (data copied from
35587 ** buffer pBuf).
35588 **
35589 ** A total of "amt" bytes are read or written beginning at "offset".
35590 ** Data is read to or from the buffer pBuf.
35591 **
35592 ** This routine does not make a distinction between key and data.
35593 ** It just reads or writes bytes from the payload area.  Data might 
35594 ** appear on the main page or be scattered out on multiple overflow 
35595 ** pages.
35596 **
35597 ** If the BtCursor.isIncrblobHandle flag is set, and the current
35598 ** cursor entry uses one or more overflow pages, this function
35599 ** allocates space for and lazily popluates the overflow page-list 
35600 ** cache array (BtCursor.aOverflow). Subsequent calls use this
35601 ** cache to make seeking to the supplied offset more efficient.
35602 **
35603 ** Once an overflow page-list cache has been allocated, it may be
35604 ** invalidated if some other cursor writes to the same table, or if
35605 ** the cursor is moved to a different row. Additionally, in auto-vacuum
35606 ** mode, the following events may invalidate an overflow page-list cache.
35607 **
35608 **   * An incremental vacuum,
35609 **   * A commit in auto_vacuum="full" mode,
35610 **   * Creating a table (may require moving an overflow page).
35611 */
35612 static int accessPayload(
35613   BtCursor *pCur,      /* Cursor pointing to entry to read from */
35614   int offset,          /* Begin reading this far into payload */
35615   int amt,             /* Read this many bytes */
35616   unsigned char *pBuf, /* Write the bytes into this buffer */ 
35617   int skipKey,         /* offset begins at data if this is true */
35618   int eOp              /* zero to read. non-zero to write. */
35619 ){
35620   unsigned char *aPayload;
35621   int rc = SQLITE_OK;
35622   u32 nKey;
35623   int iIdx = 0;
35624   MemPage *pPage = pCur->pPage;     /* Btree page of current cursor entry */
35625   BtShared *pBt;                   /* Btree this cursor belongs to */
35626
35627   assert( pPage );
35628   assert( pCur->eState==CURSOR_VALID );
35629   assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
35630   assert( offset>=0 );
35631   assert( cursorHoldsMutex(pCur) );
35632
35633   getCellInfo(pCur);
35634   aPayload = pCur->info.pCell + pCur->info.nHeader;
35635   nKey = (pPage->intKey ? 0 : pCur->info.nKey);
35636
35637   if( skipKey ){
35638     offset += nKey;
35639   }
35640   if( offset+amt > nKey+pCur->info.nData ){
35641     /* Trying to read or write past the end of the data is an error */
35642     return SQLITE_ERROR;
35643   }
35644
35645   /* Check if data must be read/written to/from the btree page itself. */
35646   if( offset<pCur->info.nLocal ){
35647     int a = amt;
35648     if( a+offset>pCur->info.nLocal ){
35649       a = pCur->info.nLocal - offset;
35650     }
35651     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
35652     offset = 0;
35653     pBuf += a;
35654     amt -= a;
35655   }else{
35656     offset -= pCur->info.nLocal;
35657   }
35658
35659   pBt = pCur->pBt;
35660   if( rc==SQLITE_OK && amt>0 ){
35661     const int ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
35662     Pgno nextPage;
35663
35664     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
35665
35666 #ifndef SQLITE_OMIT_INCRBLOB
35667     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
35668     ** has not been allocated, allocate it now. The array is sized at
35669     ** one entry for each overflow page in the overflow chain. The
35670     ** page number of the first overflow page is stored in aOverflow[0],
35671     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
35672     ** (the cache is lazily populated).
35673     */
35674     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
35675       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
35676       pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
35677       if( nOvfl && !pCur->aOverflow ){
35678         rc = SQLITE_NOMEM;
35679       }
35680     }
35681
35682     /* If the overflow page-list cache has been allocated and the
35683     ** entry for the first required overflow page is valid, skip
35684     ** directly to it.
35685     */
35686     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
35687       iIdx = (offset/ovflSize);
35688       nextPage = pCur->aOverflow[iIdx];
35689       offset = (offset%ovflSize);
35690     }
35691 #endif
35692
35693     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
35694
35695 #ifndef SQLITE_OMIT_INCRBLOB
35696       /* If required, populate the overflow page-list cache. */
35697       if( pCur->aOverflow ){
35698         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
35699         pCur->aOverflow[iIdx] = nextPage;
35700       }
35701 #endif
35702
35703       if( offset>=ovflSize ){
35704         /* The only reason to read this page is to obtain the page
35705         ** number for the next page in the overflow chain. The page
35706         ** data is not required. So first try to lookup the overflow
35707         ** page-list cache, if any, then fall back to the getOverflowPage()
35708         ** function.
35709         */
35710 #ifndef SQLITE_OMIT_INCRBLOB
35711         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
35712           nextPage = pCur->aOverflow[iIdx+1];
35713         } else 
35714 #endif
35715           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
35716         offset -= ovflSize;
35717       }else{
35718         /* Need to read this page properly. It contains some of the
35719         ** range of data that is being read (eOp==0) or written (eOp!=0).
35720         */
35721         DbPage *pDbPage;
35722         int a = amt;
35723         rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
35724         if( rc==SQLITE_OK ){
35725           aPayload = sqlite3PagerGetData(pDbPage);
35726           nextPage = get4byte(aPayload);
35727           if( a + offset > ovflSize ){
35728             a = ovflSize - offset;
35729           }
35730           rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
35731           sqlite3PagerUnref(pDbPage);
35732           offset = 0;
35733           amt -= a;
35734           pBuf += a;
35735         }
35736       }
35737     }
35738   }
35739
35740   if( rc==SQLITE_OK && amt>0 ){
35741     return SQLITE_CORRUPT_BKPT;
35742   }
35743   return rc;
35744 }
35745
35746 /*
35747 ** Read part of the key associated with cursor pCur.  Exactly
35748 ** "amt" bytes will be transfered into pBuf[].  The transfer
35749 ** begins at "offset".
35750 **
35751 ** Return SQLITE_OK on success or an error code if anything goes
35752 ** wrong.  An error is returned if "offset+amt" is larger than
35753 ** the available payload.
35754 */
35755 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
35756   int rc;
35757
35758   assert( cursorHoldsMutex(pCur) );
35759   rc = restoreCursorPosition(pCur);
35760   if( rc==SQLITE_OK ){
35761     assert( pCur->eState==CURSOR_VALID );
35762     assert( pCur->pPage!=0 );
35763     if( pCur->pPage->intKey ){
35764       return SQLITE_CORRUPT_BKPT;
35765     }
35766     assert( pCur->pPage->intKey==0 );
35767     assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
35768     rc = accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0, 0);
35769   }
35770   return rc;
35771 }
35772
35773 /*
35774 ** Read part of the data associated with cursor pCur.  Exactly
35775 ** "amt" bytes will be transfered into pBuf[].  The transfer
35776 ** begins at "offset".
35777 **
35778 ** Return SQLITE_OK on success or an error code if anything goes
35779 ** wrong.  An error is returned if "offset+amt" is larger than
35780 ** the available payload.
35781 */
35782 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
35783   int rc;
35784
35785 #ifndef SQLITE_OMIT_INCRBLOB
35786   if ( pCur->eState==CURSOR_INVALID ){
35787     return SQLITE_ABORT;
35788   }
35789 #endif
35790
35791   assert( cursorHoldsMutex(pCur) );
35792   rc = restoreCursorPosition(pCur);
35793   if( rc==SQLITE_OK ){
35794     assert( pCur->eState==CURSOR_VALID );
35795     assert( pCur->pPage!=0 );
35796     assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
35797     rc = accessPayload(pCur, offset, amt, pBuf, 1, 0);
35798   }
35799   return rc;
35800 }
35801
35802 /*
35803 ** Return a pointer to payload information from the entry that the 
35804 ** pCur cursor is pointing to.  The pointer is to the beginning of
35805 ** the key if skipKey==0 and it points to the beginning of data if
35806 ** skipKey==1.  The number of bytes of available key/data is written
35807 ** into *pAmt.  If *pAmt==0, then the value returned will not be
35808 ** a valid pointer.
35809 **
35810 ** This routine is an optimization.  It is common for the entire key
35811 ** and data to fit on the local page and for there to be no overflow
35812 ** pages.  When that is so, this routine can be used to access the
35813 ** key and data without making a copy.  If the key and/or data spills
35814 ** onto overflow pages, then accessPayload() must be used to reassembly
35815 ** the key/data and copy it into a preallocated buffer.
35816 **
35817 ** The pointer returned by this routine looks directly into the cached
35818 ** page of the database.  The data might change or move the next time
35819 ** any btree routine is called.
35820 */
35821 static const unsigned char *fetchPayload(
35822   BtCursor *pCur,      /* Cursor pointing to entry to read from */
35823   int *pAmt,           /* Write the number of available bytes here */
35824   int skipKey          /* read beginning at data if this is true */
35825 ){
35826   unsigned char *aPayload;
35827   MemPage *pPage;
35828   u32 nKey;
35829   int nLocal;
35830
35831   assert( pCur!=0 && pCur->pPage!=0 );
35832   assert( pCur->eState==CURSOR_VALID );
35833   assert( cursorHoldsMutex(pCur) );
35834   pPage = pCur->pPage;
35835   assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
35836   getCellInfo(pCur);
35837   aPayload = pCur->info.pCell;
35838   aPayload += pCur->info.nHeader;
35839   if( pPage->intKey ){
35840     nKey = 0;
35841   }else{
35842     nKey = pCur->info.nKey;
35843   }
35844   if( skipKey ){
35845     aPayload += nKey;
35846     nLocal = pCur->info.nLocal - nKey;
35847   }else{
35848     nLocal = pCur->info.nLocal;
35849     if( nLocal>nKey ){
35850       nLocal = nKey;
35851     }
35852   }
35853   *pAmt = nLocal;
35854   return aPayload;
35855 }
35856
35857
35858 /*
35859 ** For the entry that cursor pCur is point to, return as
35860 ** many bytes of the key or data as are available on the local
35861 ** b-tree page.  Write the number of available bytes into *pAmt.
35862 **
35863 ** The pointer returned is ephemeral.  The key/data may move
35864 ** or be destroyed on the next call to any Btree routine,
35865 ** including calls from other threads against the same cache.
35866 ** Hence, a mutex on the BtShared should be held prior to calling
35867 ** this routine.
35868 **
35869 ** These routines is used to get quick access to key and data
35870 ** in the common case where no overflow pages are used.
35871 */
35872 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
35873   assert( cursorHoldsMutex(pCur) );
35874   if( pCur->eState==CURSOR_VALID ){
35875     return (const void*)fetchPayload(pCur, pAmt, 0);
35876   }
35877   return 0;
35878 }
35879 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
35880   assert( cursorHoldsMutex(pCur) );
35881   if( pCur->eState==CURSOR_VALID ){
35882     return (const void*)fetchPayload(pCur, pAmt, 1);
35883   }
35884   return 0;
35885 }
35886
35887
35888 /*
35889 ** Move the cursor down to a new child page.  The newPgno argument is the
35890 ** page number of the child page to move to.
35891 */
35892 static int moveToChild(BtCursor *pCur, u32 newPgno){
35893   int rc;
35894   MemPage *pNewPage;
35895   MemPage *pOldPage;
35896   BtShared *pBt = pCur->pBt;
35897
35898   assert( cursorHoldsMutex(pCur) );
35899   assert( pCur->eState==CURSOR_VALID );
35900   rc = getAndInitPage(pBt, newPgno, &pNewPage, pCur->pPage);
35901   if( rc ) return rc;
35902   pNewPage->idxParent = pCur->idx;
35903   pOldPage = pCur->pPage;
35904   pOldPage->idxShift = 0;
35905   releasePage(pOldPage);
35906   pCur->pPage = pNewPage;
35907   pCur->idx = 0;
35908   pCur->info.nSize = 0;
35909   pCur->validNKey = 0;
35910   if( pNewPage->nCell<1 ){
35911     return SQLITE_CORRUPT_BKPT;
35912   }
35913   return SQLITE_OK;
35914 }
35915
35916 /*
35917 ** Return true if the page is the virtual root of its table.
35918 **
35919 ** The virtual root page is the root page for most tables.  But
35920 ** for the table rooted on page 1, sometime the real root page
35921 ** is empty except for the right-pointer.  In such cases the
35922 ** virtual root page is the page that the right-pointer of page
35923 ** 1 is pointing to.
35924 */
35925 SQLITE_PRIVATE int sqlite3BtreeIsRootPage(MemPage *pPage){
35926   MemPage *pParent;
35927
35928   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
35929   pParent = pPage->pParent;
35930   if( pParent==0 ) return 1;
35931   if( pParent->pgno>1 ) return 0;
35932   if( get2byte(&pParent->aData[pParent->hdrOffset+3])==0 ) return 1;
35933   return 0;
35934 }
35935
35936 /*
35937 ** Move the cursor up to the parent page.
35938 **
35939 ** pCur->idx is set to the cell index that contains the pointer
35940 ** to the page we are coming from.  If we are coming from the
35941 ** right-most child page then pCur->idx is set to one more than
35942 ** the largest cell index.
35943 */
35944 SQLITE_PRIVATE void sqlite3BtreeMoveToParent(BtCursor *pCur){
35945   MemPage *pParent;
35946   MemPage *pPage;
35947   int idxParent;
35948
35949   assert( cursorHoldsMutex(pCur) );
35950   assert( pCur->eState==CURSOR_VALID );
35951   pPage = pCur->pPage;
35952   assert( pPage!=0 );
35953   assert( !sqlite3BtreeIsRootPage(pPage) );
35954   pParent = pPage->pParent;
35955   assert( pParent!=0 );
35956   idxParent = pPage->idxParent;
35957   sqlite3PagerRef(pParent->pDbPage);
35958   releasePage(pPage);
35959   pCur->pPage = pParent;
35960   pCur->info.nSize = 0;
35961   pCur->validNKey = 0;
35962   assert( pParent->idxShift==0 );
35963   pCur->idx = idxParent;
35964 }
35965
35966 /*
35967 ** Move the cursor to the root page
35968 */
35969 static int moveToRoot(BtCursor *pCur){
35970   MemPage *pRoot;
35971   int rc = SQLITE_OK;
35972   Btree *p = pCur->pBtree;
35973   BtShared *pBt = p->pBt;
35974
35975   assert( cursorHoldsMutex(pCur) );
35976   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
35977   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
35978   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
35979   if( pCur->eState>=CURSOR_REQUIRESEEK ){
35980     if( pCur->eState==CURSOR_FAULT ){
35981       return pCur->skip;
35982     }
35983     clearCursorPosition(pCur);
35984   }
35985   pRoot = pCur->pPage;
35986   if( pRoot && pRoot->pgno==pCur->pgnoRoot ){
35987     assert( pRoot->isInit );
35988   }else{
35989     if( 
35990       SQLITE_OK!=(rc = getAndInitPage(pBt, pCur->pgnoRoot, &pRoot, 0))
35991     ){
35992       pCur->eState = CURSOR_INVALID;
35993       return rc;
35994     }
35995     releasePage(pCur->pPage);
35996     pCur->pPage = pRoot;
35997   }
35998   pCur->idx = 0;
35999   pCur->info.nSize = 0;
36000   pCur->atLast = 0;
36001   pCur->validNKey = 0;
36002   if( pRoot->nCell==0 && !pRoot->leaf ){
36003     Pgno subpage;
36004     assert( pRoot->pgno==1 );
36005     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
36006     assert( subpage>0 );
36007     pCur->eState = CURSOR_VALID;
36008     rc = moveToChild(pCur, subpage);
36009   }
36010   pCur->eState = ((pCur->pPage->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
36011   return rc;
36012 }
36013
36014 /*
36015 ** Move the cursor down to the left-most leaf entry beneath the
36016 ** entry to which it is currently pointing.
36017 **
36018 ** The left-most leaf is the one with the smallest key - the first
36019 ** in ascending order.
36020 */
36021 static int moveToLeftmost(BtCursor *pCur){
36022   Pgno pgno;
36023   int rc = SQLITE_OK;
36024   MemPage *pPage;
36025
36026   assert( cursorHoldsMutex(pCur) );
36027   assert( pCur->eState==CURSOR_VALID );
36028   while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
36029     assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
36030     pgno = get4byte(findCell(pPage, pCur->idx));
36031     rc = moveToChild(pCur, pgno);
36032   }
36033   return rc;
36034 }
36035
36036 /*
36037 ** Move the cursor down to the right-most leaf entry beneath the
36038 ** page to which it is currently pointing.  Notice the difference
36039 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
36040 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
36041 ** finds the right-most entry beneath the *page*.
36042 **
36043 ** The right-most entry is the one with the largest key - the last
36044 ** key in ascending order.
36045 */
36046 static int moveToRightmost(BtCursor *pCur){
36047   Pgno pgno;
36048   int rc = SQLITE_OK;
36049   MemPage *pPage;
36050
36051   assert( cursorHoldsMutex(pCur) );
36052   assert( pCur->eState==CURSOR_VALID );
36053   while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
36054     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
36055     pCur->idx = pPage->nCell;
36056     rc = moveToChild(pCur, pgno);
36057   }
36058   if( rc==SQLITE_OK ){
36059     pCur->idx = pPage->nCell - 1;
36060     pCur->info.nSize = 0;
36061     pCur->validNKey = 0;
36062   }
36063   return SQLITE_OK;
36064 }
36065
36066 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
36067 ** on success.  Set *pRes to 0 if the cursor actually points to something
36068 ** or set *pRes to 1 if the table is empty.
36069 */
36070 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
36071   int rc;
36072
36073   assert( cursorHoldsMutex(pCur) );
36074   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
36075   rc = moveToRoot(pCur);
36076   if( rc==SQLITE_OK ){
36077     if( pCur->eState==CURSOR_INVALID ){
36078       assert( pCur->pPage->nCell==0 );
36079       *pRes = 1;
36080       rc = SQLITE_OK;
36081     }else{
36082       assert( pCur->pPage->nCell>0 );
36083       *pRes = 0;
36084       rc = moveToLeftmost(pCur);
36085     }
36086   }
36087   return rc;
36088 }
36089
36090 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
36091 ** on success.  Set *pRes to 0 if the cursor actually points to something
36092 ** or set *pRes to 1 if the table is empty.
36093 */
36094 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
36095   int rc;
36096  
36097   assert( cursorHoldsMutex(pCur) );
36098   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
36099   rc = moveToRoot(pCur);
36100   if( rc==SQLITE_OK ){
36101     if( CURSOR_INVALID==pCur->eState ){
36102       assert( pCur->pPage->nCell==0 );
36103       *pRes = 1;
36104     }else{
36105       assert( pCur->eState==CURSOR_VALID );
36106       *pRes = 0;
36107       rc = moveToRightmost(pCur);
36108       getCellInfo(pCur);
36109       pCur->atLast = rc==SQLITE_OK;
36110     }
36111   }
36112   return rc;
36113 }
36114
36115 /* Move the cursor so that it points to an entry near the key 
36116 ** specified by pKey/nKey/pUnKey. Return a success code.
36117 **
36118 ** For INTKEY tables, only the nKey parameter is used.  pKey 
36119 ** and pUnKey must be NULL.  For index tables, either pUnKey
36120 ** must point to a key that has already been unpacked, or else
36121 ** pKey/nKey describes a blob containing the key.
36122 **
36123 ** If an exact match is not found, then the cursor is always
36124 ** left pointing at a leaf page which would hold the entry if it
36125 ** were present.  The cursor might point to an entry that comes
36126 ** before or after the key.
36127 **
36128 ** The result of comparing the key with the entry to which the
36129 ** cursor is written to *pRes if pRes!=NULL.  The meaning of
36130 ** this value is as follows:
36131 **
36132 **     *pRes<0      The cursor is left pointing at an entry that
36133 **                  is smaller than pKey or if the table is empty
36134 **                  and the cursor is therefore left point to nothing.
36135 **
36136 **     *pRes==0     The cursor is left pointing at an entry that
36137 **                  exactly matches pKey.
36138 **
36139 **     *pRes>0      The cursor is left pointing at an entry that
36140 **                  is larger than pKey.
36141 **
36142 */
36143 SQLITE_PRIVATE int sqlite3BtreeMoveto(
36144   BtCursor *pCur,        /* The cursor to be moved */
36145   const void *pKey,      /* The key content for indices.  Not used by tables */
36146   UnpackedRecord *pUnKey,/* Unpacked version of pKey */
36147   i64 nKey,              /* Size of pKey.  Or the key for tables */
36148   int biasRight,         /* If true, bias the search to the high end */
36149   int *pRes              /* Search result flag */
36150 ){
36151   int rc;
36152   char aSpace[200];
36153
36154   assert( cursorHoldsMutex(pCur) );
36155   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
36156
36157   /* If the cursor is already positioned at the point we are trying
36158   ** to move to, then just return without doing any work */
36159   if( pCur->eState==CURSOR_VALID && pCur->validNKey && pCur->pPage->intKey ){
36160     if( pCur->info.nKey==nKey ){
36161       *pRes = 0;
36162       return SQLITE_OK;
36163     }
36164     if( pCur->atLast && pCur->info.nKey<nKey ){
36165       *pRes = -1;
36166       return SQLITE_OK;
36167     }
36168   }
36169
36170
36171   rc = moveToRoot(pCur);
36172   if( rc ){
36173     return rc;
36174   }
36175   assert( pCur->pPage );
36176   assert( pCur->pPage->isInit );
36177   if( pCur->eState==CURSOR_INVALID ){
36178     *pRes = -1;
36179     assert( pCur->pPage->nCell==0 );
36180     return SQLITE_OK;
36181   }
36182   if( pCur->pPage->intKey ){
36183     /* We are given an SQL table to search.  The key is the integer
36184     ** rowid contained in nKey.  pKey and pUnKey should both be NULL */
36185     assert( pUnKey==0 );
36186     assert( pKey==0 );
36187   }else if( pUnKey==0 ){
36188     /* We are to search an SQL index using a key encoded as a blob.
36189     ** The blob is found at pKey and is nKey bytes in length.  Unpack
36190     ** this key so that we can use it. */
36191     assert( pKey!=0 );
36192     pUnKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, nKey, pKey,
36193                                    aSpace, sizeof(aSpace));
36194     if( pUnKey==0 ) return SQLITE_NOMEM;
36195   }else{
36196     /* We are to search an SQL index using a key that is already unpacked
36197     ** and handed to us in pUnKey. */
36198     assert( pKey==0 );
36199   }
36200   for(;;){
36201     int lwr, upr;
36202     Pgno chldPg;
36203     MemPage *pPage = pCur->pPage;
36204     int c = -1;  /* pRes return if table is empty must be -1 */
36205     lwr = 0;
36206     upr = pPage->nCell-1;
36207     if( !pPage->intKey && pUnKey==0 ){
36208       rc = SQLITE_CORRUPT_BKPT;
36209       goto moveto_finish;
36210     }
36211     if( biasRight ){
36212       pCur->idx = upr;
36213     }else{
36214       pCur->idx = (upr+lwr)/2;
36215     }
36216     if( lwr<=upr ) for(;;){
36217       void *pCellKey;
36218       i64 nCellKey;
36219       pCur->info.nSize = 0;
36220       pCur->validNKey = 1;
36221       if( pPage->intKey ){
36222         u8 *pCell;
36223         pCell = findCell(pPage, pCur->idx) + pPage->childPtrSize;
36224         if( pPage->hasData ){
36225           u32 dummy;
36226           pCell += getVarint32(pCell, dummy);
36227         }
36228         getVarint(pCell, (u64*)&nCellKey);
36229         if( nCellKey==nKey ){
36230           c = 0;
36231         }else if( nCellKey<nKey ){
36232           c = -1;
36233         }else{
36234           assert( nCellKey>nKey );
36235           c = +1;
36236         }
36237       }else{
36238         int available;
36239         pCellKey = (void *)fetchPayload(pCur, &available, 0);
36240         nCellKey = pCur->info.nKey;
36241         if( available>=nCellKey ){
36242           c = sqlite3VdbeRecordCompare(nCellKey, pCellKey, pUnKey);
36243         }else{
36244           pCellKey = sqlite3Malloc( nCellKey );
36245           if( pCellKey==0 ){
36246             rc = SQLITE_NOMEM;
36247             goto moveto_finish;
36248           }
36249           rc = sqlite3BtreeKey(pCur, 0, nCellKey, (void *)pCellKey);
36250           c = sqlite3VdbeRecordCompare(nCellKey, pCellKey, pUnKey);
36251           sqlite3_free(pCellKey);
36252           if( rc ) goto moveto_finish;
36253         }
36254       }
36255       if( c==0 ){
36256         pCur->info.nKey = nCellKey;
36257         if( pPage->intKey && !pPage->leaf ){
36258           lwr = pCur->idx;
36259           upr = lwr - 1;
36260           break;
36261         }else{
36262           if( pRes ) *pRes = 0;
36263           rc = SQLITE_OK;
36264           goto moveto_finish;
36265         }
36266       }
36267       if( c<0 ){
36268         lwr = pCur->idx+1;
36269       }else{
36270         upr = pCur->idx-1;
36271       }
36272       if( lwr>upr ){
36273         pCur->info.nKey = nCellKey;
36274         break;
36275       }
36276       pCur->idx = (lwr+upr)/2;
36277     }
36278     assert( lwr==upr+1 );
36279     assert( pPage->isInit );
36280     if( pPage->leaf ){
36281       chldPg = 0;
36282     }else if( lwr>=pPage->nCell ){
36283       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
36284     }else{
36285       chldPg = get4byte(findCell(pPage, lwr));
36286     }
36287     if( chldPg==0 ){
36288       assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
36289       if( pRes ) *pRes = c;
36290       rc = SQLITE_OK;
36291       goto moveto_finish;
36292     }
36293     pCur->idx = lwr;
36294     pCur->info.nSize = 0;
36295     pCur->validNKey = 0;
36296     rc = moveToChild(pCur, chldPg);
36297     if( rc ) goto moveto_finish;
36298   }
36299 moveto_finish:
36300   if( pKey ){
36301     /* If we created our own unpacked key at the top of this
36302     ** procedure, then destroy that key before returning. */
36303     sqlite3VdbeDeleteUnpackedRecord(pUnKey);
36304   }
36305   return rc;
36306 }
36307
36308
36309 /*
36310 ** Return TRUE if the cursor is not pointing at an entry of the table.
36311 **
36312 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
36313 ** past the last entry in the table or sqlite3BtreePrev() moves past
36314 ** the first entry.  TRUE is also returned if the table is empty.
36315 */
36316 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
36317   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
36318   ** have been deleted? This API will need to change to return an error code
36319   ** as well as the boolean result value.
36320   */
36321   return (CURSOR_VALID!=pCur->eState);
36322 }
36323
36324 /*
36325 ** Return the database connection handle for a cursor.
36326 */
36327 SQLITE_PRIVATE sqlite3 *sqlite3BtreeCursorDb(const BtCursor *pCur){
36328   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
36329   return pCur->pBtree->db;
36330 }
36331
36332 /*
36333 ** Advance the cursor to the next entry in the database.  If
36334 ** successful then set *pRes=0.  If the cursor
36335 ** was already pointing to the last entry in the database before
36336 ** this routine was called, then set *pRes=1.
36337 */
36338 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
36339   int rc;
36340   MemPage *pPage;
36341
36342   assert( cursorHoldsMutex(pCur) );
36343   rc = restoreCursorPosition(pCur);
36344   if( rc!=SQLITE_OK ){
36345     return rc;
36346   }
36347   assert( pRes!=0 );
36348   pPage = pCur->pPage;
36349   if( CURSOR_INVALID==pCur->eState ){
36350     *pRes = 1;
36351     return SQLITE_OK;
36352   }
36353   if( pCur->skip>0 ){
36354     pCur->skip = 0;
36355     *pRes = 0;
36356     return SQLITE_OK;
36357   }
36358   pCur->skip = 0;
36359
36360   assert( pPage->isInit );
36361   assert( pCur->idx<pPage->nCell );
36362
36363   pCur->idx++;
36364   pCur->info.nSize = 0;
36365   pCur->validNKey = 0;
36366   if( pCur->idx>=pPage->nCell ){
36367     if( !pPage->leaf ){
36368       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
36369       if( rc ) return rc;
36370       rc = moveToLeftmost(pCur);
36371       *pRes = 0;
36372       return rc;
36373     }
36374     do{
36375       if( sqlite3BtreeIsRootPage(pPage) ){
36376         *pRes = 1;
36377         pCur->eState = CURSOR_INVALID;
36378         return SQLITE_OK;
36379       }
36380       sqlite3BtreeMoveToParent(pCur);
36381       pPage = pCur->pPage;
36382     }while( pCur->idx>=pPage->nCell );
36383     *pRes = 0;
36384     if( pPage->intKey ){
36385       rc = sqlite3BtreeNext(pCur, pRes);
36386     }else{
36387       rc = SQLITE_OK;
36388     }
36389     return rc;
36390   }
36391   *pRes = 0;
36392   if( pPage->leaf ){
36393     return SQLITE_OK;
36394   }
36395   rc = moveToLeftmost(pCur);
36396   return rc;
36397 }
36398
36399
36400 /*
36401 ** Step the cursor to the back to the previous entry in the database.  If
36402 ** successful then set *pRes=0.  If the cursor
36403 ** was already pointing to the first entry in the database before
36404 ** this routine was called, then set *pRes=1.
36405 */
36406 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
36407   int rc;
36408   Pgno pgno;
36409   MemPage *pPage;
36410
36411   assert( cursorHoldsMutex(pCur) );
36412   rc = restoreCursorPosition(pCur);
36413   if( rc!=SQLITE_OK ){
36414     return rc;
36415   }
36416   pCur->atLast = 0;
36417   if( CURSOR_INVALID==pCur->eState ){
36418     *pRes = 1;
36419     return SQLITE_OK;
36420   }
36421   if( pCur->skip<0 ){
36422     pCur->skip = 0;
36423     *pRes = 0;
36424     return SQLITE_OK;
36425   }
36426   pCur->skip = 0;
36427
36428   pPage = pCur->pPage;
36429   assert( pPage->isInit );
36430   assert( pCur->idx>=0 );
36431   if( !pPage->leaf ){
36432     pgno = get4byte( findCell(pPage, pCur->idx) );
36433     rc = moveToChild(pCur, pgno);
36434     if( rc ){
36435       return rc;
36436     }
36437     rc = moveToRightmost(pCur);
36438   }else{
36439     while( pCur->idx==0 ){
36440       if( sqlite3BtreeIsRootPage(pPage) ){
36441         pCur->eState = CURSOR_INVALID;
36442         *pRes = 1;
36443         return SQLITE_OK;
36444       }
36445       sqlite3BtreeMoveToParent(pCur);
36446       pPage = pCur->pPage;
36447     }
36448     pCur->idx--;
36449     pCur->info.nSize = 0;
36450     pCur->validNKey = 0;
36451     if( pPage->intKey && !pPage->leaf ){
36452       rc = sqlite3BtreePrevious(pCur, pRes);
36453     }else{
36454       rc = SQLITE_OK;
36455     }
36456   }
36457   *pRes = 0;
36458   return rc;
36459 }
36460
36461 /*
36462 ** Allocate a new page from the database file.
36463 **
36464 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
36465 ** has already been called on the new page.)  The new page has also
36466 ** been referenced and the calling routine is responsible for calling
36467 ** sqlite3PagerUnref() on the new page when it is done.
36468 **
36469 ** SQLITE_OK is returned on success.  Any other return value indicates
36470 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
36471 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
36472 **
36473 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to 
36474 ** locate a page close to the page number "nearby".  This can be used in an
36475 ** attempt to keep related pages close to each other in the database file,
36476 ** which in turn can make database access faster.
36477 **
36478 ** If the "exact" parameter is not 0, and the page-number nearby exists 
36479 ** anywhere on the free-list, then it is guarenteed to be returned. This
36480 ** is only used by auto-vacuum databases when allocating a new table.
36481 */
36482 static int allocateBtreePage(
36483   BtShared *pBt, 
36484   MemPage **ppPage, 
36485   Pgno *pPgno, 
36486   Pgno nearby,
36487   u8 exact
36488 ){
36489   MemPage *pPage1;
36490   int rc;
36491   int n;     /* Number of pages on the freelist */
36492   int k;     /* Number of leaves on the trunk of the freelist */
36493   MemPage *pTrunk = 0;
36494   MemPage *pPrevTrunk = 0;
36495
36496   assert( sqlite3_mutex_held(pBt->mutex) );
36497   pPage1 = pBt->pPage1;
36498   n = get4byte(&pPage1->aData[36]);
36499   if( n>0 ){
36500     /* There are pages on the freelist.  Reuse one of those pages. */
36501     Pgno iTrunk;
36502     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
36503     
36504     /* If the 'exact' parameter was true and a query of the pointer-map
36505     ** shows that the page 'nearby' is somewhere on the free-list, then
36506     ** the entire-list will be searched for that page.
36507     */
36508 #ifndef SQLITE_OMIT_AUTOVACUUM
36509     if( exact && nearby<=pagerPagecount(pBt->pPager) ){
36510       u8 eType;
36511       assert( nearby>0 );
36512       assert( pBt->autoVacuum );
36513       rc = ptrmapGet(pBt, nearby, &eType, 0);
36514       if( rc ) return rc;
36515       if( eType==PTRMAP_FREEPAGE ){
36516         searchList = 1;
36517       }
36518       *pPgno = nearby;
36519     }
36520 #endif
36521
36522     /* Decrement the free-list count by 1. Set iTrunk to the index of the
36523     ** first free-list trunk page. iPrevTrunk is initially 1.
36524     */
36525     rc = sqlite3PagerWrite(pPage1->pDbPage);
36526     if( rc ) return rc;
36527     put4byte(&pPage1->aData[36], n-1);
36528
36529     /* The code within this loop is run only once if the 'searchList' variable
36530     ** is not true. Otherwise, it runs once for each trunk-page on the
36531     ** free-list until the page 'nearby' is located.
36532     */
36533     do {
36534       pPrevTrunk = pTrunk;
36535       if( pPrevTrunk ){
36536         iTrunk = get4byte(&pPrevTrunk->aData[0]);
36537       }else{
36538         iTrunk = get4byte(&pPage1->aData[32]);
36539       }
36540       rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
36541       if( rc ){
36542         pTrunk = 0;
36543         goto end_allocate_page;
36544       }
36545
36546       k = get4byte(&pTrunk->aData[4]);
36547       if( k==0 && !searchList ){
36548         /* The trunk has no leaves and the list is not being searched. 
36549         ** So extract the trunk page itself and use it as the newly 
36550         ** allocated page */
36551         assert( pPrevTrunk==0 );
36552         rc = sqlite3PagerWrite(pTrunk->pDbPage);
36553         if( rc ){
36554           goto end_allocate_page;
36555         }
36556         *pPgno = iTrunk;
36557         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
36558         *ppPage = pTrunk;
36559         pTrunk = 0;
36560         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
36561       }else if( k>pBt->usableSize/4 - 2 ){
36562         /* Value of k is out of range.  Database corruption */
36563         rc = SQLITE_CORRUPT_BKPT;
36564         goto end_allocate_page;
36565 #ifndef SQLITE_OMIT_AUTOVACUUM
36566       }else if( searchList && nearby==iTrunk ){
36567         /* The list is being searched and this trunk page is the page
36568         ** to allocate, regardless of whether it has leaves.
36569         */
36570         assert( *pPgno==iTrunk );
36571         *ppPage = pTrunk;
36572         searchList = 0;
36573         rc = sqlite3PagerWrite(pTrunk->pDbPage);
36574         if( rc ){
36575           goto end_allocate_page;
36576         }
36577         if( k==0 ){
36578           if( !pPrevTrunk ){
36579             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
36580           }else{
36581             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
36582           }
36583         }else{
36584           /* The trunk page is required by the caller but it contains 
36585           ** pointers to free-list leaves. The first leaf becomes a trunk
36586           ** page in this case.
36587           */
36588           MemPage *pNewTrunk;
36589           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
36590           rc = sqlite3BtreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
36591           if( rc!=SQLITE_OK ){
36592             goto end_allocate_page;
36593           }
36594           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
36595           if( rc!=SQLITE_OK ){
36596             releasePage(pNewTrunk);
36597             goto end_allocate_page;
36598           }
36599           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
36600           put4byte(&pNewTrunk->aData[4], k-1);
36601           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
36602           releasePage(pNewTrunk);
36603           if( !pPrevTrunk ){
36604             put4byte(&pPage1->aData[32], iNewTrunk);
36605           }else{
36606             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
36607             if( rc ){
36608               goto end_allocate_page;
36609             }
36610             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
36611           }
36612         }
36613         pTrunk = 0;
36614         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
36615 #endif
36616       }else{
36617         /* Extract a leaf from the trunk */
36618         int closest;
36619         Pgno iPage;
36620         unsigned char *aData = pTrunk->aData;
36621         rc = sqlite3PagerWrite(pTrunk->pDbPage);
36622         if( rc ){
36623           goto end_allocate_page;
36624         }
36625         if( nearby>0 ){
36626           int i, dist;
36627           closest = 0;
36628           dist = get4byte(&aData[8]) - nearby;
36629           if( dist<0 ) dist = -dist;
36630           for(i=1; i<k; i++){
36631             int d2 = get4byte(&aData[8+i*4]) - nearby;
36632             if( d2<0 ) d2 = -d2;
36633             if( d2<dist ){
36634               closest = i;
36635               dist = d2;
36636             }
36637           }
36638         }else{
36639           closest = 0;
36640         }
36641
36642         iPage = get4byte(&aData[8+closest*4]);
36643         if( !searchList || iPage==nearby ){
36644           int nPage;
36645           *pPgno = iPage;
36646           nPage = pagerPagecount(pBt->pPager);
36647           if( *pPgno>nPage ){
36648             /* Free page off the end of the file */
36649             rc = SQLITE_CORRUPT_BKPT;
36650             goto end_allocate_page;
36651           }
36652           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
36653                  ": %d more free pages\n",
36654                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
36655           if( closest<k-1 ){
36656             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
36657           }
36658           put4byte(&aData[4], k-1);
36659           rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 1);
36660           if( rc==SQLITE_OK ){
36661             sqlite3PagerDontRollback((*ppPage)->pDbPage);
36662             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
36663             if( rc!=SQLITE_OK ){
36664               releasePage(*ppPage);
36665             }
36666           }
36667           searchList = 0;
36668         }
36669       }
36670       releasePage(pPrevTrunk);
36671       pPrevTrunk = 0;
36672     }while( searchList );
36673   }else{
36674     /* There are no pages on the freelist, so create a new page at the
36675     ** end of the file */
36676     int nPage = pagerPagecount(pBt->pPager);
36677     *pPgno = nPage + 1;
36678
36679 #ifndef SQLITE_OMIT_AUTOVACUUM
36680     if( pBt->nTrunc ){
36681       /* An incr-vacuum has already run within this transaction. So the
36682       ** page to allocate is not from the physical end of the file, but
36683       ** at pBt->nTrunc. 
36684       */
36685       *pPgno = pBt->nTrunc+1;
36686       if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
36687         (*pPgno)++;
36688       }
36689     }
36690     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
36691       /* If *pPgno refers to a pointer-map page, allocate two new pages
36692       ** at the end of the file instead of one. The first allocated page
36693       ** becomes a new pointer-map page, the second is used by the caller.
36694       */
36695       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
36696       assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
36697       (*pPgno)++;
36698       if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ (*pPgno)++; }
36699     }
36700     if( pBt->nTrunc ){
36701       pBt->nTrunc = *pPgno;
36702     }
36703 #endif
36704
36705     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
36706     rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 0);
36707     if( rc ) return rc;
36708     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
36709     if( rc!=SQLITE_OK ){
36710       releasePage(*ppPage);
36711     }
36712     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
36713   }
36714
36715   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
36716
36717 end_allocate_page:
36718   releasePage(pTrunk);
36719   releasePage(pPrevTrunk);
36720   return rc;
36721 }
36722
36723 /*
36724 ** Add a page of the database file to the freelist.
36725 **
36726 ** sqlite3PagerUnref() is NOT called for pPage.
36727 */
36728 static int freePage(MemPage *pPage){
36729   BtShared *pBt = pPage->pBt;
36730   MemPage *pPage1 = pBt->pPage1;
36731   int rc, n, k;
36732
36733   /* Prepare the page for freeing */
36734   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
36735   assert( pPage->pgno>1 );
36736   pPage->isInit = 0;
36737   releasePage(pPage->pParent);
36738   pPage->pParent = 0;
36739
36740   /* Increment the free page count on pPage1 */
36741   rc = sqlite3PagerWrite(pPage1->pDbPage);
36742   if( rc ) return rc;
36743   n = get4byte(&pPage1->aData[36]);
36744   put4byte(&pPage1->aData[36], n+1);
36745
36746 #ifdef SQLITE_SECURE_DELETE
36747   /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
36748   ** always fully overwrite deleted information with zeros.
36749   */
36750   rc = sqlite3PagerWrite(pPage->pDbPage);
36751   if( rc ) return rc;
36752   memset(pPage->aData, 0, pPage->pBt->pageSize);
36753 #endif
36754
36755   /* If the database supports auto-vacuum, write an entry in the pointer-map
36756   ** to indicate that the page is free.
36757   */
36758   if( ISAUTOVACUUM ){
36759     rc = ptrmapPut(pBt, pPage->pgno, PTRMAP_FREEPAGE, 0);
36760     if( rc ) return rc;
36761   }
36762
36763   if( n==0 ){
36764     /* This is the first free page */
36765     rc = sqlite3PagerWrite(pPage->pDbPage);
36766     if( rc ) return rc;
36767     memset(pPage->aData, 0, 8);
36768     put4byte(&pPage1->aData[32], pPage->pgno);
36769     TRACE(("FREE-PAGE: %d first\n", pPage->pgno));
36770   }else{
36771     /* Other free pages already exist.  Retrive the first trunk page
36772     ** of the freelist and find out how many leaves it has. */
36773     MemPage *pTrunk;
36774     rc = sqlite3BtreeGetPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk, 0);
36775     if( rc ) return rc;
36776     k = get4byte(&pTrunk->aData[4]);
36777     if( k>=pBt->usableSize/4 - 8 ){
36778       /* The trunk is full.  Turn the page being freed into a new
36779       ** trunk page with no leaves.
36780       **
36781       ** Note that the trunk page is not really full until it contains
36782       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
36783       ** coded.  But due to a coding error in versions of SQLite prior to
36784       ** 3.6.0, databases with freelist trunk pages holding more than
36785       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
36786       ** to maintain backwards compatibility with older versions of SQLite,
36787       ** we will contain to restrict the number of entries to usableSize/4 - 8
36788       ** for now.  At some point in the future (once everyone has upgraded
36789       ** to 3.6.0 or later) we should consider fixing the conditional above
36790       ** to read "usableSize/4-2" instead of "usableSize/4-8".
36791       */
36792       rc = sqlite3PagerWrite(pPage->pDbPage);
36793       if( rc==SQLITE_OK ){
36794         put4byte(pPage->aData, pTrunk->pgno);
36795         put4byte(&pPage->aData[4], 0);
36796         put4byte(&pPage1->aData[32], pPage->pgno);
36797         TRACE(("FREE-PAGE: %d new trunk page replacing %d\n",
36798                 pPage->pgno, pTrunk->pgno));
36799       }
36800     }else if( k<0 ){
36801       rc = SQLITE_CORRUPT;
36802     }else{
36803       /* Add the newly freed page as a leaf on the current trunk */
36804       rc = sqlite3PagerWrite(pTrunk->pDbPage);
36805       if( rc==SQLITE_OK ){
36806         put4byte(&pTrunk->aData[4], k+1);
36807         put4byte(&pTrunk->aData[8+k*4], pPage->pgno);
36808 #ifndef SQLITE_SECURE_DELETE
36809         sqlite3PagerDontWrite(pPage->pDbPage);
36810 #endif
36811       }
36812       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
36813     }
36814     releasePage(pTrunk);
36815   }
36816   return rc;
36817 }
36818
36819 /*
36820 ** Free any overflow pages associated with the given Cell.
36821 */
36822 static int clearCell(MemPage *pPage, unsigned char *pCell){
36823   BtShared *pBt = pPage->pBt;
36824   CellInfo info;
36825   Pgno ovflPgno;
36826   int rc;
36827   int nOvfl;
36828   int ovflPageSize;
36829
36830   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
36831   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
36832   if( info.iOverflow==0 ){
36833     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
36834   }
36835   ovflPgno = get4byte(&pCell[info.iOverflow]);
36836   ovflPageSize = pBt->usableSize - 4;
36837   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
36838   assert( ovflPgno==0 || nOvfl>0 );
36839   while( nOvfl-- ){
36840     MemPage *pOvfl;
36841     if( ovflPgno==0 || ovflPgno>pagerPagecount(pBt->pPager) ){
36842       return SQLITE_CORRUPT_BKPT;
36843     }
36844
36845     rc = getOverflowPage(pBt, ovflPgno, &pOvfl, (nOvfl==0)?0:&ovflPgno);
36846     if( rc ) return rc;
36847     rc = freePage(pOvfl);
36848     sqlite3PagerUnref(pOvfl->pDbPage);
36849     if( rc ) return rc;
36850   }
36851   return SQLITE_OK;
36852 }
36853
36854 /*
36855 ** Create the byte sequence used to represent a cell on page pPage
36856 ** and write that byte sequence into pCell[].  Overflow pages are
36857 ** allocated and filled in as necessary.  The calling procedure
36858 ** is responsible for making sure sufficient space has been allocated
36859 ** for pCell[].
36860 **
36861 ** Note that pCell does not necessary need to point to the pPage->aData
36862 ** area.  pCell might point to some temporary storage.  The cell will
36863 ** be constructed in this temporary area then copied into pPage->aData
36864 ** later.
36865 */
36866 static int fillInCell(
36867   MemPage *pPage,                /* The page that contains the cell */
36868   unsigned char *pCell,          /* Complete text of the cell */
36869   const void *pKey, i64 nKey,    /* The key */
36870   const void *pData,int nData,   /* The data */
36871   int nZero,                     /* Extra zero bytes to append to pData */
36872   int *pnSize                    /* Write cell size here */
36873 ){
36874   int nPayload;
36875   const u8 *pSrc;
36876   int nSrc, n, rc;
36877   int spaceLeft;
36878   MemPage *pOvfl = 0;
36879   MemPage *pToRelease = 0;
36880   unsigned char *pPrior;
36881   unsigned char *pPayload;
36882   BtShared *pBt = pPage->pBt;
36883   Pgno pgnoOvfl = 0;
36884   int nHeader;
36885   CellInfo info;
36886
36887   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
36888
36889   /* Fill in the header. */
36890   nHeader = 0;
36891   if( !pPage->leaf ){
36892     nHeader += 4;
36893   }
36894   if( pPage->hasData ){
36895     nHeader += putVarint(&pCell[nHeader], nData+nZero);
36896   }else{
36897     nData = nZero = 0;
36898   }
36899   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
36900   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
36901   assert( info.nHeader==nHeader );
36902   assert( info.nKey==nKey );
36903   assert( info.nData==nData+nZero );
36904   
36905   /* Fill in the payload */
36906   nPayload = nData + nZero;
36907   if( pPage->intKey ){
36908     pSrc = pData;
36909     nSrc = nData;
36910     nData = 0;
36911   }else{
36912     nPayload += nKey;
36913     pSrc = pKey;
36914     nSrc = nKey;
36915   }
36916   *pnSize = info.nSize;
36917   spaceLeft = info.nLocal;
36918   pPayload = &pCell[nHeader];
36919   pPrior = &pCell[info.iOverflow];
36920
36921   while( nPayload>0 ){
36922     if( spaceLeft==0 ){
36923       int isExact = 0;
36924 #ifndef SQLITE_OMIT_AUTOVACUUM
36925       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
36926       if( pBt->autoVacuum ){
36927         do{
36928           pgnoOvfl++;
36929         } while( 
36930           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
36931         );
36932         if( pgnoOvfl>1 ){
36933           /* isExact = 1; */
36934         }
36935       }
36936 #endif
36937       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, isExact);
36938 #ifndef SQLITE_OMIT_AUTOVACUUM
36939       /* If the database supports auto-vacuum, and the second or subsequent
36940       ** overflow page is being allocated, add an entry to the pointer-map
36941       ** for that page now. 
36942       **
36943       ** If this is the first overflow page, then write a partial entry 
36944       ** to the pointer-map. If we write nothing to this pointer-map slot,
36945       ** then the optimistic overflow chain processing in clearCell()
36946       ** may misinterpret the uninitialised values and delete the
36947       ** wrong pages from the database.
36948       */
36949       if( pBt->autoVacuum && rc==SQLITE_OK ){
36950         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
36951         rc = ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap);
36952         if( rc ){
36953           releasePage(pOvfl);
36954         }
36955       }
36956 #endif
36957       if( rc ){
36958         releasePage(pToRelease);
36959         return rc;
36960       }
36961       put4byte(pPrior, pgnoOvfl);
36962       releasePage(pToRelease);
36963       pToRelease = pOvfl;
36964       pPrior = pOvfl->aData;
36965       put4byte(pPrior, 0);
36966       pPayload = &pOvfl->aData[4];
36967       spaceLeft = pBt->usableSize - 4;
36968     }
36969     n = nPayload;
36970     if( n>spaceLeft ) n = spaceLeft;
36971     if( nSrc>0 ){
36972       if( n>nSrc ) n = nSrc;
36973       assert( pSrc );
36974       memcpy(pPayload, pSrc, n);
36975     }else{
36976       memset(pPayload, 0, n);
36977     }
36978     nPayload -= n;
36979     pPayload += n;
36980     pSrc += n;
36981     nSrc -= n;
36982     spaceLeft -= n;
36983     if( nSrc==0 ){
36984       nSrc = nData;
36985       pSrc = pData;
36986     }
36987   }
36988   releasePage(pToRelease);
36989   return SQLITE_OK;
36990 }
36991
36992
36993 /*
36994 ** Change the MemPage.pParent pointer on the page whose number is
36995 ** given in the second argument so that MemPage.pParent holds the
36996 ** pointer in the third argument.
36997 **
36998 ** If the final argument, updatePtrmap, is non-zero and the database
36999 ** is an auto-vacuum database, then the pointer-map entry for pgno
37000 ** is updated.
37001 */
37002 static int reparentPage(
37003   BtShared *pBt,                /* B-Tree structure */
37004   Pgno pgno,                    /* Page number of child being adopted */
37005   MemPage *pNewParent,          /* New parent of pgno */
37006   int idx,                      /* Index of child page pgno in pNewParent */
37007   int updatePtrmap              /* If true, update pointer-map for pgno */
37008 ){
37009   MemPage *pThis;
37010   DbPage *pDbPage;
37011
37012   assert( sqlite3_mutex_held(pBt->mutex) );
37013   assert( pNewParent!=0 );
37014   if( pgno==0 ) return SQLITE_OK;
37015   assert( pBt->pPager!=0 );
37016   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
37017   if( pDbPage ){
37018     pThis = (MemPage *)sqlite3PagerGetExtra(pDbPage);
37019     if( pThis->isInit ){
37020       assert( pThis->aData==sqlite3PagerGetData(pDbPage) );
37021       if( pThis->pParent!=pNewParent ){
37022         if( pThis->pParent ) sqlite3PagerUnref(pThis->pParent->pDbPage);
37023         pThis->pParent = pNewParent;
37024         sqlite3PagerRef(pNewParent->pDbPage);
37025       }
37026       pThis->idxParent = idx;
37027     }
37028     sqlite3PagerUnref(pDbPage);
37029   }
37030
37031   if( ISAUTOVACUUM && updatePtrmap ){
37032     return ptrmapPut(pBt, pgno, PTRMAP_BTREE, pNewParent->pgno);
37033   }
37034
37035 #ifndef NDEBUG
37036   /* If the updatePtrmap flag was clear, assert that the entry in the
37037   ** pointer-map is already correct.
37038   */
37039   if( ISAUTOVACUUM ){
37040     pDbPage = sqlite3PagerLookup(pBt->pPager,PTRMAP_PAGENO(pBt,pgno));
37041     if( pDbPage ){
37042       u8 eType;
37043       Pgno ii;
37044       int rc = ptrmapGet(pBt, pgno, &eType, &ii);
37045       assert( rc==SQLITE_OK && ii==pNewParent->pgno && eType==PTRMAP_BTREE );
37046       sqlite3PagerUnref(pDbPage);
37047     }
37048   }
37049 #endif
37050
37051   return SQLITE_OK;
37052 }
37053
37054
37055
37056 /*
37057 ** Change the pParent pointer of all children of pPage to point back
37058 ** to pPage.
37059 **
37060 ** In other words, for every child of pPage, invoke reparentPage()
37061 ** to make sure that each child knows that pPage is its parent.
37062 **
37063 ** This routine gets called after you memcpy() one page into
37064 ** another.
37065 **
37066 ** If updatePtrmap is true, then the pointer-map entries for all child
37067 ** pages of pPage are updated.
37068 */
37069 static int reparentChildPages(MemPage *pPage, int updatePtrmap){
37070   int rc = SQLITE_OK;
37071   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
37072   if( !pPage->leaf ){
37073     int i;
37074     BtShared *pBt = pPage->pBt;
37075     Pgno iRight = get4byte(&pPage->aData[pPage->hdrOffset+8]);
37076
37077     for(i=0; i<pPage->nCell; i++){
37078       u8 *pCell = findCell(pPage, i);
37079       rc = reparentPage(pBt, get4byte(pCell), pPage, i, updatePtrmap);
37080       if( rc!=SQLITE_OK ) return rc;
37081     }
37082     rc = reparentPage(pBt, iRight, pPage, i, updatePtrmap);
37083     pPage->idxShift = 0;
37084   }
37085   return rc;
37086 }
37087
37088 /*
37089 ** Remove the i-th cell from pPage.  This routine effects pPage only.
37090 ** The cell content is not freed or deallocated.  It is assumed that
37091 ** the cell content has been copied someplace else.  This routine just
37092 ** removes the reference to the cell from pPage.
37093 **
37094 ** "sz" must be the number of bytes in the cell.
37095 */
37096 static void dropCell(MemPage *pPage, int idx, int sz){
37097   int i;          /* Loop counter */
37098   int pc;         /* Offset to cell content of cell being deleted */
37099   u8 *data;       /* pPage->aData */
37100   u8 *ptr;        /* Used to move bytes around within data[] */
37101
37102   assert( idx>=0 && idx<pPage->nCell );
37103   assert( sz==cellSize(pPage, idx) );
37104   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
37105   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
37106   data = pPage->aData;
37107   ptr = &data[pPage->cellOffset + 2*idx];
37108   pc = get2byte(ptr);
37109   assert( pc>10 && pc+sz<=pPage->pBt->usableSize );
37110   freeSpace(pPage, pc, sz);
37111   for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
37112     ptr[0] = ptr[2];
37113     ptr[1] = ptr[3];
37114   }
37115   pPage->nCell--;
37116   put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
37117   pPage->nFree += 2;
37118   pPage->idxShift = 1;
37119 }
37120
37121 /*
37122 ** Insert a new cell on pPage at cell index "i".  pCell points to the
37123 ** content of the cell.
37124 **
37125 ** If the cell content will fit on the page, then put it there.  If it
37126 ** will not fit, then make a copy of the cell content into pTemp if
37127 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
37128 ** in pPage->aOvfl[] and make it point to the cell content (either
37129 ** in pTemp or the original pCell) and also record its index. 
37130 ** Allocating a new entry in pPage->aCell[] implies that 
37131 ** pPage->nOverflow is incremented.
37132 **
37133 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
37134 ** cell. The caller will overwrite them after this function returns. If
37135 ** nSkip is non-zero, then pCell may not point to an invalid memory location 
37136 ** (but pCell+nSkip is always valid).
37137 */
37138 static int insertCell(
37139   MemPage *pPage,   /* Page into which we are copying */
37140   int i,            /* New cell becomes the i-th cell of the page */
37141   u8 *pCell,        /* Content of the new cell */
37142   int sz,           /* Bytes of content in pCell */
37143   u8 *pTemp,        /* Temp storage space for pCell, if needed */
37144   u8 nSkip          /* Do not write the first nSkip bytes of the cell */
37145 ){
37146   int idx;          /* Where to write new cell content in data[] */
37147   int j;            /* Loop counter */
37148   int top;          /* First byte of content for any cell in data[] */
37149   int end;          /* First byte past the last cell pointer in data[] */
37150   int ins;          /* Index in data[] where new cell pointer is inserted */
37151   int hdr;          /* Offset into data[] of the page header */
37152   int cellOffset;   /* Address of first cell pointer in data[] */
37153   u8 *data;         /* The content of the whole page */
37154   u8 *ptr;          /* Used for moving information around in data[] */
37155
37156   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
37157   assert( sz==cellSizePtr(pPage, pCell) );
37158   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
37159   if( pPage->nOverflow || sz+2>pPage->nFree ){
37160     if( pTemp ){
37161       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
37162       pCell = pTemp;
37163     }
37164     j = pPage->nOverflow++;
37165     assert( j<sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0]) );
37166     pPage->aOvfl[j].pCell = pCell;
37167     pPage->aOvfl[j].idx = i;
37168     pPage->nFree = 0;
37169   }else{
37170     int rc = sqlite3PagerWrite(pPage->pDbPage);
37171     if( rc!=SQLITE_OK ){
37172       return rc;
37173     }
37174     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
37175     data = pPage->aData;
37176     hdr = pPage->hdrOffset;
37177     top = get2byte(&data[hdr+5]);
37178     cellOffset = pPage->cellOffset;
37179     end = cellOffset + 2*pPage->nCell + 2;
37180     ins = cellOffset + 2*i;
37181     if( end > top - sz ){
37182       defragmentPage(pPage);
37183       top = get2byte(&data[hdr+5]);
37184       assert( end + sz <= top );
37185     }
37186     idx = allocateSpace(pPage, sz);
37187     assert( idx>0 );
37188     assert( end <= get2byte(&data[hdr+5]) );
37189     pPage->nCell++;
37190     pPage->nFree -= 2;
37191     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
37192     for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
37193       ptr[0] = ptr[-2];
37194       ptr[1] = ptr[-1];
37195     }
37196     put2byte(&data[ins], idx);
37197     put2byte(&data[hdr+3], pPage->nCell);
37198     pPage->idxShift = 1;
37199 #ifndef SQLITE_OMIT_AUTOVACUUM
37200     if( pPage->pBt->autoVacuum ){
37201       /* The cell may contain a pointer to an overflow page. If so, write
37202       ** the entry for the overflow page into the pointer map.
37203       */
37204       CellInfo info;
37205       sqlite3BtreeParseCellPtr(pPage, pCell, &info);
37206       assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
37207       if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
37208         Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
37209         rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
37210         if( rc!=SQLITE_OK ) return rc;
37211       }
37212     }
37213 #endif
37214   }
37215
37216   return SQLITE_OK;
37217 }
37218
37219 /*
37220 ** Add a list of cells to a page.  The page should be initially empty.
37221 ** The cells are guaranteed to fit on the page.
37222 */
37223 static void assemblePage(
37224   MemPage *pPage,   /* The page to be assemblied */
37225   int nCell,        /* The number of cells to add to this page */
37226   u8 **apCell,      /* Pointers to cell bodies */
37227   u16 *aSize        /* Sizes of the cells */
37228 ){
37229   int i;            /* Loop counter */
37230   int totalSize;    /* Total size of all cells */
37231   int hdr;          /* Index of page header */
37232   int cellptr;      /* Address of next cell pointer */
37233   int cellbody;     /* Address of next cell body */
37234   u8 *data;         /* Data for the page */
37235
37236   assert( pPage->nOverflow==0 );
37237   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
37238   totalSize = 0;
37239   for(i=0; i<nCell; i++){
37240     totalSize += aSize[i];
37241   }
37242   assert( totalSize+2*nCell<=pPage->nFree );
37243   assert( pPage->nCell==0 );
37244   cellptr = pPage->cellOffset;
37245   data = pPage->aData;
37246   hdr = pPage->hdrOffset;
37247   put2byte(&data[hdr+3], nCell);
37248   if( nCell ){
37249     cellbody = allocateSpace(pPage, totalSize);
37250     assert( cellbody>0 );
37251     assert( pPage->nFree >= 2*nCell );
37252     pPage->nFree -= 2*nCell;
37253     for(i=0; i<nCell; i++){
37254       put2byte(&data[cellptr], cellbody);
37255       memcpy(&data[cellbody], apCell[i], aSize[i]);
37256       cellptr += 2;
37257       cellbody += aSize[i];
37258     }
37259     assert( cellbody==pPage->pBt->usableSize );
37260   }
37261   pPage->nCell = nCell;
37262 }
37263
37264 /*
37265 ** The following parameters determine how many adjacent pages get involved
37266 ** in a balancing operation.  NN is the number of neighbors on either side
37267 ** of the page that participate in the balancing operation.  NB is the
37268 ** total number of pages that participate, including the target page and
37269 ** NN neighbors on either side.
37270 **
37271 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
37272 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
37273 ** in exchange for a larger degradation in INSERT and UPDATE performance.
37274 ** The value of NN appears to give the best results overall.
37275 */
37276 #define NN 1             /* Number of neighbors on either side of pPage */
37277 #define NB (NN*2+1)      /* Total pages involved in the balance */
37278
37279 /* Forward reference */
37280 static int balance(MemPage*, int);
37281
37282 #ifndef SQLITE_OMIT_QUICKBALANCE
37283 /*
37284 ** This version of balance() handles the common special case where
37285 ** a new entry is being inserted on the extreme right-end of the
37286 ** tree, in other words, when the new entry will become the largest
37287 ** entry in the tree.
37288 **
37289 ** Instead of trying balance the 3 right-most leaf pages, just add
37290 ** a new page to the right-hand side and put the one new entry in
37291 ** that page.  This leaves the right side of the tree somewhat
37292 ** unbalanced.  But odds are that we will be inserting new entries
37293 ** at the end soon afterwards so the nearly empty page will quickly
37294 ** fill up.  On average.
37295 **
37296 ** pPage is the leaf page which is the right-most page in the tree.
37297 ** pParent is its parent.  pPage must have a single overflow entry
37298 ** which is also the right-most entry on the page.
37299 */
37300 static int balance_quick(MemPage *pPage, MemPage *pParent){
37301   int rc;
37302   MemPage *pNew;
37303   Pgno pgnoNew;
37304   u8 *pCell;
37305   u16 szCell;
37306   CellInfo info;
37307   BtShared *pBt = pPage->pBt;
37308   int parentIdx = pParent->nCell;   /* pParent new divider cell index */
37309   int parentSize;                   /* Size of new divider cell */
37310   u8 parentCell[64];                /* Space for the new divider cell */
37311
37312   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
37313
37314   /* Allocate a new page. Insert the overflow cell from pPage
37315   ** into it. Then remove the overflow cell from pPage.
37316   */
37317   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
37318   if( rc!=SQLITE_OK ){
37319     return rc;
37320   }
37321   pCell = pPage->aOvfl[0].pCell;
37322   szCell = cellSizePtr(pPage, pCell);
37323   zeroPage(pNew, pPage->aData[0]);
37324   assemblePage(pNew, 1, &pCell, &szCell);
37325   pPage->nOverflow = 0;
37326
37327   /* Set the parent of the newly allocated page to pParent. */
37328   pNew->pParent = pParent;
37329   sqlite3PagerRef(pParent->pDbPage);
37330
37331   /* pPage is currently the right-child of pParent. Change this
37332   ** so that the right-child is the new page allocated above and
37333   ** pPage is the next-to-right child. 
37334   **
37335   ** Ignore the return value of the call to fillInCell(). fillInCell()
37336   ** may only return other than SQLITE_OK if it is required to allocate
37337   ** one or more overflow pages. Since an internal table B-Tree cell 
37338   ** may never spill over onto an overflow page (it is a maximum of 
37339   ** 13 bytes in size), it is not neccessary to check the return code.
37340   **
37341   ** Similarly, the insertCell() function cannot fail if the page
37342   ** being inserted into is already writable and the cell does not 
37343   ** contain an overflow pointer. So ignore this return code too.
37344   */
37345   assert( pPage->nCell>0 );
37346   pCell = findCell(pPage, pPage->nCell-1);
37347   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
37348   fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, 0, &parentSize);
37349   assert( parentSize<64 );
37350   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
37351   insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4);
37352   put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno);
37353   put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
37354
37355   /* If this is an auto-vacuum database, update the pointer map
37356   ** with entries for the new page, and any pointer from the 
37357   ** cell on the page to an overflow page.
37358   */
37359   if( ISAUTOVACUUM ){
37360     rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
37361     if( rc==SQLITE_OK ){
37362       rc = ptrmapPutOvfl(pNew, 0);
37363     }
37364     if( rc!=SQLITE_OK ){
37365       releasePage(pNew);
37366       return rc;
37367     }
37368   }
37369
37370   /* Release the reference to the new page and balance the parent page,
37371   ** in case the divider cell inserted caused it to become overfull.
37372   */
37373   releasePage(pNew);
37374   return balance(pParent, 0);
37375 }
37376 #endif /* SQLITE_OMIT_QUICKBALANCE */
37377
37378 /*
37379 ** This routine redistributes Cells on pPage and up to NN*2 siblings
37380 ** of pPage so that all pages have about the same amount of free space.
37381 ** Usually NN siblings on either side of pPage is used in the balancing,
37382 ** though more siblings might come from one side if pPage is the first
37383 ** or last child of its parent.  If pPage has fewer than 2*NN siblings
37384 ** (something which can only happen if pPage is the root page or a 
37385 ** child of root) then all available siblings participate in the balancing.
37386 **
37387 ** The number of siblings of pPage might be increased or decreased by one or
37388 ** two in an effort to keep pages nearly full but not over full. The root page
37389 ** is special and is allowed to be nearly empty. If pPage is 
37390 ** the root page, then the depth of the tree might be increased
37391 ** or decreased by one, as necessary, to keep the root page from being
37392 ** overfull or completely empty.
37393 **
37394 ** Note that when this routine is called, some of the Cells on pPage
37395 ** might not actually be stored in pPage->aData[].  This can happen
37396 ** if the page is overfull.  Part of the job of this routine is to
37397 ** make sure all Cells for pPage once again fit in pPage->aData[].
37398 **
37399 ** In the course of balancing the siblings of pPage, the parent of pPage
37400 ** might become overfull or underfull.  If that happens, then this routine
37401 ** is called recursively on the parent.
37402 **
37403 ** If this routine fails for any reason, it might leave the database
37404 ** in a corrupted state.  So if this routine fails, the database should
37405 ** be rolled back.
37406 */
37407 static int balance_nonroot(MemPage *pPage){
37408   MemPage *pParent;            /* The parent of pPage */
37409   BtShared *pBt;               /* The whole database */
37410   int nCell = 0;               /* Number of cells in apCell[] */
37411   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
37412   int nOld;                    /* Number of pages in apOld[] */
37413   int nNew;                    /* Number of pages in apNew[] */
37414   int nDiv;                    /* Number of cells in apDiv[] */
37415   int i, j, k;                 /* Loop counters */
37416   int idx;                     /* Index of pPage in pParent->aCell[] */
37417   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
37418   int rc;                      /* The return code */
37419   int leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
37420   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
37421   int usableSpace;             /* Bytes in pPage beyond the header */
37422   int pageFlags;               /* Value of pPage->aData[0] */
37423   int subtotal;                /* Subtotal of bytes in cells on one page */
37424   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
37425   int iSpace2 = 0;             /* First unused byte of aSpace2[] */
37426   int szScratch;               /* Size of scratch memory requested */
37427   MemPage *apOld[NB];          /* pPage and up to two siblings */
37428   Pgno pgnoOld[NB];            /* Page numbers for each page in apOld[] */
37429   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
37430   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
37431   Pgno pgnoNew[NB+2];          /* Page numbers for each page in apNew[] */
37432   u8 *apDiv[NB];               /* Divider cells in pParent */
37433   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
37434   int szNew[NB+2];             /* Combined size of cells place on i-th page */
37435   u8 **apCell = 0;             /* All cells begin balanced */
37436   u16 *szCell;                 /* Local size of all cells in apCell[] */
37437   u8 *aCopy[NB];         /* Space for holding data of apCopy[] */
37438   u8 *aSpace1;           /* Space for copies of dividers cells before balance */
37439   u8 *aSpace2 = 0;       /* Space for overflow dividers cells after balance */
37440   u8 *aFrom = 0;
37441
37442   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
37443
37444   /* 
37445   ** Find the parent page.
37446   */
37447   assert( pPage->isInit );
37448   assert( sqlite3PagerIswriteable(pPage->pDbPage) || pPage->nOverflow==1 );
37449   pBt = pPage->pBt;
37450   pParent = pPage->pParent;
37451   assert( pParent );
37452   if( SQLITE_OK!=(rc = sqlite3PagerWrite(pParent->pDbPage)) ){
37453     return rc;
37454   }
37455
37456   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
37457
37458 #ifndef SQLITE_OMIT_QUICKBALANCE
37459   /*
37460   ** A special case:  If a new entry has just been inserted into a
37461   ** table (that is, a btree with integer keys and all data at the leaves)
37462   ** and the new entry is the right-most entry in the tree (it has the
37463   ** largest key) then use the special balance_quick() routine for
37464   ** balancing.  balance_quick() is much faster and results in a tighter
37465   ** packing of data in the common case.
37466   */
37467   if( pPage->leaf &&
37468       pPage->intKey &&
37469       pPage->nOverflow==1 &&
37470       pPage->aOvfl[0].idx==pPage->nCell &&
37471       pPage->pParent->pgno!=1 &&
37472       get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno
37473   ){
37474     assert( pPage->intKey );
37475     /*
37476     ** TODO: Check the siblings to the left of pPage. It may be that
37477     ** they are not full and no new page is required.
37478     */
37479     return balance_quick(pPage, pParent);
37480   }
37481 #endif
37482
37483   if( SQLITE_OK!=(rc = sqlite3PagerWrite(pPage->pDbPage)) ){
37484     return rc;
37485   }
37486
37487   /*
37488   ** Find the cell in the parent page whose left child points back
37489   ** to pPage.  The "idx" variable is the index of that cell.  If pPage
37490   ** is the rightmost child of pParent then set idx to pParent->nCell 
37491   */
37492   if( pParent->idxShift ){
37493     Pgno pgno;
37494     pgno = pPage->pgno;
37495     assert( pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
37496     for(idx=0; idx<pParent->nCell; idx++){
37497       if( get4byte(findCell(pParent, idx))==pgno ){
37498         break;
37499       }
37500     }
37501     assert( idx<pParent->nCell
37502              || get4byte(&pParent->aData[pParent->hdrOffset+8])==pgno );
37503   }else{
37504     idx = pPage->idxParent;
37505   }
37506
37507   /*
37508   ** Initialize variables so that it will be safe to jump
37509   ** directly to balance_cleanup at any moment.
37510   */
37511   nOld = nNew = 0;
37512   sqlite3PagerRef(pParent->pDbPage);
37513
37514   /*
37515   ** Find sibling pages to pPage and the cells in pParent that divide
37516   ** the siblings.  An attempt is made to find NN siblings on either
37517   ** side of pPage.  More siblings are taken from one side, however, if
37518   ** pPage there are fewer than NN siblings on the other side.  If pParent
37519   ** has NB or fewer children then all children of pParent are taken.
37520   */
37521   nxDiv = idx - NN;
37522   if( nxDiv + NB > pParent->nCell ){
37523     nxDiv = pParent->nCell - NB + 1;
37524   }
37525   if( nxDiv<0 ){
37526     nxDiv = 0;
37527   }
37528   nDiv = 0;
37529   for(i=0, k=nxDiv; i<NB; i++, k++){
37530     if( k<pParent->nCell ){
37531       apDiv[i] = findCell(pParent, k);
37532       nDiv++;
37533       assert( !pParent->leaf );
37534       pgnoOld[i] = get4byte(apDiv[i]);
37535     }else if( k==pParent->nCell ){
37536       pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
37537     }else{
37538       break;
37539     }
37540     rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i], pParent);
37541     if( rc ) goto balance_cleanup;
37542     apOld[i]->idxParent = k;
37543     apCopy[i] = 0;
37544     assert( i==nOld );
37545     nOld++;
37546     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
37547   }
37548
37549   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
37550   ** alignment */
37551   nMaxCells = (nMaxCells + 3)&~3;
37552
37553   /*
37554   ** Allocate space for memory structures
37555   */
37556   szScratch =
37557        nMaxCells*sizeof(u8*)                       /* apCell */
37558      + nMaxCells*sizeof(u16)                       /* szCell */
37559      + (ROUND8(sizeof(MemPage))+pBt->pageSize)*NB  /* aCopy */
37560      + pBt->pageSize                               /* aSpace1 */
37561      + (ISAUTOVACUUM ? nMaxCells : 0);             /* aFrom */
37562   apCell = sqlite3ScratchMalloc( szScratch ); 
37563   if( apCell==0 ){
37564     rc = SQLITE_NOMEM;
37565     goto balance_cleanup;
37566   }
37567   szCell = (u16*)&apCell[nMaxCells];
37568   aCopy[0] = (u8*)&szCell[nMaxCells];
37569   assert( ((aCopy[0] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
37570   for(i=1; i<NB; i++){
37571     aCopy[i] = &aCopy[i-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
37572     assert( ((aCopy[i] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
37573   }
37574   aSpace1 = &aCopy[NB-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
37575   assert( ((aSpace1 - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
37576   if( ISAUTOVACUUM ){
37577     aFrom = &aSpace1[pBt->pageSize];
37578   }
37579   aSpace2 = sqlite3PageMalloc(pBt->pageSize);
37580   if( aSpace2==0 ){
37581     rc = SQLITE_NOMEM;
37582     goto balance_cleanup;
37583   }
37584   
37585   /*
37586   ** Make copies of the content of pPage and its siblings into aOld[].
37587   ** The rest of this function will use data from the copies rather
37588   ** that the original pages since the original pages will be in the
37589   ** process of being overwritten.
37590   */
37591   for(i=0; i<nOld; i++){
37592     MemPage *p = apCopy[i] = (MemPage*)aCopy[i];
37593     memcpy(p, apOld[i], sizeof(MemPage));
37594     p->aData = (void*)&p[1];
37595     memcpy(p->aData, apOld[i]->aData, pBt->pageSize);
37596   }
37597
37598   /*
37599   ** Load pointers to all cells on sibling pages and the divider cells
37600   ** into the local apCell[] array.  Make copies of the divider cells
37601   ** into space obtained form aSpace1[] and remove the the divider Cells
37602   ** from pParent.
37603   **
37604   ** If the siblings are on leaf pages, then the child pointers of the
37605   ** divider cells are stripped from the cells before they are copied
37606   ** into aSpace1[].  In this way, all cells in apCell[] are without
37607   ** child pointers.  If siblings are not leaves, then all cell in
37608   ** apCell[] include child pointers.  Either way, all cells in apCell[]
37609   ** are alike.
37610   **
37611   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
37612   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
37613   */
37614   nCell = 0;
37615   leafCorrection = pPage->leaf*4;
37616   leafData = pPage->hasData;
37617   for(i=0; i<nOld; i++){
37618     MemPage *pOld = apCopy[i];
37619     int limit = pOld->nCell+pOld->nOverflow;
37620     for(j=0; j<limit; j++){
37621       assert( nCell<nMaxCells );
37622       apCell[nCell] = findOverflowCell(pOld, j);
37623       szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
37624       if( ISAUTOVACUUM ){
37625         int a;
37626         aFrom[nCell] = i;
37627         for(a=0; a<pOld->nOverflow; a++){
37628           if( pOld->aOvfl[a].pCell==apCell[nCell] ){
37629             aFrom[nCell] = 0xFF;
37630             break;
37631           }
37632         }
37633       }
37634       nCell++;
37635     }
37636     if( i<nOld-1 ){
37637       u16 sz = cellSizePtr(pParent, apDiv[i]);
37638       if( leafData ){
37639         /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
37640         ** are duplicates of keys on the child pages.  We need to remove
37641         ** the divider cells from pParent, but the dividers cells are not
37642         ** added to apCell[] because they are duplicates of child cells.
37643         */
37644         dropCell(pParent, nxDiv, sz);
37645       }else{
37646         u8 *pTemp;
37647         assert( nCell<nMaxCells );
37648         szCell[nCell] = sz;
37649         pTemp = &aSpace1[iSpace1];
37650         iSpace1 += sz;
37651         assert( sz<=pBt->pageSize/4 );
37652         assert( iSpace1<=pBt->pageSize );
37653         memcpy(pTemp, apDiv[i], sz);
37654         apCell[nCell] = pTemp+leafCorrection;
37655         if( ISAUTOVACUUM ){
37656           aFrom[nCell] = 0xFF;
37657         }
37658         dropCell(pParent, nxDiv, sz);
37659         szCell[nCell] -= leafCorrection;
37660         assert( get4byte(pTemp)==pgnoOld[i] );
37661         if( !pOld->leaf ){
37662           assert( leafCorrection==0 );
37663           /* The right pointer of the child page pOld becomes the left
37664           ** pointer of the divider cell */
37665           memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
37666         }else{
37667           assert( leafCorrection==4 );
37668           if( szCell[nCell]<4 ){
37669             /* Do not allow any cells smaller than 4 bytes. */
37670             szCell[nCell] = 4;
37671           }
37672         }
37673         nCell++;
37674       }
37675     }
37676   }
37677
37678   /*
37679   ** Figure out the number of pages needed to hold all nCell cells.
37680   ** Store this number in "k".  Also compute szNew[] which is the total
37681   ** size of all cells on the i-th page and cntNew[] which is the index
37682   ** in apCell[] of the cell that divides page i from page i+1.  
37683   ** cntNew[k] should equal nCell.
37684   **
37685   ** Values computed by this block:
37686   **
37687   **           k: The total number of sibling pages
37688   **    szNew[i]: Spaced used on the i-th sibling page.
37689   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
37690   **              the right of the i-th sibling page.
37691   ** usableSpace: Number of bytes of space available on each sibling.
37692   ** 
37693   */
37694   usableSpace = pBt->usableSize - 12 + leafCorrection;
37695   for(subtotal=k=i=0; i<nCell; i++){
37696     assert( i<nMaxCells );
37697     subtotal += szCell[i] + 2;
37698     if( subtotal > usableSpace ){
37699       szNew[k] = subtotal - szCell[i];
37700       cntNew[k] = i;
37701       if( leafData ){ i--; }
37702       subtotal = 0;
37703       k++;
37704     }
37705   }
37706   szNew[k] = subtotal;
37707   cntNew[k] = nCell;
37708   k++;
37709
37710   /*
37711   ** The packing computed by the previous block is biased toward the siblings
37712   ** on the left side.  The left siblings are always nearly full, while the
37713   ** right-most sibling might be nearly empty.  This block of code attempts
37714   ** to adjust the packing of siblings to get a better balance.
37715   **
37716   ** This adjustment is more than an optimization.  The packing above might
37717   ** be so out of balance as to be illegal.  For example, the right-most
37718   ** sibling might be completely empty.  This adjustment is not optional.
37719   */
37720   for(i=k-1; i>0; i--){
37721     int szRight = szNew[i];  /* Size of sibling on the right */
37722     int szLeft = szNew[i-1]; /* Size of sibling on the left */
37723     int r;              /* Index of right-most cell in left sibling */
37724     int d;              /* Index of first cell to the left of right sibling */
37725
37726     r = cntNew[i-1] - 1;
37727     d = r + 1 - leafData;
37728     assert( d<nMaxCells );
37729     assert( r<nMaxCells );
37730     while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
37731       szRight += szCell[d] + 2;
37732       szLeft -= szCell[r] + 2;
37733       cntNew[i-1]--;
37734       r = cntNew[i-1] - 1;
37735       d = r + 1 - leafData;
37736     }
37737     szNew[i] = szRight;
37738     szNew[i-1] = szLeft;
37739   }
37740
37741   /* Either we found one or more cells (cntnew[0])>0) or we are the
37742   ** a virtual root page.  A virtual root page is when the real root
37743   ** page is page 1 and we are the only child of that page.
37744   */
37745   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
37746
37747   /*
37748   ** Allocate k new pages.  Reuse old pages where possible.
37749   */
37750   assert( pPage->pgno>1 );
37751   pageFlags = pPage->aData[0];
37752   for(i=0; i<k; i++){
37753     MemPage *pNew;
37754     if( i<nOld ){
37755       pNew = apNew[i] = apOld[i];
37756       pgnoNew[i] = pgnoOld[i];
37757       apOld[i] = 0;
37758       rc = sqlite3PagerWrite(pNew->pDbPage);
37759       nNew++;
37760       if( rc ) goto balance_cleanup;
37761     }else{
37762       assert( i>0 );
37763       rc = allocateBtreePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0);
37764       if( rc ) goto balance_cleanup;
37765       apNew[i] = pNew;
37766       nNew++;
37767     }
37768   }
37769
37770   /* Free any old pages that were not reused as new pages.
37771   */
37772   while( i<nOld ){
37773     rc = freePage(apOld[i]);
37774     if( rc ) goto balance_cleanup;
37775     releasePage(apOld[i]);
37776     apOld[i] = 0;
37777     i++;
37778   }
37779
37780   /*
37781   ** Put the new pages in accending order.  This helps to
37782   ** keep entries in the disk file in order so that a scan
37783   ** of the table is a linear scan through the file.  That
37784   ** in turn helps the operating system to deliver pages
37785   ** from the disk more rapidly.
37786   **
37787   ** An O(n^2) insertion sort algorithm is used, but since
37788   ** n is never more than NB (a small constant), that should
37789   ** not be a problem.
37790   **
37791   ** When NB==3, this one optimization makes the database
37792   ** about 25% faster for large insertions and deletions.
37793   */
37794   for(i=0; i<k-1; i++){
37795     int minV = pgnoNew[i];
37796     int minI = i;
37797     for(j=i+1; j<k; j++){
37798       if( pgnoNew[j]<(unsigned)minV ){
37799         minI = j;
37800         minV = pgnoNew[j];
37801       }
37802     }
37803     if( minI>i ){
37804       int t;
37805       MemPage *pT;
37806       t = pgnoNew[i];
37807       pT = apNew[i];
37808       pgnoNew[i] = pgnoNew[minI];
37809       apNew[i] = apNew[minI];
37810       pgnoNew[minI] = t;
37811       apNew[minI] = pT;
37812     }
37813   }
37814   TRACE(("BALANCE: old: %d %d %d  new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
37815     pgnoOld[0], 
37816     nOld>=2 ? pgnoOld[1] : 0,
37817     nOld>=3 ? pgnoOld[2] : 0,
37818     pgnoNew[0], szNew[0],
37819     nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
37820     nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
37821     nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
37822     nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
37823
37824   /*
37825   ** Evenly distribute the data in apCell[] across the new pages.
37826   ** Insert divider cells into pParent as necessary.
37827   */
37828   j = 0;
37829   for(i=0; i<nNew; i++){
37830     /* Assemble the new sibling page. */
37831     MemPage *pNew = apNew[i];
37832     assert( j<nMaxCells );
37833     assert( pNew->pgno==pgnoNew[i] );
37834     zeroPage(pNew, pageFlags);
37835     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
37836     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
37837     assert( pNew->nOverflow==0 );
37838
37839     /* If this is an auto-vacuum database, update the pointer map entries
37840     ** that point to the siblings that were rearranged. These can be: left
37841     ** children of cells, the right-child of the page, or overflow pages
37842     ** pointed to by cells.
37843     */
37844     if( ISAUTOVACUUM ){
37845       for(k=j; k<cntNew[i]; k++){
37846         assert( k<nMaxCells );
37847         if( aFrom[k]==0xFF || apCopy[aFrom[k]]->pgno!=pNew->pgno ){
37848           rc = ptrmapPutOvfl(pNew, k-j);
37849           if( rc==SQLITE_OK && leafCorrection==0 ){
37850             rc = ptrmapPut(pBt, get4byte(apCell[k]), PTRMAP_BTREE, pNew->pgno);
37851           }
37852           if( rc!=SQLITE_OK ){
37853             goto balance_cleanup;
37854           }
37855         }
37856       }
37857     }
37858
37859     j = cntNew[i];
37860
37861     /* If the sibling page assembled above was not the right-most sibling,
37862     ** insert a divider cell into the parent page.
37863     */
37864     if( i<nNew-1 && j<nCell ){
37865       u8 *pCell;
37866       u8 *pTemp;
37867       int sz;
37868
37869       assert( j<nMaxCells );
37870       pCell = apCell[j];
37871       sz = szCell[j] + leafCorrection;
37872       pTemp = &aSpace2[iSpace2];
37873       if( !pNew->leaf ){
37874         memcpy(&pNew->aData[8], pCell, 4);
37875         if( ISAUTOVACUUM 
37876          && (aFrom[j]==0xFF || apCopy[aFrom[j]]->pgno!=pNew->pgno)
37877         ){
37878           rc = ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno);
37879           if( rc!=SQLITE_OK ){
37880             goto balance_cleanup;
37881           }
37882         }
37883       }else if( leafData ){
37884         /* If the tree is a leaf-data tree, and the siblings are leaves, 
37885         ** then there is no divider cell in apCell[]. Instead, the divider 
37886         ** cell consists of the integer key for the right-most cell of 
37887         ** the sibling-page assembled above only.
37888         */
37889         CellInfo info;
37890         j--;
37891         sqlite3BtreeParseCellPtr(pNew, apCell[j], &info);
37892         pCell = pTemp;
37893         fillInCell(pParent, pCell, 0, info.nKey, 0, 0, 0, &sz);
37894         pTemp = 0;
37895       }else{
37896         pCell -= 4;
37897         /* Obscure case for non-leaf-data trees: If the cell at pCell was
37898         ** previously stored on a leaf node, and its reported size was 4
37899         ** bytes, then it may actually be smaller than this 
37900         ** (see sqlite3BtreeParseCellPtr(), 4 bytes is the minimum size of
37901         ** any cell). But it is important to pass the correct size to 
37902         ** insertCell(), so reparse the cell now.
37903         **
37904         ** Note that this can never happen in an SQLite data file, as all
37905         ** cells are at least 4 bytes. It only happens in b-trees used
37906         ** to evaluate "IN (SELECT ...)" and similar clauses.
37907         */
37908         if( szCell[j]==4 ){
37909           assert(leafCorrection==4);
37910           sz = cellSizePtr(pParent, pCell);
37911         }
37912       }
37913       iSpace2 += sz;
37914       assert( sz<=pBt->pageSize/4 );
37915       assert( iSpace2<=pBt->pageSize );
37916       rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4);
37917       if( rc!=SQLITE_OK ) goto balance_cleanup;
37918       put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
37919
37920       /* If this is an auto-vacuum database, and not a leaf-data tree,
37921       ** then update the pointer map with an entry for the overflow page
37922       ** that the cell just inserted points to (if any).
37923       */
37924       if( ISAUTOVACUUM && !leafData ){
37925         rc = ptrmapPutOvfl(pParent, nxDiv);
37926         if( rc!=SQLITE_OK ){
37927           goto balance_cleanup;
37928         }
37929       }
37930       j++;
37931       nxDiv++;
37932     }
37933
37934     /* Set the pointer-map entry for the new sibling page. */
37935     if( ISAUTOVACUUM ){
37936       rc = ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno);
37937       if( rc!=SQLITE_OK ){
37938         goto balance_cleanup;
37939       }
37940     }
37941   }
37942   assert( j==nCell );
37943   assert( nOld>0 );
37944   assert( nNew>0 );
37945   if( (pageFlags & PTF_LEAF)==0 ){
37946     u8 *zChild = &apCopy[nOld-1]->aData[8];
37947     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
37948     if( ISAUTOVACUUM ){
37949       rc = ptrmapPut(pBt, get4byte(zChild), PTRMAP_BTREE, apNew[nNew-1]->pgno);
37950       if( rc!=SQLITE_OK ){
37951         goto balance_cleanup;
37952       }
37953     }
37954   }
37955   if( nxDiv==pParent->nCell+pParent->nOverflow ){
37956     /* Right-most sibling is the right-most child of pParent */
37957     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
37958   }else{
37959     /* Right-most sibling is the left child of the first entry in pParent
37960     ** past the right-most divider entry */
37961     put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
37962   }
37963
37964   /*
37965   ** Reparent children of all cells.
37966   */
37967   for(i=0; i<nNew; i++){
37968     rc = reparentChildPages(apNew[i], 0);
37969     if( rc!=SQLITE_OK ) goto balance_cleanup;
37970   }
37971   rc = reparentChildPages(pParent, 0);
37972   if( rc!=SQLITE_OK ) goto balance_cleanup;
37973
37974   /*
37975   ** Balance the parent page.  Note that the current page (pPage) might
37976   ** have been added to the freelist so it might no longer be initialized.
37977   ** But the parent page will always be initialized.
37978   */
37979   assert( pParent->isInit );
37980   sqlite3ScratchFree(apCell);
37981   apCell = 0;
37982   rc = balance(pParent, 0);
37983   
37984   /*
37985   ** Cleanup before returning.
37986   */
37987 balance_cleanup:
37988   sqlite3PageFree(aSpace2);
37989   sqlite3ScratchFree(apCell);
37990   for(i=0; i<nOld; i++){
37991     releasePage(apOld[i]);
37992   }
37993   for(i=0; i<nNew; i++){
37994     releasePage(apNew[i]);
37995   }
37996   releasePage(pParent);
37997   TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
37998           pPage->pgno, nOld, nNew, nCell));
37999   return rc;
38000 }
38001
38002 /*
38003 ** This routine is called for the root page of a btree when the root
38004 ** page contains no cells.  This is an opportunity to make the tree
38005 ** shallower by one level.
38006 */
38007 static int balance_shallower(MemPage *pPage){
38008   MemPage *pChild;             /* The only child page of pPage */
38009   Pgno pgnoChild;              /* Page number for pChild */
38010   int rc = SQLITE_OK;          /* Return code from subprocedures */
38011   BtShared *pBt;                  /* The main BTree structure */
38012   int mxCellPerPage;           /* Maximum number of cells per page */
38013   u8 **apCell;                 /* All cells from pages being balanced */
38014   u16 *szCell;                 /* Local size of all cells */
38015
38016   assert( pPage->pParent==0 );
38017   assert( pPage->nCell==0 );
38018   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38019   pBt = pPage->pBt;
38020   mxCellPerPage = MX_CELL(pBt);
38021   apCell = sqlite3Malloc( mxCellPerPage*(sizeof(u8*)+sizeof(u16)) );
38022   if( apCell==0 ) return SQLITE_NOMEM;
38023   szCell = (u16*)&apCell[mxCellPerPage];
38024   if( pPage->leaf ){
38025     /* The table is completely empty */
38026     TRACE(("BALANCE: empty table %d\n", pPage->pgno));
38027   }else{
38028     /* The root page is empty but has one child.  Transfer the
38029     ** information from that one child into the root page if it 
38030     ** will fit.  This reduces the depth of the tree by one.
38031     **
38032     ** If the root page is page 1, it has less space available than
38033     ** its child (due to the 100 byte header that occurs at the beginning
38034     ** of the database fle), so it might not be able to hold all of the 
38035     ** information currently contained in the child.  If this is the 
38036     ** case, then do not do the transfer.  Leave page 1 empty except
38037     ** for the right-pointer to the child page.  The child page becomes
38038     ** the virtual root of the tree.
38039     */
38040     pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
38041     assert( pgnoChild>0 );
38042     assert( pgnoChild<=pagerPagecount(pPage->pBt->pPager) );
38043     rc = sqlite3BtreeGetPage(pPage->pBt, pgnoChild, &pChild, 0);
38044     if( rc ) goto end_shallow_balance;
38045     if( pPage->pgno==1 ){
38046       rc = sqlite3BtreeInitPage(pChild, pPage);
38047       if( rc ) goto end_shallow_balance;
38048       assert( pChild->nOverflow==0 );
38049       if( pChild->nFree>=100 ){
38050         /* The child information will fit on the root page, so do the
38051         ** copy */
38052         int i;
38053         zeroPage(pPage, pChild->aData[0]);
38054         for(i=0; i<pChild->nCell; i++){
38055           apCell[i] = findCell(pChild,i);
38056           szCell[i] = cellSizePtr(pChild, apCell[i]);
38057         }
38058         assemblePage(pPage, pChild->nCell, apCell, szCell);
38059         /* Copy the right-pointer of the child to the parent. */
38060         put4byte(&pPage->aData[pPage->hdrOffset+8], 
38061             get4byte(&pChild->aData[pChild->hdrOffset+8]));
38062         freePage(pChild);
38063         TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
38064       }else{
38065         /* The child has more information that will fit on the root.
38066         ** The tree is already balanced.  Do nothing. */
38067         TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
38068       }
38069     }else{
38070       memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
38071       pPage->isInit = 0;
38072       pPage->pParent = 0;
38073       rc = sqlite3BtreeInitPage(pPage, 0);
38074       assert( rc==SQLITE_OK );
38075       freePage(pChild);
38076       TRACE(("BALANCE: transfer child %d into root %d\n",
38077               pChild->pgno, pPage->pgno));
38078     }
38079     rc = reparentChildPages(pPage, 1);
38080     assert( pPage->nOverflow==0 );
38081     if( ISAUTOVACUUM ){
38082       int i;
38083       for(i=0; i<pPage->nCell; i++){ 
38084         rc = ptrmapPutOvfl(pPage, i);
38085         if( rc!=SQLITE_OK ){
38086           goto end_shallow_balance;
38087         }
38088       }
38089     }
38090     releasePage(pChild);
38091   }
38092 end_shallow_balance:
38093   sqlite3_free(apCell);
38094   return rc;
38095 }
38096
38097
38098 /*
38099 ** The root page is overfull
38100 **
38101 ** When this happens, Create a new child page and copy the
38102 ** contents of the root into the child.  Then make the root
38103 ** page an empty page with rightChild pointing to the new
38104 ** child.   Finally, call balance_internal() on the new child
38105 ** to cause it to split.
38106 */
38107 static int balance_deeper(MemPage *pPage){
38108   int rc;             /* Return value from subprocedures */
38109   MemPage *pChild;    /* Pointer to a new child page */
38110   Pgno pgnoChild;     /* Page number of the new child page */
38111   BtShared *pBt;         /* The BTree */
38112   int usableSize;     /* Total usable size of a page */
38113   u8 *data;           /* Content of the parent page */
38114   u8 *cdata;          /* Content of the child page */
38115   int hdr;            /* Offset to page header in parent */
38116   int brk;            /* Offset to content of first cell in parent */
38117
38118   assert( pPage->pParent==0 );
38119   assert( pPage->nOverflow>0 );
38120   pBt = pPage->pBt;
38121   assert( sqlite3_mutex_held(pBt->mutex) );
38122   rc = allocateBtreePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0);
38123   if( rc ) return rc;
38124   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
38125   usableSize = pBt->usableSize;
38126   data = pPage->aData;
38127   hdr = pPage->hdrOffset;
38128   brk = get2byte(&data[hdr+5]);
38129   cdata = pChild->aData;
38130   memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
38131   memcpy(&cdata[brk], &data[brk], usableSize-brk);
38132   if( pChild->isInit ) return SQLITE_CORRUPT;
38133   rc = sqlite3BtreeInitPage(pChild, pPage);
38134   if( rc ) goto balancedeeper_out;
38135   memcpy(pChild->aOvfl, pPage->aOvfl, pPage->nOverflow*sizeof(pPage->aOvfl[0]));
38136   pChild->nOverflow = pPage->nOverflow;
38137   if( pChild->nOverflow ){
38138     pChild->nFree = 0;
38139   }
38140   assert( pChild->nCell==pPage->nCell );
38141   zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
38142   put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
38143   TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
38144   if( ISAUTOVACUUM ){
38145     int i;
38146     rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno);
38147     if( rc ) goto balancedeeper_out;
38148     for(i=0; i<pChild->nCell; i++){
38149       rc = ptrmapPutOvfl(pChild, i);
38150       if( rc!=SQLITE_OK ){
38151         goto balancedeeper_out;
38152       }
38153     }
38154     rc = reparentChildPages(pChild, 1);
38155   }
38156   if( rc==SQLITE_OK ){
38157     rc = balance_nonroot(pChild);
38158   }
38159
38160 balancedeeper_out:
38161   releasePage(pChild);
38162   return rc;
38163 }
38164
38165 /*
38166 ** Decide if the page pPage needs to be balanced.  If balancing is
38167 ** required, call the appropriate balancing routine.
38168 */
38169 static int balance(MemPage *pPage, int insert){
38170   int rc = SQLITE_OK;
38171   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38172   if( pPage->pParent==0 ){
38173     rc = sqlite3PagerWrite(pPage->pDbPage);
38174     if( rc==SQLITE_OK && pPage->nOverflow>0 ){
38175       rc = balance_deeper(pPage);
38176     }
38177     if( rc==SQLITE_OK && pPage->nCell==0 ){
38178       rc = balance_shallower(pPage);
38179     }
38180   }else{
38181     if( pPage->nOverflow>0 || 
38182         (!insert && pPage->nFree>pPage->pBt->usableSize*2/3) ){
38183       rc = balance_nonroot(pPage);
38184     }
38185   }
38186   return rc;
38187 }
38188
38189 /*
38190 ** This routine checks all cursors that point to table pgnoRoot.
38191 ** If any of those cursors were opened with wrFlag==0 in a different
38192 ** database connection (a database connection that shares the pager
38193 ** cache with the current connection) and that other connection 
38194 ** is not in the ReadUncommmitted state, then this routine returns 
38195 ** SQLITE_LOCKED.
38196 **
38197 ** As well as cursors with wrFlag==0, cursors with wrFlag==1 and 
38198 ** isIncrblobHandle==1 are also considered 'read' cursors. Incremental 
38199 ** blob cursors are used for both reading and writing.
38200 **
38201 ** When pgnoRoot is the root page of an intkey table, this function is also
38202 ** responsible for invalidating incremental blob cursors when the table row
38203 ** on which they are opened is deleted or modified. Cursors are invalidated
38204 ** according to the following rules:
38205 **
38206 **   1) When BtreeClearTable() is called to completely delete the contents
38207 **      of a B-Tree table, pExclude is set to zero and parameter iRow is 
38208 **      set to non-zero. In this case all incremental blob cursors open
38209 **      on the table rooted at pgnoRoot are invalidated.
38210 **
38211 **   2) When BtreeInsert(), BtreeDelete() or BtreePutData() is called to 
38212 **      modify a table row via an SQL statement, pExclude is set to the 
38213 **      write cursor used to do the modification and parameter iRow is set
38214 **      to the integer row id of the B-Tree entry being modified. Unless
38215 **      pExclude is itself an incremental blob cursor, then all incremental
38216 **      blob cursors open on row iRow of the B-Tree are invalidated.
38217 **
38218 **   3) If both pExclude and iRow are set to zero, no incremental blob 
38219 **      cursors are invalidated.
38220 */
38221 static int checkReadLocks(
38222   Btree *pBtree, 
38223   Pgno pgnoRoot, 
38224   BtCursor *pExclude,
38225   i64 iRow
38226 ){
38227   BtCursor *p;
38228   BtShared *pBt = pBtree->pBt;
38229   sqlite3 *db = pBtree->db;
38230   assert( sqlite3BtreeHoldsMutex(pBtree) );
38231   for(p=pBt->pCursor; p; p=p->pNext){
38232     if( p==pExclude ) continue;
38233     if( p->pgnoRoot!=pgnoRoot ) continue;
38234 #ifndef SQLITE_OMIT_INCRBLOB
38235     if( p->isIncrblobHandle && ( 
38236          (!pExclude && iRow)
38237       || (pExclude && !pExclude->isIncrblobHandle && p->info.nKey==iRow)
38238     )){
38239       p->eState = CURSOR_INVALID;
38240     }
38241 #endif
38242     if( p->eState!=CURSOR_VALID ) continue;
38243     if( p->wrFlag==0 
38244 #ifndef SQLITE_OMIT_INCRBLOB
38245      || p->isIncrblobHandle
38246 #endif
38247     ){
38248       sqlite3 *dbOther = p->pBtree->db;
38249       if( dbOther==0 ||
38250          (dbOther!=db && (dbOther->flags & SQLITE_ReadUncommitted)==0) ){
38251         return SQLITE_LOCKED;
38252       }
38253     }
38254   }
38255   return SQLITE_OK;
38256 }
38257
38258 /*
38259 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
38260 ** and the data is given by (pData,nData).  The cursor is used only to
38261 ** define what table the record should be inserted into.  The cursor
38262 ** is left pointing at a random location.
38263 **
38264 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
38265 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
38266 */
38267 SQLITE_PRIVATE int sqlite3BtreeInsert(
38268   BtCursor *pCur,                /* Insert data into the table of this cursor */
38269   const void *pKey, i64 nKey,    /* The key of the new record */
38270   const void *pData, int nData,  /* The data of the new record */
38271   int nZero,                     /* Number of extra 0 bytes to append to data */
38272   int appendBias                 /* True if this is likely an append */
38273 ){
38274   int rc;
38275   int loc;
38276   int szNew;
38277   MemPage *pPage;
38278   Btree *p = pCur->pBtree;
38279   BtShared *pBt = p->pBt;
38280   unsigned char *oldCell;
38281   unsigned char *newCell = 0;
38282
38283   assert( cursorHoldsMutex(pCur) );
38284   if( pBt->inTransaction!=TRANS_WRITE ){
38285     /* Must start a transaction before doing an insert */
38286     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
38287     return rc;
38288   }
38289   assert( !pBt->readOnly );
38290   if( !pCur->wrFlag ){
38291     return SQLITE_PERM;   /* Cursor not open for writing */
38292   }
38293   if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur, nKey) ){
38294     return SQLITE_LOCKED; /* The table pCur points to has a read lock */
38295   }
38296   if( pCur->eState==CURSOR_FAULT ){
38297     return pCur->skip;
38298   }
38299
38300   /* Save the positions of any other cursors open on this table */
38301   clearCursorPosition(pCur);
38302   if( 
38303     SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
38304     SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, 0, nKey, appendBias, &loc))
38305   ){
38306     return rc;
38307   }
38308
38309   pPage = pCur->pPage;
38310   assert( pPage->intKey || nKey>=0 );
38311   assert( pPage->leaf || !pPage->intKey );
38312   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
38313           pCur->pgnoRoot, nKey, nData, pPage->pgno,
38314           loc==0 ? "overwrite" : "new entry"));
38315   assert( pPage->isInit );
38316   allocateTempSpace(pBt);
38317   newCell = pBt->pTmpSpace;
38318   if( newCell==0 ) return SQLITE_NOMEM;
38319   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
38320   if( rc ) goto end_insert;
38321   assert( szNew==cellSizePtr(pPage, newCell) );
38322   assert( szNew<=MX_CELL_SIZE(pBt) );
38323   if( loc==0 && CURSOR_VALID==pCur->eState ){
38324     u16 szOld;
38325     assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
38326     rc = sqlite3PagerWrite(pPage->pDbPage);
38327     if( rc ){
38328       goto end_insert;
38329     }
38330     oldCell = findCell(pPage, pCur->idx);
38331     if( !pPage->leaf ){
38332       memcpy(newCell, oldCell, 4);
38333     }
38334     szOld = cellSizePtr(pPage, oldCell);
38335     rc = clearCell(pPage, oldCell);
38336     if( rc ) goto end_insert;
38337     dropCell(pPage, pCur->idx, szOld);
38338   }else if( loc<0 && pPage->nCell>0 ){
38339     assert( pPage->leaf );
38340     pCur->idx++;
38341     pCur->info.nSize = 0;
38342     pCur->validNKey = 0;
38343   }else{
38344     assert( pPage->leaf );
38345   }
38346   rc = insertCell(pPage, pCur->idx, newCell, szNew, 0, 0);
38347   if( rc!=SQLITE_OK ) goto end_insert;
38348   rc = balance(pPage, 1);
38349   if( rc==SQLITE_OK ){
38350     moveToRoot(pCur);
38351   }
38352 end_insert:
38353   return rc;
38354 }
38355
38356 /*
38357 ** Delete the entry that the cursor is pointing to.  The cursor
38358 ** is left pointing at a random location.
38359 */
38360 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
38361   MemPage *pPage = pCur->pPage;
38362   unsigned char *pCell;
38363   int rc;
38364   Pgno pgnoChild = 0;
38365   Btree *p = pCur->pBtree;
38366   BtShared *pBt = p->pBt;
38367
38368   assert( cursorHoldsMutex(pCur) );
38369   assert( pPage->isInit );
38370   if( pBt->inTransaction!=TRANS_WRITE ){
38371     /* Must start a transaction before doing a delete */
38372     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
38373     return rc;
38374   }
38375   assert( !pBt->readOnly );
38376   if( pCur->eState==CURSOR_FAULT ){
38377     return pCur->skip;
38378   }
38379   if( pCur->idx >= pPage->nCell ){
38380     return SQLITE_ERROR;  /* The cursor is not pointing to anything */
38381   }
38382   if( !pCur->wrFlag ){
38383     return SQLITE_PERM;   /* Did not open this cursor for writing */
38384   }
38385   if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur, pCur->info.nKey) ){
38386     return SQLITE_LOCKED; /* The table pCur points to has a read lock */
38387   }
38388
38389   /* Restore the current cursor position (a no-op if the cursor is not in 
38390   ** CURSOR_REQUIRESEEK state) and save the positions of any other cursors 
38391   ** open on the same table. Then call sqlite3PagerWrite() on the page
38392   ** that the entry will be deleted from.
38393   */
38394   if( 
38395     (rc = restoreCursorPosition(pCur))!=0 ||
38396     (rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur))!=0 ||
38397     (rc = sqlite3PagerWrite(pPage->pDbPage))!=0
38398   ){
38399     return rc;
38400   }
38401
38402   /* Locate the cell within its page and leave pCell pointing to the
38403   ** data. The clearCell() call frees any overflow pages associated with the
38404   ** cell. The cell itself is still intact.
38405   */
38406   pCell = findCell(pPage, pCur->idx);
38407   if( !pPage->leaf ){
38408     pgnoChild = get4byte(pCell);
38409   }
38410   rc = clearCell(pPage, pCell);
38411   if( rc ){
38412     return rc;
38413   }
38414
38415   if( !pPage->leaf ){
38416     /*
38417     ** The entry we are about to delete is not a leaf so if we do not
38418     ** do something we will leave a hole on an internal page.
38419     ** We have to fill the hole by moving in a cell from a leaf.  The
38420     ** next Cell after the one to be deleted is guaranteed to exist and
38421     ** to be a leaf so we can use it.
38422     */
38423     BtCursor leafCur;
38424     unsigned char *pNext;
38425     int notUsed;
38426     unsigned char *tempCell = 0;
38427     assert( !pPage->intKey );
38428     sqlite3BtreeGetTempCursor(pCur, &leafCur);
38429     rc = sqlite3BtreeNext(&leafCur, &notUsed);
38430     if( rc==SQLITE_OK ){
38431       rc = sqlite3PagerWrite(leafCur.pPage->pDbPage);
38432     }
38433     if( rc==SQLITE_OK ){
38434       u16 szNext;
38435       TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
38436          pCur->pgnoRoot, pPage->pgno, leafCur.pPage->pgno));
38437       dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
38438       pNext = findCell(leafCur.pPage, leafCur.idx);
38439       szNext = cellSizePtr(leafCur.pPage, pNext);
38440       assert( MX_CELL_SIZE(pBt)>=szNext+4 );
38441       allocateTempSpace(pBt);
38442       tempCell = pBt->pTmpSpace;
38443       if( tempCell==0 ){
38444         rc = SQLITE_NOMEM;
38445       }
38446       if( rc==SQLITE_OK ){
38447         rc = insertCell(pPage, pCur->idx, pNext-4, szNext+4, tempCell, 0);
38448       }
38449       if( rc==SQLITE_OK ){
38450         put4byte(findOverflowCell(pPage, pCur->idx), pgnoChild);
38451         rc = balance(pPage, 0);
38452       }
38453       if( rc==SQLITE_OK ){
38454         dropCell(leafCur.pPage, leafCur.idx, szNext);
38455         rc = balance(leafCur.pPage, 0);
38456       }
38457     }
38458     sqlite3BtreeReleaseTempCursor(&leafCur);
38459   }else{
38460     TRACE(("DELETE: table=%d delete from leaf %d\n",
38461        pCur->pgnoRoot, pPage->pgno));
38462     dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
38463     rc = balance(pPage, 0);
38464   }
38465   if( rc==SQLITE_OK ){
38466     moveToRoot(pCur);
38467   }
38468   return rc;
38469 }
38470
38471 /*
38472 ** Create a new BTree table.  Write into *piTable the page
38473 ** number for the root page of the new table.
38474 **
38475 ** The type of type is determined by the flags parameter.  Only the
38476 ** following values of flags are currently in use.  Other values for
38477 ** flags might not work:
38478 **
38479 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
38480 **     BTREE_ZERODATA                  Used for SQL indices
38481 */
38482 static int btreeCreateTable(Btree *p, int *piTable, int flags){
38483   BtShared *pBt = p->pBt;
38484   MemPage *pRoot;
38485   Pgno pgnoRoot;
38486   int rc;
38487
38488   assert( sqlite3BtreeHoldsMutex(p) );
38489   if( pBt->inTransaction!=TRANS_WRITE ){
38490     /* Must start a transaction first */
38491     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
38492     return rc;
38493   }
38494   assert( !pBt->readOnly );
38495
38496 #ifdef SQLITE_OMIT_AUTOVACUUM
38497   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
38498   if( rc ){
38499     return rc;
38500   }
38501 #else
38502   if( pBt->autoVacuum ){
38503     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
38504     MemPage *pPageMove; /* The page to move to. */
38505
38506     /* Creating a new table may probably require moving an existing database
38507     ** to make room for the new tables root page. In case this page turns
38508     ** out to be an overflow page, delete all overflow page-map caches
38509     ** held by open cursors.
38510     */
38511     invalidateAllOverflowCache(pBt);
38512
38513     /* Read the value of meta[3] from the database to determine where the
38514     ** root page of the new table should go. meta[3] is the largest root-page
38515     ** created so far, so the new root-page is (meta[3]+1).
38516     */
38517     rc = sqlite3BtreeGetMeta(p, 4, &pgnoRoot);
38518     if( rc!=SQLITE_OK ){
38519       return rc;
38520     }
38521     pgnoRoot++;
38522
38523     /* The new root-page may not be allocated on a pointer-map page, or the
38524     ** PENDING_BYTE page.
38525     */
38526     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
38527         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
38528       pgnoRoot++;
38529     }
38530     assert( pgnoRoot>=3 );
38531
38532     /* Allocate a page. The page that currently resides at pgnoRoot will
38533     ** be moved to the allocated page (unless the allocated page happens
38534     ** to reside at pgnoRoot).
38535     */
38536     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
38537     if( rc!=SQLITE_OK ){
38538       return rc;
38539     }
38540
38541     if( pgnoMove!=pgnoRoot ){
38542       /* pgnoRoot is the page that will be used for the root-page of
38543       ** the new table (assuming an error did not occur). But we were
38544       ** allocated pgnoMove. If required (i.e. if it was not allocated
38545       ** by extending the file), the current page at position pgnoMove
38546       ** is already journaled.
38547       */
38548       u8 eType;
38549       Pgno iPtrPage;
38550
38551       releasePage(pPageMove);
38552
38553       /* Move the page currently at pgnoRoot to pgnoMove. */
38554       rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
38555       if( rc!=SQLITE_OK ){
38556         return rc;
38557       }
38558       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
38559       if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
38560         releasePage(pRoot);
38561         return rc;
38562       }
38563       assert( eType!=PTRMAP_ROOTPAGE );
38564       assert( eType!=PTRMAP_FREEPAGE );
38565       rc = sqlite3PagerWrite(pRoot->pDbPage);
38566       if( rc!=SQLITE_OK ){
38567         releasePage(pRoot);
38568         return rc;
38569       }
38570       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
38571       releasePage(pRoot);
38572
38573       /* Obtain the page at pgnoRoot */
38574       if( rc!=SQLITE_OK ){
38575         return rc;
38576       }
38577       rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
38578       if( rc!=SQLITE_OK ){
38579         return rc;
38580       }
38581       rc = sqlite3PagerWrite(pRoot->pDbPage);
38582       if( rc!=SQLITE_OK ){
38583         releasePage(pRoot);
38584         return rc;
38585       }
38586     }else{
38587       pRoot = pPageMove;
38588     } 
38589
38590     /* Update the pointer-map and meta-data with the new root-page number. */
38591     rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
38592     if( rc ){
38593       releasePage(pRoot);
38594       return rc;
38595     }
38596     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
38597     if( rc ){
38598       releasePage(pRoot);
38599       return rc;
38600     }
38601
38602   }else{
38603     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
38604     if( rc ) return rc;
38605   }
38606 #endif
38607   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
38608   zeroPage(pRoot, flags | PTF_LEAF);
38609   sqlite3PagerUnref(pRoot->pDbPage);
38610   *piTable = (int)pgnoRoot;
38611   return SQLITE_OK;
38612 }
38613 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
38614   int rc;
38615   sqlite3BtreeEnter(p);
38616   p->pBt->db = p->db;
38617   rc = btreeCreateTable(p, piTable, flags);
38618   sqlite3BtreeLeave(p);
38619   return rc;
38620 }
38621
38622 /*
38623 ** Erase the given database page and all its children.  Return
38624 ** the page to the freelist.
38625 */
38626 static int clearDatabasePage(
38627   BtShared *pBt,           /* The BTree that contains the table */
38628   Pgno pgno,            /* Page number to clear */
38629   MemPage *pParent,     /* Parent page.  NULL for the root */
38630   int freePageFlag      /* Deallocate page if true */
38631 ){
38632   MemPage *pPage = 0;
38633   int rc;
38634   unsigned char *pCell;
38635   int i;
38636
38637   assert( sqlite3_mutex_held(pBt->mutex) );
38638   if( pgno>pagerPagecount(pBt->pPager) ){
38639     return SQLITE_CORRUPT_BKPT;
38640   }
38641
38642   rc = getAndInitPage(pBt, pgno, &pPage, pParent);
38643   if( rc ) goto cleardatabasepage_out;
38644   for(i=0; i<pPage->nCell; i++){
38645     pCell = findCell(pPage, i);
38646     if( !pPage->leaf ){
38647       rc = clearDatabasePage(pBt, get4byte(pCell), pPage->pParent, 1);
38648       if( rc ) goto cleardatabasepage_out;
38649     }
38650     rc = clearCell(pPage, pCell);
38651     if( rc ) goto cleardatabasepage_out;
38652   }
38653   if( !pPage->leaf ){
38654     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), pPage->pParent, 1);
38655     if( rc ) goto cleardatabasepage_out;
38656   }
38657   if( freePageFlag ){
38658     rc = freePage(pPage);
38659   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
38660     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
38661   }
38662
38663 cleardatabasepage_out:
38664   releasePage(pPage);
38665   return rc;
38666 }
38667
38668 /*
38669 ** Delete all information from a single table in the database.  iTable is
38670 ** the page number of the root of the table.  After this routine returns,
38671 ** the root page is empty, but still exists.
38672 **
38673 ** This routine will fail with SQLITE_LOCKED if there are any open
38674 ** read cursors on the table.  Open write cursors are moved to the
38675 ** root of the table.
38676 */
38677 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable){
38678   int rc;
38679   BtShared *pBt = p->pBt;
38680   sqlite3BtreeEnter(p);
38681   pBt->db = p->db;
38682   if( p->inTrans!=TRANS_WRITE ){
38683     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
38684   }else if( (rc = checkReadLocks(p, iTable, 0, 1))!=SQLITE_OK ){
38685     /* nothing to do */
38686   }else if( SQLITE_OK!=(rc = saveAllCursors(pBt, iTable, 0)) ){
38687     /* nothing to do */
38688   }else{
38689     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, 0);
38690   }
38691   sqlite3BtreeLeave(p);
38692   return rc;
38693 }
38694
38695 /*
38696 ** Erase all information in a table and add the root of the table to
38697 ** the freelist.  Except, the root of the principle table (the one on
38698 ** page 1) is never added to the freelist.
38699 **
38700 ** This routine will fail with SQLITE_LOCKED if there are any open
38701 ** cursors on the table.
38702 **
38703 ** If AUTOVACUUM is enabled and the page at iTable is not the last
38704 ** root page in the database file, then the last root page 
38705 ** in the database file is moved into the slot formerly occupied by
38706 ** iTable and that last slot formerly occupied by the last root page
38707 ** is added to the freelist instead of iTable.  In this say, all
38708 ** root pages are kept at the beginning of the database file, which
38709 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
38710 ** page number that used to be the last root page in the file before
38711 ** the move.  If no page gets moved, *piMoved is set to 0.
38712 ** The last root page is recorded in meta[3] and the value of
38713 ** meta[3] is updated by this procedure.
38714 */
38715 static int btreeDropTable(Btree *p, int iTable, int *piMoved){
38716   int rc;
38717   MemPage *pPage = 0;
38718   BtShared *pBt = p->pBt;
38719
38720   assert( sqlite3BtreeHoldsMutex(p) );
38721   if( p->inTrans!=TRANS_WRITE ){
38722     return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
38723   }
38724
38725   /* It is illegal to drop a table if any cursors are open on the
38726   ** database. This is because in auto-vacuum mode the backend may
38727   ** need to move another root-page to fill a gap left by the deleted
38728   ** root page. If an open cursor was using this page a problem would 
38729   ** occur.
38730   */
38731   if( pBt->pCursor ){
38732     return SQLITE_LOCKED;
38733   }
38734
38735   rc = sqlite3BtreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
38736   if( rc ) return rc;
38737   rc = sqlite3BtreeClearTable(p, iTable);
38738   if( rc ){
38739     releasePage(pPage);
38740     return rc;
38741   }
38742
38743   *piMoved = 0;
38744
38745   if( iTable>1 ){
38746 #ifdef SQLITE_OMIT_AUTOVACUUM
38747     rc = freePage(pPage);
38748     releasePage(pPage);
38749 #else
38750     if( pBt->autoVacuum ){
38751       Pgno maxRootPgno;
38752       rc = sqlite3BtreeGetMeta(p, 4, &maxRootPgno);
38753       if( rc!=SQLITE_OK ){
38754         releasePage(pPage);
38755         return rc;
38756       }
38757
38758       if( iTable==maxRootPgno ){
38759         /* If the table being dropped is the table with the largest root-page
38760         ** number in the database, put the root page on the free list. 
38761         */
38762         rc = freePage(pPage);
38763         releasePage(pPage);
38764         if( rc!=SQLITE_OK ){
38765           return rc;
38766         }
38767       }else{
38768         /* The table being dropped does not have the largest root-page
38769         ** number in the database. So move the page that does into the 
38770         ** gap left by the deleted root-page.
38771         */
38772         MemPage *pMove;
38773         releasePage(pPage);
38774         rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
38775         if( rc!=SQLITE_OK ){
38776           return rc;
38777         }
38778         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
38779         releasePage(pMove);
38780         if( rc!=SQLITE_OK ){
38781           return rc;
38782         }
38783         rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
38784         if( rc!=SQLITE_OK ){
38785           return rc;
38786         }
38787         rc = freePage(pMove);
38788         releasePage(pMove);
38789         if( rc!=SQLITE_OK ){
38790           return rc;
38791         }
38792         *piMoved = maxRootPgno;
38793       }
38794
38795       /* Set the new 'max-root-page' value in the database header. This
38796       ** is the old value less one, less one more if that happens to
38797       ** be a root-page number, less one again if that is the
38798       ** PENDING_BYTE_PAGE.
38799       */
38800       maxRootPgno--;
38801       if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
38802         maxRootPgno--;
38803       }
38804       if( maxRootPgno==PTRMAP_PAGENO(pBt, maxRootPgno) ){
38805         maxRootPgno--;
38806       }
38807       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
38808
38809       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
38810     }else{
38811       rc = freePage(pPage);
38812       releasePage(pPage);
38813     }
38814 #endif
38815   }else{
38816     /* If sqlite3BtreeDropTable was called on page 1. */
38817     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
38818     releasePage(pPage);
38819   }
38820   return rc;  
38821 }
38822 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
38823   int rc;
38824   sqlite3BtreeEnter(p);
38825   p->pBt->db = p->db;
38826   rc = btreeDropTable(p, iTable, piMoved);
38827   sqlite3BtreeLeave(p);
38828   return rc;
38829 }
38830
38831
38832 /*
38833 ** Read the meta-information out of a database file.  Meta[0]
38834 ** is the number of free pages currently in the database.  Meta[1]
38835 ** through meta[15] are available for use by higher layers.  Meta[0]
38836 ** is read-only, the others are read/write.
38837 ** 
38838 ** The schema layer numbers meta values differently.  At the schema
38839 ** layer (and the SetCookie and ReadCookie opcodes) the number of
38840 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
38841 */
38842 SQLITE_PRIVATE int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
38843   DbPage *pDbPage;
38844   int rc;
38845   unsigned char *pP1;
38846   BtShared *pBt = p->pBt;
38847
38848   sqlite3BtreeEnter(p);
38849   pBt->db = p->db;
38850
38851   /* Reading a meta-data value requires a read-lock on page 1 (and hence
38852   ** the sqlite_master table. We grab this lock regardless of whether or
38853   ** not the SQLITE_ReadUncommitted flag is set (the table rooted at page
38854   ** 1 is treated as a special case by queryTableLock() and lockTable()).
38855   */
38856   rc = queryTableLock(p, 1, READ_LOCK);
38857   if( rc!=SQLITE_OK ){
38858     sqlite3BtreeLeave(p);
38859     return rc;
38860   }
38861
38862   assert( idx>=0 && idx<=15 );
38863   rc = sqlite3PagerGet(pBt->pPager, 1, &pDbPage);
38864   if( rc ){
38865     sqlite3BtreeLeave(p);
38866     return rc;
38867   }
38868   pP1 = (unsigned char *)sqlite3PagerGetData(pDbPage);
38869   *pMeta = get4byte(&pP1[36 + idx*4]);
38870   sqlite3PagerUnref(pDbPage);
38871
38872   /* If autovacuumed is disabled in this build but we are trying to 
38873   ** access an autovacuumed database, then make the database readonly. 
38874   */
38875 #ifdef SQLITE_OMIT_AUTOVACUUM
38876   if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
38877 #endif
38878
38879   /* Grab the read-lock on page 1. */
38880   rc = lockTable(p, 1, READ_LOCK);
38881   sqlite3BtreeLeave(p);
38882   return rc;
38883 }
38884
38885 /*
38886 ** Write meta-information back into the database.  Meta[0] is
38887 ** read-only and may not be written.
38888 */
38889 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
38890   BtShared *pBt = p->pBt;
38891   unsigned char *pP1;
38892   int rc;
38893   assert( idx>=1 && idx<=15 );
38894   sqlite3BtreeEnter(p);
38895   pBt->db = p->db;
38896   if( p->inTrans!=TRANS_WRITE ){
38897     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
38898   }else{
38899     assert( pBt->pPage1!=0 );
38900     pP1 = pBt->pPage1->aData;
38901     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
38902     if( rc==SQLITE_OK ){
38903       put4byte(&pP1[36 + idx*4], iMeta);
38904 #ifndef SQLITE_OMIT_AUTOVACUUM
38905       if( idx==7 ){
38906         assert( pBt->autoVacuum || iMeta==0 );
38907         assert( iMeta==0 || iMeta==1 );
38908         pBt->incrVacuum = iMeta;
38909       }
38910 #endif
38911     }
38912   }
38913   sqlite3BtreeLeave(p);
38914   return rc;
38915 }
38916
38917 /*
38918 ** Return the flag byte at the beginning of the page that the cursor
38919 ** is currently pointing to.
38920 */
38921 SQLITE_PRIVATE int sqlite3BtreeFlags(BtCursor *pCur){
38922   /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call
38923   ** restoreCursorPosition() here.
38924   */
38925   MemPage *pPage;
38926   restoreCursorPosition(pCur);
38927   pPage = pCur->pPage;
38928   assert( cursorHoldsMutex(pCur) );
38929   assert( pPage->pBt==pCur->pBt );
38930   return pPage ? pPage->aData[pPage->hdrOffset] : 0;
38931 }
38932
38933
38934 /*
38935 ** Return the pager associated with a BTree.  This routine is used for
38936 ** testing and debugging only.
38937 */
38938 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
38939   return p->pBt->pPager;
38940 }
38941
38942 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
38943 /*
38944 ** Append a message to the error message string.
38945 */
38946 static void checkAppendMsg(
38947   IntegrityCk *pCheck,
38948   char *zMsg1,
38949   const char *zFormat,
38950   ...
38951 ){
38952   va_list ap;
38953   if( !pCheck->mxErr ) return;
38954   pCheck->mxErr--;
38955   pCheck->nErr++;
38956   va_start(ap, zFormat);
38957   if( pCheck->errMsg.nChar ){
38958     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
38959   }
38960   if( zMsg1 ){
38961     sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
38962   }
38963   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
38964   va_end(ap);
38965   if( pCheck->errMsg.mallocFailed ){
38966     pCheck->mallocFailed = 1;
38967   }
38968 }
38969 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
38970
38971 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
38972 /*
38973 ** Add 1 to the reference count for page iPage.  If this is the second
38974 ** reference to the page, add an error message to pCheck->zErrMsg.
38975 ** Return 1 if there are 2 ore more references to the page and 0 if
38976 ** if this is the first reference to the page.
38977 **
38978 ** Also check that the page number is in bounds.
38979 */
38980 static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
38981   if( iPage==0 ) return 1;
38982   if( iPage>pCheck->nPage || iPage<0 ){
38983     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
38984     return 1;
38985   }
38986   if( pCheck->anRef[iPage]==1 ){
38987     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
38988     return 1;
38989   }
38990   return  (pCheck->anRef[iPage]++)>1;
38991 }
38992
38993 #ifndef SQLITE_OMIT_AUTOVACUUM
38994 /*
38995 ** Check that the entry in the pointer-map for page iChild maps to 
38996 ** page iParent, pointer type ptrType. If not, append an error message
38997 ** to pCheck.
38998 */
38999 static void checkPtrmap(
39000   IntegrityCk *pCheck,   /* Integrity check context */
39001   Pgno iChild,           /* Child page number */
39002   u8 eType,              /* Expected pointer map type */
39003   Pgno iParent,          /* Expected pointer map parent page number */
39004   char *zContext         /* Context description (used for error msg) */
39005 ){
39006   int rc;
39007   u8 ePtrmapType;
39008   Pgno iPtrmapParent;
39009
39010   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
39011   if( rc!=SQLITE_OK ){
39012     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
39013     return;
39014   }
39015
39016   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
39017     checkAppendMsg(pCheck, zContext, 
39018       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
39019       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
39020   }
39021 }
39022 #endif
39023
39024 /*
39025 ** Check the integrity of the freelist or of an overflow page list.
39026 ** Verify that the number of pages on the list is N.
39027 */
39028 static void checkList(
39029   IntegrityCk *pCheck,  /* Integrity checking context */
39030   int isFreeList,       /* True for a freelist.  False for overflow page list */
39031   int iPage,            /* Page number for first page in the list */
39032   int N,                /* Expected number of pages in the list */
39033   char *zContext        /* Context for error messages */
39034 ){
39035   int i;
39036   int expected = N;
39037   int iFirst = iPage;
39038   while( N-- > 0 && pCheck->mxErr ){
39039     DbPage *pOvflPage;
39040     unsigned char *pOvflData;
39041     if( iPage<1 ){
39042       checkAppendMsg(pCheck, zContext,
39043          "%d of %d pages missing from overflow list starting at %d",
39044           N+1, expected, iFirst);
39045       break;
39046     }
39047     if( checkRef(pCheck, iPage, zContext) ) break;
39048     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
39049       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
39050       break;
39051     }
39052     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
39053     if( isFreeList ){
39054       int n = get4byte(&pOvflData[4]);
39055 #ifndef SQLITE_OMIT_AUTOVACUUM
39056       if( pCheck->pBt->autoVacuum ){
39057         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
39058       }
39059 #endif
39060       if( n>pCheck->pBt->usableSize/4-2 ){
39061         checkAppendMsg(pCheck, zContext,
39062            "freelist leaf count too big on page %d", iPage);
39063         N--;
39064       }else{
39065         for(i=0; i<n; i++){
39066           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
39067 #ifndef SQLITE_OMIT_AUTOVACUUM
39068           if( pCheck->pBt->autoVacuum ){
39069             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
39070           }
39071 #endif
39072           checkRef(pCheck, iFreePage, zContext);
39073         }
39074         N -= n;
39075       }
39076     }
39077 #ifndef SQLITE_OMIT_AUTOVACUUM
39078     else{
39079       /* If this database supports auto-vacuum and iPage is not the last
39080       ** page in this overflow list, check that the pointer-map entry for
39081       ** the following page matches iPage.
39082       */
39083       if( pCheck->pBt->autoVacuum && N>0 ){
39084         i = get4byte(pOvflData);
39085         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
39086       }
39087     }
39088 #endif
39089     iPage = get4byte(pOvflData);
39090     sqlite3PagerUnref(pOvflPage);
39091   }
39092 }
39093 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
39094
39095 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
39096 /*
39097 ** Do various sanity checks on a single page of a tree.  Return
39098 ** the tree depth.  Root pages return 0.  Parents of root pages
39099 ** return 1, and so forth.
39100 ** 
39101 ** These checks are done:
39102 **
39103 **      1.  Make sure that cells and freeblocks do not overlap
39104 **          but combine to completely cover the page.
39105 **  NO  2.  Make sure cell keys are in order.
39106 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
39107 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
39108 **      5.  Check the integrity of overflow pages.
39109 **      6.  Recursively call checkTreePage on all children.
39110 **      7.  Verify that the depth of all children is the same.
39111 **      8.  Make sure this page is at least 33% full or else it is
39112 **          the root of the tree.
39113 */
39114 static int checkTreePage(
39115   IntegrityCk *pCheck,  /* Context for the sanity check */
39116   int iPage,            /* Page number of the page to check */
39117   MemPage *pParent,     /* Parent page */
39118   char *zParentContext  /* Parent context */
39119 ){
39120   MemPage *pPage;
39121   int i, rc, depth, d2, pgno, cnt;
39122   int hdr, cellStart;
39123   int nCell;
39124   u8 *data;
39125   BtShared *pBt;
39126   int usableSize;
39127   char zContext[100];
39128   char *hit;
39129
39130   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
39131
39132   /* Check that the page exists
39133   */
39134   pBt = pCheck->pBt;
39135   usableSize = pBt->usableSize;
39136   if( iPage==0 ) return 0;
39137   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
39138   if( (rc = sqlite3BtreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
39139     checkAppendMsg(pCheck, zContext,
39140        "unable to get the page. error code=%d", rc);
39141     return 0;
39142   }
39143   if( (rc = sqlite3BtreeInitPage(pPage, pParent))!=0 ){
39144     checkAppendMsg(pCheck, zContext, 
39145                    "sqlite3BtreeInitPage() returns error code %d", rc);
39146     releasePage(pPage);
39147     return 0;
39148   }
39149
39150   /* Check out all the cells.
39151   */
39152   depth = 0;
39153   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
39154     u8 *pCell;
39155     int sz;
39156     CellInfo info;
39157
39158     /* Check payload overflow pages
39159     */
39160     sqlite3_snprintf(sizeof(zContext), zContext,
39161              "On tree page %d cell %d: ", iPage, i);
39162     pCell = findCell(pPage,i);
39163     sqlite3BtreeParseCellPtr(pPage, pCell, &info);
39164     sz = info.nData;
39165     if( !pPage->intKey ) sz += info.nKey;
39166     assert( sz==info.nPayload );
39167     if( sz>info.nLocal ){
39168       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
39169       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
39170 #ifndef SQLITE_OMIT_AUTOVACUUM
39171       if( pBt->autoVacuum ){
39172         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
39173       }
39174 #endif
39175       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
39176     }
39177
39178     /* Check sanity of left child page.
39179     */
39180     if( !pPage->leaf ){
39181       pgno = get4byte(pCell);
39182 #ifndef SQLITE_OMIT_AUTOVACUUM
39183       if( pBt->autoVacuum ){
39184         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
39185       }
39186 #endif
39187       d2 = checkTreePage(pCheck,pgno,pPage,zContext);
39188       if( i>0 && d2!=depth ){
39189         checkAppendMsg(pCheck, zContext, "Child page depth differs");
39190       }
39191       depth = d2;
39192     }
39193   }
39194   if( !pPage->leaf ){
39195     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
39196     sqlite3_snprintf(sizeof(zContext), zContext, 
39197                      "On page %d at right child: ", iPage);
39198 #ifndef SQLITE_OMIT_AUTOVACUUM
39199     if( pBt->autoVacuum ){
39200       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
39201     }
39202 #endif
39203     checkTreePage(pCheck, pgno, pPage, zContext);
39204   }
39205  
39206   /* Check for complete coverage of the page
39207   */
39208   data = pPage->aData;
39209   hdr = pPage->hdrOffset;
39210   hit = sqlite3PageMalloc( pBt->pageSize );
39211   if( hit==0 ){
39212     pCheck->mallocFailed = 1;
39213   }else{
39214     memset(hit, 0, usableSize );
39215     memset(hit, 1, get2byte(&data[hdr+5]));
39216     nCell = get2byte(&data[hdr+3]);
39217     cellStart = hdr + 12 - 4*pPage->leaf;
39218     for(i=0; i<nCell; i++){
39219       int pc = get2byte(&data[cellStart+i*2]);
39220       u16 size = cellSizePtr(pPage, &data[pc]);
39221       int j;
39222       if( (pc+size-1)>=usableSize || pc<0 ){
39223         checkAppendMsg(pCheck, 0, 
39224             "Corruption detected in cell %d on page %d",i,iPage,0);
39225       }else{
39226         for(j=pc+size-1; j>=pc; j--) hit[j]++;
39227       }
39228     }
39229     for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000; 
39230            cnt++){
39231       int size = get2byte(&data[i+2]);
39232       int j;
39233       if( (i+size-1)>=usableSize || i<0 ){
39234         checkAppendMsg(pCheck, 0,  
39235             "Corruption detected in cell %d on page %d",i,iPage,0);
39236       }else{
39237         for(j=i+size-1; j>=i; j--) hit[j]++;
39238       }
39239       i = get2byte(&data[i]);
39240     }
39241     for(i=cnt=0; i<usableSize; i++){
39242       if( hit[i]==0 ){
39243         cnt++;
39244       }else if( hit[i]>1 ){
39245         checkAppendMsg(pCheck, 0,
39246           "Multiple uses for byte %d of page %d", i, iPage);
39247         break;
39248       }
39249     }
39250     if( cnt!=data[hdr+7] ){
39251       checkAppendMsg(pCheck, 0, 
39252           "Fragmented space is %d byte reported as %d on page %d",
39253           cnt, data[hdr+7], iPage);
39254     }
39255   }
39256   sqlite3PageFree(hit);
39257
39258   releasePage(pPage);
39259   return depth+1;
39260 }
39261 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
39262
39263 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
39264 /*
39265 ** This routine does a complete check of the given BTree file.  aRoot[] is
39266 ** an array of pages numbers were each page number is the root page of
39267 ** a table.  nRoot is the number of entries in aRoot.
39268 **
39269 ** Write the number of error seen in *pnErr.  Except for some memory
39270 ** allocation errors,  nn error message is held in memory obtained from
39271 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
39272 ** returned.
39273 */
39274 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
39275   Btree *p,     /* The btree to be checked */
39276   int *aRoot,   /* An array of root pages numbers for individual trees */
39277   int nRoot,    /* Number of entries in aRoot[] */
39278   int mxErr,    /* Stop reporting errors after this many */
39279   int *pnErr    /* Write number of errors seen to this variable */
39280 ){
39281   int i;
39282   int nRef;
39283   IntegrityCk sCheck;
39284   BtShared *pBt = p->pBt;
39285   char zErr[100];
39286
39287   sqlite3BtreeEnter(p);
39288   pBt->db = p->db;
39289   nRef = sqlite3PagerRefcount(pBt->pPager);
39290   if( lockBtreeWithRetry(p)!=SQLITE_OK ){
39291     *pnErr = 1;
39292     sqlite3BtreeLeave(p);
39293     return sqlite3DbStrDup(0, "cannot acquire a read lock on the database");
39294   }
39295   sCheck.pBt = pBt;
39296   sCheck.pPager = pBt->pPager;
39297   sCheck.nPage = pagerPagecount(sCheck.pPager);
39298   sCheck.mxErr = mxErr;
39299   sCheck.nErr = 0;
39300   sCheck.mallocFailed = 0;
39301   *pnErr = 0;
39302 #ifndef SQLITE_OMIT_AUTOVACUUM
39303   if( pBt->nTrunc!=0 ){
39304     sCheck.nPage = pBt->nTrunc;
39305   }
39306 #endif
39307   if( sCheck.nPage==0 ){
39308     unlockBtreeIfUnused(pBt);
39309     sqlite3BtreeLeave(p);
39310     return 0;
39311   }
39312   sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
39313   if( !sCheck.anRef ){
39314     unlockBtreeIfUnused(pBt);
39315     *pnErr = 1;
39316     sqlite3BtreeLeave(p);
39317     return 0;
39318   }
39319   for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
39320   i = PENDING_BYTE_PAGE(pBt);
39321   if( i<=sCheck.nPage ){
39322     sCheck.anRef[i] = 1;
39323   }
39324   sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
39325
39326   /* Check the integrity of the freelist
39327   */
39328   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
39329             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
39330
39331   /* Check all the tables.
39332   */
39333   for(i=0; i<nRoot && sCheck.mxErr; i++){
39334     if( aRoot[i]==0 ) continue;
39335 #ifndef SQLITE_OMIT_AUTOVACUUM
39336     if( pBt->autoVacuum && aRoot[i]>1 ){
39337       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
39338     }
39339 #endif
39340     checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ");
39341   }
39342
39343   /* Make sure every page in the file is referenced
39344   */
39345   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
39346 #ifdef SQLITE_OMIT_AUTOVACUUM
39347     if( sCheck.anRef[i]==0 ){
39348       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
39349     }
39350 #else
39351     /* If the database supports auto-vacuum, make sure no tables contain
39352     ** references to pointer-map pages.
39353     */
39354     if( sCheck.anRef[i]==0 && 
39355        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
39356       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
39357     }
39358     if( sCheck.anRef[i]!=0 && 
39359        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
39360       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
39361     }
39362 #endif
39363   }
39364
39365   /* Make sure this analysis did not leave any unref() pages
39366   */
39367   unlockBtreeIfUnused(pBt);
39368   if( nRef != sqlite3PagerRefcount(pBt->pPager) ){
39369     checkAppendMsg(&sCheck, 0, 
39370       "Outstanding page count goes from %d to %d during this analysis",
39371       nRef, sqlite3PagerRefcount(pBt->pPager)
39372     );
39373   }
39374
39375   /* Clean  up and report errors.
39376   */
39377   sqlite3BtreeLeave(p);
39378   sqlite3_free(sCheck.anRef);
39379   if( sCheck.mallocFailed ){
39380     sqlite3StrAccumReset(&sCheck.errMsg);
39381     *pnErr = sCheck.nErr+1;
39382     return 0;
39383   }
39384   *pnErr = sCheck.nErr;
39385   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
39386   return sqlite3StrAccumFinish(&sCheck.errMsg);
39387 }
39388 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
39389
39390 /*
39391 ** Return the full pathname of the underlying database file.
39392 **
39393 ** The pager filename is invariant as long as the pager is
39394 ** open so it is safe to access without the BtShared mutex.
39395 */
39396 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
39397   assert( p->pBt->pPager!=0 );
39398   return sqlite3PagerFilename(p->pBt->pPager);
39399 }
39400
39401 /*
39402 ** Return the pathname of the directory that contains the database file.
39403 **
39404 ** The pager directory name is invariant as long as the pager is
39405 ** open so it is safe to access without the BtShared mutex.
39406 */
39407 SQLITE_PRIVATE const char *sqlite3BtreeGetDirname(Btree *p){
39408   assert( p->pBt->pPager!=0 );
39409   return sqlite3PagerDirname(p->pBt->pPager);
39410 }
39411
39412 /*
39413 ** Return the pathname of the journal file for this database. The return
39414 ** value of this routine is the same regardless of whether the journal file
39415 ** has been created or not.
39416 **
39417 ** The pager journal filename is invariant as long as the pager is
39418 ** open so it is safe to access without the BtShared mutex.
39419 */
39420 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
39421   assert( p->pBt->pPager!=0 );
39422   return sqlite3PagerJournalname(p->pBt->pPager);
39423 }
39424
39425 #ifndef SQLITE_OMIT_VACUUM
39426 /*
39427 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
39428 ** must be active for both files.
39429 **
39430 ** The size of file pTo may be reduced by this operation.
39431 ** If anything goes wrong, the transaction on pTo is rolled back. 
39432 **
39433 ** If successful, CommitPhaseOne() may be called on pTo before returning. 
39434 ** The caller should finish committing the transaction on pTo by calling
39435 ** sqlite3BtreeCommit().
39436 */
39437 static int btreeCopyFile(Btree *pTo, Btree *pFrom){
39438   int rc = SQLITE_OK;
39439   Pgno i;
39440
39441   Pgno nFromPage;     /* Number of pages in pFrom */
39442   Pgno nToPage;       /* Number of pages in pTo */
39443   Pgno nNewPage;      /* Number of pages in pTo after the copy */
39444
39445   Pgno iSkip;         /* Pending byte page in pTo */
39446   int nToPageSize;    /* Page size of pTo in bytes */
39447   int nFromPageSize;  /* Page size of pFrom in bytes */
39448
39449   BtShared *pBtTo = pTo->pBt;
39450   BtShared *pBtFrom = pFrom->pBt;
39451   pBtTo->db = pTo->db;
39452   pBtFrom->db = pFrom->db;
39453
39454   nToPageSize = pBtTo->pageSize;
39455   nFromPageSize = pBtFrom->pageSize;
39456
39457   if( pTo->inTrans!=TRANS_WRITE || pFrom->inTrans!=TRANS_WRITE ){
39458     return SQLITE_ERROR;
39459   }
39460   if( pBtTo->pCursor ){
39461     return SQLITE_BUSY;
39462   }
39463
39464   nToPage = pagerPagecount(pBtTo->pPager);
39465   nFromPage = pagerPagecount(pBtFrom->pPager);
39466   iSkip = PENDING_BYTE_PAGE(pBtTo);
39467
39468   /* Variable nNewPage is the number of pages required to store the
39469   ** contents of pFrom using the current page-size of pTo.
39470   */
39471   nNewPage = ((i64)nFromPage * (i64)nFromPageSize + (i64)nToPageSize - 1) / 
39472       (i64)nToPageSize;
39473
39474   for(i=1; rc==SQLITE_OK && (i<=nToPage || i<=nNewPage); i++){
39475
39476     /* Journal the original page.
39477     **
39478     ** iSkip is the page number of the locking page (PENDING_BYTE_PAGE)
39479     ** in database *pTo (before the copy). This page is never written 
39480     ** into the journal file. Unless i==iSkip or the page was not
39481     ** present in pTo before the copy operation, journal page i from pTo.
39482     */
39483     if( i!=iSkip && i<=nToPage ){
39484       DbPage *pDbPage = 0;
39485       rc = sqlite3PagerGet(pBtTo->pPager, i, &pDbPage);
39486       if( rc==SQLITE_OK ){
39487         rc = sqlite3PagerWrite(pDbPage);
39488         if( rc==SQLITE_OK && i>nFromPage ){
39489           /* Yeah.  It seems wierd to call DontWrite() right after Write(). But
39490           ** that is because the names of those procedures do not exactly 
39491           ** represent what they do.  Write() really means "put this page in the
39492           ** rollback journal and mark it as dirty so that it will be written
39493           ** to the database file later."  DontWrite() undoes the second part of
39494           ** that and prevents the page from being written to the database. The
39495           ** page is still on the rollback journal, though.  And that is the 
39496           ** whole point of this block: to put pages on the rollback journal. 
39497           */
39498           sqlite3PagerDontWrite(pDbPage);
39499         }
39500         sqlite3PagerUnref(pDbPage);
39501       }
39502     }
39503
39504     /* Overwrite the data in page i of the target database */
39505     if( rc==SQLITE_OK && i!=iSkip && i<=nNewPage ){
39506
39507       DbPage *pToPage = 0;
39508       sqlite3_int64 iOff;
39509
39510       rc = sqlite3PagerGet(pBtTo->pPager, i, &pToPage);
39511       if( rc==SQLITE_OK ){
39512         rc = sqlite3PagerWrite(pToPage);
39513       }
39514
39515       for(
39516         iOff=(i-1)*nToPageSize; 
39517         rc==SQLITE_OK && iOff<i*nToPageSize; 
39518         iOff += nFromPageSize
39519       ){
39520         DbPage *pFromPage = 0;
39521         Pgno iFrom = (iOff/nFromPageSize)+1;
39522
39523         if( iFrom==PENDING_BYTE_PAGE(pBtFrom) ){
39524           continue;
39525         }
39526
39527         rc = sqlite3PagerGet(pBtFrom->pPager, iFrom, &pFromPage);
39528         if( rc==SQLITE_OK ){
39529           char *zTo = sqlite3PagerGetData(pToPage);
39530           char *zFrom = sqlite3PagerGetData(pFromPage);
39531           int nCopy;
39532
39533           if( nFromPageSize>=nToPageSize ){
39534             zFrom += ((i-1)*nToPageSize - ((iFrom-1)*nFromPageSize));
39535             nCopy = nToPageSize;
39536           }else{
39537             zTo += (((iFrom-1)*nFromPageSize) - (i-1)*nToPageSize);
39538             nCopy = nFromPageSize;
39539           }
39540
39541           memcpy(zTo, zFrom, nCopy);
39542           sqlite3PagerUnref(pFromPage);
39543         }
39544       }
39545
39546       if( pToPage ) sqlite3PagerUnref(pToPage);
39547     }
39548   }
39549
39550   /* If things have worked so far, the database file may need to be 
39551   ** truncated. The complex part is that it may need to be truncated to
39552   ** a size that is not an integer multiple of nToPageSize - the current
39553   ** page size used by the pager associated with B-Tree pTo.
39554   **
39555   ** For example, say the page-size of pTo is 2048 bytes and the original 
39556   ** number of pages is 5 (10 KB file). If pFrom has a page size of 1024 
39557   ** bytes and 9 pages, then the file needs to be truncated to 9KB.
39558   */
39559   if( rc==SQLITE_OK ){
39560     if( nFromPageSize!=nToPageSize ){
39561       sqlite3_file *pFile = sqlite3PagerFile(pBtTo->pPager);
39562       i64 iSize = (i64)nFromPageSize * (i64)nFromPage;
39563       i64 iNow = (i64)((nToPage>nNewPage)?nToPage:nNewPage) * (i64)nToPageSize; 
39564       i64 iPending = ((i64)PENDING_BYTE_PAGE(pBtTo)-1) *(i64)nToPageSize;
39565   
39566       assert( iSize<=iNow );
39567   
39568       /* Commit phase one syncs the journal file associated with pTo 
39569       ** containing the original data. It does not sync the database file
39570       ** itself. After doing this it is safe to use OsTruncate() and other
39571       ** file APIs on the database file directly.
39572       */
39573       pBtTo->db = pTo->db;
39574       rc = sqlite3PagerCommitPhaseOne(pBtTo->pPager, 0, 0, 1);
39575       if( iSize<iNow && rc==SQLITE_OK ){
39576         rc = sqlite3OsTruncate(pFile, iSize);
39577       }
39578   
39579       /* The loop that copied data from database pFrom to pTo did not
39580       ** populate the locking page of database pTo. If the page-size of
39581       ** pFrom is smaller than that of pTo, this means some data will
39582       ** not have been copied. 
39583       **
39584       ** This block copies the missing data from database pFrom to pTo 
39585       ** using file APIs. This is safe because at this point we know that
39586       ** all of the original data from pTo has been synced into the 
39587       ** journal file. At this point it would be safe to do anything at
39588       ** all to the database file except truncate it to zero bytes.
39589       */
39590       if( rc==SQLITE_OK && nFromPageSize<nToPageSize && iSize>iPending){
39591         i64 iOff;
39592         for(
39593           iOff=iPending; 
39594           rc==SQLITE_OK && iOff<(iPending+nToPageSize); 
39595           iOff += nFromPageSize
39596         ){
39597           DbPage *pFromPage = 0;
39598           Pgno iFrom = (iOff/nFromPageSize)+1;
39599   
39600           if( iFrom==PENDING_BYTE_PAGE(pBtFrom) || iFrom>nFromPage ){
39601             continue;
39602           }
39603   
39604           rc = sqlite3PagerGet(pBtFrom->pPager, iFrom, &pFromPage);
39605           if( rc==SQLITE_OK ){
39606             char *zFrom = sqlite3PagerGetData(pFromPage);
39607           rc = sqlite3OsWrite(pFile, zFrom, nFromPageSize, iOff);
39608             sqlite3PagerUnref(pFromPage);
39609           }
39610         }
39611       }
39612   
39613       /* Sync the database file */
39614       if( rc==SQLITE_OK ){
39615         rc = sqlite3PagerSync(pBtTo->pPager);
39616       }
39617     }else{
39618       rc = sqlite3PagerTruncate(pBtTo->pPager, nNewPage);
39619     }
39620     if( rc==SQLITE_OK ){
39621       pBtTo->pageSizeFixed = 0;
39622     }
39623   }
39624
39625   if( rc ){
39626     sqlite3BtreeRollback(pTo);
39627   }
39628
39629   return rc;  
39630 }
39631 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
39632   int rc;
39633   sqlite3BtreeEnter(pTo);
39634   sqlite3BtreeEnter(pFrom);
39635   rc = btreeCopyFile(pTo, pFrom);
39636   sqlite3BtreeLeave(pFrom);
39637   sqlite3BtreeLeave(pTo);
39638   return rc;
39639 }
39640
39641 #endif /* SQLITE_OMIT_VACUUM */
39642
39643 /*
39644 ** Return non-zero if a transaction is active.
39645 */
39646 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
39647   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
39648   return (p && (p->inTrans==TRANS_WRITE));
39649 }
39650
39651 /*
39652 ** Return non-zero if a statement transaction is active.
39653 */
39654 SQLITE_PRIVATE int sqlite3BtreeIsInStmt(Btree *p){
39655   assert( sqlite3BtreeHoldsMutex(p) );
39656   return (p->pBt && p->pBt->inStmt);
39657 }
39658
39659 /*
39660 ** Return non-zero if a read (or write) transaction is active.
39661 */
39662 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
39663   assert( sqlite3_mutex_held(p->db->mutex) );
39664   return (p && (p->inTrans!=TRANS_NONE));
39665 }
39666
39667 /*
39668 ** This function returns a pointer to a blob of memory associated with
39669 ** a single shared-btree. The memory is used by client code for its own
39670 ** purposes (for example, to store a high-level schema associated with 
39671 ** the shared-btree). The btree layer manages reference counting issues.
39672 **
39673 ** The first time this is called on a shared-btree, nBytes bytes of memory
39674 ** are allocated, zeroed, and returned to the caller. For each subsequent 
39675 ** call the nBytes parameter is ignored and a pointer to the same blob
39676 ** of memory returned. 
39677 **
39678 ** If the nBytes parameter is 0 and the blob of memory has not yet been
39679 ** allocated, a null pointer is returned. If the blob has already been
39680 ** allocated, it is returned as normal.
39681 **
39682 ** Just before the shared-btree is closed, the function passed as the 
39683 ** xFree argument when the memory allocation was made is invoked on the 
39684 ** blob of allocated memory. This function should not call sqlite3_free()
39685 ** on the memory, the btree layer does that.
39686 */
39687 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
39688   BtShared *pBt = p->pBt;
39689   sqlite3BtreeEnter(p);
39690   if( !pBt->pSchema && nBytes ){
39691     pBt->pSchema = sqlite3MallocZero(nBytes);
39692     pBt->xFreeSchema = xFree;
39693   }
39694   sqlite3BtreeLeave(p);
39695   return pBt->pSchema;
39696 }
39697
39698 /*
39699 ** Return true if another user of the same shared btree as the argument
39700 ** handle holds an exclusive lock on the sqlite_master table.
39701 */
39702 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
39703   int rc;
39704   assert( sqlite3_mutex_held(p->db->mutex) );
39705   sqlite3BtreeEnter(p);
39706   rc = (queryTableLock(p, MASTER_ROOT, READ_LOCK)!=SQLITE_OK);
39707   sqlite3BtreeLeave(p);
39708   return rc;
39709 }
39710
39711
39712 #ifndef SQLITE_OMIT_SHARED_CACHE
39713 /*
39714 ** Obtain a lock on the table whose root page is iTab.  The
39715 ** lock is a write lock if isWritelock is true or a read lock
39716 ** if it is false.
39717 */
39718 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
39719   int rc = SQLITE_OK;
39720   if( p->sharable ){
39721     u8 lockType = READ_LOCK + isWriteLock;
39722     assert( READ_LOCK+1==WRITE_LOCK );
39723     assert( isWriteLock==0 || isWriteLock==1 );
39724     sqlite3BtreeEnter(p);
39725     rc = queryTableLock(p, iTab, lockType);
39726     if( rc==SQLITE_OK ){
39727       rc = lockTable(p, iTab, lockType);
39728     }
39729     sqlite3BtreeLeave(p);
39730   }
39731   return rc;
39732 }
39733 #endif
39734
39735 #ifndef SQLITE_OMIT_INCRBLOB
39736 /*
39737 ** Argument pCsr must be a cursor opened for writing on an 
39738 ** INTKEY table currently pointing at a valid table entry. 
39739 ** This function modifies the data stored as part of that entry.
39740 ** Only the data content may only be modified, it is not possible
39741 ** to change the length of the data stored.
39742 */
39743 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
39744   assert( cursorHoldsMutex(pCsr) );
39745   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
39746   assert(pCsr->isIncrblobHandle);
39747
39748   restoreCursorPosition(pCsr);
39749   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
39750   if( pCsr->eState!=CURSOR_VALID ){
39751     return SQLITE_ABORT;
39752   }
39753
39754   /* Check some preconditions: 
39755   **   (a) the cursor is open for writing,
39756   **   (b) there is no read-lock on the table being modified and
39757   **   (c) the cursor points at a valid row of an intKey table.
39758   */
39759   if( !pCsr->wrFlag ){
39760     return SQLITE_READONLY;
39761   }
39762   assert( !pCsr->pBt->readOnly 
39763           && pCsr->pBt->inTransaction==TRANS_WRITE );
39764   if( checkReadLocks(pCsr->pBtree, pCsr->pgnoRoot, pCsr, 0) ){
39765     return SQLITE_LOCKED; /* The table pCur points to has a read lock */
39766   }
39767   if( pCsr->eState==CURSOR_INVALID || !pCsr->pPage->intKey ){
39768     return SQLITE_ERROR;
39769   }
39770
39771   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 0, 1);
39772 }
39773
39774 /* 
39775 ** Set a flag on this cursor to cache the locations of pages from the 
39776 ** overflow list for the current row. This is used by cursors opened
39777 ** for incremental blob IO only.
39778 **
39779 ** This function sets a flag only. The actual page location cache
39780 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
39781 ** accessPayload() (the worker function for sqlite3BtreeData() and
39782 ** sqlite3BtreePutData()).
39783 */
39784 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
39785   assert( cursorHoldsMutex(pCur) );
39786   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
39787   assert(!pCur->isIncrblobHandle);
39788   assert(!pCur->aOverflow);
39789   pCur->isIncrblobHandle = 1;
39790 }
39791 #endif
39792
39793 /************** End of btree.c ***********************************************/
39794 /************** Begin file vdbefifo.c ****************************************/
39795 /*
39796 ** 2005 June 16
39797 **
39798 ** The author disclaims copyright to this source code.  In place of
39799 ** a legal notice, here is a blessing:
39800 **
39801 **    May you do good and not evil.
39802 **    May you find forgiveness for yourself and forgive others.
39803 **    May you share freely, never taking more than you give.
39804 **
39805 *************************************************************************
39806 ** This file implements a FIFO queue of rowids used for processing
39807 ** UPDATE and DELETE statements.
39808 **
39809 ** $Id: vdbefifo.c,v 1.8 2008/07/28 19:34:54 drh Exp $
39810 */
39811
39812 /*
39813 ** Constants FIFOSIZE_FIRST and FIFOSIZE_MAX are the initial
39814 ** number of entries in a fifo page and the maximum number of
39815 ** entries in a fifo page.
39816 */
39817 #define FIFOSIZE_FIRST (((128-sizeof(FifoPage))/8)+1)
39818 #ifdef SQLITE_MALLOC_SOFT_LIMIT
39819 # define FIFOSIZE_MAX   (((SQLITE_MALLOC_SOFT_LIMIT-sizeof(FifoPage))/8)+1)
39820 #else
39821 # define FIFOSIZE_MAX   (((262144-sizeof(FifoPage))/8)+1)
39822 #endif
39823
39824 /*
39825 ** Allocate a new FifoPage and return a pointer to it.  Return NULL if
39826 ** we run out of memory.  Leave space on the page for nEntry entries.
39827 */
39828 static FifoPage *allocateFifoPage(sqlite3 *db, int nEntry){
39829   FifoPage *pPage;
39830   if( nEntry>FIFOSIZE_MAX ){
39831     nEntry = FIFOSIZE_MAX;
39832   }
39833   pPage = sqlite3DbMallocRaw(db, sizeof(FifoPage) + sizeof(i64)*(nEntry-1) );
39834   if( pPage ){
39835     pPage->nSlot = nEntry;
39836     pPage->iWrite = 0;
39837     pPage->iRead = 0;
39838     pPage->pNext = 0;
39839   }
39840   return pPage;
39841 }
39842
39843 /*
39844 ** Initialize a Fifo structure.
39845 */
39846 SQLITE_PRIVATE void sqlite3VdbeFifoInit(Fifo *pFifo, sqlite3 *db){
39847   memset(pFifo, 0, sizeof(*pFifo));
39848   pFifo->db = db;
39849 }
39850
39851 /*
39852 ** Push a single 64-bit integer value into the Fifo.  Return SQLITE_OK
39853 ** normally.   SQLITE_NOMEM is returned if we are unable to allocate
39854 ** memory.
39855 */
39856 SQLITE_PRIVATE int sqlite3VdbeFifoPush(Fifo *pFifo, i64 val){
39857   FifoPage *pPage;
39858   pPage = pFifo->pLast;
39859   if( pPage==0 ){
39860     pPage = pFifo->pLast = pFifo->pFirst =
39861          allocateFifoPage(pFifo->db, FIFOSIZE_FIRST);
39862     if( pPage==0 ){
39863       return SQLITE_NOMEM;
39864     }
39865   }else if( pPage->iWrite>=pPage->nSlot ){
39866     pPage->pNext = allocateFifoPage(pFifo->db, pFifo->nEntry);
39867     if( pPage->pNext==0 ){
39868       return SQLITE_NOMEM;
39869     }
39870     pPage = pFifo->pLast = pPage->pNext;
39871   }
39872   pPage->aSlot[pPage->iWrite++] = val;
39873   pFifo->nEntry++;
39874   return SQLITE_OK;
39875 }
39876
39877 /*
39878 ** Extract a single 64-bit integer value from the Fifo.  The integer
39879 ** extracted is the one least recently inserted.  If the Fifo is empty
39880 ** return SQLITE_DONE.
39881 */
39882 SQLITE_PRIVATE int sqlite3VdbeFifoPop(Fifo *pFifo, i64 *pVal){
39883   FifoPage *pPage;
39884   if( pFifo->nEntry==0 ){
39885     return SQLITE_DONE;
39886   }
39887   assert( pFifo->nEntry>0 );
39888   pPage = pFifo->pFirst;
39889   assert( pPage!=0 );
39890   assert( pPage->iWrite>pPage->iRead );
39891   assert( pPage->iWrite<=pPage->nSlot );
39892   assert( pPage->iRead<pPage->nSlot );
39893   assert( pPage->iRead>=0 );
39894   *pVal = pPage->aSlot[pPage->iRead++];
39895   pFifo->nEntry--;
39896   if( pPage->iRead>=pPage->iWrite ){
39897     pFifo->pFirst = pPage->pNext;
39898     sqlite3DbFree(pFifo->db, pPage);
39899     if( pFifo->nEntry==0 ){
39900       assert( pFifo->pLast==pPage );
39901       pFifo->pLast = 0;
39902     }else{
39903       assert( pFifo->pFirst!=0 );
39904     }
39905   }else{
39906     assert( pFifo->nEntry>0 );
39907   }
39908   return SQLITE_OK;
39909 }
39910
39911 /*
39912 ** Delete all information from a Fifo object.   Free all memory held
39913 ** by the Fifo.
39914 */
39915 SQLITE_PRIVATE void sqlite3VdbeFifoClear(Fifo *pFifo){
39916   FifoPage *pPage, *pNextPage;
39917   for(pPage=pFifo->pFirst; pPage; pPage=pNextPage){
39918     pNextPage = pPage->pNext;
39919     sqlite3DbFree(pFifo->db, pPage);
39920   }
39921   sqlite3VdbeFifoInit(pFifo, pFifo->db);
39922 }
39923
39924 /************** End of vdbefifo.c ********************************************/
39925 /************** Begin file vdbemem.c *****************************************/
39926 /*
39927 ** 2004 May 26
39928 **
39929 ** The author disclaims copyright to this source code.  In place of
39930 ** a legal notice, here is a blessing:
39931 **
39932 **    May you do good and not evil.
39933 **    May you find forgiveness for yourself and forgive others.
39934 **    May you share freely, never taking more than you give.
39935 **
39936 *************************************************************************
39937 **
39938 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
39939 ** stores a single value in the VDBE.  Mem is an opaque structure visible
39940 ** only within the VDBE.  Interface routines refer to a Mem using the
39941 ** name sqlite_value
39942 **
39943 ** $Id: vdbemem.c,v 1.121 2008/08/01 20:10:09 drh Exp $
39944 */
39945
39946 /*
39947 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
39948 ** P if required.
39949 */
39950 #define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
39951
39952 /*
39953 ** If pMem is an object with a valid string representation, this routine
39954 ** ensures the internal encoding for the string representation is
39955 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
39956 **
39957 ** If pMem is not a string object, or the encoding of the string
39958 ** representation is already stored using the requested encoding, then this
39959 ** routine is a no-op.
39960 **
39961 ** SQLITE_OK is returned if the conversion is successful (or not required).
39962 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
39963 ** between formats.
39964 */
39965 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
39966   int rc;
39967   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
39968     return SQLITE_OK;
39969   }
39970   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
39971 #ifdef SQLITE_OMIT_UTF16
39972   return SQLITE_ERROR;
39973 #else
39974
39975   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
39976   ** then the encoding of the value may not have changed.
39977   */
39978   rc = sqlite3VdbeMemTranslate(pMem, desiredEnc);
39979   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
39980   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
39981   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
39982   return rc;
39983 #endif
39984 }
39985
39986 /*
39987 ** Make sure pMem->z points to a writable allocation of at least 
39988 ** n bytes.
39989 **
39990 ** If the memory cell currently contains string or blob data
39991 ** and the third argument passed to this function is true, the 
39992 ** current content of the cell is preserved. Otherwise, it may
39993 ** be discarded.  
39994 **
39995 ** This function sets the MEM_Dyn flag and clears any xDel callback.
39996 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is 
39997 ** not set, Mem.n is zeroed.
39998 */
39999 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
40000   assert( 1 >=
40001     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
40002     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) + 
40003     ((pMem->flags&MEM_Ephem) ? 1 : 0) + 
40004     ((pMem->flags&MEM_Static) ? 1 : 0)
40005   );
40006
40007   if( n<32 ) n = 32;
40008   if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
40009     if( preserve && pMem->z==pMem->zMalloc ){
40010       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
40011       if( !pMem->z ){
40012         pMem->flags = MEM_Null;
40013       }
40014       preserve = 0;
40015     }else{
40016       sqlite3DbFree(pMem->db, pMem->zMalloc);
40017       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
40018     }
40019   }
40020
40021   if( preserve && pMem->z && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
40022     memcpy(pMem->zMalloc, pMem->z, pMem->n);
40023   }
40024   if( pMem->flags&MEM_Dyn && pMem->xDel ){
40025     pMem->xDel((void *)(pMem->z));
40026   }
40027
40028   pMem->z = pMem->zMalloc;
40029   pMem->flags &= ~(MEM_Ephem|MEM_Static);
40030   pMem->xDel = 0;
40031   return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
40032 }
40033
40034 /*
40035 ** Make the given Mem object MEM_Dyn.  In other words, make it so
40036 ** that any TEXT or BLOB content is stored in memory obtained from
40037 ** malloc().  In this way, we know that the memory is safe to be
40038 ** overwritten or altered.
40039 **
40040 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
40041 */
40042 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
40043   int f;
40044   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
40045   expandBlob(pMem);
40046   f = pMem->flags;
40047   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
40048     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
40049       return SQLITE_NOMEM;
40050     }
40051     pMem->z[pMem->n] = 0;
40052     pMem->z[pMem->n+1] = 0;
40053     pMem->flags |= MEM_Term;
40054   }
40055
40056   return SQLITE_OK;
40057 }
40058
40059 /*
40060 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
40061 ** blob stored in dynamically allocated space.
40062 */
40063 #ifndef SQLITE_OMIT_INCRBLOB
40064 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
40065   if( pMem->flags & MEM_Zero ){
40066     int nByte;
40067     assert( pMem->flags&MEM_Blob );
40068     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
40069
40070     /* Set nByte to the number of bytes required to store the expanded blob. */
40071     nByte = pMem->n + pMem->u.i;
40072     if( nByte<=0 ){
40073       nByte = 1;
40074     }
40075     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
40076       return SQLITE_NOMEM;
40077     }
40078
40079     memset(&pMem->z[pMem->n], 0, pMem->u.i);
40080     pMem->n += pMem->u.i;
40081     pMem->flags &= ~(MEM_Zero|MEM_Term);
40082   }
40083   return SQLITE_OK;
40084 }
40085 #endif
40086
40087
40088 /*
40089 ** Make sure the given Mem is \u0000 terminated.
40090 */
40091 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
40092   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
40093   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
40094     return SQLITE_OK;   /* Nothing to do */
40095   }
40096   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
40097     return SQLITE_NOMEM;
40098   }
40099   pMem->z[pMem->n] = 0;
40100   pMem->z[pMem->n+1] = 0;
40101   pMem->flags |= MEM_Term;
40102   return SQLITE_OK;
40103 }
40104
40105 /*
40106 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
40107 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
40108 ** is a no-op.
40109 **
40110 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
40111 **
40112 ** A MEM_Null value will never be passed to this function. This function is
40113 ** used for converting values to text for returning to the user (i.e. via
40114 ** sqlite3_value_text()), or for ensuring that values to be used as btree
40115 ** keys are strings. In the former case a NULL pointer is returned the
40116 ** user and the later is an internal programming error.
40117 */
40118 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
40119   int rc = SQLITE_OK;
40120   int fg = pMem->flags;
40121   const int nByte = 32;
40122
40123   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
40124   assert( !(fg&MEM_Zero) );
40125   assert( !(fg&(MEM_Str|MEM_Blob)) );
40126   assert( fg&(MEM_Int|MEM_Real) );
40127
40128   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
40129     return SQLITE_NOMEM;
40130   }
40131
40132   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
40133   ** string representation of the value. Then, if the required encoding
40134   ** is UTF-16le or UTF-16be do a translation.
40135   ** 
40136   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
40137   */
40138   if( fg & MEM_Int ){
40139     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
40140   }else{
40141     assert( fg & MEM_Real );
40142     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
40143   }
40144   pMem->n = strlen(pMem->z);
40145   pMem->enc = SQLITE_UTF8;
40146   pMem->flags |= MEM_Str|MEM_Term;
40147   sqlite3VdbeChangeEncoding(pMem, enc);
40148   return rc;
40149 }
40150
40151 /*
40152 ** Memory cell pMem contains the context of an aggregate function.
40153 ** This routine calls the finalize method for that function.  The
40154 ** result of the aggregate is stored back into pMem.
40155 **
40156 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
40157 ** otherwise.
40158 */
40159 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
40160   int rc = SQLITE_OK;
40161   if( pFunc && pFunc->xFinalize ){
40162     sqlite3_context ctx;
40163     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
40164     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
40165     ctx.s.flags = MEM_Null;
40166     ctx.s.db = pMem->db;
40167     ctx.s.zMalloc = 0;
40168     ctx.pMem = pMem;
40169     ctx.pFunc = pFunc;
40170     ctx.isError = 0;
40171     pFunc->xFinalize(&ctx);
40172     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
40173     sqlite3DbFree(pMem->db, pMem->zMalloc);
40174     *pMem = ctx.s;
40175     rc = (ctx.isError?SQLITE_ERROR:SQLITE_OK);
40176   }
40177   return rc;
40178 }
40179
40180 /*
40181 ** If the memory cell contains a string value that must be freed by
40182 ** invoking an external callback, free it now. Calling this function
40183 ** does not free any Mem.zMalloc buffer.
40184 */
40185 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
40186   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
40187   if( p->flags&MEM_Agg ){
40188     sqlite3VdbeMemFinalize(p, p->u.pDef);
40189     assert( (p->flags & MEM_Agg)==0 );
40190     sqlite3VdbeMemRelease(p);
40191   }else if( p->flags&MEM_Dyn && p->xDel ){
40192     p->xDel((void *)p->z);
40193     p->xDel = 0;
40194   }
40195 }
40196
40197 /*
40198 ** Release any memory held by the Mem. This may leave the Mem in an
40199 ** inconsistent state, for example with (Mem.z==0) and
40200 ** (Mem.type==SQLITE_TEXT).
40201 */
40202 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
40203   sqlite3VdbeMemReleaseExternal(p);
40204   sqlite3DbFree(p->db, p->zMalloc);
40205   p->z = 0;
40206   p->zMalloc = 0;
40207   p->xDel = 0;
40208 }
40209
40210 /*
40211 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
40212 ** If the double is too large, return 0x8000000000000000.
40213 **
40214 ** Most systems appear to do this simply by assigning
40215 ** variables and without the extra range tests.  But
40216 ** there are reports that windows throws an expection
40217 ** if the floating point value is out of range. (See ticket #2880.)
40218 ** Because we do not completely understand the problem, we will
40219 ** take the conservative approach and always do range tests
40220 ** before attempting the conversion.
40221 */
40222 static i64 doubleToInt64(double r){
40223   /*
40224   ** Many compilers we encounter do not define constants for the
40225   ** minimum and maximum 64-bit integers, or they define them
40226   ** inconsistently.  And many do not understand the "LL" notation.
40227   ** So we define our own static constants here using nothing
40228   ** larger than a 32-bit integer constant.
40229   */
40230   static const i64 maxInt = LARGEST_INT64;
40231   static const i64 minInt = SMALLEST_INT64;
40232
40233   if( r<(double)minInt ){
40234     return minInt;
40235   }else if( r>(double)maxInt ){
40236     return minInt;
40237   }else{
40238     return (i64)r;
40239   }
40240 }
40241
40242 /*
40243 ** Return some kind of integer value which is the best we can do
40244 ** at representing the value that *pMem describes as an integer.
40245 ** If pMem is an integer, then the value is exact.  If pMem is
40246 ** a floating-point then the value returned is the integer part.
40247 ** If pMem is a string or blob, then we make an attempt to convert
40248 ** it into a integer and return that.  If pMem is NULL, return 0.
40249 **
40250 ** If pMem is a string, its encoding might be changed.
40251 */
40252 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
40253   int flags;
40254   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
40255   flags = pMem->flags;
40256   if( flags & MEM_Int ){
40257     return pMem->u.i;
40258   }else if( flags & MEM_Real ){
40259     return doubleToInt64(pMem->r);
40260   }else if( flags & (MEM_Str|MEM_Blob) ){
40261     i64 value;
40262     pMem->flags |= MEM_Str;
40263     if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
40264        || sqlite3VdbeMemNulTerminate(pMem) ){
40265       return 0;
40266     }
40267     assert( pMem->z );
40268     sqlite3Atoi64(pMem->z, &value);
40269     return value;
40270   }else{
40271     return 0;
40272   }
40273 }
40274
40275 /*
40276 ** Return the best representation of pMem that we can get into a
40277 ** double.  If pMem is already a double or an integer, return its
40278 ** value.  If it is a string or blob, try to convert it to a double.
40279 ** If it is a NULL, return 0.0.
40280 */
40281 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
40282   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
40283   if( pMem->flags & MEM_Real ){
40284     return pMem->r;
40285   }else if( pMem->flags & MEM_Int ){
40286     return (double)pMem->u.i;
40287   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
40288     double val = 0.0;
40289     pMem->flags |= MEM_Str;
40290     if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
40291        || sqlite3VdbeMemNulTerminate(pMem) ){
40292       return 0.0;
40293     }
40294     assert( pMem->z );
40295     sqlite3AtoF(pMem->z, &val);
40296     return val;
40297   }else{
40298     return 0.0;
40299   }
40300 }
40301
40302 /*
40303 ** The MEM structure is already a MEM_Real.  Try to also make it a
40304 ** MEM_Int if we can.
40305 */
40306 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
40307   assert( pMem->flags & MEM_Real );
40308   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
40309
40310   pMem->u.i = doubleToInt64(pMem->r);
40311   if( pMem->r==(double)pMem->u.i ){
40312     pMem->flags |= MEM_Int;
40313   }
40314 }
40315
40316 static void setTypeFlag(Mem *pMem, int f){
40317   MemSetTypeFlag(pMem, f);
40318 }
40319
40320 /*
40321 ** Convert pMem to type integer.  Invalidate any prior representations.
40322 */
40323 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
40324   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
40325   pMem->u.i = sqlite3VdbeIntValue(pMem);
40326   setTypeFlag(pMem, MEM_Int);
40327   return SQLITE_OK;
40328 }
40329
40330 /*
40331 ** Convert pMem so that it is of type MEM_Real.
40332 ** Invalidate any prior representations.
40333 */
40334 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
40335   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
40336   pMem->r = sqlite3VdbeRealValue(pMem);
40337   setTypeFlag(pMem, MEM_Real);
40338   return SQLITE_OK;
40339 }
40340
40341 /*
40342 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
40343 ** Invalidate any prior representations.
40344 */
40345 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
40346   double r1, r2;
40347   i64 i;
40348   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 );
40349   assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
40350   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
40351   r1 = sqlite3VdbeRealValue(pMem);
40352   i = doubleToInt64(r1);
40353   r2 = (double)i;
40354   if( r1==r2 ){
40355     sqlite3VdbeMemIntegerify(pMem);
40356   }else{
40357     pMem->r = r1;
40358     setTypeFlag(pMem, MEM_Real);
40359   }
40360   return SQLITE_OK;
40361 }
40362
40363 /*
40364 ** Delete any previous value and set the value stored in *pMem to NULL.
40365 */
40366 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
40367   setTypeFlag(pMem, MEM_Null);
40368   pMem->type = SQLITE_NULL;
40369 }
40370
40371 /*
40372 ** Delete any previous value and set the value to be a BLOB of length
40373 ** n containing all zeros.
40374 */
40375 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
40376   sqlite3VdbeMemRelease(pMem);
40377   setTypeFlag(pMem, MEM_Blob);
40378   pMem->flags = MEM_Blob|MEM_Zero;
40379   pMem->type = SQLITE_BLOB;
40380   pMem->n = 0;
40381   if( n<0 ) n = 0;
40382   pMem->u.i = n;
40383   pMem->enc = SQLITE_UTF8;
40384 }
40385
40386 /*
40387 ** Delete any previous value and set the value stored in *pMem to val,
40388 ** manifest type INTEGER.
40389 */
40390 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
40391   sqlite3VdbeMemRelease(pMem);
40392   pMem->u.i = val;
40393   pMem->flags = MEM_Int;
40394   pMem->type = SQLITE_INTEGER;
40395 }
40396
40397 /*
40398 ** Delete any previous value and set the value stored in *pMem to val,
40399 ** manifest type REAL.
40400 */
40401 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
40402   if( sqlite3IsNaN(val) ){
40403     sqlite3VdbeMemSetNull(pMem);
40404   }else{
40405     sqlite3VdbeMemRelease(pMem);
40406     pMem->r = val;
40407     pMem->flags = MEM_Real;
40408     pMem->type = SQLITE_FLOAT;
40409   }
40410 }
40411
40412 /*
40413 ** Return true if the Mem object contains a TEXT or BLOB that is
40414 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
40415 */
40416 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
40417   assert( p->db!=0 );
40418   if( p->flags & (MEM_Str|MEM_Blob) ){
40419     int n = p->n;
40420     if( p->flags & MEM_Zero ){
40421       n += p->u.i;
40422     }
40423     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
40424   }
40425   return 0; 
40426 }
40427
40428 /*
40429 ** Size of struct Mem not including the Mem.zMalloc member.
40430 */
40431 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
40432
40433 /*
40434 ** Make an shallow copy of pFrom into pTo.  Prior contents of
40435 ** pTo are freed.  The pFrom->z field is not duplicated.  If
40436 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
40437 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
40438 */
40439 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
40440   sqlite3VdbeMemReleaseExternal(pTo);
40441   memcpy(pTo, pFrom, MEMCELLSIZE);
40442   pTo->xDel = 0;
40443   if( (pFrom->flags&MEM_Dyn)!=0 || pFrom->z==pFrom->zMalloc ){
40444     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
40445     assert( srcType==MEM_Ephem || srcType==MEM_Static );
40446     pTo->flags |= srcType;
40447   }
40448 }
40449
40450 /*
40451 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
40452 ** freed before the copy is made.
40453 */
40454 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
40455   int rc = SQLITE_OK;
40456
40457   sqlite3VdbeMemReleaseExternal(pTo);
40458   memcpy(pTo, pFrom, MEMCELLSIZE);
40459   pTo->flags &= ~MEM_Dyn;
40460
40461   if( pTo->flags&(MEM_Str|MEM_Blob) ){
40462     if( 0==(pFrom->flags&MEM_Static) ){
40463       pTo->flags |= MEM_Ephem;
40464       rc = sqlite3VdbeMemMakeWriteable(pTo);
40465     }
40466   }
40467
40468   return rc;
40469 }
40470
40471 /*
40472 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
40473 ** freed. If pFrom contains ephemeral data, a copy is made.
40474 **
40475 ** pFrom contains an SQL NULL when this routine returns.
40476 */
40477 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
40478   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
40479   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
40480   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
40481
40482   sqlite3VdbeMemRelease(pTo);
40483   memcpy(pTo, pFrom, sizeof(Mem));
40484   pFrom->flags = MEM_Null;
40485   pFrom->xDel = 0;
40486   pFrom->zMalloc = 0;
40487 }
40488
40489 /*
40490 ** Change the value of a Mem to be a string or a BLOB.
40491 **
40492 ** The memory management strategy depends on the value of the xDel
40493 ** parameter. If the value passed is SQLITE_TRANSIENT, then the 
40494 ** string is copied into a (possibly existing) buffer managed by the 
40495 ** Mem structure. Otherwise, any existing buffer is freed and the
40496 ** pointer copied.
40497 */
40498 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
40499   Mem *pMem,          /* Memory cell to set to string value */
40500   const char *z,      /* String pointer */
40501   int n,              /* Bytes in string, or negative */
40502   u8 enc,             /* Encoding of z.  0 for BLOBs */
40503   void (*xDel)(void*) /* Destructor function */
40504 ){
40505   int nByte = n;      /* New value for pMem->n */
40506   int iLimit;         /* Maximum allowed string or blob size */
40507   int flags = 0;      /* New value for pMem->flags */
40508
40509   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
40510
40511   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
40512   if( !z ){
40513     sqlite3VdbeMemSetNull(pMem);
40514     return SQLITE_OK;
40515   }
40516
40517   if( pMem->db ){
40518     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
40519   }else{
40520     iLimit = SQLITE_MAX_LENGTH;
40521   }
40522   flags = (enc==0?MEM_Blob:MEM_Str);
40523   if( nByte<0 ){
40524     assert( enc!=0 );
40525     if( enc==SQLITE_UTF8 ){
40526       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
40527     }else{
40528       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
40529     }
40530     flags |= MEM_Term;
40531   }
40532   if( nByte>iLimit ){
40533     return SQLITE_TOOBIG;
40534   }
40535
40536   /* The following block sets the new values of Mem.z and Mem.xDel. It
40537   ** also sets a flag in local variable "flags" to indicate the memory
40538   ** management (one of MEM_Dyn or MEM_Static).
40539   */
40540   if( xDel==SQLITE_TRANSIENT ){
40541     int nAlloc = nByte;
40542     if( flags&MEM_Term ){
40543       nAlloc += (enc==SQLITE_UTF8?1:2);
40544     }
40545     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
40546       return SQLITE_NOMEM;
40547     }
40548     memcpy(pMem->z, z, nAlloc);
40549   }else if( xDel==SQLITE_DYNAMIC ){
40550     sqlite3VdbeMemRelease(pMem);
40551     pMem->zMalloc = pMem->z = (char *)z;
40552     pMem->xDel = 0;
40553   }else{
40554     sqlite3VdbeMemRelease(pMem);
40555     pMem->z = (char *)z;
40556     pMem->xDel = xDel;
40557     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
40558   }
40559
40560   pMem->n = nByte;
40561   pMem->flags = flags;
40562   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
40563   pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
40564
40565 #ifndef SQLITE_OMIT_UTF16
40566   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
40567     return SQLITE_NOMEM;
40568   }
40569 #endif
40570
40571   return SQLITE_OK;
40572 }
40573
40574 /*
40575 ** Compare the values contained by the two memory cells, returning
40576 ** negative, zero or positive if pMem1 is less than, equal to, or greater
40577 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
40578 ** and reals) sorted numerically, followed by text ordered by the collating
40579 ** sequence pColl and finally blob's ordered by memcmp().
40580 **
40581 ** Two NULL values are considered equal by this function.
40582 */
40583 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
40584   int rc;
40585   int f1, f2;
40586   int combined_flags;
40587
40588   /* Interchange pMem1 and pMem2 if the collating sequence specifies
40589   ** DESC order.
40590   */
40591   f1 = pMem1->flags;
40592   f2 = pMem2->flags;
40593   combined_flags = f1|f2;
40594  
40595   /* If one value is NULL, it is less than the other. If both values
40596   ** are NULL, return 0.
40597   */
40598   if( combined_flags&MEM_Null ){
40599     return (f2&MEM_Null) - (f1&MEM_Null);
40600   }
40601
40602   /* If one value is a number and the other is not, the number is less.
40603   ** If both are numbers, compare as reals if one is a real, or as integers
40604   ** if both values are integers.
40605   */
40606   if( combined_flags&(MEM_Int|MEM_Real) ){
40607     if( !(f1&(MEM_Int|MEM_Real)) ){
40608       return 1;
40609     }
40610     if( !(f2&(MEM_Int|MEM_Real)) ){
40611       return -1;
40612     }
40613     if( (f1 & f2 & MEM_Int)==0 ){
40614       double r1, r2;
40615       if( (f1&MEM_Real)==0 ){
40616         r1 = pMem1->u.i;
40617       }else{
40618         r1 = pMem1->r;
40619       }
40620       if( (f2&MEM_Real)==0 ){
40621         r2 = pMem2->u.i;
40622       }else{
40623         r2 = pMem2->r;
40624       }
40625       if( r1<r2 ) return -1;
40626       if( r1>r2 ) return 1;
40627       return 0;
40628     }else{
40629       assert( f1&MEM_Int );
40630       assert( f2&MEM_Int );
40631       if( pMem1->u.i < pMem2->u.i ) return -1;
40632       if( pMem1->u.i > pMem2->u.i ) return 1;
40633       return 0;
40634     }
40635   }
40636
40637   /* If one value is a string and the other is a blob, the string is less.
40638   ** If both are strings, compare using the collating functions.
40639   */
40640   if( combined_flags&MEM_Str ){
40641     if( (f1 & MEM_Str)==0 ){
40642       return 1;
40643     }
40644     if( (f2 & MEM_Str)==0 ){
40645       return -1;
40646     }
40647
40648     assert( pMem1->enc==pMem2->enc );
40649     assert( pMem1->enc==SQLITE_UTF8 || 
40650             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
40651
40652     /* The collation sequence must be defined at this point, even if
40653     ** the user deletes the collation sequence after the vdbe program is
40654     ** compiled (this was not always the case).
40655     */
40656     assert( !pColl || pColl->xCmp );
40657
40658     if( pColl ){
40659       if( pMem1->enc==pColl->enc ){
40660         /* The strings are already in the correct encoding.  Call the
40661         ** comparison function directly */
40662         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
40663       }else{
40664         u8 origEnc = pMem1->enc;
40665         const void *v1, *v2;
40666         int n1, n2;
40667         /* Convert the strings into the encoding that the comparison
40668         ** function expects */
40669         v1 = sqlite3ValueText((sqlite3_value*)pMem1, pColl->enc);
40670         n1 = v1==0 ? 0 : pMem1->n;
40671         assert( n1==sqlite3ValueBytes((sqlite3_value*)pMem1, pColl->enc) );
40672         v2 = sqlite3ValueText((sqlite3_value*)pMem2, pColl->enc);
40673         n2 = v2==0 ? 0 : pMem2->n;
40674         assert( n2==sqlite3ValueBytes((sqlite3_value*)pMem2, pColl->enc) );
40675         /* Do the comparison */
40676         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
40677         /* Convert the strings back into the database encoding */
40678         sqlite3ValueText((sqlite3_value*)pMem1, origEnc);
40679         sqlite3ValueText((sqlite3_value*)pMem2, origEnc);
40680         return rc;
40681       }
40682     }
40683     /* If a NULL pointer was passed as the collate function, fall through
40684     ** to the blob case and use memcmp().  */
40685   }
40686  
40687   /* Both values must be blobs.  Compare using memcmp().  */
40688   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
40689   if( rc==0 ){
40690     rc = pMem1->n - pMem2->n;
40691   }
40692   return rc;
40693 }
40694
40695 /*
40696 ** Move data out of a btree key or data field and into a Mem structure.
40697 ** The data or key is taken from the entry that pCur is currently pointing
40698 ** to.  offset and amt determine what portion of the data or key to retrieve.
40699 ** key is true to get the key or false to get data.  The result is written
40700 ** into the pMem element.
40701 **
40702 ** The pMem structure is assumed to be uninitialized.  Any prior content
40703 ** is overwritten without being freed.
40704 **
40705 ** If this routine fails for any reason (malloc returns NULL or unable
40706 ** to read from the disk) then the pMem is left in an inconsistent state.
40707 */
40708 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
40709   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
40710   int offset,       /* Offset from the start of data to return bytes from. */
40711   int amt,          /* Number of bytes to return. */
40712   int key,          /* If true, retrieve from the btree key, not data. */
40713   Mem *pMem         /* OUT: Return data in this Mem structure. */
40714 ){
40715   char *zData;       /* Data from the btree layer */
40716   int available = 0; /* Number of bytes available on the local btree page */
40717   sqlite3 *db;       /* Database connection */
40718   int rc = SQLITE_OK;
40719
40720   db = sqlite3BtreeCursorDb(pCur);
40721   assert( sqlite3_mutex_held(db->mutex) );
40722   if( key ){
40723     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
40724   }else{
40725     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
40726   }
40727   assert( zData!=0 );
40728
40729   if( offset+amt<=available && ((pMem->flags&MEM_Dyn)==0 || pMem->xDel) ){
40730     sqlite3VdbeMemRelease(pMem);
40731     pMem->z = &zData[offset];
40732     pMem->flags = MEM_Blob|MEM_Ephem;
40733   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
40734     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
40735     pMem->enc = 0;
40736     pMem->type = SQLITE_BLOB;
40737     if( key ){
40738       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
40739     }else{
40740       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
40741     }
40742     pMem->z[amt] = 0;
40743     pMem->z[amt+1] = 0;
40744     if( rc!=SQLITE_OK ){
40745       sqlite3VdbeMemRelease(pMem);
40746     }
40747   }
40748   pMem->n = amt;
40749
40750   return rc;
40751 }
40752
40753 #if 0
40754 /*
40755 ** Perform various checks on the memory cell pMem. An assert() will
40756 ** fail if pMem is internally inconsistent.
40757 */
40758 SQLITE_PRIVATE void sqlite3VdbeMemSanity(Mem *pMem){
40759   int flags = pMem->flags;
40760   assert( flags!=0 );  /* Must define some type */
40761   if( flags & (MEM_Str|MEM_Blob) ){
40762     int x = flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short);
40763     assert( x!=0 );            /* Strings must define a string subtype */
40764     assert( (x & (x-1))==0 );  /* Only one string subtype can be defined */
40765     assert( pMem->z!=0 );      /* Strings must have a value */
40766     /* Mem.z points to Mem.zShort iff the subtype is MEM_Short */
40767     assert( (x & MEM_Short)==0 || pMem->z==pMem->zShort );
40768     assert( (x & MEM_Short)!=0 || pMem->z!=pMem->zShort );
40769     /* No destructor unless there is MEM_Dyn */
40770     assert( pMem->xDel==0 || (pMem->flags & MEM_Dyn)!=0 );
40771
40772     if( (flags & MEM_Str) ){
40773       assert( pMem->enc==SQLITE_UTF8 || 
40774               pMem->enc==SQLITE_UTF16BE ||
40775               pMem->enc==SQLITE_UTF16LE 
40776       );
40777       /* If the string is UTF-8 encoded and nul terminated, then pMem->n
40778       ** must be the length of the string.  (Later:)  If the database file
40779       ** has been corrupted, '\000' characters might have been inserted
40780       ** into the middle of the string.  In that case, the strlen() might
40781       ** be less.
40782       */
40783       if( pMem->enc==SQLITE_UTF8 && (flags & MEM_Term) ){ 
40784         assert( strlen(pMem->z)<=pMem->n );
40785         assert( pMem->z[pMem->n]==0 );
40786       }
40787     }
40788   }else{
40789     /* Cannot define a string subtype for non-string objects */
40790     assert( (pMem->flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short))==0 );
40791     assert( pMem->xDel==0 );
40792   }
40793   /* MEM_Null excludes all other types */
40794   assert( (pMem->flags&(MEM_Str|MEM_Int|MEM_Real|MEM_Blob))==0
40795           || (pMem->flags&MEM_Null)==0 );
40796   /* If the MEM is both real and integer, the values are equal */
40797   assert( (pMem->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) 
40798           || pMem->r==pMem->u.i );
40799 }
40800 #endif
40801
40802 /* This function is only available internally, it is not part of the
40803 ** external API. It works in a similar way to sqlite3_value_text(),
40804 ** except the data returned is in the encoding specified by the second
40805 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
40806 ** SQLITE_UTF8.
40807 **
40808 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
40809 ** If that is the case, then the result must be aligned on an even byte
40810 ** boundary.
40811 */
40812 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
40813   if( !pVal ) return 0;
40814
40815   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
40816   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
40817
40818   if( pVal->flags&MEM_Null ){
40819     return 0;
40820   }
40821   assert( (MEM_Blob>>3) == MEM_Str );
40822   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
40823   expandBlob(pVal);
40824   if( pVal->flags&MEM_Str ){
40825     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
40826     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
40827       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
40828       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
40829         return 0;
40830       }
40831     }
40832     sqlite3VdbeMemNulTerminate(pVal);
40833   }else{
40834     assert( (pVal->flags&MEM_Blob)==0 );
40835     sqlite3VdbeMemStringify(pVal, enc);
40836     assert( 0==(1&(int)pVal->z) );
40837   }
40838   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
40839               || pVal->db->mallocFailed );
40840   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
40841     return pVal->z;
40842   }else{
40843     return 0;
40844   }
40845 }
40846
40847 /*
40848 ** Create a new sqlite3_value object.
40849 */
40850 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
40851   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
40852   if( p ){
40853     p->flags = MEM_Null;
40854     p->type = SQLITE_NULL;
40855     p->db = db;
40856   }
40857   return p;
40858 }
40859
40860 /*
40861 ** Create a new sqlite3_value object, containing the value of pExpr.
40862 **
40863 ** This only works for very simple expressions that consist of one constant
40864 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
40865 ** be converted directly into a value, then the value is allocated and
40866 ** a pointer written to *ppVal. The caller is responsible for deallocating
40867 ** the value by passing it to sqlite3ValueFree() later on. If the expression
40868 ** cannot be converted to a value, then *ppVal is set to NULL.
40869 */
40870 SQLITE_PRIVATE int sqlite3ValueFromExpr(
40871   sqlite3 *db,              /* The database connection */
40872   Expr *pExpr,              /* The expression to evaluate */
40873   u8 enc,                   /* Encoding to use */
40874   u8 affinity,              /* Affinity to use */
40875   sqlite3_value **ppVal     /* Write the new value here */
40876 ){
40877   int op;
40878   char *zVal = 0;
40879   sqlite3_value *pVal = 0;
40880
40881   if( !pExpr ){
40882     *ppVal = 0;
40883     return SQLITE_OK;
40884   }
40885   op = pExpr->op;
40886
40887   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
40888     zVal = sqlite3DbStrNDup(db, (char*)pExpr->token.z, pExpr->token.n);
40889     pVal = sqlite3ValueNew(db);
40890     if( !zVal || !pVal ) goto no_mem;
40891     sqlite3Dequote(zVal);
40892     sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
40893     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
40894       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, enc);
40895     }else{
40896       sqlite3ValueApplyAffinity(pVal, affinity, enc);
40897     }
40898   }else if( op==TK_UMINUS ) {
40899     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
40900       pVal->u.i = -1 * pVal->u.i;
40901       pVal->r = -1.0 * pVal->r;
40902     }
40903   }
40904 #ifndef SQLITE_OMIT_BLOB_LITERAL
40905   else if( op==TK_BLOB ){
40906     int nVal;
40907     assert( pExpr->token.n>=3 );
40908     assert( pExpr->token.z[0]=='x' || pExpr->token.z[0]=='X' );
40909     assert( pExpr->token.z[1]=='\'' );
40910     assert( pExpr->token.z[pExpr->token.n-1]=='\'' );
40911     pVal = sqlite3ValueNew(db);
40912     nVal = pExpr->token.n - 3;
40913     zVal = (char*)pExpr->token.z + 2;
40914     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
40915                          0, SQLITE_DYNAMIC);
40916   }
40917 #endif
40918
40919   *ppVal = pVal;
40920   return SQLITE_OK;
40921
40922 no_mem:
40923   db->mallocFailed = 1;
40924   sqlite3DbFree(db, zVal);
40925   sqlite3ValueFree(pVal);
40926   *ppVal = 0;
40927   return SQLITE_NOMEM;
40928 }
40929
40930 /*
40931 ** Change the string value of an sqlite3_value object
40932 */
40933 SQLITE_PRIVATE void sqlite3ValueSetStr(
40934   sqlite3_value *v,     /* Value to be set */
40935   int n,                /* Length of string z */
40936   const void *z,        /* Text of the new string */
40937   u8 enc,               /* Encoding to use */
40938   void (*xDel)(void*)   /* Destructor for the string */
40939 ){
40940   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
40941 }
40942
40943 /*
40944 ** Free an sqlite3_value object
40945 */
40946 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
40947   if( !v ) return;
40948   sqlite3VdbeMemRelease((Mem *)v);
40949   sqlite3DbFree(((Mem*)v)->db, v);
40950 }
40951
40952 /*
40953 ** Return the number of bytes in the sqlite3_value object assuming
40954 ** that it uses the encoding "enc"
40955 */
40956 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
40957   Mem *p = (Mem*)pVal;
40958   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
40959     if( p->flags & MEM_Zero ){
40960       return p->n+p->u.i;
40961     }else{
40962       return p->n;
40963     }
40964   }
40965   return 0;
40966 }
40967
40968 /************** End of vdbemem.c *********************************************/
40969 /************** Begin file vdbeaux.c *****************************************/
40970 /*
40971 ** 2003 September 6
40972 **
40973 ** The author disclaims copyright to this source code.  In place of
40974 ** a legal notice, here is a blessing:
40975 **
40976 **    May you do good and not evil.
40977 **    May you find forgiveness for yourself and forgive others.
40978 **    May you share freely, never taking more than you give.
40979 **
40980 *************************************************************************
40981 ** This file contains code used for creating, destroying, and populating
40982 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
40983 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
40984 ** But that file was getting too big so this subroutines were split out.
40985 **
40986 ** $Id: vdbeaux.c,v 1.405 2008/08/02 03:50:39 drh Exp $
40987 */
40988
40989
40990
40991 /*
40992 ** When debugging the code generator in a symbolic debugger, one can
40993 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
40994 ** as they are added to the instruction stream.
40995 */
40996 #ifdef SQLITE_DEBUG
40997 SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
40998 #endif
40999
41000
41001 /*
41002 ** Create a new virtual database engine.
41003 */
41004 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
41005   Vdbe *p;
41006   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
41007   if( p==0 ) return 0;
41008   p->db = db;
41009   if( db->pVdbe ){
41010     db->pVdbe->pPrev = p;
41011   }
41012   p->pNext = db->pVdbe;
41013   p->pPrev = 0;
41014   db->pVdbe = p;
41015   p->magic = VDBE_MAGIC_INIT;
41016   return p;
41017 }
41018
41019 /*
41020 ** Remember the SQL string for a prepared statement.
41021 */
41022 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n){
41023   if( p==0 ) return;
41024   assert( p->zSql==0 );
41025   p->zSql = sqlite3DbStrNDup(p->db, z, n);
41026 }
41027
41028 /*
41029 ** Return the SQL associated with a prepared statement
41030 */
41031 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
41032   return ((Vdbe *)pStmt)->zSql;
41033 }
41034
41035 /*
41036 ** Swap all content between two VDBE structures.
41037 */
41038 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
41039   Vdbe tmp, *pTmp;
41040   char *zTmp;
41041   int nTmp;
41042   tmp = *pA;
41043   *pA = *pB;
41044   *pB = tmp;
41045   pTmp = pA->pNext;
41046   pA->pNext = pB->pNext;
41047   pB->pNext = pTmp;
41048   pTmp = pA->pPrev;
41049   pA->pPrev = pB->pPrev;
41050   pB->pPrev = pTmp;
41051   zTmp = pA->zSql;
41052   pA->zSql = pB->zSql;
41053   pB->zSql = zTmp;
41054   nTmp = pA->nSql;
41055   pA->nSql = pB->nSql;
41056   pB->nSql = nTmp;
41057 }
41058
41059 #ifdef SQLITE_DEBUG
41060 /*
41061 ** Turn tracing on or off
41062 */
41063 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
41064   p->trace = trace;
41065 }
41066 #endif
41067
41068 /*
41069 ** Resize the Vdbe.aOp array so that it contains at least N
41070 ** elements.
41071 **
41072 ** If an out-of-memory error occurs while resizing the array,
41073 ** Vdbe.aOp and Vdbe.nOpAlloc remain unchanged (this is so that
41074 ** any opcodes already allocated can be correctly deallocated
41075 ** along with the rest of the Vdbe).
41076 */
41077 static void resizeOpArray(Vdbe *p, int N){
41078   VdbeOp *pNew;
41079   pNew = sqlite3DbRealloc(p->db, p->aOp, N*sizeof(Op));
41080   if( pNew ){
41081     p->nOpAlloc = N;
41082     p->aOp = pNew;
41083   }
41084 }
41085
41086 /*
41087 ** Add a new instruction to the list of instructions current in the
41088 ** VDBE.  Return the address of the new instruction.
41089 **
41090 ** Parameters:
41091 **
41092 **    p               Pointer to the VDBE
41093 **
41094 **    op              The opcode for this instruction
41095 **
41096 **    p1, p2, p3      Operands
41097 **
41098 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
41099 ** the sqlite3VdbeChangeP4() function to change the value of the P4
41100 ** operand.
41101 */
41102 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
41103   int i;
41104   VdbeOp *pOp;
41105
41106   i = p->nOp;
41107   assert( p->magic==VDBE_MAGIC_INIT );
41108   if( p->nOpAlloc<=i ){
41109     resizeOpArray(p, p->nOpAlloc ? p->nOpAlloc*2 : 1024/sizeof(Op));
41110     if( p->db->mallocFailed ){
41111       return 0;
41112     }
41113   }
41114   p->nOp++;
41115   pOp = &p->aOp[i];
41116   pOp->opcode = op;
41117   pOp->p5 = 0;
41118   pOp->p1 = p1;
41119   pOp->p2 = p2;
41120   pOp->p3 = p3;
41121   pOp->p4.p = 0;
41122   pOp->p4type = P4_NOTUSED;
41123   p->expired = 0;
41124 #ifdef SQLITE_DEBUG
41125   pOp->zComment = 0;
41126   if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
41127 #endif
41128 #ifdef VDBE_PROFILE
41129   pOp->cycles = 0;
41130   pOp->cnt = 0;
41131 #endif
41132   return i;
41133 }
41134 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
41135   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
41136 }
41137 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
41138   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
41139 }
41140 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
41141   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
41142 }
41143
41144
41145 /*
41146 ** Add an opcode that includes the p4 value as a pointer.
41147 */
41148 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
41149   Vdbe *p,            /* Add the opcode to this VM */
41150   int op,             /* The new opcode */
41151   int p1,             /* The P1 operand */
41152   int p2,             /* The P2 operand */
41153   int p3,             /* The P3 operand */
41154   const char *zP4,    /* The P4 operand */
41155   int p4type          /* P4 operand type */
41156 ){
41157   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
41158   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
41159   return addr;
41160 }
41161
41162 /*
41163 ** Create a new symbolic label for an instruction that has yet to be
41164 ** coded.  The symbolic label is really just a negative number.  The
41165 ** label can be used as the P2 value of an operation.  Later, when
41166 ** the label is resolved to a specific address, the VDBE will scan
41167 ** through its operation list and change all values of P2 which match
41168 ** the label into the resolved address.
41169 **
41170 ** The VDBE knows that a P2 value is a label because labels are
41171 ** always negative and P2 values are suppose to be non-negative.
41172 ** Hence, a negative P2 value is a label that has yet to be resolved.
41173 **
41174 ** Zero is returned if a malloc() fails.
41175 */
41176 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
41177   int i;
41178   i = p->nLabel++;
41179   assert( p->magic==VDBE_MAGIC_INIT );
41180   if( i>=p->nLabelAlloc ){
41181     p->nLabelAlloc = p->nLabelAlloc*2 + 10;
41182     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
41183                                     p->nLabelAlloc*sizeof(p->aLabel[0]));
41184   }
41185   if( p->aLabel ){
41186     p->aLabel[i] = -1;
41187   }
41188   return -1-i;
41189 }
41190
41191 /*
41192 ** Resolve label "x" to be the address of the next instruction to
41193 ** be inserted.  The parameter "x" must have been obtained from
41194 ** a prior call to sqlite3VdbeMakeLabel().
41195 */
41196 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
41197   int j = -1-x;
41198   assert( p->magic==VDBE_MAGIC_INIT );
41199   assert( j>=0 && j<p->nLabel );
41200   if( p->aLabel ){
41201     p->aLabel[j] = p->nOp;
41202   }
41203 }
41204
41205 /*
41206 ** Loop through the program looking for P2 values that are negative
41207 ** on jump instructions.  Each such value is a label.  Resolve the
41208 ** label by setting the P2 value to its correct non-zero value.
41209 **
41210 ** This routine is called once after all opcodes have been inserted.
41211 **
41212 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
41213 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by 
41214 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
41215 **
41216 ** This routine also does the following optimization:  It scans for
41217 ** instructions that might cause a statement rollback.  Such instructions
41218 ** are:
41219 **
41220 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
41221 **   *  OP_Destroy
41222 **   *  OP_VUpdate
41223 **   *  OP_VRename
41224 **
41225 ** If no such instruction is found, then every Statement instruction 
41226 ** is changed to a Noop.  In this way, we avoid creating the statement 
41227 ** journal file unnecessarily.
41228 */
41229 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
41230   int i;
41231   int nMaxArgs = 0;
41232   Op *pOp;
41233   int *aLabel = p->aLabel;
41234   int doesStatementRollback = 0;
41235   int hasStatementBegin = 0;
41236   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
41237     u8 opcode = pOp->opcode;
41238
41239     if( opcode==OP_Function || opcode==OP_AggStep ){
41240       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
41241 #ifndef SQLITE_OMIT_VIRTUALTABLE
41242     }else if( opcode==OP_VUpdate ){
41243       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
41244 #endif
41245     }
41246     if( opcode==OP_Halt ){
41247       if( pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort ){
41248         doesStatementRollback = 1;
41249       }
41250     }else if( opcode==OP_Statement ){
41251       hasStatementBegin = 1;
41252     }else if( opcode==OP_Destroy ){
41253       doesStatementRollback = 1;
41254 #ifndef SQLITE_OMIT_VIRTUALTABLE
41255     }else if( opcode==OP_VUpdate || opcode==OP_VRename ){
41256       doesStatementRollback = 1;
41257     }else if( opcode==OP_VFilter ){
41258       int n;
41259       assert( p->nOp - i >= 3 );
41260       assert( pOp[-1].opcode==OP_Integer );
41261       n = pOp[-1].p1;
41262       if( n>nMaxArgs ) nMaxArgs = n;
41263 #endif
41264     }
41265
41266     if( sqlite3VdbeOpcodeHasProperty(opcode, OPFLG_JUMP) && pOp->p2<0 ){
41267       assert( -1-pOp->p2<p->nLabel );
41268       pOp->p2 = aLabel[-1-pOp->p2];
41269     }
41270   }
41271   sqlite3DbFree(p->db, p->aLabel);
41272   p->aLabel = 0;
41273
41274   *pMaxFuncArgs = nMaxArgs;
41275
41276   /* If we never rollback a statement transaction, then statement
41277   ** transactions are not needed.  So change every OP_Statement
41278   ** opcode into an OP_Noop.  This avoid a call to sqlite3OsOpenExclusive()
41279   ** which can be expensive on some platforms.
41280   */
41281   if( hasStatementBegin && !doesStatementRollback ){
41282     for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
41283       if( pOp->opcode==OP_Statement ){
41284         pOp->opcode = OP_Noop;
41285       }
41286     }
41287   }
41288 }
41289
41290 /*
41291 ** Return the address of the next instruction to be inserted.
41292 */
41293 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
41294   assert( p->magic==VDBE_MAGIC_INIT );
41295   return p->nOp;
41296 }
41297
41298 /*
41299 ** Add a whole list of operations to the operation stack.  Return the
41300 ** address of the first operation added.
41301 */
41302 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
41303   int addr;
41304   assert( p->magic==VDBE_MAGIC_INIT );
41305   if( p->nOp + nOp > p->nOpAlloc ){
41306     resizeOpArray(p, p->nOpAlloc ? p->nOpAlloc*2 : 1024/sizeof(Op));
41307     assert( p->nOp+nOp<=p->nOpAlloc || p->db->mallocFailed );
41308   }
41309   if( p->db->mallocFailed ){
41310     return 0;
41311   }
41312   addr = p->nOp;
41313   if( nOp>0 ){
41314     int i;
41315     VdbeOpList const *pIn = aOp;
41316     for(i=0; i<nOp; i++, pIn++){
41317       int p2 = pIn->p2;
41318       VdbeOp *pOut = &p->aOp[i+addr];
41319       pOut->opcode = pIn->opcode;
41320       pOut->p1 = pIn->p1;
41321       if( p2<0 && sqlite3VdbeOpcodeHasProperty(pOut->opcode, OPFLG_JUMP) ){
41322         pOut->p2 = addr + ADDR(p2);
41323       }else{
41324         pOut->p2 = p2;
41325       }
41326       pOut->p3 = pIn->p3;
41327       pOut->p4type = P4_NOTUSED;
41328       pOut->p4.p = 0;
41329       pOut->p5 = 0;
41330 #ifdef SQLITE_DEBUG
41331       pOut->zComment = 0;
41332       if( sqlite3VdbeAddopTrace ){
41333         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
41334       }
41335 #endif
41336     }
41337     p->nOp += nOp;
41338   }
41339   return addr;
41340 }
41341
41342 /*
41343 ** Change the value of the P1 operand for a specific instruction.
41344 ** This routine is useful when a large program is loaded from a
41345 ** static array using sqlite3VdbeAddOpList but we want to make a
41346 ** few minor changes to the program.
41347 */
41348 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
41349   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
41350   if( p && addr>=0 && p->nOp>addr && p->aOp ){
41351     p->aOp[addr].p1 = val;
41352   }
41353 }
41354
41355 /*
41356 ** Change the value of the P2 operand for a specific instruction.
41357 ** This routine is useful for setting a jump destination.
41358 */
41359 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
41360   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
41361   if( p && addr>=0 && p->nOp>addr && p->aOp ){
41362     p->aOp[addr].p2 = val;
41363   }
41364 }
41365
41366 /*
41367 ** Change the value of the P3 operand for a specific instruction.
41368 */
41369 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
41370   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
41371   if( p && addr>=0 && p->nOp>addr && p->aOp ){
41372     p->aOp[addr].p3 = val;
41373   }
41374 }
41375
41376 /*
41377 ** Change the value of the P5 operand for the most recently
41378 ** added operation.
41379 */
41380 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
41381   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
41382   if( p && p->aOp ){
41383     assert( p->nOp>0 );
41384     p->aOp[p->nOp-1].p5 = val;
41385   }
41386 }
41387
41388 /*
41389 ** Change the P2 operand of instruction addr so that it points to
41390 ** the address of the next instruction to be coded.
41391 */
41392 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
41393   sqlite3VdbeChangeP2(p, addr, p->nOp);
41394 }
41395
41396
41397 /*
41398 ** If the input FuncDef structure is ephemeral, then free it.  If
41399 ** the FuncDef is not ephermal, then do nothing.
41400 */
41401 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
41402   if( pDef && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
41403     sqlite3DbFree(db, pDef);
41404   }
41405 }
41406
41407 /*
41408 ** Delete a P4 value if necessary.
41409 */
41410 static void freeP4(sqlite3 *db, int p4type, void *p4){
41411   if( p4 ){
41412     switch( p4type ){
41413       case P4_REAL:
41414       case P4_INT64:
41415       case P4_MPRINTF:
41416       case P4_DYNAMIC:
41417       case P4_KEYINFO:
41418       case P4_INTARRAY:
41419       case P4_KEYINFO_HANDOFF: {
41420         sqlite3DbFree(db, p4);
41421         break;
41422       }
41423       case P4_VDBEFUNC: {
41424         VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
41425         freeEphemeralFunction(db, pVdbeFunc->pFunc);
41426         sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
41427         sqlite3DbFree(db, pVdbeFunc);
41428         break;
41429       }
41430       case P4_FUNCDEF: {
41431         freeEphemeralFunction(db, (FuncDef*)p4);
41432         break;
41433       }
41434       case P4_MEM: {
41435         sqlite3ValueFree((sqlite3_value*)p4);
41436         break;
41437       }
41438     }
41439   }
41440 }
41441
41442
41443 /*
41444 ** Change N opcodes starting at addr to No-ops.
41445 */
41446 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
41447   if( p && p->aOp ){
41448     VdbeOp *pOp = &p->aOp[addr];
41449     sqlite3 *db = p->db;
41450     while( N-- ){
41451       freeP4(db, pOp->p4type, pOp->p4.p);
41452       memset(pOp, 0, sizeof(pOp[0]));
41453       pOp->opcode = OP_Noop;
41454       pOp++;
41455     }
41456   }
41457 }
41458
41459 /*
41460 ** Change the value of the P4 operand for a specific instruction.
41461 ** This routine is useful when a large program is loaded from a
41462 ** static array using sqlite3VdbeAddOpList but we want to make a
41463 ** few minor changes to the program.
41464 **
41465 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
41466 ** the string is made into memory obtained from sqlite3_malloc().
41467 ** A value of n==0 means copy bytes of zP4 up to and including the
41468 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
41469 **
41470 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
41471 ** A copy is made of the KeyInfo structure into memory obtained from
41472 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
41473 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
41474 ** stored in memory that the caller has obtained from sqlite3_malloc. The 
41475 ** caller should not free the allocation, it will be freed when the Vdbe is
41476 ** finalized.
41477 ** 
41478 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
41479 ** to a string or structure that is guaranteed to exist for the lifetime of
41480 ** the Vdbe. In these cases we can just copy the pointer.
41481 **
41482 ** If addr<0 then change P4 on the most recently inserted instruction.
41483 */
41484 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
41485   Op *pOp;
41486   sqlite3 *db;
41487   assert( p!=0 );
41488   db = p->db;
41489   assert( p->magic==VDBE_MAGIC_INIT );
41490   if( p->aOp==0 || db->mallocFailed ){
41491     if (n != P4_KEYINFO) {
41492       freeP4(db, n, (void*)*(char**)&zP4);
41493     }
41494     return;
41495   }
41496   assert( addr<p->nOp );
41497   if( addr<0 ){
41498     addr = p->nOp - 1;
41499     if( addr<0 ) return;
41500   }
41501   pOp = &p->aOp[addr];
41502   freeP4(db, pOp->p4type, pOp->p4.p);
41503   pOp->p4.p = 0;
41504   if( n==P4_INT32 ){
41505     /* Note: this cast is safe, because the origin data point was an int
41506     ** that was cast to a (const char *). */
41507     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
41508     pOp->p4type = n;
41509   }else if( zP4==0 ){
41510     pOp->p4.p = 0;
41511     pOp->p4type = P4_NOTUSED;
41512   }else if( n==P4_KEYINFO ){
41513     KeyInfo *pKeyInfo;
41514     int nField, nByte;
41515
41516     nField = ((KeyInfo*)zP4)->nField;
41517     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
41518     pKeyInfo = sqlite3Malloc( nByte );
41519     pOp->p4.pKeyInfo = pKeyInfo;
41520     if( pKeyInfo ){
41521       u8 *aSortOrder;
41522       memcpy(pKeyInfo, zP4, nByte);
41523       aSortOrder = pKeyInfo->aSortOrder;
41524       if( aSortOrder ){
41525         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
41526         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
41527       }
41528       pOp->p4type = P4_KEYINFO;
41529     }else{
41530       p->db->mallocFailed = 1;
41531       pOp->p4type = P4_NOTUSED;
41532     }
41533   }else if( n==P4_KEYINFO_HANDOFF ){
41534     pOp->p4.p = (void*)zP4;
41535     pOp->p4type = P4_KEYINFO;
41536   }else if( n<0 ){
41537     pOp->p4.p = (void*)zP4;
41538     pOp->p4type = n;
41539   }else{
41540     if( n==0 ) n = strlen(zP4);
41541     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
41542     pOp->p4type = P4_DYNAMIC;
41543   }
41544 }
41545
41546 #ifndef NDEBUG
41547 /*
41548 ** Change the comment on the the most recently coded instruction.  Or
41549 ** insert a No-op and add the comment to that new instruction.  This
41550 ** makes the code easier to read during debugging.  None of this happens
41551 ** in a production build.
41552 */
41553 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
41554   va_list ap;
41555   assert( p->nOp>0 || p->aOp==0 );
41556   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
41557   if( p->nOp ){
41558     char **pz = &p->aOp[p->nOp-1].zComment;
41559     va_start(ap, zFormat);
41560     sqlite3DbFree(p->db, *pz);
41561     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
41562     va_end(ap);
41563   }
41564 }
41565 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
41566   va_list ap;
41567   sqlite3VdbeAddOp0(p, OP_Noop);
41568   assert( p->nOp>0 || p->aOp==0 );
41569   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
41570   if( p->nOp ){
41571     char **pz = &p->aOp[p->nOp-1].zComment;
41572     va_start(ap, zFormat);
41573     sqlite3DbFree(p->db, *pz);
41574     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
41575     va_end(ap);
41576   }
41577 }
41578 #endif  /* NDEBUG */
41579
41580 /*
41581 ** Return the opcode for a given address.
41582 */
41583 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
41584   assert( p->magic==VDBE_MAGIC_INIT );
41585   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
41586   return ((addr>=0 && addr<p->nOp)?(&p->aOp[addr]):0);
41587 }
41588
41589 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
41590      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
41591 /*
41592 ** Compute a string that describes the P4 parameter for an opcode.
41593 ** Use zTemp for any required temporary buffer space.
41594 */
41595 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
41596   char *zP4 = zTemp;
41597   assert( nTemp>=20 );
41598   switch( pOp->p4type ){
41599     case P4_KEYINFO_STATIC:
41600     case P4_KEYINFO: {
41601       int i, j;
41602       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
41603       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
41604       i = strlen(zTemp);
41605       for(j=0; j<pKeyInfo->nField; j++){
41606         CollSeq *pColl = pKeyInfo->aColl[j];
41607         if( pColl ){
41608           int n = strlen(pColl->zName);
41609           if( i+n>nTemp-6 ){
41610             memcpy(&zTemp[i],",...",4);
41611             break;
41612           }
41613           zTemp[i++] = ',';
41614           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
41615             zTemp[i++] = '-';
41616           }
41617           memcpy(&zTemp[i], pColl->zName,n+1);
41618           i += n;
41619         }else if( i+4<nTemp-6 ){
41620           memcpy(&zTemp[i],",nil",4);
41621           i += 4;
41622         }
41623       }
41624       zTemp[i++] = ')';
41625       zTemp[i] = 0;
41626       assert( i<nTemp );
41627       break;
41628     }
41629     case P4_COLLSEQ: {
41630       CollSeq *pColl = pOp->p4.pColl;
41631       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
41632       break;
41633     }
41634     case P4_FUNCDEF: {
41635       FuncDef *pDef = pOp->p4.pFunc;
41636       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
41637       break;
41638     }
41639     case P4_INT64: {
41640       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
41641       break;
41642     }
41643     case P4_INT32: {
41644       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
41645       break;
41646     }
41647     case P4_REAL: {
41648       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
41649       break;
41650     }
41651     case P4_MEM: {
41652       Mem *pMem = pOp->p4.pMem;
41653       assert( (pMem->flags & MEM_Null)==0 );
41654       if( pMem->flags & MEM_Str ){
41655         zP4 = pMem->z;
41656       }else if( pMem->flags & MEM_Int ){
41657         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
41658       }else if( pMem->flags & MEM_Real ){
41659         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
41660       }
41661       break;
41662     }
41663 #ifndef SQLITE_OMIT_VIRTUALTABLE
41664     case P4_VTAB: {
41665       sqlite3_vtab *pVtab = pOp->p4.pVtab;
41666       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
41667       break;
41668     }
41669 #endif
41670     case P4_INTARRAY: {
41671       sqlite3_snprintf(nTemp, zTemp, "intarray");
41672       break;
41673     }
41674     default: {
41675       zP4 = pOp->p4.z;
41676       if( zP4==0 ){
41677         zP4 = zTemp;
41678         zTemp[0] = 0;
41679       }
41680     }
41681   }
41682   assert( zP4!=0 );
41683   return zP4;
41684 }
41685 #endif
41686
41687 /*
41688 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
41689 **
41690 */
41691 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
41692   int mask;
41693   assert( i>=0 && i<p->db->nDb );
41694   assert( i<sizeof(p->btreeMask)*8 );
41695   mask = 1<<i;
41696   if( (p->btreeMask & mask)==0 ){
41697     p->btreeMask |= mask;
41698     sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
41699   }
41700 }
41701
41702
41703 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
41704 /*
41705 ** Print a single opcode.  This routine is used for debugging only.
41706 */
41707 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
41708   char *zP4;
41709   char zPtr[50];
41710   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
41711   if( pOut==0 ) pOut = stdout;
41712   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
41713   fprintf(pOut, zFormat1, pc, 
41714       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
41715 #ifdef SQLITE_DEBUG
41716       pOp->zComment ? pOp->zComment : ""
41717 #else
41718       ""
41719 #endif
41720   );
41721   fflush(pOut);
41722 }
41723 #endif
41724
41725 /*
41726 ** Release an array of N Mem elements
41727 */
41728 static void releaseMemArray(Mem *p, int N){
41729   if( p && N ){
41730     sqlite3 *db = p->db;
41731     int malloc_failed = db->mallocFailed;
41732     while( N-->0 ){
41733       assert( N<2 || p[0].db==p[1].db );
41734       sqlite3VdbeMemRelease(p);
41735       p->flags = MEM_Null;
41736       p++;
41737     }
41738     db->mallocFailed = malloc_failed;
41739   }
41740 }
41741
41742 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
41743 SQLITE_PRIVATE int sqlite3VdbeReleaseBuffers(Vdbe *p){
41744   int ii;
41745   int nFree = 0;
41746   assert( sqlite3_mutex_held(p->db->mutex) );
41747   for(ii=1; ii<=p->nMem; ii++){
41748     Mem *pMem = &p->aMem[ii];
41749     if( pMem->z && pMem->flags&MEM_Dyn ){
41750       assert( !pMem->xDel );
41751       nFree += sqlite3DbMallocSize(pMem->db, pMem->z);
41752       sqlite3VdbeMemRelease(pMem);
41753     }
41754   }
41755   return nFree;
41756 }
41757 #endif
41758
41759 #ifndef SQLITE_OMIT_EXPLAIN
41760 /*
41761 ** Give a listing of the program in the virtual machine.
41762 **
41763 ** The interface is the same as sqlite3VdbeExec().  But instead of
41764 ** running the code, it invokes the callback once for each instruction.
41765 ** This feature is used to implement "EXPLAIN".
41766 **
41767 ** When p->explain==1, each instruction is listed.  When
41768 ** p->explain==2, only OP_Explain instructions are listed and these
41769 ** are shown in a different format.  p->explain==2 is used to implement
41770 ** EXPLAIN QUERY PLAN.
41771 */
41772 SQLITE_PRIVATE int sqlite3VdbeList(
41773   Vdbe *p                   /* The VDBE */
41774 ){
41775   sqlite3 *db = p->db;
41776   int i;
41777   int rc = SQLITE_OK;
41778   Mem *pMem = p->pResultSet = &p->aMem[1];
41779
41780   assert( p->explain );
41781   if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
41782   assert( db->magic==SQLITE_MAGIC_BUSY );
41783   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
41784
41785   /* Even though this opcode does not use dynamic strings for
41786   ** the result, result columns may become dynamic if the user calls
41787   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
41788   */
41789   releaseMemArray(pMem, p->nMem);
41790
41791   do{
41792     i = p->pc++;
41793   }while( i<p->nOp && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
41794   if( i>=p->nOp ){
41795     p->rc = SQLITE_OK;
41796     rc = SQLITE_DONE;
41797   }else if( db->u1.isInterrupted ){
41798     p->rc = SQLITE_INTERRUPT;
41799     rc = SQLITE_ERROR;
41800     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
41801   }else{
41802     char *z;
41803     Op *pOp = &p->aOp[i];
41804     if( p->explain==1 ){
41805       pMem->flags = MEM_Int;
41806       pMem->type = SQLITE_INTEGER;
41807       pMem->u.i = i;                                /* Program counter */
41808       pMem++;
41809   
41810       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
41811       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
41812       assert( pMem->z!=0 );
41813       pMem->n = strlen(pMem->z);
41814       pMem->type = SQLITE_TEXT;
41815       pMem->enc = SQLITE_UTF8;
41816       pMem++;
41817     }
41818
41819     pMem->flags = MEM_Int;
41820     pMem->u.i = pOp->p1;                          /* P1 */
41821     pMem->type = SQLITE_INTEGER;
41822     pMem++;
41823
41824     pMem->flags = MEM_Int;
41825     pMem->u.i = pOp->p2;                          /* P2 */
41826     pMem->type = SQLITE_INTEGER;
41827     pMem++;
41828
41829     if( p->explain==1 ){
41830       pMem->flags = MEM_Int;
41831       pMem->u.i = pOp->p3;                          /* P3 */
41832       pMem->type = SQLITE_INTEGER;
41833       pMem++;
41834     }
41835
41836     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
41837       p->db->mallocFailed = 1;
41838       return SQLITE_NOMEM;
41839     }
41840     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
41841     z = displayP4(pOp, pMem->z, 32);
41842     if( z!=pMem->z ){
41843       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
41844     }else{
41845       assert( pMem->z!=0 );
41846       pMem->n = strlen(pMem->z);
41847       pMem->enc = SQLITE_UTF8;
41848     }
41849     pMem->type = SQLITE_TEXT;
41850     pMem++;
41851
41852     if( p->explain==1 ){
41853       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
41854         p->db->mallocFailed = 1;
41855         return SQLITE_NOMEM;
41856       }
41857       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
41858       pMem->n = 2;
41859       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
41860       pMem->type = SQLITE_TEXT;
41861       pMem->enc = SQLITE_UTF8;
41862       pMem++;
41863   
41864 #ifdef SQLITE_DEBUG
41865       if( pOp->zComment ){
41866         pMem->flags = MEM_Str|MEM_Term;
41867         pMem->z = pOp->zComment;
41868         pMem->n = strlen(pMem->z);
41869         pMem->enc = SQLITE_UTF8;
41870       }else
41871 #endif
41872       {
41873         pMem->flags = MEM_Null;                       /* Comment */
41874         pMem->type = SQLITE_NULL;
41875       }
41876     }
41877
41878     p->nResColumn = 8 - 5*(p->explain-1);
41879     p->rc = SQLITE_OK;
41880     rc = SQLITE_ROW;
41881   }
41882   return rc;
41883 }
41884 #endif /* SQLITE_OMIT_EXPLAIN */
41885
41886 #ifdef SQLITE_DEBUG
41887 /*
41888 ** Print the SQL that was used to generate a VDBE program.
41889 */
41890 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
41891   int nOp = p->nOp;
41892   VdbeOp *pOp;
41893   if( nOp<1 ) return;
41894   pOp = &p->aOp[0];
41895   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
41896     const char *z = pOp->p4.z;
41897     while( isspace(*(u8*)z) ) z++;
41898     printf("SQL: [%s]\n", z);
41899   }
41900 }
41901 #endif
41902
41903 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
41904 /*
41905 ** Print an IOTRACE message showing SQL content.
41906 */
41907 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
41908   int nOp = p->nOp;
41909   VdbeOp *pOp;
41910   if( sqlite3IoTrace==0 ) return;
41911   if( nOp<1 ) return;
41912   pOp = &p->aOp[0];
41913   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
41914     int i, j;
41915     char z[1000];
41916     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
41917     for(i=0; isspace((unsigned char)z[i]); i++){}
41918     for(j=0; z[i]; i++){
41919       if( isspace((unsigned char)z[i]) ){
41920         if( z[i-1]!=' ' ){
41921           z[j++] = ' ';
41922         }
41923       }else{
41924         z[j++] = z[i];
41925       }
41926     }
41927     z[j] = 0;
41928     sqlite3IoTrace("SQL %s\n", z);
41929   }
41930 }
41931 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
41932
41933
41934 /*
41935 ** Prepare a virtual machine for execution.  This involves things such
41936 ** as allocating stack space and initializing the program counter.
41937 ** After the VDBE has be prepped, it can be executed by one or more
41938 ** calls to sqlite3VdbeExec().  
41939 **
41940 ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
41941 ** VDBE_MAGIC_RUN.
41942 */
41943 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
41944   Vdbe *p,                       /* The VDBE */
41945   int nVar,                      /* Number of '?' see in the SQL statement */
41946   int nMem,                      /* Number of memory cells to allocate */
41947   int nCursor,                   /* Number of cursors to allocate */
41948   int isExplain                  /* True if the EXPLAIN keywords is present */
41949 ){
41950   int n;
41951   sqlite3 *db = p->db;
41952
41953   assert( p!=0 );
41954   assert( p->magic==VDBE_MAGIC_INIT );
41955
41956   /* There should be at least one opcode.
41957   */
41958   assert( p->nOp>0 );
41959
41960   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. This
41961    * is because the call to resizeOpArray() below may shrink the
41962    * p->aOp[] array to save memory if called when in VDBE_MAGIC_RUN 
41963    * state.
41964    */
41965   p->magic = VDBE_MAGIC_RUN;
41966
41967   /* For each cursor required, also allocate a memory cell. Memory
41968   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
41969   ** the vdbe program. Instead they are used to allocate space for
41970   ** Cursor/BtCursor structures. The blob of memory associated with 
41971   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
41972   ** stores the blob of memory associated with cursor 1, etc.
41973   **
41974   ** See also: allocateCursor().
41975   */
41976   nMem += nCursor;
41977
41978   /*
41979   ** Allocation space for registers.
41980   */
41981   if( p->aMem==0 ){
41982     int nArg;       /* Maximum number of args passed to a user function. */
41983     resolveP2Values(p, &nArg);
41984     /*resizeOpArray(p, p->nOp);*/
41985     assert( nVar>=0 );
41986     if( isExplain && nMem<10 ){
41987       p->nMem = nMem = 10;
41988     }
41989     p->aMem = sqlite3DbMallocZero(db,
41990         nMem*sizeof(Mem)               /* aMem */
41991       + nVar*sizeof(Mem)               /* aVar */
41992       + nArg*sizeof(Mem*)              /* apArg */
41993       + nVar*sizeof(char*)             /* azVar */
41994       + nCursor*sizeof(Cursor*) + 1    /* apCsr */
41995     );
41996     if( !db->mallocFailed ){
41997       p->aMem--;             /* aMem[] goes from 1..nMem */
41998       p->nMem = nMem;        /*       not from 0..nMem-1 */
41999       p->aVar = &p->aMem[nMem+1];
42000       p->nVar = nVar;
42001       p->okVar = 0;
42002       p->apArg = (Mem**)&p->aVar[nVar];
42003       p->azVar = (char**)&p->apArg[nArg];
42004       p->apCsr = (Cursor**)&p->azVar[nVar];
42005       p->nCursor = nCursor;
42006       for(n=0; n<nVar; n++){
42007         p->aVar[n].flags = MEM_Null;
42008         p->aVar[n].db = db;
42009       }
42010       for(n=1; n<=nMem; n++){
42011         p->aMem[n].flags = MEM_Null;
42012         p->aMem[n].db = db;
42013       }
42014     }
42015   }
42016 #ifdef SQLITE_DEBUG
42017   for(n=1; n<p->nMem; n++){
42018     assert( p->aMem[n].db==db );
42019   }
42020 #endif
42021
42022   p->pc = -1;
42023   p->rc = SQLITE_OK;
42024   p->uniqueCnt = 0;
42025   p->errorAction = OE_Abort;
42026   p->explain |= isExplain;
42027   p->magic = VDBE_MAGIC_RUN;
42028   p->nChange = 0;
42029   p->cacheCtr = 1;
42030   p->minWriteFileFormat = 255;
42031   p->openedStatement = 0;
42032 #ifdef VDBE_PROFILE
42033   {
42034     int i;
42035     for(i=0; i<p->nOp; i++){
42036       p->aOp[i].cnt = 0;
42037       p->aOp[i].cycles = 0;
42038     }
42039   }
42040 #endif
42041 }
42042
42043 /*
42044 ** Close a VDBE cursor and release all the resources that cursor 
42045 ** happens to hold.
42046 */
42047 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, Cursor *pCx){
42048   if( pCx==0 ){
42049     return;
42050   }
42051   if( pCx->pBt ){
42052     sqlite3BtreeClose(pCx->pBt);
42053     /* The pCx->pCursor will be close automatically, if it exists, by
42054     ** the call above. */
42055   }else if( pCx->pCursor ){
42056     sqlite3BtreeCloseCursor(pCx->pCursor);
42057   }
42058 #ifndef SQLITE_OMIT_VIRTUALTABLE
42059   if( pCx->pVtabCursor ){
42060     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
42061     const sqlite3_module *pModule = pCx->pModule;
42062     p->inVtabMethod = 1;
42063     (void)sqlite3SafetyOff(p->db);
42064     pModule->xClose(pVtabCursor);
42065     (void)sqlite3SafetyOn(p->db);
42066     p->inVtabMethod = 0;
42067   }
42068 #endif
42069   if( !pCx->ephemPseudoTable ){
42070     sqlite3DbFree(p->db, pCx->pData);
42071   }
42072 }
42073
42074 /*
42075 ** Close all cursors except for VTab cursors that are currently
42076 ** in use.
42077 */
42078 static void closeAllCursorsExceptActiveVtabs(Vdbe *p){
42079   int i;
42080   if( p->apCsr==0 ) return;
42081   for(i=0; i<p->nCursor; i++){
42082     Cursor *pC = p->apCsr[i];
42083     if( pC && (!p->inVtabMethod || !pC->pVtabCursor) ){
42084       sqlite3VdbeFreeCursor(p, pC);
42085       p->apCsr[i] = 0;
42086     }
42087   }
42088 }
42089
42090 /*
42091 ** Clean up the VM after execution.
42092 **
42093 ** This routine will automatically close any cursors, lists, and/or
42094 ** sorters that were left open.  It also deletes the values of
42095 ** variables in the aVar[] array.
42096 */
42097 static void Cleanup(Vdbe *p){
42098   int i;
42099   sqlite3 *db = p->db;
42100   closeAllCursorsExceptActiveVtabs(p);
42101   for(i=1; i<=p->nMem; i++){
42102     MemSetTypeFlag(&p->aMem[i], MEM_Null);
42103   }
42104   releaseMemArray(&p->aMem[1], p->nMem);
42105   sqlite3VdbeFifoClear(&p->sFifo);
42106   if( p->contextStack ){
42107     for(i=0; i<p->contextStackTop; i++){
42108       sqlite3VdbeFifoClear(&p->contextStack[i].sFifo);
42109     }
42110     sqlite3DbFree(db, p->contextStack);
42111   }
42112   p->contextStack = 0;
42113   p->contextStackDepth = 0;
42114   p->contextStackTop = 0;
42115   sqlite3DbFree(db, p->zErrMsg);
42116   p->zErrMsg = 0;
42117   p->pResultSet = 0;
42118 }
42119
42120 /*
42121 ** Set the number of result columns that will be returned by this SQL
42122 ** statement. This is now set at compile time, rather than during
42123 ** execution of the vdbe program so that sqlite3_column_count() can
42124 ** be called on an SQL statement before sqlite3_step().
42125 */
42126 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
42127   Mem *pColName;
42128   int n;
42129   sqlite3 *db = p->db;
42130
42131   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
42132   sqlite3DbFree(db, p->aColName);
42133   n = nResColumn*COLNAME_N;
42134   p->nResColumn = nResColumn;
42135   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
42136   if( p->aColName==0 ) return;
42137   while( n-- > 0 ){
42138     pColName->flags = MEM_Null;
42139     pColName->db = p->db;
42140     pColName++;
42141   }
42142 }
42143
42144 /*
42145 ** Set the name of the idx'th column to be returned by the SQL statement.
42146 ** zName must be a pointer to a nul terminated string.
42147 **
42148 ** This call must be made after a call to sqlite3VdbeSetNumCols().
42149 **
42150 ** If N==P4_STATIC  it means that zName is a pointer to a constant static
42151 ** string and we can just copy the pointer. If it is P4_DYNAMIC, then 
42152 ** the string is freed using sqlite3DbFree(db, ) when the vdbe is finished with
42153 ** it. Otherwise, N bytes of zName are copied.
42154 */
42155 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe *p, int idx, int var, const char *zName, int N){
42156   int rc;
42157   Mem *pColName;
42158   assert( idx<p->nResColumn );
42159   assert( var<COLNAME_N );
42160   if( p->db->mallocFailed ) return SQLITE_NOMEM;
42161   assert( p->aColName!=0 );
42162   pColName = &(p->aColName[idx+var*p->nResColumn]);
42163   if( N==P4_DYNAMIC || N==P4_STATIC ){
42164     rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, SQLITE_STATIC);
42165   }else{
42166     rc = sqlite3VdbeMemSetStr(pColName, zName, N, SQLITE_UTF8,SQLITE_TRANSIENT);
42167   }
42168   if( rc==SQLITE_OK && N==P4_DYNAMIC ){
42169     pColName->flags &= (~MEM_Static);
42170     pColName->zMalloc = pColName->z;
42171   }
42172   return rc;
42173 }
42174
42175 /*
42176 ** A read or write transaction may or may not be active on database handle
42177 ** db. If a transaction is active, commit it. If there is a
42178 ** write-transaction spanning more than one database file, this routine
42179 ** takes care of the master journal trickery.
42180 */
42181 static int vdbeCommit(sqlite3 *db, Vdbe *p){
42182   int i;
42183   int nTrans = 0;  /* Number of databases with an active write-transaction */
42184   int rc = SQLITE_OK;
42185   int needXcommit = 0;
42186
42187   /* Before doing anything else, call the xSync() callback for any
42188   ** virtual module tables written in this transaction. This has to
42189   ** be done before determining whether a master journal file is 
42190   ** required, as an xSync() callback may add an attached database
42191   ** to the transaction.
42192   */
42193   rc = sqlite3VtabSync(db, &p->zErrMsg);
42194   if( rc!=SQLITE_OK ){
42195     return rc;
42196   }
42197
42198   /* This loop determines (a) if the commit hook should be invoked and
42199   ** (b) how many database files have open write transactions, not 
42200   ** including the temp database. (b) is important because if more than 
42201   ** one database file has an open write transaction, a master journal
42202   ** file is required for an atomic commit.
42203   */ 
42204   for(i=0; i<db->nDb; i++){ 
42205     Btree *pBt = db->aDb[i].pBt;
42206     if( sqlite3BtreeIsInTrans(pBt) ){
42207       needXcommit = 1;
42208       if( i!=1 ) nTrans++;
42209     }
42210   }
42211
42212   /* If there are any write-transactions at all, invoke the commit hook */
42213   if( needXcommit && db->xCommitCallback ){
42214     (void)sqlite3SafetyOff(db);
42215     rc = db->xCommitCallback(db->pCommitArg);
42216     (void)sqlite3SafetyOn(db);
42217     if( rc ){
42218       return SQLITE_CONSTRAINT;
42219     }
42220   }
42221
42222   /* The simple case - no more than one database file (not counting the
42223   ** TEMP database) has a transaction active.   There is no need for the
42224   ** master-journal.
42225   **
42226   ** If the return value of sqlite3BtreeGetFilename() is a zero length
42227   ** string, it means the main database is :memory: or a temp file.  In 
42228   ** that case we do not support atomic multi-file commits, so use the 
42229   ** simple case then too.
42230   */
42231   if( 0==strlen(sqlite3BtreeGetFilename(db->aDb[0].pBt)) || nTrans<=1 ){
42232     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
42233       Btree *pBt = db->aDb[i].pBt;
42234       if( pBt ){
42235         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
42236       }
42237     }
42238
42239     /* Do the commit only if all databases successfully complete phase 1. 
42240     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
42241     ** IO error while deleting or truncating a journal file. It is unlikely,
42242     ** but could happen. In this case abandon processing and return the error.
42243     */
42244     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
42245       Btree *pBt = db->aDb[i].pBt;
42246       if( pBt ){
42247         rc = sqlite3BtreeCommitPhaseTwo(pBt);
42248       }
42249     }
42250     if( rc==SQLITE_OK ){
42251       sqlite3VtabCommit(db);
42252     }
42253   }
42254
42255   /* The complex case - There is a multi-file write-transaction active.
42256   ** This requires a master journal file to ensure the transaction is
42257   ** committed atomicly.
42258   */
42259 #ifndef SQLITE_OMIT_DISKIO
42260   else{
42261     sqlite3_vfs *pVfs = db->pVfs;
42262     int needSync = 0;
42263     char *zMaster = 0;   /* File-name for the master journal */
42264     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
42265     sqlite3_file *pMaster = 0;
42266     i64 offset = 0;
42267     int res;
42268
42269     /* Select a master journal file name */
42270     do {
42271       u32 random;
42272       sqlite3DbFree(db, zMaster);
42273       sqlite3_randomness(sizeof(random), &random);
42274       zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, random&0x7fffffff);
42275       if( !zMaster ){
42276         return SQLITE_NOMEM;
42277       }
42278       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
42279     }while( rc==SQLITE_OK && res );
42280     if( rc==SQLITE_OK ){
42281       /* Open the master journal. */
42282       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
42283           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
42284           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
42285       );
42286     }
42287     if( rc!=SQLITE_OK ){
42288       sqlite3DbFree(db, zMaster);
42289       return rc;
42290     }
42291  
42292     /* Write the name of each database file in the transaction into the new
42293     ** master journal file. If an error occurs at this point close
42294     ** and delete the master journal file. All the individual journal files
42295     ** still have 'null' as the master journal pointer, so they will roll
42296     ** back independently if a failure occurs.
42297     */
42298     for(i=0; i<db->nDb; i++){
42299       Btree *pBt = db->aDb[i].pBt;
42300       if( i==1 ) continue;   /* Ignore the TEMP database */
42301       if( sqlite3BtreeIsInTrans(pBt) ){
42302         char const *zFile = sqlite3BtreeGetJournalname(pBt);
42303         if( zFile[0]==0 ) continue;  /* Ignore :memory: databases */
42304         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
42305           needSync = 1;
42306         }
42307         rc = sqlite3OsWrite(pMaster, zFile, strlen(zFile)+1, offset);
42308         offset += strlen(zFile)+1;
42309         if( rc!=SQLITE_OK ){
42310           sqlite3OsCloseFree(pMaster);
42311           sqlite3OsDelete(pVfs, zMaster, 0);
42312           sqlite3DbFree(db, zMaster);
42313           return rc;
42314         }
42315       }
42316     }
42317
42318     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
42319     ** flag is set this is not required.
42320     */
42321     zMainFile = sqlite3BtreeGetDirname(db->aDb[0].pBt);
42322     if( (needSync 
42323      && (0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL))
42324      && (rc=sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))!=SQLITE_OK) ){
42325       sqlite3OsCloseFree(pMaster);
42326       sqlite3OsDelete(pVfs, zMaster, 0);
42327       sqlite3DbFree(db, zMaster);
42328       return rc;
42329     }
42330
42331     /* Sync all the db files involved in the transaction. The same call
42332     ** sets the master journal pointer in each individual journal. If
42333     ** an error occurs here, do not delete the master journal file.
42334     **
42335     ** If the error occurs during the first call to
42336     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
42337     ** master journal file will be orphaned. But we cannot delete it,
42338     ** in case the master journal file name was written into the journal
42339     ** file before the failure occured.
42340     */
42341     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
42342       Btree *pBt = db->aDb[i].pBt;
42343       if( pBt ){
42344         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
42345       }
42346     }
42347     sqlite3OsCloseFree(pMaster);
42348     if( rc!=SQLITE_OK ){
42349       sqlite3DbFree(db, zMaster);
42350       return rc;
42351     }
42352
42353     /* Delete the master journal file. This commits the transaction. After
42354     ** doing this the directory is synced again before any individual
42355     ** transaction files are deleted.
42356     */
42357     rc = sqlite3OsDelete(pVfs, zMaster, 1);
42358     sqlite3DbFree(db, zMaster);
42359     zMaster = 0;
42360     if( rc ){
42361       return rc;
42362     }
42363
42364     /* All files and directories have already been synced, so the following
42365     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
42366     ** deleting or truncating journals. If something goes wrong while
42367     ** this is happening we don't really care. The integrity of the
42368     ** transaction is already guaranteed, but some stray 'cold' journals
42369     ** may be lying around. Returning an error code won't help matters.
42370     */
42371     disable_simulated_io_errors();
42372     sqlite3BeginBenignMalloc();
42373     for(i=0; i<db->nDb; i++){ 
42374       Btree *pBt = db->aDb[i].pBt;
42375       if( pBt ){
42376         sqlite3BtreeCommitPhaseTwo(pBt);
42377       }
42378     }
42379     sqlite3EndBenignMalloc();
42380     enable_simulated_io_errors();
42381
42382     sqlite3VtabCommit(db);
42383   }
42384 #endif
42385
42386   return rc;
42387 }
42388
42389 /* 
42390 ** This routine checks that the sqlite3.activeVdbeCnt count variable
42391 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
42392 ** currently active. An assertion fails if the two counts do not match.
42393 ** This is an internal self-check only - it is not an essential processing
42394 ** step.
42395 **
42396 ** This is a no-op if NDEBUG is defined.
42397 */
42398 #ifndef NDEBUG
42399 static void checkActiveVdbeCnt(sqlite3 *db){
42400   Vdbe *p;
42401   int cnt = 0;
42402   p = db->pVdbe;
42403   while( p ){
42404     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
42405       cnt++;
42406     }
42407     p = p->pNext;
42408   }
42409   assert( cnt==db->activeVdbeCnt );
42410 }
42411 #else
42412 #define checkActiveVdbeCnt(x)
42413 #endif
42414
42415 /*
42416 ** For every Btree that in database connection db which 
42417 ** has been modified, "trip" or invalidate each cursor in
42418 ** that Btree might have been modified so that the cursor
42419 ** can never be used again.  This happens when a rollback
42420 *** occurs.  We have to trip all the other cursors, even
42421 ** cursor from other VMs in different database connections,
42422 ** so that none of them try to use the data at which they
42423 ** were pointing and which now may have been changed due
42424 ** to the rollback.
42425 **
42426 ** Remember that a rollback can delete tables complete and
42427 ** reorder rootpages.  So it is not sufficient just to save
42428 ** the state of the cursor.  We have to invalidate the cursor
42429 ** so that it is never used again.
42430 */
42431 static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
42432   int i;
42433   for(i=0; i<db->nDb; i++){
42434     Btree *p = db->aDb[i].pBt;
42435     if( p && sqlite3BtreeIsInTrans(p) ){
42436       sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
42437     }
42438   }
42439 }
42440
42441 /*
42442 ** This routine is called the when a VDBE tries to halt.  If the VDBE
42443 ** has made changes and is in autocommit mode, then commit those
42444 ** changes.  If a rollback is needed, then do the rollback.
42445 **
42446 ** This routine is the only way to move the state of a VM from
42447 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
42448 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
42449 **
42450 ** Return an error code.  If the commit could not complete because of
42451 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
42452 ** means the close did not happen and needs to be repeated.
42453 */
42454 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
42455   sqlite3 *db = p->db;
42456   int i;
42457   int (*xFunc)(Btree *pBt) = 0;  /* Function to call on each btree backend */
42458   int isSpecialError;            /* Set to true if SQLITE_NOMEM or IOERR */
42459
42460   /* This function contains the logic that determines if a statement or
42461   ** transaction will be committed or rolled back as a result of the
42462   ** execution of this virtual machine. 
42463   **
42464   ** If any of the following errors occur:
42465   **
42466   **     SQLITE_NOMEM
42467   **     SQLITE_IOERR
42468   **     SQLITE_FULL
42469   **     SQLITE_INTERRUPT
42470   **
42471   ** Then the internal cache might have been left in an inconsistent
42472   ** state.  We need to rollback the statement transaction, if there is
42473   ** one, or the complete transaction if there is no statement transaction.
42474   */
42475
42476   if( p->db->mallocFailed ){
42477     p->rc = SQLITE_NOMEM;
42478   }
42479   closeAllCursorsExceptActiveVtabs(p);
42480   if( p->magic!=VDBE_MAGIC_RUN ){
42481     return SQLITE_OK;
42482   }
42483   checkActiveVdbeCnt(db);
42484
42485   /* No commit or rollback needed if the program never started */
42486   if( p->pc>=0 ){
42487     int mrc;   /* Primary error code from p->rc */
42488
42489     /* Lock all btrees used by the statement */
42490     sqlite3BtreeMutexArrayEnter(&p->aMutex);
42491
42492     /* Check for one of the special errors */
42493     mrc = p->rc & 0xff;
42494     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
42495                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
42496     if( isSpecialError ){
42497       /* This loop does static analysis of the query to see which of the
42498       ** following three categories it falls into:
42499       **
42500       **     Read-only
42501       **     Query with statement journal
42502       **     Query without statement journal
42503       **
42504       ** We could do something more elegant than this static analysis (i.e.
42505       ** store the type of query as part of the compliation phase), but 
42506       ** handling malloc() or IO failure is a fairly obscure edge case so 
42507       ** this is probably easier. Todo: Might be an opportunity to reduce 
42508       ** code size a very small amount though...
42509       */
42510       int notReadOnly = 0;
42511       int isStatement = 0;
42512       assert(p->aOp || p->nOp==0);
42513       for(i=0; i<p->nOp; i++){ 
42514         switch( p->aOp[i].opcode ){
42515           case OP_Transaction:
42516             notReadOnly |= p->aOp[i].p2;
42517             break;
42518           case OP_Statement:
42519             isStatement = 1;
42520             break;
42521         }
42522       }
42523
42524    
42525       /* If the query was read-only, we need do no rollback at all. Otherwise,
42526       ** proceed with the special handling.
42527       */
42528       if( notReadOnly || mrc!=SQLITE_INTERRUPT ){
42529         if( p->rc==SQLITE_IOERR_BLOCKED && isStatement ){
42530           xFunc = sqlite3BtreeRollbackStmt;
42531           p->rc = SQLITE_BUSY;
42532         } else if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && isStatement ){
42533           xFunc = sqlite3BtreeRollbackStmt;
42534         }else{
42535           /* We are forced to roll back the active transaction. Before doing
42536           ** so, abort any other statements this handle currently has active.
42537           */
42538           invalidateCursorsOnModifiedBtrees(db);
42539           sqlite3RollbackAll(db);
42540           db->autoCommit = 1;
42541         }
42542       }
42543     }
42544   
42545     /* If the auto-commit flag is set and this is the only active vdbe, then
42546     ** we do either a commit or rollback of the current transaction. 
42547     **
42548     ** Note: This block also runs if one of the special errors handled 
42549     ** above has occured. 
42550     */
42551     if( db->autoCommit && db->activeVdbeCnt==1 ){
42552       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
42553         /* The auto-commit flag is true, and the vdbe program was 
42554         ** successful or hit an 'OR FAIL' constraint. This means a commit 
42555         ** is required.
42556         */
42557         int rc = vdbeCommit(db, p);
42558         if( rc==SQLITE_BUSY ){
42559           sqlite3BtreeMutexArrayLeave(&p->aMutex);
42560           return SQLITE_BUSY;
42561         }else if( rc!=SQLITE_OK ){
42562           p->rc = rc;
42563           sqlite3RollbackAll(db);
42564         }else{
42565           sqlite3CommitInternalChanges(db);
42566         }
42567       }else{
42568         sqlite3RollbackAll(db);
42569       }
42570     }else if( !xFunc ){
42571       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
42572         if( p->openedStatement ){
42573           xFunc = sqlite3BtreeCommitStmt;
42574         } 
42575       }else if( p->errorAction==OE_Abort ){
42576         xFunc = sqlite3BtreeRollbackStmt;
42577       }else{
42578         invalidateCursorsOnModifiedBtrees(db);
42579         sqlite3RollbackAll(db);
42580         db->autoCommit = 1;
42581       }
42582     }
42583   
42584     /* If xFunc is not NULL, then it is one of sqlite3BtreeRollbackStmt or
42585     ** sqlite3BtreeCommitStmt. Call it once on each backend. If an error occurs
42586     ** and the return code is still SQLITE_OK, set the return code to the new
42587     ** error value.
42588     */
42589     assert(!xFunc ||
42590       xFunc==sqlite3BtreeCommitStmt ||
42591       xFunc==sqlite3BtreeRollbackStmt
42592     );
42593     for(i=0; xFunc && i<db->nDb; i++){ 
42594       int rc;
42595       Btree *pBt = db->aDb[i].pBt;
42596       if( pBt ){
42597         rc = xFunc(pBt);
42598         if( rc && (p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT) ){
42599           p->rc = rc;
42600           sqlite3DbFree(db, p->zErrMsg);
42601           p->zErrMsg = 0;
42602         }
42603       }
42604     }
42605   
42606     /* If this was an INSERT, UPDATE or DELETE and the statement was committed, 
42607     ** set the change counter. 
42608     */
42609     if( p->changeCntOn && p->pc>=0 ){
42610       if( !xFunc || xFunc==sqlite3BtreeCommitStmt ){
42611         sqlite3VdbeSetChanges(db, p->nChange);
42612       }else{
42613         sqlite3VdbeSetChanges(db, 0);
42614       }
42615       p->nChange = 0;
42616     }
42617   
42618     /* Rollback or commit any schema changes that occurred. */
42619     if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
42620       sqlite3ResetInternalSchema(db, 0);
42621       db->flags = (db->flags | SQLITE_InternChanges);
42622     }
42623
42624     /* Release the locks */
42625     sqlite3BtreeMutexArrayLeave(&p->aMutex);
42626   }
42627
42628   /* We have successfully halted and closed the VM.  Record this fact. */
42629   if( p->pc>=0 ){
42630     db->activeVdbeCnt--;
42631   }
42632   p->magic = VDBE_MAGIC_HALT;
42633   checkActiveVdbeCnt(db);
42634   if( p->db->mallocFailed ){
42635     p->rc = SQLITE_NOMEM;
42636   }
42637
42638   return SQLITE_OK;
42639 }
42640
42641
42642 /*
42643 ** Each VDBE holds the result of the most recent sqlite3_step() call
42644 ** in p->rc.  This routine sets that result back to SQLITE_OK.
42645 */
42646 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
42647   p->rc = SQLITE_OK;
42648 }
42649
42650 /*
42651 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
42652 ** Write any error messages into *pzErrMsg.  Return the result code.
42653 **
42654 ** After this routine is run, the VDBE should be ready to be executed
42655 ** again.
42656 **
42657 ** To look at it another way, this routine resets the state of the
42658 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
42659 ** VDBE_MAGIC_INIT.
42660 */
42661 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
42662   sqlite3 *db;
42663   db = p->db;
42664
42665   /* If the VM did not run to completion or if it encountered an
42666   ** error, then it might not have been halted properly.  So halt
42667   ** it now.
42668   */
42669   (void)sqlite3SafetyOn(db);
42670   sqlite3VdbeHalt(p);
42671   (void)sqlite3SafetyOff(db);
42672
42673   /* If the VDBE has be run even partially, then transfer the error code
42674   ** and error message from the VDBE into the main database structure.  But
42675   ** if the VDBE has just been set to run but has not actually executed any
42676   ** instructions yet, leave the main database error information unchanged.
42677   */
42678   if( p->pc>=0 ){
42679     if( p->zErrMsg ){
42680       sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
42681       db->errCode = p->rc;
42682       sqlite3DbFree(db, p->zErrMsg);
42683       p->zErrMsg = 0;
42684     }else if( p->rc ){
42685       sqlite3Error(db, p->rc, 0);
42686     }else{
42687       sqlite3Error(db, SQLITE_OK, 0);
42688     }
42689   }else if( p->rc && p->expired ){
42690     /* The expired flag was set on the VDBE before the first call
42691     ** to sqlite3_step(). For consistency (since sqlite3_step() was
42692     ** called), set the database error in this case as well.
42693     */
42694     sqlite3Error(db, p->rc, 0);
42695     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
42696     sqlite3DbFree(db, p->zErrMsg);
42697     p->zErrMsg = 0;
42698   }
42699
42700   /* Reclaim all memory used by the VDBE
42701   */
42702   Cleanup(p);
42703
42704   /* Save profiling information from this VDBE run.
42705   */
42706 #ifdef VDBE_PROFILE
42707   {
42708     FILE *out = fopen("vdbe_profile.out", "a");
42709     if( out ){
42710       int i;
42711       fprintf(out, "---- ");
42712       for(i=0; i<p->nOp; i++){
42713         fprintf(out, "%02x", p->aOp[i].opcode);
42714       }
42715       fprintf(out, "\n");
42716       for(i=0; i<p->nOp; i++){
42717         fprintf(out, "%6d %10lld %8lld ",
42718            p->aOp[i].cnt,
42719            p->aOp[i].cycles,
42720            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
42721         );
42722         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
42723       }
42724       fclose(out);
42725     }
42726   }
42727 #endif
42728   p->magic = VDBE_MAGIC_INIT;
42729   return p->rc & db->errMask;
42730 }
42731  
42732 /*
42733 ** Clean up and delete a VDBE after execution.  Return an integer which is
42734 ** the result code.  Write any error message text into *pzErrMsg.
42735 */
42736 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
42737   int rc = SQLITE_OK;
42738   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
42739     rc = sqlite3VdbeReset(p);
42740     assert( (rc & p->db->errMask)==rc );
42741   }else if( p->magic!=VDBE_MAGIC_INIT ){
42742     return SQLITE_MISUSE;
42743   }
42744   sqlite3VdbeDelete(p);
42745   return rc;
42746 }
42747
42748 /*
42749 ** Call the destructor for each auxdata entry in pVdbeFunc for which
42750 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
42751 ** are always destroyed.  To destroy all auxdata entries, call this
42752 ** routine with mask==0.
42753 */
42754 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
42755   int i;
42756   for(i=0; i<pVdbeFunc->nAux; i++){
42757     struct AuxData *pAux = &pVdbeFunc->apAux[i];
42758     if( (i>31 || !(mask&(1<<i))) && pAux->pAux ){
42759       if( pAux->xDelete ){
42760         pAux->xDelete(pAux->pAux);
42761       }
42762       pAux->pAux = 0;
42763     }
42764   }
42765 }
42766
42767 /*
42768 ** Delete an entire VDBE.
42769 */
42770 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
42771   int i;
42772   sqlite3 *db;
42773
42774   if( p==0 ) return;
42775   db = p->db;
42776   if( p->pPrev ){
42777     p->pPrev->pNext = p->pNext;
42778   }else{
42779     assert( db->pVdbe==p );
42780     db->pVdbe = p->pNext;
42781   }
42782   if( p->pNext ){
42783     p->pNext->pPrev = p->pPrev;
42784   }
42785   if( p->aOp ){
42786     Op *pOp = p->aOp;
42787     for(i=0; i<p->nOp; i++, pOp++){
42788       freeP4(db, pOp->p4type, pOp->p4.p);
42789 #ifdef SQLITE_DEBUG
42790       sqlite3DbFree(db, pOp->zComment);
42791 #endif     
42792     }
42793     sqlite3DbFree(db, p->aOp);
42794   }
42795   releaseMemArray(p->aVar, p->nVar);
42796   sqlite3DbFree(db, p->aLabel);
42797   if( p->aMem ){
42798     sqlite3DbFree(db, &p->aMem[1]);
42799   }
42800   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
42801   sqlite3DbFree(db, p->aColName);
42802   sqlite3DbFree(db, p->zSql);
42803   p->magic = VDBE_MAGIC_DEAD;
42804   sqlite3DbFree(db, p);
42805 }
42806
42807 /*
42808 ** If a MoveTo operation is pending on the given cursor, then do that
42809 ** MoveTo now.  Return an error code.  If no MoveTo is pending, this
42810 ** routine does nothing and returns SQLITE_OK.
42811 */
42812 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(Cursor *p){
42813   if( p->deferredMoveto ){
42814     int res, rc;
42815 #ifdef SQLITE_TEST
42816     extern int sqlite3_search_count;
42817 #endif
42818     assert( p->isTable );
42819     rc = sqlite3BtreeMoveto(p->pCursor, 0, 0, p->movetoTarget, 0, &res);
42820     if( rc ) return rc;
42821     *p->pIncrKey = 0;
42822     p->lastRowid = keyToInt(p->movetoTarget);
42823     p->rowidIsValid = res==0;
42824     if( res<0 ){
42825       rc = sqlite3BtreeNext(p->pCursor, &res);
42826       if( rc ) return rc;
42827     }
42828 #ifdef SQLITE_TEST
42829     sqlite3_search_count++;
42830 #endif
42831     p->deferredMoveto = 0;
42832     p->cacheStatus = CACHE_STALE;
42833   }else if( p->pCursor ){
42834     int hasMoved;
42835     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
42836     if( rc ) return rc;
42837     if( hasMoved ){
42838       p->cacheStatus = CACHE_STALE;
42839       p->nullRow = 1;
42840     }
42841   }
42842   return SQLITE_OK;
42843 }
42844
42845 /*
42846 ** The following functions:
42847 **
42848 ** sqlite3VdbeSerialType()
42849 ** sqlite3VdbeSerialTypeLen()
42850 ** sqlite3VdbeSerialLen()
42851 ** sqlite3VdbeSerialPut()
42852 ** sqlite3VdbeSerialGet()
42853 **
42854 ** encapsulate the code that serializes values for storage in SQLite
42855 ** data and index records. Each serialized value consists of a
42856 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
42857 ** integer, stored as a varint.
42858 **
42859 ** In an SQLite index record, the serial type is stored directly before
42860 ** the blob of data that it corresponds to. In a table record, all serial
42861 ** types are stored at the start of the record, and the blobs of data at
42862 ** the end. Hence these functions allow the caller to handle the
42863 ** serial-type and data blob seperately.
42864 **
42865 ** The following table describes the various storage classes for data:
42866 **
42867 **   serial type        bytes of data      type
42868 **   --------------     ---------------    ---------------
42869 **      0                     0            NULL
42870 **      1                     1            signed integer
42871 **      2                     2            signed integer
42872 **      3                     3            signed integer
42873 **      4                     4            signed integer
42874 **      5                     6            signed integer
42875 **      6                     8            signed integer
42876 **      7                     8            IEEE float
42877 **      8                     0            Integer constant 0
42878 **      9                     0            Integer constant 1
42879 **     10,11                               reserved for expansion
42880 **    N>=12 and even       (N-12)/2        BLOB
42881 **    N>=13 and odd        (N-13)/2        text
42882 **
42883 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
42884 ** of SQLite will not understand those serial types.
42885 */
42886
42887 /*
42888 ** Return the serial-type for the value stored in pMem.
42889 */
42890 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
42891   int flags = pMem->flags;
42892   int n;
42893
42894   if( flags&MEM_Null ){
42895     return 0;
42896   }
42897   if( flags&MEM_Int ){
42898     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
42899 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
42900     i64 i = pMem->u.i;
42901     u64 u;
42902     if( file_format>=4 && (i&1)==i ){
42903       return 8+i;
42904     }
42905     u = i<0 ? -i : i;
42906     if( u<=127 ) return 1;
42907     if( u<=32767 ) return 2;
42908     if( u<=8388607 ) return 3;
42909     if( u<=2147483647 ) return 4;
42910     if( u<=MAX_6BYTE ) return 5;
42911     return 6;
42912   }
42913   if( flags&MEM_Real ){
42914     return 7;
42915   }
42916   assert( flags&(MEM_Str|MEM_Blob) );
42917   n = pMem->n;
42918   if( flags & MEM_Zero ){
42919     n += pMem->u.i;
42920   }
42921   assert( n>=0 );
42922   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
42923 }
42924
42925 /*
42926 ** Return the length of the data corresponding to the supplied serial-type.
42927 */
42928 SQLITE_PRIVATE int sqlite3VdbeSerialTypeLen(u32 serial_type){
42929   if( serial_type>=12 ){
42930     return (serial_type-12)/2;
42931   }else{
42932     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
42933     return aSize[serial_type];
42934   }
42935 }
42936
42937 /*
42938 ** If we are on an architecture with mixed-endian floating 
42939 ** points (ex: ARM7) then swap the lower 4 bytes with the 
42940 ** upper 4 bytes.  Return the result.
42941 **
42942 ** For most architectures, this is a no-op.
42943 **
42944 ** (later):  It is reported to me that the mixed-endian problem
42945 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
42946 ** that early versions of GCC stored the two words of a 64-bit
42947 ** float in the wrong order.  And that error has been propagated
42948 ** ever since.  The blame is not necessarily with GCC, though.
42949 ** GCC might have just copying the problem from a prior compiler.
42950 ** I am also told that newer versions of GCC that follow a different
42951 ** ABI get the byte order right.
42952 **
42953 ** Developers using SQLite on an ARM7 should compile and run their
42954 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
42955 ** enabled, some asserts below will ensure that the byte order of
42956 ** floating point values is correct.
42957 **
42958 ** (2007-08-30)  Frank van Vugt has studied this problem closely
42959 ** and has send his findings to the SQLite developers.  Frank
42960 ** writes that some Linux kernels offer floating point hardware
42961 ** emulation that uses only 32-bit mantissas instead of a full 
42962 ** 48-bits as required by the IEEE standard.  (This is the
42963 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
42964 ** byte swapping becomes very complicated.  To avoid problems,
42965 ** the necessary byte swapping is carried out using a 64-bit integer
42966 ** rather than a 64-bit float.  Frank assures us that the code here
42967 ** works for him.  We, the developers, have no way to independently
42968 ** verify this, but Frank seems to know what he is talking about
42969 ** so we trust him.
42970 */
42971 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
42972 static u64 floatSwap(u64 in){
42973   union {
42974     u64 r;
42975     u32 i[2];
42976   } u;
42977   u32 t;
42978
42979   u.r = in;
42980   t = u.i[0];
42981   u.i[0] = u.i[1];
42982   u.i[1] = t;
42983   return u.r;
42984 }
42985 # define swapMixedEndianFloat(X)  X = floatSwap(X)
42986 #else
42987 # define swapMixedEndianFloat(X)
42988 #endif
42989
42990 /*
42991 ** Write the serialized data blob for the value stored in pMem into 
42992 ** buf. It is assumed that the caller has allocated sufficient space.
42993 ** Return the number of bytes written.
42994 **
42995 ** nBuf is the amount of space left in buf[].  nBuf must always be
42996 ** large enough to hold the entire field.  Except, if the field is
42997 ** a blob with a zero-filled tail, then buf[] might be just the right
42998 ** size to hold everything except for the zero-filled tail.  If buf[]
42999 ** is only big enough to hold the non-zero prefix, then only write that
43000 ** prefix into buf[].  But if buf[] is large enough to hold both the
43001 ** prefix and the tail then write the prefix and set the tail to all
43002 ** zeros.
43003 **
43004 ** Return the number of bytes actually written into buf[].  The number
43005 ** of bytes in the zero-filled tail is included in the return value only
43006 ** if those bytes were zeroed in buf[].
43007 */ 
43008 SQLITE_PRIVATE int sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
43009   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
43010   int len;
43011
43012   /* Integer and Real */
43013   if( serial_type<=7 && serial_type>0 ){
43014     u64 v;
43015     int i;
43016     if( serial_type==7 ){
43017       assert( sizeof(v)==sizeof(pMem->r) );
43018       memcpy(&v, &pMem->r, sizeof(v));
43019       swapMixedEndianFloat(v);
43020     }else{
43021       v = pMem->u.i;
43022     }
43023     len = i = sqlite3VdbeSerialTypeLen(serial_type);
43024     assert( len<=nBuf );
43025     while( i-- ){
43026       buf[i] = (v&0xFF);
43027       v >>= 8;
43028     }
43029     return len;
43030   }
43031
43032   /* String or blob */
43033   if( serial_type>=12 ){
43034     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.i:0)
43035              == sqlite3VdbeSerialTypeLen(serial_type) );
43036     assert( pMem->n<=nBuf );
43037     len = pMem->n;
43038     memcpy(buf, pMem->z, len);
43039     if( pMem->flags & MEM_Zero ){
43040       len += pMem->u.i;
43041       if( len>nBuf ){
43042         len = nBuf;
43043       }
43044       memset(&buf[pMem->n], 0, len-pMem->n);
43045     }
43046     return len;
43047   }
43048
43049   /* NULL or constants 0 or 1 */
43050   return 0;
43051 }
43052
43053 /*
43054 ** Deserialize the data blob pointed to by buf as serial type serial_type
43055 ** and store the result in pMem.  Return the number of bytes read.
43056 */ 
43057 SQLITE_PRIVATE int sqlite3VdbeSerialGet(
43058   const unsigned char *buf,     /* Buffer to deserialize from */
43059   u32 serial_type,              /* Serial type to deserialize */
43060   Mem *pMem                     /* Memory cell to write value into */
43061 ){
43062   switch( serial_type ){
43063     case 10:   /* Reserved for future use */
43064     case 11:   /* Reserved for future use */
43065     case 0: {  /* NULL */
43066       pMem->flags = MEM_Null;
43067       break;
43068     }
43069     case 1: { /* 1-byte signed integer */
43070       pMem->u.i = (signed char)buf[0];
43071       pMem->flags = MEM_Int;
43072       return 1;
43073     }
43074     case 2: { /* 2-byte signed integer */
43075       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
43076       pMem->flags = MEM_Int;
43077       return 2;
43078     }
43079     case 3: { /* 3-byte signed integer */
43080       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
43081       pMem->flags = MEM_Int;
43082       return 3;
43083     }
43084     case 4: { /* 4-byte signed integer */
43085       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
43086       pMem->flags = MEM_Int;
43087       return 4;
43088     }
43089     case 5: { /* 6-byte signed integer */
43090       u64 x = (((signed char)buf[0])<<8) | buf[1];
43091       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
43092       x = (x<<32) | y;
43093       pMem->u.i = *(i64*)&x;
43094       pMem->flags = MEM_Int;
43095       return 6;
43096     }
43097     case 6:   /* 8-byte signed integer */
43098     case 7: { /* IEEE floating point */
43099       u64 x;
43100       u32 y;
43101 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
43102       /* Verify that integers and floating point values use the same
43103       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
43104       ** defined that 64-bit floating point values really are mixed
43105       ** endian.
43106       */
43107       static const u64 t1 = ((u64)0x3ff00000)<<32;
43108       static const double r1 = 1.0;
43109       u64 t2 = t1;
43110       swapMixedEndianFloat(t2);
43111       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
43112 #endif
43113
43114       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
43115       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
43116       x = (x<<32) | y;
43117       if( serial_type==6 ){
43118         pMem->u.i = *(i64*)&x;
43119         pMem->flags = MEM_Int;
43120       }else{
43121         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
43122         swapMixedEndianFloat(x);
43123         memcpy(&pMem->r, &x, sizeof(x));
43124         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
43125       }
43126       return 8;
43127     }
43128     case 8:    /* Integer 0 */
43129     case 9: {  /* Integer 1 */
43130       pMem->u.i = serial_type-8;
43131       pMem->flags = MEM_Int;
43132       return 0;
43133     }
43134     default: {
43135       int len = (serial_type-12)/2;
43136       pMem->z = (char *)buf;
43137       pMem->n = len;
43138       pMem->xDel = 0;
43139       if( serial_type&0x01 ){
43140         pMem->flags = MEM_Str | MEM_Ephem;
43141       }else{
43142         pMem->flags = MEM_Blob | MEM_Ephem;
43143       }
43144       return len;
43145     }
43146   }
43147   return 0;
43148 }
43149
43150
43151 /*
43152 ** Given the nKey-byte encoding of a record in pKey[], parse the
43153 ** record into a UnpackedRecord structure.  Return a pointer to
43154 ** that structure.
43155 **
43156 ** The calling function might provide szSpace bytes of memory
43157 ** space at pSpace.  This space can be used to hold the returned
43158 ** VDbeParsedRecord structure if it is large enough.  If it is
43159 ** not big enough, space is obtained from sqlite3_malloc().
43160 **
43161 ** The returned structure should be closed by a call to
43162 ** sqlite3VdbeDeleteUnpackedRecord().
43163 */ 
43164 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(
43165   KeyInfo *pKeyInfo,     /* Information about the record format */
43166   int nKey,              /* Size of the binary record */
43167   const void *pKey,      /* The binary record */
43168   void *pSpace,          /* Space available to hold resulting object */
43169   int szSpace            /* Size of pSpace[] in bytes */
43170 ){
43171   const unsigned char *aKey = (const unsigned char *)pKey;
43172   UnpackedRecord *p;
43173   int nByte;
43174   int idx, d;
43175   u16 u;                 /* Unsigned loop counter */
43176   u32 szHdr;
43177   Mem *pMem;
43178   
43179   assert( sizeof(Mem)>sizeof(*p) );
43180   nByte = sizeof(Mem)*(pKeyInfo->nField+2);
43181   if( nByte>szSpace ){
43182     p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
43183     if( p==0 ) return 0;
43184     p->needFree = 1;
43185   }else{
43186     p = pSpace;
43187     p->needFree = 0;
43188   }
43189   p->pKeyInfo = pKeyInfo;
43190   p->nField = pKeyInfo->nField + 1;
43191   p->needDestroy = 1;
43192   p->aMem = pMem = &((Mem*)p)[1];
43193   idx = getVarint32(aKey, szHdr);
43194   d = szHdr;
43195   u = 0;
43196   while( idx<szHdr && u<p->nField ){
43197     u32 serial_type;
43198
43199     idx += getVarint32( aKey+idx, serial_type);
43200     if( d>=nKey && sqlite3VdbeSerialTypeLen(serial_type)>0 ) break;
43201     pMem->enc = pKeyInfo->enc;
43202     pMem->db = pKeyInfo->db;
43203     pMem->flags = 0;
43204     pMem->zMalloc = 0;
43205     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
43206     pMem++;
43207     u++;
43208   }
43209   p->nField = u;
43210   return (void*)p;
43211 }
43212
43213 /*
43214 ** This routine destroys a UnpackedRecord object
43215 */
43216 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
43217   if( p ){
43218     if( p->needDestroy ){
43219       int i;
43220       Mem *pMem;
43221       for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
43222         if( pMem->zMalloc ){
43223           sqlite3VdbeMemRelease(pMem);
43224         }
43225       }
43226     }
43227     if( p->needFree ){
43228       sqlite3DbFree(p->pKeyInfo->db, p);
43229     }
43230   }
43231 }
43232
43233 /*
43234 ** This function compares the two table rows or index records
43235 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
43236 ** or positive integer if {nKey1, pKey1} is less than, equal to or 
43237 ** greater than pPKey2.  The {nKey1, pKey1} key must be a blob
43238 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
43239 ** key must be a parsed key such as obtained from
43240 ** sqlite3VdbeParseRecord.
43241 **
43242 ** Key1 and Key2 do not have to contain the same number of fields.
43243 ** But if the lengths differ, Key2 must be the shorter of the two.
43244 **
43245 ** Historical note: In earlier versions of this routine both Key1
43246 ** and Key2 were blobs obtained from OP_MakeRecord.  But we found
43247 ** that in typical use the same Key2 would be submitted multiple times
43248 ** in a row.  So an optimization was added to parse the Key2 key
43249 ** separately and submit the parsed version.  In this way, we avoid
43250 ** parsing the same Key2 multiple times in a row.
43251 */
43252 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
43253   int nKey1, const void *pKey1, 
43254   UnpackedRecord *pPKey2
43255 ){
43256   u32 d1;            /* Offset into aKey[] of next data element */
43257   u32 idx1;          /* Offset into aKey[] of next header element */
43258   u32 szHdr1;        /* Number of bytes in header */
43259   int i = 0;
43260   int nField;
43261   int rc = 0;
43262   const unsigned char *aKey1 = (const unsigned char *)pKey1;
43263   KeyInfo *pKeyInfo;
43264   Mem mem1;
43265
43266   pKeyInfo = pPKey2->pKeyInfo;
43267   mem1.enc = pKeyInfo->enc;
43268   mem1.db = pKeyInfo->db;
43269   mem1.flags = 0;
43270   mem1.zMalloc = 0;
43271   
43272   idx1 = getVarint32(aKey1, szHdr1);
43273   d1 = szHdr1;
43274   nField = pKeyInfo->nField;
43275   while( idx1<szHdr1 && i<pPKey2->nField ){
43276     u32 serial_type1;
43277
43278     /* Read the serial types for the next element in each key. */
43279     idx1 += getVarint32( aKey1+idx1, serial_type1 );
43280     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
43281
43282     /* Extract the values to be compared.
43283     */
43284     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
43285
43286     /* Do the comparison
43287     */
43288     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
43289                            i<nField ? pKeyInfo->aColl[i] : 0);
43290     if( rc!=0 ){
43291       break;
43292     }
43293     i++;
43294   }
43295   if( mem1.zMalloc ) sqlite3VdbeMemRelease(&mem1);
43296
43297   /* One of the keys ran out of fields, but all the fields up to that point
43298   ** were equal. If the incrKey flag is true, then the second key is
43299   ** treated as larger.
43300   */
43301   if( rc==0 ){
43302     if( pKeyInfo->incrKey ){
43303       rc = -1;
43304     }else if( !pKeyInfo->prefixIsEqual ){
43305       if( d1<nKey1 ){
43306         rc = 1;
43307       }
43308     }
43309   }else if( pKeyInfo->aSortOrder && i<pKeyInfo->nField
43310                && pKeyInfo->aSortOrder[i] ){
43311     rc = -rc;
43312   }
43313
43314   return rc;
43315 }
43316
43317 /*
43318 ** The argument is an index entry composed using the OP_MakeRecord opcode.
43319 ** The last entry in this record should be an integer (specifically
43320 ** an integer rowid).  This routine returns the number of bytes in
43321 ** that integer.
43322 */
43323 SQLITE_PRIVATE int sqlite3VdbeIdxRowidLen(const u8 *aKey, int nKey, int *pRowidLen){
43324   u32 szHdr;        /* Size of the header */
43325   u32 typeRowid;    /* Serial type of the rowid */
43326
43327   (void)getVarint32(aKey, szHdr);
43328   if( szHdr>nKey ){
43329     return SQLITE_CORRUPT_BKPT;
43330   }
43331   (void)getVarint32(&aKey[szHdr-1], typeRowid);
43332   *pRowidLen = sqlite3VdbeSerialTypeLen(typeRowid);
43333   return SQLITE_OK;
43334 }
43335   
43336
43337 /*
43338 ** pCur points at an index entry created using the OP_MakeRecord opcode.
43339 ** Read the rowid (the last field in the record) and store it in *rowid.
43340 ** Return SQLITE_OK if everything works, or an error code otherwise.
43341 */
43342 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(BtCursor *pCur, i64 *rowid){
43343   i64 nCellKey = 0;
43344   int rc;
43345   u32 szHdr;        /* Size of the header */
43346   u32 typeRowid;    /* Serial type of the rowid */
43347   u32 lenRowid;     /* Size of the rowid */
43348   Mem m, v;
43349
43350   sqlite3BtreeKeySize(pCur, &nCellKey);
43351   if( nCellKey<=0 ){
43352     return SQLITE_CORRUPT_BKPT;
43353   }
43354   m.flags = 0;
43355   m.db = 0;
43356   m.zMalloc = 0;
43357   rc = sqlite3VdbeMemFromBtree(pCur, 0, nCellKey, 1, &m);
43358   if( rc ){
43359     return rc;
43360   }
43361   (void)getVarint32((u8*)m.z, szHdr);
43362   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
43363   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
43364   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
43365   *rowid = v.u.i;
43366   sqlite3VdbeMemRelease(&m);
43367   return SQLITE_OK;
43368 }
43369
43370 /*
43371 ** Compare the key of the index entry that cursor pC is point to against
43372 ** the key string in pKey (of length nKey).  Write into *pRes a number
43373 ** that is negative, zero, or positive if pC is less than, equal to,
43374 ** or greater than pKey.  Return SQLITE_OK on success.
43375 **
43376 ** pKey is either created without a rowid or is truncated so that it
43377 ** omits the rowid at the end.  The rowid at the end of the index entry
43378 ** is ignored as well.
43379 */
43380 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
43381   Cursor *pC,                 /* The cursor to compare against */
43382   UnpackedRecord *pUnpacked,
43383   int nKey, const u8 *pKey,   /* The key to compare */
43384   int *res                    /* Write the comparison result here */
43385 ){
43386   i64 nCellKey = 0;
43387   int rc;
43388   BtCursor *pCur = pC->pCursor;
43389   int lenRowid;
43390   Mem m;
43391   UnpackedRecord *pRec;
43392   char zSpace[200];
43393
43394   sqlite3BtreeKeySize(pCur, &nCellKey);
43395   if( nCellKey<=0 ){
43396     *res = 0;
43397     return SQLITE_OK;
43398   }
43399   m.db = 0;
43400   m.flags = 0;
43401   m.zMalloc = 0;
43402   if( (rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, nCellKey, 1, &m))
43403    || (rc = sqlite3VdbeIdxRowidLen((u8*)m.z, m.n, &lenRowid))
43404   ){
43405     return rc;
43406   }
43407   if( !pUnpacked ){
43408     pRec = sqlite3VdbeRecordUnpack(pC->pKeyInfo, nKey, pKey,
43409                                 zSpace, sizeof(zSpace));
43410   }else{
43411     pRec = pUnpacked;
43412   }
43413   if( pRec==0 ){
43414     return SQLITE_NOMEM;
43415   }
43416   *res = sqlite3VdbeRecordCompare(m.n-lenRowid, m.z, pRec);
43417   if( !pUnpacked ){
43418     sqlite3VdbeDeleteUnpackedRecord(pRec);
43419   }
43420   sqlite3VdbeMemRelease(&m);
43421   return SQLITE_OK;
43422 }
43423
43424 /*
43425 ** This routine sets the value to be returned by subsequent calls to
43426 ** sqlite3_changes() on the database handle 'db'. 
43427 */
43428 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
43429   assert( sqlite3_mutex_held(db->mutex) );
43430   db->nChange = nChange;
43431   db->nTotalChange += nChange;
43432 }
43433
43434 /*
43435 ** Set a flag in the vdbe to update the change counter when it is finalised
43436 ** or reset.
43437 */
43438 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
43439   v->changeCntOn = 1;
43440 }
43441
43442 /*
43443 ** Mark every prepared statement associated with a database connection
43444 ** as expired.
43445 **
43446 ** An expired statement means that recompilation of the statement is
43447 ** recommend.  Statements expire when things happen that make their
43448 ** programs obsolete.  Removing user-defined functions or collating
43449 ** sequences, or changing an authorization function are the types of
43450 ** things that make prepared statements obsolete.
43451 */
43452 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
43453   Vdbe *p;
43454   for(p = db->pVdbe; p; p=p->pNext){
43455     p->expired = 1;
43456   }
43457 }
43458
43459 /*
43460 ** Return the database associated with the Vdbe.
43461 */
43462 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
43463   return v->db;
43464 }
43465
43466 /************** End of vdbeaux.c *********************************************/
43467 /************** Begin file vdbeapi.c *****************************************/
43468 /*
43469 ** 2004 May 26
43470 **
43471 ** The author disclaims copyright to this source code.  In place of
43472 ** a legal notice, here is a blessing:
43473 **
43474 **    May you do good and not evil.
43475 **    May you find forgiveness for yourself and forgive others.
43476 **    May you share freely, never taking more than you give.
43477 **
43478 *************************************************************************
43479 **
43480 ** This file contains code use to implement APIs that are part of the
43481 ** VDBE.
43482 **
43483 ** $Id: vdbeapi.c,v 1.138 2008/08/02 03:50:39 drh Exp $
43484 */
43485
43486 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
43487 /*
43488 ** The following structure contains pointers to the end points of a
43489 ** doubly-linked list of all compiled SQL statements that may be holding
43490 ** buffers eligible for release when the sqlite3_release_memory() interface is
43491 ** invoked. Access to this list is protected by the SQLITE_MUTEX_STATIC_LRU2
43492 ** mutex.
43493 **
43494 ** Statements are added to the end of this list when sqlite3_reset() is
43495 ** called. They are removed either when sqlite3_step() or sqlite3_finalize()
43496 ** is called. When statements are added to this list, the associated 
43497 ** register array (p->aMem[1..p->nMem]) may contain dynamic buffers that
43498 ** can be freed using sqlite3VdbeReleaseMemory().
43499 **
43500 ** When statements are added or removed from this list, the mutex
43501 ** associated with the Vdbe being added or removed (Vdbe.db->mutex) is
43502 ** already held. The LRU2 mutex is then obtained, blocking if necessary,
43503 ** the linked-list pointers manipulated and the LRU2 mutex relinquished.
43504 */
43505 struct StatementLruList {
43506   Vdbe *pFirst;
43507   Vdbe *pLast;
43508 };
43509 static struct StatementLruList sqlite3LruStatements;
43510
43511 /*
43512 ** Check that the list looks to be internally consistent. This is used
43513 ** as part of an assert() statement as follows:
43514 **
43515 **   assert( stmtLruCheck() );
43516 */
43517 #ifndef NDEBUG
43518 static int stmtLruCheck(){
43519   Vdbe *p;
43520   for(p=sqlite3LruStatements.pFirst; p; p=p->pLruNext){
43521     assert(p->pLruNext || p==sqlite3LruStatements.pLast);
43522     assert(!p->pLruNext || p->pLruNext->pLruPrev==p);
43523     assert(p->pLruPrev || p==sqlite3LruStatements.pFirst);
43524     assert(!p->pLruPrev || p->pLruPrev->pLruNext==p);
43525   }
43526   return 1;
43527 }
43528 #endif
43529
43530 /*
43531 ** Add vdbe p to the end of the statement lru list. It is assumed that
43532 ** p is not already part of the list when this is called. The lru list
43533 ** is protected by the SQLITE_MUTEX_STATIC_LRU mutex.
43534 */
43535 static void stmtLruAdd(Vdbe *p){
43536   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
43537
43538   if( p->pLruPrev || p->pLruNext || sqlite3LruStatements.pFirst==p ){
43539     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
43540     return;
43541   }
43542
43543   assert( stmtLruCheck() );
43544
43545   if( !sqlite3LruStatements.pFirst ){
43546     assert( !sqlite3LruStatements.pLast );
43547     sqlite3LruStatements.pFirst = p;
43548     sqlite3LruStatements.pLast = p;
43549   }else{
43550     assert( !sqlite3LruStatements.pLast->pLruNext );
43551     p->pLruPrev = sqlite3LruStatements.pLast;
43552     sqlite3LruStatements.pLast->pLruNext = p;
43553     sqlite3LruStatements.pLast = p;
43554   }
43555
43556   assert( stmtLruCheck() );
43557
43558   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
43559 }
43560
43561 /*
43562 ** Assuming the SQLITE_MUTEX_STATIC_LRU2 mutext is already held, remove
43563 ** statement p from the least-recently-used statement list. If the 
43564 ** statement is not currently part of the list, this call is a no-op.
43565 */
43566 static void stmtLruRemoveNomutex(Vdbe *p){
43567   if( p->pLruPrev || p->pLruNext || p==sqlite3LruStatements.pFirst ){
43568     assert( stmtLruCheck() );
43569     if( p->pLruNext ){
43570       p->pLruNext->pLruPrev = p->pLruPrev;
43571     }else{
43572       sqlite3LruStatements.pLast = p->pLruPrev;
43573     }
43574     if( p->pLruPrev ){
43575       p->pLruPrev->pLruNext = p->pLruNext;
43576     }else{
43577       sqlite3LruStatements.pFirst = p->pLruNext;
43578     }
43579     p->pLruNext = 0;
43580     p->pLruPrev = 0;
43581     assert( stmtLruCheck() );
43582   }
43583 }
43584
43585 /*
43586 ** Assuming the SQLITE_MUTEX_STATIC_LRU2 mutext is not held, remove
43587 ** statement p from the least-recently-used statement list. If the 
43588 ** statement is not currently part of the list, this call is a no-op.
43589 */
43590 static void stmtLruRemove(Vdbe *p){
43591   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
43592   stmtLruRemoveNomutex(p);
43593   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
43594 }
43595
43596 /*
43597 ** Try to release n bytes of memory by freeing buffers associated 
43598 ** with the memory registers of currently unused vdbes.
43599 */
43600 SQLITE_PRIVATE int sqlite3VdbeReleaseMemory(int n){
43601   Vdbe *p;
43602   Vdbe *pNext;
43603   int nFree = 0;
43604
43605   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
43606   for(p=sqlite3LruStatements.pFirst; p && nFree<n; p=pNext){
43607     pNext = p->pLruNext;
43608
43609     /* For each statement handle in the lru list, attempt to obtain the
43610     ** associated database mutex. If it cannot be obtained, continue
43611     ** to the next statement handle. It is not possible to block on
43612     ** the database mutex - that could cause deadlock.
43613     */
43614     if( SQLITE_OK==sqlite3_mutex_try(p->db->mutex) ){
43615       nFree += sqlite3VdbeReleaseBuffers(p);
43616       stmtLruRemoveNomutex(p);
43617       sqlite3_mutex_leave(p->db->mutex);
43618     }
43619   }
43620   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
43621
43622   return nFree;
43623 }
43624
43625 /*
43626 ** Call sqlite3Reprepare() on the statement. Remove it from the
43627 ** lru list before doing so, as Reprepare() will free all the
43628 ** memory register buffers anyway.
43629 */
43630 int vdbeReprepare(Vdbe *p){
43631   stmtLruRemove(p);
43632   return sqlite3Reprepare(p);
43633 }
43634
43635 #else       /* !SQLITE_ENABLE_MEMORY_MANAGEMENT */
43636   #define stmtLruRemove(x)
43637   #define stmtLruAdd(x)
43638   #define vdbeReprepare(x) sqlite3Reprepare(x)
43639 #endif
43640
43641
43642 /*
43643 ** Return TRUE (non-zero) of the statement supplied as an argument needs
43644 ** to be recompiled.  A statement needs to be recompiled whenever the
43645 ** execution environment changes in a way that would alter the program
43646 ** that sqlite3_prepare() generates.  For example, if new functions or
43647 ** collating sequences are registered or if an authorizer function is
43648 ** added or changed.
43649 */
43650 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
43651   Vdbe *p = (Vdbe*)pStmt;
43652   return p==0 || p->expired;
43653 }
43654
43655 /*
43656 ** The following routine destroys a virtual machine that is created by
43657 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
43658 ** success/failure code that describes the result of executing the virtual
43659 ** machine.
43660 **
43661 ** This routine sets the error code and string returned by
43662 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
43663 */
43664 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
43665   int rc;
43666   if( pStmt==0 ){
43667     rc = SQLITE_OK;
43668   }else{
43669     Vdbe *v = (Vdbe*)pStmt;
43670 #ifndef SQLITE_MUTEX_NOOP
43671     sqlite3_mutex *mutex = v->db->mutex;
43672 #endif
43673     sqlite3_mutex_enter(mutex);
43674     stmtLruRemove(v);
43675     rc = sqlite3VdbeFinalize(v);
43676     sqlite3_mutex_leave(mutex);
43677   }
43678   return rc;
43679 }
43680
43681 /*
43682 ** Terminate the current execution of an SQL statement and reset it
43683 ** back to its starting state so that it can be reused. A success code from
43684 ** the prior execution is returned.
43685 **
43686 ** This routine sets the error code and string returned by
43687 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
43688 */
43689 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
43690   int rc;
43691   if( pStmt==0 ){
43692     rc = SQLITE_OK;
43693   }else{
43694     Vdbe *v = (Vdbe*)pStmt;
43695     sqlite3_mutex_enter(v->db->mutex);
43696     rc = sqlite3VdbeReset(v);
43697     stmtLruAdd(v);
43698     sqlite3VdbeMakeReady(v, -1, 0, 0, 0);
43699     assert( (rc & (v->db->errMask))==rc );
43700     sqlite3_mutex_leave(v->db->mutex);
43701   }
43702   return rc;
43703 }
43704
43705 /*
43706 ** Set all the parameters in the compiled SQL statement to NULL.
43707 */
43708 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
43709   int i;
43710   int rc = SQLITE_OK;
43711   Vdbe *p = (Vdbe*)pStmt;
43712 #ifndef SQLITE_MUTEX_NOOP
43713   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
43714 #endif
43715   sqlite3_mutex_enter(mutex);
43716   for(i=0; i<p->nVar; i++){
43717     sqlite3VdbeMemRelease(&p->aVar[i]);
43718     p->aVar[i].flags = MEM_Null;
43719   }
43720   sqlite3_mutex_leave(mutex);
43721   return rc;
43722 }
43723
43724
43725 /**************************** sqlite3_value_  *******************************
43726 ** The following routines extract information from a Mem or sqlite3_value
43727 ** structure.
43728 */
43729 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
43730   Mem *p = (Mem*)pVal;
43731   if( p->flags & (MEM_Blob|MEM_Str) ){
43732     sqlite3VdbeMemExpandBlob(p);
43733     p->flags &= ~MEM_Str;
43734     p->flags |= MEM_Blob;
43735     return p->z;
43736   }else{
43737     return sqlite3_value_text(pVal);
43738   }
43739 }
43740 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
43741   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
43742 }
43743 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
43744   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
43745 }
43746 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
43747   return sqlite3VdbeRealValue((Mem*)pVal);
43748 }
43749 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
43750   return sqlite3VdbeIntValue((Mem*)pVal);
43751 }
43752 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
43753   return sqlite3VdbeIntValue((Mem*)pVal);
43754 }
43755 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
43756   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
43757 }
43758 #ifndef SQLITE_OMIT_UTF16
43759 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
43760   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
43761 }
43762 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
43763   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
43764 }
43765 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
43766   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
43767 }
43768 #endif /* SQLITE_OMIT_UTF16 */
43769 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
43770   return pVal->type;
43771 }
43772
43773 /**************************** sqlite3_result_  *******************************
43774 ** The following routines are used by user-defined functions to specify
43775 ** the function result.
43776 */
43777 SQLITE_API void sqlite3_result_blob(
43778   sqlite3_context *pCtx, 
43779   const void *z, 
43780   int n, 
43781   void (*xDel)(void *)
43782 ){
43783   assert( n>=0 );
43784   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
43785   sqlite3VdbeMemSetStr(&pCtx->s, z, n, 0, xDel);
43786 }
43787 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
43788   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
43789   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
43790 }
43791 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
43792   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
43793   pCtx->isError = SQLITE_ERROR;
43794   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
43795 }
43796 #ifndef SQLITE_OMIT_UTF16
43797 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
43798   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
43799   pCtx->isError = SQLITE_ERROR;
43800   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
43801 }
43802 #endif
43803 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
43804   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
43805   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
43806 }
43807 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
43808   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
43809   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
43810 }
43811 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
43812   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
43813   sqlite3VdbeMemSetNull(&pCtx->s);
43814 }
43815 SQLITE_API void sqlite3_result_text(
43816   sqlite3_context *pCtx, 
43817   const char *z, 
43818   int n,
43819   void (*xDel)(void *)
43820 ){
43821   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
43822   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, xDel);
43823 }
43824 #ifndef SQLITE_OMIT_UTF16
43825 SQLITE_API void sqlite3_result_text16(
43826   sqlite3_context *pCtx, 
43827   const void *z, 
43828   int n, 
43829   void (*xDel)(void *)
43830 ){
43831   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
43832   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, xDel);
43833 }
43834 SQLITE_API void sqlite3_result_text16be(
43835   sqlite3_context *pCtx, 
43836   const void *z, 
43837   int n, 
43838   void (*xDel)(void *)
43839 ){
43840   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
43841   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16BE, xDel);
43842 }
43843 SQLITE_API void sqlite3_result_text16le(
43844   sqlite3_context *pCtx, 
43845   const void *z, 
43846   int n, 
43847   void (*xDel)(void *)
43848 ){
43849   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
43850   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16LE, xDel);
43851 }
43852 #endif /* SQLITE_OMIT_UTF16 */
43853 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
43854   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
43855   sqlite3VdbeMemCopy(&pCtx->s, pValue);
43856 }
43857 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
43858   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
43859   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
43860 }
43861 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
43862   pCtx->isError = errCode;
43863 }
43864
43865 /* Force an SQLITE_TOOBIG error. */
43866 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
43867   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
43868   pCtx->isError = SQLITE_TOOBIG;
43869   sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1, 
43870                        SQLITE_UTF8, SQLITE_STATIC);
43871 }
43872
43873 /* An SQLITE_NOMEM error. */
43874 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
43875   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
43876   sqlite3VdbeMemSetNull(&pCtx->s);
43877   pCtx->isError = SQLITE_NOMEM;
43878   pCtx->s.db->mallocFailed = 1;
43879 }
43880
43881 /*
43882 ** Execute the statement pStmt, either until a row of data is ready, the
43883 ** statement is completely executed or an error occurs.
43884 **
43885 ** This routine implements the bulk of the logic behind the sqlite_step()
43886 ** API.  The only thing omitted is the automatic recompile if a 
43887 ** schema change has occurred.  That detail is handled by the
43888 ** outer sqlite3_step() wrapper procedure.
43889 */
43890 static int sqlite3Step(Vdbe *p){
43891   sqlite3 *db;
43892   int rc;
43893
43894   assert(p);
43895   if( p->magic!=VDBE_MAGIC_RUN ){
43896     return SQLITE_MISUSE;
43897   }
43898
43899   /* Assert that malloc() has not failed */
43900   db = p->db;
43901   assert( !db->mallocFailed );
43902
43903   if( p->pc<=0 && p->expired ){
43904     if( p->rc==SQLITE_OK ){
43905       p->rc = SQLITE_SCHEMA;
43906     }
43907     rc = SQLITE_ERROR;
43908     goto end_of_step;
43909   }
43910   if( sqlite3SafetyOn(db) ){
43911     p->rc = SQLITE_MISUSE;
43912     return SQLITE_MISUSE;
43913   }
43914   if( p->pc<0 ){
43915     /* If there are no other statements currently running, then
43916     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
43917     ** from interrupting a statement that has not yet started.
43918     */
43919     if( db->activeVdbeCnt==0 ){
43920       db->u1.isInterrupted = 0;
43921     }
43922
43923 #ifndef SQLITE_OMIT_TRACE
43924     if( db->xProfile && !db->init.busy ){
43925       double rNow;
43926       sqlite3OsCurrentTime(db->pVfs, &rNow);
43927       p->startTime = (rNow - (int)rNow)*3600.0*24.0*1000000000.0;
43928     }
43929 #endif
43930
43931     db->activeVdbeCnt++;
43932     p->pc = 0;
43933     stmtLruRemove(p);
43934   }
43935 #ifndef SQLITE_OMIT_EXPLAIN
43936   if( p->explain ){
43937     rc = sqlite3VdbeList(p);
43938   }else
43939 #endif /* SQLITE_OMIT_EXPLAIN */
43940   {
43941     rc = sqlite3VdbeExec(p);
43942   }
43943
43944   if( sqlite3SafetyOff(db) ){
43945     rc = SQLITE_MISUSE;
43946   }
43947
43948 #ifndef SQLITE_OMIT_TRACE
43949   /* Invoke the profile callback if there is one
43950   */
43951   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->nOp>0
43952            && p->aOp[0].opcode==OP_Trace && p->aOp[0].p4.z!=0 ){
43953     double rNow;
43954     u64 elapseTime;
43955
43956     sqlite3OsCurrentTime(db->pVfs, &rNow);
43957     elapseTime = (rNow - (int)rNow)*3600.0*24.0*1000000000.0 - p->startTime;
43958     db->xProfile(db->pProfileArg, p->aOp[0].p4.z, elapseTime);
43959   }
43960 #endif
43961
43962   db->errCode = rc;
43963   /*sqlite3Error(p->db, rc, 0);*/
43964   p->rc = sqlite3ApiExit(p->db, p->rc);
43965 end_of_step:
43966   assert( (rc&0xff)==rc );
43967   if( p->zSql && (rc&0xff)<SQLITE_ROW ){
43968     /* This behavior occurs if sqlite3_prepare_v2() was used to build
43969     ** the prepared statement.  Return error codes directly */
43970     p->db->errCode = p->rc;
43971     /* sqlite3Error(p->db, p->rc, 0); */
43972     return p->rc;
43973   }else{
43974     /* This is for legacy sqlite3_prepare() builds and when the code
43975     ** is SQLITE_ROW or SQLITE_DONE */
43976     return rc;
43977   }
43978 }
43979
43980 /*
43981 ** This is the top-level implementation of sqlite3_step().  Call
43982 ** sqlite3Step() to do most of the work.  If a schema error occurs,
43983 ** call sqlite3Reprepare() and try again.
43984 */
43985 #ifdef SQLITE_OMIT_PARSER
43986 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
43987   int rc = SQLITE_MISUSE;
43988   if( pStmt ){
43989     Vdbe *v;
43990     v = (Vdbe*)pStmt;
43991     sqlite3_mutex_enter(v->db->mutex);
43992     rc = sqlite3Step(v);
43993     sqlite3_mutex_leave(v->db->mutex);
43994   }
43995   return rc;
43996 }
43997 #else
43998 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
43999   int rc = SQLITE_MISUSE;
44000   if( pStmt ){
44001     int cnt = 0;
44002     Vdbe *v = (Vdbe*)pStmt;
44003     sqlite3 *db = v->db;
44004     sqlite3_mutex_enter(db->mutex);
44005     while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
44006            && cnt++ < 5
44007            && vdbeReprepare(v) ){
44008       sqlite3_reset(pStmt);
44009       v->expired = 0;
44010     }
44011     if( rc==SQLITE_SCHEMA && v->zSql && db->pErr ){
44012       /* This case occurs after failing to recompile an sql statement. 
44013       ** The error message from the SQL compiler has already been loaded 
44014       ** into the database handle. This block copies the error message 
44015       ** from the database handle into the statement and sets the statement
44016       ** program counter to 0 to ensure that when the statement is 
44017       ** finalized or reset the parser error message is available via
44018       ** sqlite3_errmsg() and sqlite3_errcode().
44019       */
44020       const char *zErr = (const char *)sqlite3_value_text(db->pErr); 
44021       sqlite3DbFree(db, v->zErrMsg);
44022       if( !db->mallocFailed ){
44023         v->zErrMsg = sqlite3DbStrDup(db, zErr);
44024       } else {
44025         v->zErrMsg = 0;
44026         v->rc = SQLITE_NOMEM;
44027       }
44028     }
44029     rc = sqlite3ApiExit(db, rc);
44030     sqlite3_mutex_leave(db->mutex);
44031   }
44032   return rc;
44033 }
44034 #endif
44035
44036 /*
44037 ** Extract the user data from a sqlite3_context structure and return a
44038 ** pointer to it.
44039 */
44040 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
44041   assert( p && p->pFunc );
44042   return p->pFunc->pUserData;
44043 }
44044
44045 /*
44046 ** Extract the user data from a sqlite3_context structure and return a
44047 ** pointer to it.
44048 */
44049 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
44050   assert( p && p->pFunc );
44051   return p->s.db;
44052 }
44053
44054 /*
44055 ** The following is the implementation of an SQL function that always
44056 ** fails with an error message stating that the function is used in the
44057 ** wrong context.  The sqlite3_overload_function() API might construct
44058 ** SQL function that use this routine so that the functions will exist
44059 ** for name resolution but are actually overloaded by the xFindFunction
44060 ** method of virtual tables.
44061 */
44062 SQLITE_PRIVATE void sqlite3InvalidFunction(
44063   sqlite3_context *context,  /* The function calling context */
44064   int argc,                  /* Number of arguments to the function */
44065   sqlite3_value **argv       /* Value of each argument */
44066 ){
44067   const char *zName = context->pFunc->zName;
44068   char *zErr;
44069   zErr = sqlite3MPrintf(0,
44070       "unable to use function %s in the requested context", zName);
44071   sqlite3_result_error(context, zErr, -1);
44072   sqlite3_free(zErr);
44073 }
44074
44075 /*
44076 ** Allocate or return the aggregate context for a user function.  A new
44077 ** context is allocated on the first call.  Subsequent calls return the
44078 ** same context that was returned on prior calls.
44079 */
44080 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
44081   Mem *pMem;
44082   assert( p && p->pFunc && p->pFunc->xStep );
44083   assert( sqlite3_mutex_held(p->s.db->mutex) );
44084   pMem = p->pMem;
44085   if( (pMem->flags & MEM_Agg)==0 ){
44086     if( nByte==0 ){
44087       sqlite3VdbeMemReleaseExternal(pMem);
44088       pMem->flags = MEM_Null;
44089       pMem->z = 0;
44090     }else{
44091       sqlite3VdbeMemGrow(pMem, nByte, 0);
44092       pMem->flags = MEM_Agg;
44093       pMem->u.pDef = p->pFunc;
44094       if( pMem->z ){
44095         memset(pMem->z, 0, nByte);
44096       }
44097     }
44098   }
44099   return (void*)pMem->z;
44100 }
44101
44102 /*
44103 ** Return the auxilary data pointer, if any, for the iArg'th argument to
44104 ** the user-function defined by pCtx.
44105 */
44106 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
44107   VdbeFunc *pVdbeFunc;
44108
44109   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44110   pVdbeFunc = pCtx->pVdbeFunc;
44111   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
44112     return 0;
44113   }
44114   return pVdbeFunc->apAux[iArg].pAux;
44115 }
44116
44117 /*
44118 ** Set the auxilary data pointer and delete function, for the iArg'th
44119 ** argument to the user-function defined by pCtx. Any previous value is
44120 ** deleted by calling the delete function specified when it was set.
44121 */
44122 SQLITE_API void sqlite3_set_auxdata(
44123   sqlite3_context *pCtx, 
44124   int iArg, 
44125   void *pAux, 
44126   void (*xDelete)(void*)
44127 ){
44128   struct AuxData *pAuxData;
44129   VdbeFunc *pVdbeFunc;
44130   if( iArg<0 ) goto failed;
44131
44132   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44133   pVdbeFunc = pCtx->pVdbeFunc;
44134   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
44135     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
44136     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
44137     pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
44138     if( !pVdbeFunc ){
44139       goto failed;
44140     }
44141     pCtx->pVdbeFunc = pVdbeFunc;
44142     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
44143     pVdbeFunc->nAux = iArg+1;
44144     pVdbeFunc->pFunc = pCtx->pFunc;
44145   }
44146
44147   pAuxData = &pVdbeFunc->apAux[iArg];
44148   if( pAuxData->pAux && pAuxData->xDelete ){
44149     pAuxData->xDelete(pAuxData->pAux);
44150   }
44151   pAuxData->pAux = pAux;
44152   pAuxData->xDelete = xDelete;
44153   return;
44154
44155 failed:
44156   if( xDelete ){
44157     xDelete(pAux);
44158   }
44159 }
44160
44161 /*
44162 ** Return the number of times the Step function of a aggregate has been 
44163 ** called.
44164 **
44165 ** This function is deprecated.  Do not use it for new code.  It is
44166 ** provide only to avoid breaking legacy code.  New aggregate function
44167 ** implementations should keep their own counts within their aggregate
44168 ** context.
44169 */
44170 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
44171   assert( p && p->pFunc && p->pFunc->xStep );
44172   return p->pMem->n;
44173 }
44174
44175 /*
44176 ** Return the number of columns in the result set for the statement pStmt.
44177 */
44178 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
44179   Vdbe *pVm = (Vdbe *)pStmt;
44180   return pVm ? pVm->nResColumn : 0;
44181 }
44182
44183 /*
44184 ** Return the number of values available from the current row of the
44185 ** currently executing statement pStmt.
44186 */
44187 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
44188   Vdbe *pVm = (Vdbe *)pStmt;
44189   if( pVm==0 || pVm->pResultSet==0 ) return 0;
44190   return pVm->nResColumn;
44191 }
44192
44193
44194 /*
44195 ** Check to see if column iCol of the given statement is valid.  If
44196 ** it is, return a pointer to the Mem for the value of that column.
44197 ** If iCol is not valid, return a pointer to a Mem which has a value
44198 ** of NULL.
44199 */
44200 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
44201   Vdbe *pVm;
44202   int vals;
44203   Mem *pOut;
44204
44205   pVm = (Vdbe *)pStmt;
44206   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
44207     sqlite3_mutex_enter(pVm->db->mutex);
44208     vals = sqlite3_data_count(pStmt);
44209     pOut = &pVm->pResultSet[i];
44210   }else{
44211     static const Mem nullMem = {{0}, 0.0, 0, "", 0, MEM_Null, SQLITE_NULL, 0, 0, 0 };
44212     if( pVm->db ){
44213       sqlite3_mutex_enter(pVm->db->mutex);
44214       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
44215     }
44216     pOut = (Mem*)&nullMem;
44217   }
44218   return pOut;
44219 }
44220
44221 /*
44222 ** This function is called after invoking an sqlite3_value_XXX function on a 
44223 ** column value (i.e. a value returned by evaluating an SQL expression in the
44224 ** select list of a SELECT statement) that may cause a malloc() failure. If 
44225 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
44226 ** code of statement pStmt set to SQLITE_NOMEM.
44227 **
44228 ** Specifically, this is called from within:
44229 **
44230 **     sqlite3_column_int()
44231 **     sqlite3_column_int64()
44232 **     sqlite3_column_text()
44233 **     sqlite3_column_text16()
44234 **     sqlite3_column_real()
44235 **     sqlite3_column_bytes()
44236 **     sqlite3_column_bytes16()
44237 **
44238 ** But not for sqlite3_column_blob(), which never calls malloc().
44239 */
44240 static void columnMallocFailure(sqlite3_stmt *pStmt)
44241 {
44242   /* If malloc() failed during an encoding conversion within an
44243   ** sqlite3_column_XXX API, then set the return code of the statement to
44244   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
44245   ** and _finalize() will return NOMEM.
44246   */
44247   Vdbe *p = (Vdbe *)pStmt;
44248   if( p ){
44249     p->rc = sqlite3ApiExit(p->db, p->rc);
44250     sqlite3_mutex_leave(p->db->mutex);
44251   }
44252 }
44253
44254 /**************************** sqlite3_column_  *******************************
44255 ** The following routines are used to access elements of the current row
44256 ** in the result set.
44257 */
44258 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
44259   const void *val;
44260   val = sqlite3_value_blob( columnMem(pStmt,i) );
44261   /* Even though there is no encoding conversion, value_blob() might
44262   ** need to call malloc() to expand the result of a zeroblob() 
44263   ** expression. 
44264   */
44265   columnMallocFailure(pStmt);
44266   return val;
44267 }
44268 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
44269   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
44270   columnMallocFailure(pStmt);
44271   return val;
44272 }
44273 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
44274   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
44275   columnMallocFailure(pStmt);
44276   return val;
44277 }
44278 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
44279   double val = sqlite3_value_double( columnMem(pStmt,i) );
44280   columnMallocFailure(pStmt);
44281   return val;
44282 }
44283 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
44284   int val = sqlite3_value_int( columnMem(pStmt,i) );
44285   columnMallocFailure(pStmt);
44286   return val;
44287 }
44288 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
44289   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
44290   columnMallocFailure(pStmt);
44291   return val;
44292 }
44293 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
44294   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
44295   columnMallocFailure(pStmt);
44296   return val;
44297 }
44298 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
44299   sqlite3_value *pOut = columnMem(pStmt, i);
44300   columnMallocFailure(pStmt);
44301   return pOut;
44302 }
44303 #ifndef SQLITE_OMIT_UTF16
44304 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
44305   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
44306   columnMallocFailure(pStmt);
44307   return val;
44308 }
44309 #endif /* SQLITE_OMIT_UTF16 */
44310 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
44311   int iType = sqlite3_value_type( columnMem(pStmt,i) );
44312   columnMallocFailure(pStmt);
44313   return iType;
44314 }
44315
44316 /* The following function is experimental and subject to change or
44317 ** removal */
44318 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
44319 **  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
44320 **}
44321 */
44322
44323 /*
44324 ** Convert the N-th element of pStmt->pColName[] into a string using
44325 ** xFunc() then return that string.  If N is out of range, return 0.
44326 **
44327 ** There are up to 5 names for each column.  useType determines which
44328 ** name is returned.  Here are the names:
44329 **
44330 **    0      The column name as it should be displayed for output
44331 **    1      The datatype name for the column
44332 **    2      The name of the database that the column derives from
44333 **    3      The name of the table that the column derives from
44334 **    4      The name of the table column that the result column derives from
44335 **
44336 ** If the result is not a simple column reference (if it is an expression
44337 ** or a constant) then useTypes 2, 3, and 4 return NULL.
44338 */
44339 static const void *columnName(
44340   sqlite3_stmt *pStmt,
44341   int N,
44342   const void *(*xFunc)(Mem*),
44343   int useType
44344 ){
44345   const void *ret = 0;
44346   Vdbe *p = (Vdbe *)pStmt;
44347   int n;
44348   
44349
44350   if( p!=0 ){
44351     n = sqlite3_column_count(pStmt);
44352     if( N<n && N>=0 ){
44353       N += useType*n;
44354       sqlite3_mutex_enter(p->db->mutex);
44355       ret = xFunc(&p->aColName[N]);
44356
44357       /* A malloc may have failed inside of the xFunc() call. If this
44358       ** is the case, clear the mallocFailed flag and return NULL.
44359       */
44360       if( p->db && p->db->mallocFailed ){
44361         p->db->mallocFailed = 0;
44362         ret = 0;
44363       }
44364       sqlite3_mutex_leave(p->db->mutex);
44365     }
44366   }
44367   return ret;
44368 }
44369
44370 /*
44371 ** Return the name of the Nth column of the result set returned by SQL
44372 ** statement pStmt.
44373 */
44374 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
44375   return columnName(
44376       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
44377 }
44378 #ifndef SQLITE_OMIT_UTF16
44379 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
44380   return columnName(
44381       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
44382 }
44383 #endif
44384
44385 /*
44386 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
44387 ** not define OMIT_DECLTYPE.
44388 */
44389 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
44390 # error "Must not define both SQLITE_OMIT_DECLTYPE \
44391          and SQLITE_ENABLE_COLUMN_METADATA"
44392 #endif
44393
44394 #ifndef SQLITE_OMIT_DECLTYPE
44395 /*
44396 ** Return the column declaration type (if applicable) of the 'i'th column
44397 ** of the result set of SQL statement pStmt.
44398 */
44399 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
44400   return columnName(
44401       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
44402 }
44403 #ifndef SQLITE_OMIT_UTF16
44404 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
44405   return columnName(
44406       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
44407 }
44408 #endif /* SQLITE_OMIT_UTF16 */
44409 #endif /* SQLITE_OMIT_DECLTYPE */
44410
44411 #ifdef SQLITE_ENABLE_COLUMN_METADATA
44412 /*
44413 ** Return the name of the database from which a result column derives.
44414 ** NULL is returned if the result column is an expression or constant or
44415 ** anything else which is not an unabiguous reference to a database column.
44416 */
44417 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
44418   return columnName(
44419       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
44420 }
44421 #ifndef SQLITE_OMIT_UTF16
44422 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
44423   return columnName(
44424       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
44425 }
44426 #endif /* SQLITE_OMIT_UTF16 */
44427
44428 /*
44429 ** Return the name of the table from which a result column derives.
44430 ** NULL is returned if the result column is an expression or constant or
44431 ** anything else which is not an unabiguous reference to a database column.
44432 */
44433 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
44434   return columnName(
44435       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
44436 }
44437 #ifndef SQLITE_OMIT_UTF16
44438 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
44439   return columnName(
44440       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
44441 }
44442 #endif /* SQLITE_OMIT_UTF16 */
44443
44444 /*
44445 ** Return the name of the table column from which a result column derives.
44446 ** NULL is returned if the result column is an expression or constant or
44447 ** anything else which is not an unabiguous reference to a database column.
44448 */
44449 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
44450   return columnName(
44451       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
44452 }
44453 #ifndef SQLITE_OMIT_UTF16
44454 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
44455   return columnName(
44456       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
44457 }
44458 #endif /* SQLITE_OMIT_UTF16 */
44459 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
44460
44461
44462 /******************************* sqlite3_bind_  ***************************
44463 ** 
44464 ** Routines used to attach values to wildcards in a compiled SQL statement.
44465 */
44466 /*
44467 ** Unbind the value bound to variable i in virtual machine p. This is the 
44468 ** the same as binding a NULL value to the column. If the "i" parameter is
44469 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
44470 **
44471 ** The error code stored in database p->db is overwritten with the return
44472 ** value in any case.
44473 */
44474 static int vdbeUnbind(Vdbe *p, int i){
44475   Mem *pVar;
44476   if( p==0 || p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
44477     if( p ) sqlite3Error(p->db, SQLITE_MISUSE, 0);
44478     return SQLITE_MISUSE;
44479   }
44480   if( i<1 || i>p->nVar ){
44481     sqlite3Error(p->db, SQLITE_RANGE, 0);
44482     return SQLITE_RANGE;
44483   }
44484   i--;
44485   pVar = &p->aVar[i];
44486   sqlite3VdbeMemRelease(pVar);
44487   pVar->flags = MEM_Null;
44488   sqlite3Error(p->db, SQLITE_OK, 0);
44489   return SQLITE_OK;
44490 }
44491
44492 /*
44493 ** Bind a text or BLOB value.
44494 */
44495 static int bindText(
44496   sqlite3_stmt *pStmt,   /* The statement to bind against */
44497   int i,                 /* Index of the parameter to bind */
44498   const void *zData,     /* Pointer to the data to be bound */
44499   int nData,             /* Number of bytes of data to be bound */
44500   void (*xDel)(void*),   /* Destructor for the data */
44501   int encoding           /* Encoding for the data */
44502 ){
44503   Vdbe *p = (Vdbe *)pStmt;
44504   Mem *pVar;
44505   int rc;
44506
44507   if( p==0 ){
44508     return SQLITE_MISUSE;
44509   }
44510   sqlite3_mutex_enter(p->db->mutex);
44511   rc = vdbeUnbind(p, i);
44512   if( rc==SQLITE_OK && zData!=0 ){
44513     pVar = &p->aVar[i-1];
44514     rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
44515     if( rc==SQLITE_OK && encoding!=0 ){
44516       rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
44517     }
44518     sqlite3Error(p->db, rc, 0);
44519     rc = sqlite3ApiExit(p->db, rc);
44520   }
44521   sqlite3_mutex_leave(p->db->mutex);
44522   return rc;
44523 }
44524
44525
44526 /*
44527 ** Bind a blob value to an SQL statement variable.
44528 */
44529 SQLITE_API int sqlite3_bind_blob(
44530   sqlite3_stmt *pStmt, 
44531   int i, 
44532   const void *zData, 
44533   int nData, 
44534   void (*xDel)(void*)
44535 ){
44536   return bindText(pStmt, i, zData, nData, xDel, 0);
44537 }
44538 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
44539   int rc;
44540   Vdbe *p = (Vdbe *)pStmt;
44541   sqlite3_mutex_enter(p->db->mutex);
44542   rc = vdbeUnbind(p, i);
44543   if( rc==SQLITE_OK ){
44544     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
44545   }
44546   sqlite3_mutex_leave(p->db->mutex);
44547   return rc;
44548 }
44549 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
44550   return sqlite3_bind_int64(p, i, (i64)iValue);
44551 }
44552 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
44553   int rc;
44554   Vdbe *p = (Vdbe *)pStmt;
44555   sqlite3_mutex_enter(p->db->mutex);
44556   rc = vdbeUnbind(p, i);
44557   if( rc==SQLITE_OK ){
44558     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
44559   }
44560   sqlite3_mutex_leave(p->db->mutex);
44561   return rc;
44562 }
44563 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
44564   int rc;
44565   Vdbe *p = (Vdbe*)pStmt;
44566   sqlite3_mutex_enter(p->db->mutex);
44567   rc = vdbeUnbind(p, i);
44568   sqlite3_mutex_leave(p->db->mutex);
44569   return rc;
44570 }
44571 SQLITE_API int sqlite3_bind_text( 
44572   sqlite3_stmt *pStmt, 
44573   int i, 
44574   const char *zData, 
44575   int nData, 
44576   void (*xDel)(void*)
44577 ){
44578   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
44579 }
44580 #ifndef SQLITE_OMIT_UTF16
44581 SQLITE_API int sqlite3_bind_text16(
44582   sqlite3_stmt *pStmt, 
44583   int i, 
44584   const void *zData, 
44585   int nData, 
44586   void (*xDel)(void*)
44587 ){
44588   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
44589 }
44590 #endif /* SQLITE_OMIT_UTF16 */
44591 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
44592   int rc;
44593   Vdbe *p = (Vdbe *)pStmt;
44594   sqlite3_mutex_enter(p->db->mutex);
44595   rc = vdbeUnbind(p, i);
44596   if( rc==SQLITE_OK ){
44597     rc = sqlite3VdbeMemCopy(&p->aVar[i-1], pValue);
44598     if( rc==SQLITE_OK ){
44599       rc = sqlite3VdbeChangeEncoding(&p->aVar[i-1], ENC(p->db));
44600     }
44601   }
44602   rc = sqlite3ApiExit(p->db, rc);
44603   sqlite3_mutex_leave(p->db->mutex);
44604   return rc;
44605 }
44606 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
44607   int rc;
44608   Vdbe *p = (Vdbe *)pStmt;
44609   sqlite3_mutex_enter(p->db->mutex);
44610   rc = vdbeUnbind(p, i);
44611   if( rc==SQLITE_OK ){
44612     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
44613   }
44614   sqlite3_mutex_leave(p->db->mutex);
44615   return rc;
44616 }
44617
44618 /*
44619 ** Return the number of wildcards that can be potentially bound to.
44620 ** This routine is added to support DBD::SQLite.  
44621 */
44622 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
44623   Vdbe *p = (Vdbe*)pStmt;
44624   return p ? p->nVar : 0;
44625 }
44626
44627 /*
44628 ** Create a mapping from variable numbers to variable names
44629 ** in the Vdbe.azVar[] array, if such a mapping does not already
44630 ** exist.
44631 */
44632 static void createVarMap(Vdbe *p){
44633   if( !p->okVar ){
44634     sqlite3_mutex_enter(p->db->mutex);
44635     if( !p->okVar ){
44636       int j;
44637       Op *pOp;
44638       for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
44639         if( pOp->opcode==OP_Variable ){
44640           assert( pOp->p1>0 && pOp->p1<=p->nVar );
44641           p->azVar[pOp->p1-1] = pOp->p4.z;
44642         }
44643       }
44644       p->okVar = 1;
44645     }
44646     sqlite3_mutex_leave(p->db->mutex);
44647   }
44648 }
44649
44650 /*
44651 ** Return the name of a wildcard parameter.  Return NULL if the index
44652 ** is out of range or if the wildcard is unnamed.
44653 **
44654 ** The result is always UTF-8.
44655 */
44656 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
44657   Vdbe *p = (Vdbe*)pStmt;
44658   if( p==0 || i<1 || i>p->nVar ){
44659     return 0;
44660   }
44661   createVarMap(p);
44662   return p->azVar[i-1];
44663 }
44664
44665 /*
44666 ** Given a wildcard parameter name, return the index of the variable
44667 ** with that name.  If there is no variable with the given name,
44668 ** return 0.
44669 */
44670 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
44671   Vdbe *p = (Vdbe*)pStmt;
44672   int i;
44673   if( p==0 ){
44674     return 0;
44675   }
44676   createVarMap(p); 
44677   if( zName ){
44678     for(i=0; i<p->nVar; i++){
44679       const char *z = p->azVar[i];
44680       if( z && strcmp(z,zName)==0 ){
44681         return i+1;
44682       }
44683     }
44684   }
44685   return 0;
44686 }
44687
44688 /*
44689 ** Transfer all bindings from the first statement over to the second.
44690 ** If the two statements contain a different number of bindings, then
44691 ** an SQLITE_ERROR is returned.
44692 */
44693 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
44694   Vdbe *pFrom = (Vdbe*)pFromStmt;
44695   Vdbe *pTo = (Vdbe*)pToStmt;
44696   int i, rc = SQLITE_OK;
44697   if( (pFrom->magic!=VDBE_MAGIC_RUN && pFrom->magic!=VDBE_MAGIC_HALT)
44698     || (pTo->magic!=VDBE_MAGIC_RUN && pTo->magic!=VDBE_MAGIC_HALT)
44699     || pTo->db!=pFrom->db ){
44700     return SQLITE_MISUSE;
44701   }
44702   if( pFrom->nVar!=pTo->nVar ){
44703     return SQLITE_ERROR;
44704   }
44705   sqlite3_mutex_enter(pTo->db->mutex);
44706   for(i=0; rc==SQLITE_OK && i<pFrom->nVar; i++){
44707     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
44708   }
44709   sqlite3_mutex_leave(pTo->db->mutex);
44710   assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
44711   return rc;
44712 }
44713
44714 /*
44715 ** Return the sqlite3* database handle to which the prepared statement given
44716 ** in the argument belongs.  This is the same database handle that was
44717 ** the first argument to the sqlite3_prepare() that was used to create
44718 ** the statement in the first place.
44719 */
44720 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
44721   return pStmt ? ((Vdbe*)pStmt)->db : 0;
44722 }
44723
44724 /*
44725 ** Return a pointer to the next prepared statement after pStmt associated
44726 ** with database connection pDb.  If pStmt is NULL, return the first
44727 ** prepared statement for the database connection.  Return NULL if there
44728 ** are no more.
44729 */
44730 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
44731   sqlite3_stmt *pNext;
44732   sqlite3_mutex_enter(pDb->mutex);
44733   if( pStmt==0 ){
44734     pNext = (sqlite3_stmt*)pDb->pVdbe;
44735   }else{
44736     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
44737   }
44738   sqlite3_mutex_leave(pDb->mutex);
44739   return pNext;
44740 }
44741
44742 /************** End of vdbeapi.c *********************************************/
44743 /************** Begin file vdbe.c ********************************************/
44744 /*
44745 ** 2001 September 15
44746 **
44747 ** The author disclaims copyright to this source code.  In place of
44748 ** a legal notice, here is a blessing:
44749 **
44750 **    May you do good and not evil.
44751 **    May you find forgiveness for yourself and forgive others.
44752 **    May you share freely, never taking more than you give.
44753 **
44754 *************************************************************************
44755 ** The code in this file implements execution method of the 
44756 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
44757 ** handles housekeeping details such as creating and deleting
44758 ** VDBE instances.  This file is solely interested in executing
44759 ** the VDBE program.
44760 **
44761 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
44762 ** to a VDBE.
44763 **
44764 ** The SQL parser generates a program which is then executed by
44765 ** the VDBE to do the work of the SQL statement.  VDBE programs are 
44766 ** similar in form to assembly language.  The program consists of
44767 ** a linear sequence of operations.  Each operation has an opcode 
44768 ** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4 
44769 ** is a null-terminated string.  Operand P5 is an unsigned character.
44770 ** Few opcodes use all 5 operands.
44771 **
44772 ** Computation results are stored on a set of registers numbered beginning
44773 ** with 1 and going up to Vdbe.nMem.  Each register can store
44774 ** either an integer, a null-terminated string, a floating point
44775 ** number, or the SQL "NULL" value.  An implicit conversion from one
44776 ** type to the other occurs as necessary.
44777 ** 
44778 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
44779 ** function which does the work of interpreting a VDBE program.
44780 ** But other routines are also provided to help in building up
44781 ** a program instruction by instruction.
44782 **
44783 ** Various scripts scan this source file in order to generate HTML
44784 ** documentation, headers files, or other derived files.  The formatting
44785 ** of the code in this file is, therefore, important.  See other comments
44786 ** in this file for details.  If in doubt, do not deviate from existing
44787 ** commenting and indentation practices when changing or adding code.
44788 **
44789 ** $Id: vdbe.c,v 1.772 2008/08/02 15:10:09 danielk1977 Exp $
44790 */
44791
44792 /*
44793 ** The following global variable is incremented every time a cursor
44794 ** moves, either by the OP_MoveXX, OP_Next, or OP_Prev opcodes.  The test
44795 ** procedures use this information to make sure that indices are
44796 ** working correctly.  This variable has no function other than to
44797 ** help verify the correct operation of the library.
44798 */
44799 #ifdef SQLITE_TEST
44800 SQLITE_API int sqlite3_search_count = 0;
44801 #endif
44802
44803 /*
44804 ** When this global variable is positive, it gets decremented once before
44805 ** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
44806 ** field of the sqlite3 structure is set in order to simulate and interrupt.
44807 **
44808 ** This facility is used for testing purposes only.  It does not function
44809 ** in an ordinary build.
44810 */
44811 #ifdef SQLITE_TEST
44812 SQLITE_API int sqlite3_interrupt_count = 0;
44813 #endif
44814
44815 /*
44816 ** The next global variable is incremented each type the OP_Sort opcode
44817 ** is executed.  The test procedures use this information to make sure that
44818 ** sorting is occurring or not occurring at appropriate times.   This variable
44819 ** has no function other than to help verify the correct operation of the
44820 ** library.
44821 */
44822 #ifdef SQLITE_TEST
44823 SQLITE_API int sqlite3_sort_count = 0;
44824 #endif
44825
44826 /*
44827 ** The next global variable records the size of the largest MEM_Blob
44828 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
44829 ** use this information to make sure that the zero-blob functionality
44830 ** is working correctly.   This variable has no function other than to
44831 ** help verify the correct operation of the library.
44832 */
44833 #ifdef SQLITE_TEST
44834 SQLITE_API int sqlite3_max_blobsize = 0;
44835 static void updateMaxBlobsize(Mem *p){
44836   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
44837     sqlite3_max_blobsize = p->n;
44838   }
44839 }
44840 #endif
44841
44842 /*
44843 ** Test a register to see if it exceeds the current maximum blob size.
44844 ** If it does, record the new maximum blob size.
44845 */
44846 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
44847 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
44848 #else
44849 # define UPDATE_MAX_BLOBSIZE(P)
44850 #endif
44851
44852 /*
44853 ** Release the memory associated with a register.  This
44854 ** leaves the Mem.flags field in an inconsistent state.
44855 */
44856 #define Release(P) if((P)->flags&MEM_Dyn){ sqlite3VdbeMemRelease(P); }
44857
44858 /*
44859 ** Convert the given register into a string if it isn't one
44860 ** already. Return non-zero if a malloc() fails.
44861 */
44862 #define Stringify(P, enc) \
44863    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
44864      { goto no_mem; }
44865
44866 /*
44867 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
44868 ** a pointer to a dynamically allocated string where some other entity
44869 ** is responsible for deallocating that string.  Because the register
44870 ** does not control the string, it might be deleted without the register
44871 ** knowing it.
44872 **
44873 ** This routine converts an ephemeral string into a dynamically allocated
44874 ** string that the register itself controls.  In other words, it
44875 ** converts an MEM_Ephem string into an MEM_Dyn string.
44876 */
44877 #define Deephemeralize(P) \
44878    if( ((P)->flags&MEM_Ephem)!=0 \
44879        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
44880
44881 /*
44882 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
44883 ** P if required.
44884 */
44885 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
44886
44887 /*
44888 ** Argument pMem points at a register that will be passed to a
44889 ** user-defined function or returned to the user as the result of a query.
44890 ** The second argument, 'db_enc' is the text encoding used by the vdbe for
44891 ** register variables.  This routine sets the pMem->enc and pMem->type
44892 ** variables used by the sqlite3_value_*() routines.
44893 */
44894 #define storeTypeInfo(A,B) _storeTypeInfo(A)
44895 static void _storeTypeInfo(Mem *pMem){
44896   int flags = pMem->flags;
44897   if( flags & MEM_Null ){
44898     pMem->type = SQLITE_NULL;
44899   }
44900   else if( flags & MEM_Int ){
44901     pMem->type = SQLITE_INTEGER;
44902   }
44903   else if( flags & MEM_Real ){
44904     pMem->type = SQLITE_FLOAT;
44905   }
44906   else if( flags & MEM_Str ){
44907     pMem->type = SQLITE_TEXT;
44908   }else{
44909     pMem->type = SQLITE_BLOB;
44910   }
44911 }
44912
44913 /*
44914 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
44915 ** created by mkopcodeh.awk during compilation.  Data is obtained
44916 ** from the comments following the "case OP_xxxx:" statements in
44917 ** this file.  
44918 */
44919 static unsigned char opcodeProperty[] = OPFLG_INITIALIZER;
44920
44921 /*
44922 ** Return true if an opcode has any of the OPFLG_xxx properties
44923 ** specified by mask.
44924 */
44925 SQLITE_PRIVATE int sqlite3VdbeOpcodeHasProperty(int opcode, int mask){
44926   assert( opcode>0 && opcode<sizeof(opcodeProperty) );
44927   return (opcodeProperty[opcode]&mask)!=0;
44928 }
44929
44930 /*
44931 ** Allocate cursor number iCur.  Return a pointer to it.  Return NULL
44932 ** if we run out of memory.
44933 */
44934 static Cursor *allocateCursor(
44935   Vdbe *p, 
44936   int iCur, 
44937   Op *pOp,
44938   int iDb, 
44939   int isBtreeCursor
44940 ){
44941   /* Find the memory cell that will be used to store the blob of memory
44942   ** required for this Cursor structure. It is convenient to use a 
44943   ** vdbe memory cell to manage the memory allocation required for a
44944   ** Cursor structure for the following reasons:
44945   **
44946   **   * Sometimes cursor numbers are used for a couple of different
44947   **     purposes in a vdbe program. The different uses might require
44948   **     different sized allocations. Memory cells provide growable
44949   **     allocations.
44950   **
44951   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
44952   **     be freed lazily via the sqlite3_release_memory() API. This
44953   **     minimizes the number of malloc calls made by the system.
44954   **
44955   ** Memory cells for cursors are allocated at the top of the address
44956   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
44957   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
44958   */
44959   Mem *pMem = &p->aMem[p->nMem-iCur];
44960
44961   int nByte;
44962   Cursor *pCx = 0;
44963   /* If the opcode of pOp is OP_SetNumColumns, then pOp->p2 contains
44964   ** the number of fields in the records contained in the table or
44965   ** index being opened. Use this to reserve space for the 
44966   ** Cursor.aType[] array.
44967   */
44968   int nField = 0;
44969   if( pOp->opcode==OP_SetNumColumns || pOp->opcode==OP_OpenEphemeral ){
44970     nField = pOp->p2;
44971   }
44972   nByte = 
44973       sizeof(Cursor) + 
44974       (isBtreeCursor?sqlite3BtreeCursorSize():0) + 
44975       2*nField*sizeof(u32);
44976
44977   assert( iCur<p->nCursor );
44978   if( p->apCsr[iCur] ){
44979     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
44980     p->apCsr[iCur] = 0;
44981   }
44982   if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
44983     p->apCsr[iCur] = pCx = (Cursor *)pMem->z;
44984     memset(pMem->z, 0, nByte);
44985     pCx->iDb = iDb;
44986     pCx->nField = nField;
44987     if( nField ){
44988       pCx->aType = (u32 *)&pMem->z[sizeof(Cursor)];
44989     }
44990     if( isBtreeCursor ){
44991       pCx->pCursor = (BtCursor *)&pMem->z[sizeof(Cursor)+2*nField*sizeof(u32)];
44992     }
44993   }
44994   return pCx;
44995 }
44996
44997 /*
44998 ** Try to convert a value into a numeric representation if we can
44999 ** do so without loss of information.  In other words, if the string
45000 ** looks like a number, convert it into a number.  If it does not
45001 ** look like a number, leave it alone.
45002 */
45003 static void applyNumericAffinity(Mem *pRec){
45004   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
45005     int realnum;
45006     sqlite3VdbeMemNulTerminate(pRec);
45007     if( (pRec->flags&MEM_Str)
45008          && sqlite3IsNumber(pRec->z, &realnum, pRec->enc) ){
45009       i64 value;
45010       sqlite3VdbeChangeEncoding(pRec, SQLITE_UTF8);
45011       if( !realnum && sqlite3Atoi64(pRec->z, &value) ){
45012         pRec->u.i = value;
45013         MemSetTypeFlag(pRec, MEM_Int);
45014       }else{
45015         sqlite3VdbeMemRealify(pRec);
45016       }
45017     }
45018   }
45019 }
45020
45021 /*
45022 ** Processing is determine by the affinity parameter:
45023 **
45024 ** SQLITE_AFF_INTEGER:
45025 ** SQLITE_AFF_REAL:
45026 ** SQLITE_AFF_NUMERIC:
45027 **    Try to convert pRec to an integer representation or a 
45028 **    floating-point representation if an integer representation
45029 **    is not possible.  Note that the integer representation is
45030 **    always preferred, even if the affinity is REAL, because
45031 **    an integer representation is more space efficient on disk.
45032 **
45033 ** SQLITE_AFF_TEXT:
45034 **    Convert pRec to a text representation.
45035 **
45036 ** SQLITE_AFF_NONE:
45037 **    No-op.  pRec is unchanged.
45038 */
45039 static void applyAffinity(
45040   Mem *pRec,          /* The value to apply affinity to */
45041   char affinity,      /* The affinity to be applied */
45042   u8 enc              /* Use this text encoding */
45043 ){
45044   if( affinity==SQLITE_AFF_TEXT ){
45045     /* Only attempt the conversion to TEXT if there is an integer or real
45046     ** representation (blob and NULL do not get converted) but no string
45047     ** representation.
45048     */
45049     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
45050       sqlite3VdbeMemStringify(pRec, enc);
45051     }
45052     pRec->flags &= ~(MEM_Real|MEM_Int);
45053   }else if( affinity!=SQLITE_AFF_NONE ){
45054     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
45055              || affinity==SQLITE_AFF_NUMERIC );
45056     applyNumericAffinity(pRec);
45057     if( pRec->flags & MEM_Real ){
45058       sqlite3VdbeIntegerAffinity(pRec);
45059     }
45060   }
45061 }
45062
45063 /*
45064 ** Try to convert the type of a function argument or a result column
45065 ** into a numeric representation.  Use either INTEGER or REAL whichever
45066 ** is appropriate.  But only do the conversion if it is possible without
45067 ** loss of information and return the revised type of the argument.
45068 **
45069 ** This is an EXPERIMENTAL api and is subject to change or removal.
45070 */
45071 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
45072   Mem *pMem = (Mem*)pVal;
45073   applyNumericAffinity(pMem);
45074   storeTypeInfo(pMem, 0);
45075   return pMem->type;
45076 }
45077
45078 /*
45079 ** Exported version of applyAffinity(). This one works on sqlite3_value*, 
45080 ** not the internal Mem* type.
45081 */
45082 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
45083   sqlite3_value *pVal, 
45084   u8 affinity, 
45085   u8 enc
45086 ){
45087   applyAffinity((Mem *)pVal, affinity, enc);
45088 }
45089
45090 #ifdef SQLITE_DEBUG
45091 /*
45092 ** Write a nice string representation of the contents of cell pMem
45093 ** into buffer zBuf, length nBuf.
45094 */
45095 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
45096   char *zCsr = zBuf;
45097   int f = pMem->flags;
45098
45099   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
45100
45101   if( f&MEM_Blob ){
45102     int i;
45103     char c;
45104     if( f & MEM_Dyn ){
45105       c = 'z';
45106       assert( (f & (MEM_Static|MEM_Ephem))==0 );
45107     }else if( f & MEM_Static ){
45108       c = 't';
45109       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
45110     }else if( f & MEM_Ephem ){
45111       c = 'e';
45112       assert( (f & (MEM_Static|MEM_Dyn))==0 );
45113     }else{
45114       c = 's';
45115     }
45116
45117     sqlite3_snprintf(100, zCsr, "%c", c);
45118     zCsr += strlen(zCsr);
45119     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
45120     zCsr += strlen(zCsr);
45121     for(i=0; i<16 && i<pMem->n; i++){
45122       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
45123       zCsr += strlen(zCsr);
45124     }
45125     for(i=0; i<16 && i<pMem->n; i++){
45126       char z = pMem->z[i];
45127       if( z<32 || z>126 ) *zCsr++ = '.';
45128       else *zCsr++ = z;
45129     }
45130
45131     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
45132     zCsr += strlen(zCsr);
45133     if( f & MEM_Zero ){
45134       sqlite3_snprintf(100, zCsr,"+%lldz",pMem->u.i);
45135       zCsr += strlen(zCsr);
45136     }
45137     *zCsr = '\0';
45138   }else if( f & MEM_Str ){
45139     int j, k;
45140     zBuf[0] = ' ';
45141     if( f & MEM_Dyn ){
45142       zBuf[1] = 'z';
45143       assert( (f & (MEM_Static|MEM_Ephem))==0 );
45144     }else if( f & MEM_Static ){
45145       zBuf[1] = 't';
45146       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
45147     }else if( f & MEM_Ephem ){
45148       zBuf[1] = 'e';
45149       assert( (f & (MEM_Static|MEM_Dyn))==0 );
45150     }else{
45151       zBuf[1] = 's';
45152     }
45153     k = 2;
45154     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
45155     k += strlen(&zBuf[k]);
45156     zBuf[k++] = '[';
45157     for(j=0; j<15 && j<pMem->n; j++){
45158       u8 c = pMem->z[j];
45159       if( c>=0x20 && c<0x7f ){
45160         zBuf[k++] = c;
45161       }else{
45162         zBuf[k++] = '.';
45163       }
45164     }
45165     zBuf[k++] = ']';
45166     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
45167     k += strlen(&zBuf[k]);
45168     zBuf[k++] = 0;
45169   }
45170 }
45171 #endif
45172
45173 #ifdef SQLITE_DEBUG
45174 /*
45175 ** Print the value of a register for tracing purposes:
45176 */
45177 static void memTracePrint(FILE *out, Mem *p){
45178   if( p->flags & MEM_Null ){
45179     fprintf(out, " NULL");
45180   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
45181     fprintf(out, " si:%lld", p->u.i);
45182   }else if( p->flags & MEM_Int ){
45183     fprintf(out, " i:%lld", p->u.i);
45184   }else if( p->flags & MEM_Real ){
45185     fprintf(out, " r:%g", p->r);
45186   }else{
45187     char zBuf[200];
45188     sqlite3VdbeMemPrettyPrint(p, zBuf);
45189     fprintf(out, " ");
45190     fprintf(out, "%s", zBuf);
45191   }
45192 }
45193 static void registerTrace(FILE *out, int iReg, Mem *p){
45194   fprintf(out, "REG[%d] = ", iReg);
45195   memTracePrint(out, p);
45196   fprintf(out, "\n");
45197 }
45198 #endif
45199
45200 #ifdef SQLITE_DEBUG
45201 #  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
45202 #else
45203 #  define REGISTER_TRACE(R,M)
45204 #endif
45205
45206
45207 #ifdef VDBE_PROFILE
45208
45209 /* 
45210 ** hwtime.h contains inline assembler code for implementing 
45211 ** high-performance timing routines.
45212 */
45213 /************** Include hwtime.h in the middle of vdbe.c *********************/
45214 /************** Begin file hwtime.h ******************************************/
45215 /*
45216 ** 2008 May 27
45217 **
45218 ** The author disclaims copyright to this source code.  In place of
45219 ** a legal notice, here is a blessing:
45220 **
45221 **    May you do good and not evil.
45222 **    May you find forgiveness for yourself and forgive others.
45223 **    May you share freely, never taking more than you give.
45224 **
45225 ******************************************************************************
45226 **
45227 ** This file contains inline asm code for retrieving "high-performance"
45228 ** counters for x86 class CPUs.
45229 **
45230 ** $Id: hwtime.h,v 1.3 2008/08/01 14:33:15 shane Exp $
45231 */
45232 #ifndef _HWTIME_H_
45233 #define _HWTIME_H_
45234
45235 /*
45236 ** The following routine only works on pentium-class (or newer) processors.
45237 ** It uses the RDTSC opcode to read the cycle count value out of the
45238 ** processor and returns that value.  This can be used for high-res
45239 ** profiling.
45240 */
45241 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
45242       (defined(i386) || defined(__i386__) || defined(_M_IX86))
45243
45244   #if defined(__GNUC__)
45245
45246   __inline__ sqlite_uint64 sqlite3Hwtime(void){
45247      unsigned int lo, hi;
45248      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
45249      return (sqlite_uint64)hi << 32 | lo;
45250   }
45251
45252   #elif defined(_MSC_VER)
45253
45254   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
45255      __asm {
45256         rdtsc
45257         ret       ; return value at EDX:EAX
45258      }
45259   }
45260
45261   #endif
45262
45263 #elif (defined(__GNUC__) && defined(__x86_64__))
45264
45265   __inline__ sqlite_uint64 sqlite3Hwtime(void){
45266       unsigned long val;
45267       __asm__ __volatile__ ("rdtsc" : "=A" (val));
45268       return val;
45269   }
45270  
45271 #elif (defined(__GNUC__) && defined(__ppc__))
45272
45273   __inline__ sqlite_uint64 sqlite3Hwtime(void){
45274       unsigned long long retval;
45275       unsigned long junk;
45276       __asm__ __volatile__ ("\n\
45277           1:      mftbu   %1\n\
45278                   mftb    %L0\n\
45279                   mftbu   %0\n\
45280                   cmpw    %0,%1\n\
45281                   bne     1b"
45282                   : "=r" (retval), "=r" (junk));
45283       return retval;
45284   }
45285
45286 #else
45287
45288   #error Need implementation of sqlite3Hwtime() for your platform.
45289
45290   /*
45291   ** To compile without implementing sqlite3Hwtime() for your platform,
45292   ** you can remove the above #error and use the following
45293   ** stub function.  You will lose timing support for many
45294   ** of the debugging and testing utilities, but it should at
45295   ** least compile and run.
45296   */
45297 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
45298
45299 #endif
45300
45301 #endif /* !defined(_HWTIME_H_) */
45302
45303 /************** End of hwtime.h **********************************************/
45304 /************** Continuing where we left off in vdbe.c ***********************/
45305
45306 #endif
45307
45308 /*
45309 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
45310 ** sqlite3_interrupt() routine has been called.  If it has been, then
45311 ** processing of the VDBE program is interrupted.
45312 **
45313 ** This macro added to every instruction that does a jump in order to
45314 ** implement a loop.  This test used to be on every single instruction,
45315 ** but that meant we more testing that we needed.  By only testing the
45316 ** flag on jump instructions, we get a (small) speed improvement.
45317 */
45318 #define CHECK_FOR_INTERRUPT \
45319    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
45320
45321 #ifdef SQLITE_DEBUG
45322 static int fileExists(sqlite3 *db, const char *zFile){
45323   int res = 0;
45324   int rc = SQLITE_OK;
45325 #ifdef SQLITE_TEST
45326   /* If we are currently testing IO errors, then do not call OsAccess() to
45327   ** test for the presence of zFile. This is because any IO error that
45328   ** occurs here will not be reported, causing the test to fail.
45329   */
45330   extern int sqlite3_io_error_pending;
45331   if( sqlite3_io_error_pending<=0 )
45332 #endif
45333     rc = sqlite3OsAccess(db->pVfs, zFile, SQLITE_ACCESS_EXISTS, &res);
45334   return (res && rc==SQLITE_OK);
45335 }
45336 #endif
45337
45338 /*
45339 ** Execute as much of a VDBE program as we can then return.
45340 **
45341 ** sqlite3VdbeMakeReady() must be called before this routine in order to
45342 ** close the program with a final OP_Halt and to set up the callbacks
45343 ** and the error message pointer.
45344 **
45345 ** Whenever a row or result data is available, this routine will either
45346 ** invoke the result callback (if there is one) or return with
45347 ** SQLITE_ROW.
45348 **
45349 ** If an attempt is made to open a locked database, then this routine
45350 ** will either invoke the busy callback (if there is one) or it will
45351 ** return SQLITE_BUSY.
45352 **
45353 ** If an error occurs, an error message is written to memory obtained
45354 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
45355 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
45356 **
45357 ** If the callback ever returns non-zero, then the program exits
45358 ** immediately.  There will be no error message but the p->rc field is
45359 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
45360 **
45361 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
45362 ** routine to return SQLITE_ERROR.
45363 **
45364 ** Other fatal errors return SQLITE_ERROR.
45365 **
45366 ** After this routine has finished, sqlite3VdbeFinalize() should be
45367 ** used to clean up the mess that was left behind.
45368 */
45369 SQLITE_PRIVATE int sqlite3VdbeExec(
45370   Vdbe *p                    /* The VDBE */
45371 ){
45372   int pc;                    /* The program counter */
45373   Op *pOp;                   /* Current operation */
45374   int rc = SQLITE_OK;        /* Value to return */
45375   sqlite3 *db = p->db;       /* The database */
45376   u8 encoding = ENC(db);     /* The database encoding */
45377   Mem *pIn1, *pIn2, *pIn3;   /* Input operands */
45378   Mem *pOut;                 /* Output operand */
45379   u8 opProperty;
45380   int iCompare = 0;          /* Result of last OP_Compare operation */
45381   int *aPermute = 0;         /* Permuation of columns for OP_Compare */
45382 #ifdef VDBE_PROFILE
45383   u64 start;                 /* CPU clock count at start of opcode */
45384   int origPc;                /* Program counter at start of opcode */
45385 #endif
45386 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
45387   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
45388 #endif
45389
45390   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
45391   assert( db->magic==SQLITE_MAGIC_BUSY );
45392   sqlite3BtreeMutexArrayEnter(&p->aMutex);
45393   if( p->rc==SQLITE_NOMEM ){
45394     /* This happens if a malloc() inside a call to sqlite3_column_text() or
45395     ** sqlite3_column_text16() failed.  */
45396     goto no_mem;
45397   }
45398   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
45399   p->rc = SQLITE_OK;
45400   assert( p->explain==0 );
45401   p->pResultSet = 0;
45402   db->busyHandler.nBusy = 0;
45403   CHECK_FOR_INTERRUPT;
45404   sqlite3VdbeIOTraceSql(p);
45405 #ifdef SQLITE_DEBUG
45406   sqlite3BeginBenignMalloc();
45407   if( p->pc==0 
45408    && ((p->db->flags & SQLITE_VdbeListing) || fileExists(db, "vdbe_explain"))
45409   ){
45410     int i;
45411     printf("VDBE Program Listing:\n");
45412     sqlite3VdbePrintSql(p);
45413     for(i=0; i<p->nOp; i++){
45414       sqlite3VdbePrintOp(stdout, i, &p->aOp[i]);
45415     }
45416   }
45417   if( fileExists(db, "vdbe_trace") ){
45418     p->trace = stdout;
45419   }
45420   sqlite3EndBenignMalloc();
45421 #endif
45422   for(pc=p->pc; rc==SQLITE_OK; pc++){
45423     assert( pc>=0 && pc<p->nOp );
45424     if( db->mallocFailed ) goto no_mem;
45425 #ifdef VDBE_PROFILE
45426     origPc = pc;
45427     start = sqlite3Hwtime();
45428 #endif
45429     pOp = &p->aOp[pc];
45430
45431     /* Only allow tracing if SQLITE_DEBUG is defined.
45432     */
45433 #ifdef SQLITE_DEBUG
45434     if( p->trace ){
45435       if( pc==0 ){
45436         printf("VDBE Execution Trace:\n");
45437         sqlite3VdbePrintSql(p);
45438       }
45439       sqlite3VdbePrintOp(p->trace, pc, pOp);
45440     }
45441     if( p->trace==0 && pc==0 ){
45442       sqlite3BeginBenignMalloc();
45443       if( fileExists(db, "vdbe_sqltrace") ){
45444         sqlite3VdbePrintSql(p);
45445       }
45446       sqlite3EndBenignMalloc();
45447     }
45448 #endif
45449       
45450
45451     /* Check to see if we need to simulate an interrupt.  This only happens
45452     ** if we have a special test build.
45453     */
45454 #ifdef SQLITE_TEST
45455     if( sqlite3_interrupt_count>0 ){
45456       sqlite3_interrupt_count--;
45457       if( sqlite3_interrupt_count==0 ){
45458         sqlite3_interrupt(db);
45459       }
45460     }
45461 #endif
45462
45463 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
45464     /* Call the progress callback if it is configured and the required number
45465     ** of VDBE ops have been executed (either since this invocation of
45466     ** sqlite3VdbeExec() or since last time the progress callback was called).
45467     ** If the progress callback returns non-zero, exit the virtual machine with
45468     ** a return code SQLITE_ABORT.
45469     */
45470     if( db->xProgress ){
45471       if( db->nProgressOps==nProgressOps ){
45472         int prc;
45473         if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
45474         prc =db->xProgress(db->pProgressArg);
45475         if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
45476         if( prc!=0 ){
45477           rc = SQLITE_INTERRUPT;
45478           goto vdbe_error_halt;
45479         }
45480         nProgressOps = 0;
45481       }
45482       nProgressOps++;
45483     }
45484 #endif
45485
45486     /* Do common setup processing for any opcode that is marked
45487     ** with the "out2-prerelease" tag.  Such opcodes have a single
45488     ** output which is specified by the P2 parameter.  The P2 register
45489     ** is initialized to a NULL.
45490     */
45491     opProperty = opcodeProperty[pOp->opcode];
45492     if( (opProperty & OPFLG_OUT2_PRERELEASE)!=0 ){
45493       assert( pOp->p2>0 );
45494       assert( pOp->p2<=p->nMem );
45495       pOut = &p->aMem[pOp->p2];
45496       sqlite3VdbeMemReleaseExternal(pOut);
45497       pOut->flags = MEM_Null;
45498     }else
45499  
45500     /* Do common setup for opcodes marked with one of the following
45501     ** combinations of properties.
45502     **
45503     **           in1
45504     **           in1 in2
45505     **           in1 in2 out3
45506     **           in1 in3
45507     **
45508     ** Variables pIn1, pIn2, and pIn3 are made to point to appropriate
45509     ** registers for inputs.  Variable pOut points to the output register.
45510     */
45511     if( (opProperty & OPFLG_IN1)!=0 ){
45512       assert( pOp->p1>0 );
45513       assert( pOp->p1<=p->nMem );
45514       pIn1 = &p->aMem[pOp->p1];
45515       REGISTER_TRACE(pOp->p1, pIn1);
45516       if( (opProperty & OPFLG_IN2)!=0 ){
45517         assert( pOp->p2>0 );
45518         assert( pOp->p2<=p->nMem );
45519         pIn2 = &p->aMem[pOp->p2];
45520         REGISTER_TRACE(pOp->p2, pIn2);
45521         if( (opProperty & OPFLG_OUT3)!=0 ){
45522           assert( pOp->p3>0 );
45523           assert( pOp->p3<=p->nMem );
45524           pOut = &p->aMem[pOp->p3];
45525         }
45526       }else if( (opProperty & OPFLG_IN3)!=0 ){
45527         assert( pOp->p3>0 );
45528         assert( pOp->p3<=p->nMem );
45529         pIn3 = &p->aMem[pOp->p3];
45530         REGISTER_TRACE(pOp->p3, pIn3);
45531       }
45532     }else if( (opProperty & OPFLG_IN2)!=0 ){
45533       assert( pOp->p2>0 );
45534       assert( pOp->p2<=p->nMem );
45535       pIn2 = &p->aMem[pOp->p2];
45536       REGISTER_TRACE(pOp->p2, pIn2);
45537     }else if( (opProperty & OPFLG_IN3)!=0 ){
45538       assert( pOp->p3>0 );
45539       assert( pOp->p3<=p->nMem );
45540       pIn3 = &p->aMem[pOp->p3];
45541       REGISTER_TRACE(pOp->p3, pIn3);
45542     }
45543
45544     switch( pOp->opcode ){
45545
45546 /*****************************************************************************
45547 ** What follows is a massive switch statement where each case implements a
45548 ** separate instruction in the virtual machine.  If we follow the usual
45549 ** indentation conventions, each case should be indented by 6 spaces.  But
45550 ** that is a lot of wasted space on the left margin.  So the code within
45551 ** the switch statement will break with convention and be flush-left. Another
45552 ** big comment (similar to this one) will mark the point in the code where
45553 ** we transition back to normal indentation.
45554 **
45555 ** The formatting of each case is important.  The makefile for SQLite
45556 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
45557 ** file looking for lines that begin with "case OP_".  The opcodes.h files
45558 ** will be filled with #defines that give unique integer values to each
45559 ** opcode and the opcodes.c file is filled with an array of strings where
45560 ** each string is the symbolic name for the corresponding opcode.  If the
45561 ** case statement is followed by a comment of the form "/# same as ... #/"
45562 ** that comment is used to determine the particular value of the opcode.
45563 **
45564 ** Other keywords in the comment that follows each case are used to
45565 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
45566 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
45567 ** the mkopcodeh.awk script for additional information.
45568 **
45569 ** Documentation about VDBE opcodes is generated by scanning this file
45570 ** for lines of that contain "Opcode:".  That line and all subsequent
45571 ** comment lines are used in the generation of the opcode.html documentation
45572 ** file.
45573 **
45574 ** SUMMARY:
45575 **
45576 **     Formatting is important to scripts that scan this file.
45577 **     Do not deviate from the formatting style currently in use.
45578 **
45579 *****************************************************************************/
45580
45581 /* Opcode:  Goto * P2 * * *
45582 **
45583 ** An unconditional jump to address P2.
45584 ** The next instruction executed will be 
45585 ** the one at index P2 from the beginning of
45586 ** the program.
45587 */
45588 case OP_Goto: {             /* jump */
45589   CHECK_FOR_INTERRUPT;
45590   pc = pOp->p2 - 1;
45591   break;
45592 }
45593
45594 /* Opcode:  Gosub P1 P2 * * *
45595 **
45596 ** Write the current address onto register P1
45597 ** and then jump to address P2.
45598 */
45599 case OP_Gosub: {            /* jump */
45600   assert( pOp->p1>0 );
45601   assert( pOp->p1<=p->nMem );
45602   pIn1 = &p->aMem[pOp->p1];
45603   assert( (pIn1->flags & MEM_Dyn)==0 );
45604   pIn1->flags = MEM_Int;
45605   pIn1->u.i = pc;
45606   REGISTER_TRACE(pOp->p1, pIn1);
45607   pc = pOp->p2 - 1;
45608   break;
45609 }
45610
45611 /* Opcode:  Return P1 * * * *
45612 **
45613 ** Jump to the next instruction after the address in register P1.
45614 */
45615 case OP_Return: {           /* in1 */
45616   assert( pIn1->flags & MEM_Int );
45617   pc = pIn1->u.i;
45618   break;
45619 }
45620
45621 /* Opcode:  Yield P1 * * * *
45622 **
45623 ** Swap the program counter with the value in register P1.
45624 */
45625 case OP_Yield: {
45626   int pcDest;
45627   assert( pOp->p1>0 );
45628   assert( pOp->p1<=p->nMem );
45629   pIn1 = &p->aMem[pOp->p1];
45630   assert( (pIn1->flags & MEM_Dyn)==0 );
45631   pIn1->flags = MEM_Int;
45632   pcDest = pIn1->u.i;
45633   pIn1->u.i = pc;
45634   REGISTER_TRACE(pOp->p1, pIn1);
45635   pc = pcDest;
45636   break;
45637 }
45638
45639
45640 /* Opcode:  Halt P1 P2 * P4 *
45641 **
45642 ** Exit immediately.  All open cursors, Fifos, etc are closed
45643 ** automatically.
45644 **
45645 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
45646 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
45647 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
45648 ** whether or not to rollback the current transaction.  Do not rollback
45649 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
45650 ** then back out all changes that have occurred during this execution of the
45651 ** VDBE, but do not rollback the transaction. 
45652 **
45653 ** If P4 is not null then it is an error message string.
45654 **
45655 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
45656 ** every program.  So a jump past the last instruction of the program
45657 ** is the same as executing Halt.
45658 */
45659 case OP_Halt: {
45660   p->rc = pOp->p1;
45661   p->pc = pc;
45662   p->errorAction = pOp->p2;
45663   if( pOp->p4.z ){
45664     sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
45665   }
45666   rc = sqlite3VdbeHalt(p);
45667   assert( rc==SQLITE_BUSY || rc==SQLITE_OK );
45668   if( rc==SQLITE_BUSY ){
45669     p->rc = rc = SQLITE_BUSY;
45670   }else{
45671     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
45672   }
45673   goto vdbe_return;
45674 }
45675
45676 /* Opcode: Integer P1 P2 * * *
45677 **
45678 ** The 32-bit integer value P1 is written into register P2.
45679 */
45680 case OP_Integer: {         /* out2-prerelease */
45681   pOut->flags = MEM_Int;
45682   pOut->u.i = pOp->p1;
45683   break;
45684 }
45685
45686 /* Opcode: Int64 * P2 * P4 *
45687 **
45688 ** P4 is a pointer to a 64-bit integer value.
45689 ** Write that value into register P2.
45690 */
45691 case OP_Int64: {           /* out2-prerelease */
45692   assert( pOp->p4.pI64!=0 );
45693   pOut->flags = MEM_Int;
45694   pOut->u.i = *pOp->p4.pI64;
45695   break;
45696 }
45697
45698 /* Opcode: Real * P2 * P4 *
45699 **
45700 ** P4 is a pointer to a 64-bit floating point value.
45701 ** Write that value into register P2.
45702 */
45703 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
45704   pOut->flags = MEM_Real;
45705   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
45706   pOut->r = *pOp->p4.pReal;
45707   break;
45708 }
45709
45710 /* Opcode: String8 * P2 * P4 *
45711 **
45712 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
45713 ** into an OP_String before it is executed for the first time.
45714 */
45715 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
45716   assert( pOp->p4.z!=0 );
45717   pOp->opcode = OP_String;
45718   pOp->p1 = strlen(pOp->p4.z);
45719
45720 #ifndef SQLITE_OMIT_UTF16
45721   if( encoding!=SQLITE_UTF8 ){
45722     sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
45723     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
45724     if( SQLITE_OK!=sqlite3VdbeMemMakeWriteable(pOut) ) goto no_mem;
45725     pOut->zMalloc = 0;
45726     pOut->flags |= MEM_Static;
45727     pOut->flags &= ~MEM_Dyn;
45728     if( pOp->p4type==P4_DYNAMIC ){
45729       sqlite3DbFree(db, pOp->p4.z);
45730     }
45731     pOp->p4type = P4_DYNAMIC;
45732     pOp->p4.z = pOut->z;
45733     pOp->p1 = pOut->n;
45734     if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
45735       goto too_big;
45736     }
45737     UPDATE_MAX_BLOBSIZE(pOut);
45738     break;
45739   }
45740 #endif
45741   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
45742     goto too_big;
45743   }
45744   /* Fall through to the next case, OP_String */
45745 }
45746   
45747 /* Opcode: String P1 P2 * P4 *
45748 **
45749 ** The string value P4 of length P1 (bytes) is stored in register P2.
45750 */
45751 case OP_String: {          /* out2-prerelease */
45752   assert( pOp->p4.z!=0 );
45753   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
45754   pOut->z = pOp->p4.z;
45755   pOut->n = pOp->p1;
45756   pOut->enc = encoding;
45757   UPDATE_MAX_BLOBSIZE(pOut);
45758   break;
45759 }
45760
45761 /* Opcode: Null * P2 * * *
45762 **
45763 ** Write a NULL into register P2.
45764 */
45765 case OP_Null: {           /* out2-prerelease */
45766   break;
45767 }
45768
45769
45770 #ifndef SQLITE_OMIT_BLOB_LITERAL
45771 /* Opcode: Blob P1 P2 * P4
45772 **
45773 ** P4 points to a blob of data P1 bytes long.  Store this
45774 ** blob in register P2. This instruction is not coded directly
45775 ** by the compiler. Instead, the compiler layer specifies
45776 ** an OP_HexBlob opcode, with the hex string representation of
45777 ** the blob as P4. This opcode is transformed to an OP_Blob
45778 ** the first time it is executed.
45779 */
45780 case OP_Blob: {                /* out2-prerelease */
45781   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
45782   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
45783   pOut->enc = encoding;
45784   UPDATE_MAX_BLOBSIZE(pOut);
45785   break;
45786 }
45787 #endif /* SQLITE_OMIT_BLOB_LITERAL */
45788
45789 /* Opcode: Variable P1 P2 * * *
45790 **
45791 ** The value of variable P1 is written into register P2. A variable is
45792 ** an unknown in the original SQL string as handed to sqlite3_compile().
45793 ** Any occurrence of the '?' character in the original SQL is considered
45794 ** a variable.  Variables in the SQL string are number from left to
45795 ** right beginning with 1.  The values of variables are set using the
45796 ** sqlite3_bind() API.
45797 */
45798 case OP_Variable: {           /* out2-prerelease */
45799   int j = pOp->p1 - 1;
45800   Mem *pVar;
45801   assert( j>=0 && j<p->nVar );
45802
45803   pVar = &p->aVar[j];
45804   if( sqlite3VdbeMemTooBig(pVar) ){
45805     goto too_big;
45806   }
45807   sqlite3VdbeMemShallowCopy(pOut, &p->aVar[j], MEM_Static);
45808   UPDATE_MAX_BLOBSIZE(pOut);
45809   break;
45810 }
45811
45812 /* Opcode: Move P1 P2 P3 * *
45813 **
45814 ** Move the values in register P1..P1+P3-1 over into
45815 ** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
45816 ** left holding a NULL.  It is an error for register ranges
45817 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
45818 */
45819 case OP_Move: {
45820   char *zMalloc;
45821   int n = pOp->p3;
45822   int p1 = pOp->p1;
45823   int p2 = pOp->p2;
45824   assert( n>0 );
45825   assert( p1>0 );
45826   assert( p1+n<p->nMem );
45827   pIn1 = &p->aMem[p1];
45828   assert( p2>0 );
45829   assert( p2+n<p->nMem );
45830   pOut = &p->aMem[p2];
45831   assert( p1+n<=p2 || p2+n<=p1 );
45832   while( n-- ){
45833     zMalloc = pOut->zMalloc;
45834     pOut->zMalloc = 0;
45835     sqlite3VdbeMemMove(pOut, pIn1);
45836     pIn1->zMalloc = zMalloc;
45837     REGISTER_TRACE(p2++, pOut);
45838     pIn1++;
45839     pOut++;
45840   }
45841   break;
45842 }
45843
45844 /* Opcode: Copy P1 P2 * * *
45845 **
45846 ** Make a copy of register P1 into register P2.
45847 **
45848 ** This instruction makes a deep copy of the value.  A duplicate
45849 ** is made of any string or blob constant.  See also OP_SCopy.
45850 */
45851 case OP_Copy: {
45852   assert( pOp->p1>0 );
45853   assert( pOp->p1<=p->nMem );
45854   pIn1 = &p->aMem[pOp->p1];
45855   assert( pOp->p2>0 );
45856   assert( pOp->p2<=p->nMem );
45857   pOut = &p->aMem[pOp->p2];
45858   assert( pOut!=pIn1 );
45859   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
45860   Deephemeralize(pOut);
45861   REGISTER_TRACE(pOp->p2, pOut);
45862   break;
45863 }
45864
45865 /* Opcode: SCopy P1 P2 * * *
45866 **
45867 ** Make a shallow copy of register P1 into register P2.
45868 **
45869 ** This instruction makes a shallow copy of the value.  If the value
45870 ** is a string or blob, then the copy is only a pointer to the
45871 ** original and hence if the original changes so will the copy.
45872 ** Worse, if the original is deallocated, the copy becomes invalid.
45873 ** Thus the program must guarantee that the original will not change
45874 ** during the lifetime of the copy.  Use OP_Copy to make a complete
45875 ** copy.
45876 */
45877 case OP_SCopy: {
45878   assert( pOp->p1>0 );
45879   assert( pOp->p1<=p->nMem );
45880   pIn1 = &p->aMem[pOp->p1];
45881   REGISTER_TRACE(pOp->p1, pIn1);
45882   assert( pOp->p2>0 );
45883   assert( pOp->p2<=p->nMem );
45884   pOut = &p->aMem[pOp->p2];
45885   assert( pOut!=pIn1 );
45886   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
45887   REGISTER_TRACE(pOp->p2, pOut);
45888   break;
45889 }
45890
45891 /* Opcode: ResultRow P1 P2 * * *
45892 **
45893 ** The registers P1 through P1+P2-1 contain a single row of
45894 ** results. This opcode causes the sqlite3_step() call to terminate
45895 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
45896 ** structure to provide access to the top P1 values as the result
45897 ** row.
45898 */
45899 case OP_ResultRow: {
45900   Mem *pMem;
45901   int i;
45902   assert( p->nResColumn==pOp->p2 );
45903   assert( pOp->p1>0 );
45904   assert( pOp->p1+pOp->p2<=p->nMem );
45905
45906   /* Invalidate all ephemeral cursor row caches */
45907   p->cacheCtr = (p->cacheCtr + 2)|1;
45908
45909   /* Make sure the results of the current row are \000 terminated
45910   ** and have an assigned type.  The results are de-ephemeralized as
45911   ** as side effect.
45912   */
45913   pMem = p->pResultSet = &p->aMem[pOp->p1];
45914   for(i=0; i<pOp->p2; i++){
45915     sqlite3VdbeMemNulTerminate(&pMem[i]);
45916     storeTypeInfo(&pMem[i], encoding);
45917     REGISTER_TRACE(pOp->p1+i, &pMem[i]);
45918   }
45919   if( db->mallocFailed ) goto no_mem;
45920
45921   /* Return SQLITE_ROW
45922   */
45923   p->nCallback++;
45924   p->pc = pc + 1;
45925   rc = SQLITE_ROW;
45926   goto vdbe_return;
45927 }
45928
45929 /* Opcode: Concat P1 P2 P3 * *
45930 **
45931 ** Add the text in register P1 onto the end of the text in
45932 ** register P2 and store the result in register P3.
45933 ** If either the P1 or P2 text are NULL then store NULL in P3.
45934 **
45935 **   P3 = P2 || P1
45936 **
45937 ** It is illegal for P1 and P3 to be the same register. Sometimes,
45938 ** if P3 is the same register as P2, the implementation is able
45939 ** to avoid a memcpy().
45940 */
45941 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
45942   i64 nByte;
45943
45944   assert( pIn1!=pOut );
45945   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
45946     sqlite3VdbeMemSetNull(pOut);
45947     break;
45948   }
45949   ExpandBlob(pIn1);
45950   Stringify(pIn1, encoding);
45951   ExpandBlob(pIn2);
45952   Stringify(pIn2, encoding);
45953   nByte = pIn1->n + pIn2->n;
45954   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
45955     goto too_big;
45956   }
45957   MemSetTypeFlag(pOut, MEM_Str);
45958   if( sqlite3VdbeMemGrow(pOut, nByte+2, pOut==pIn2) ){
45959     goto no_mem;
45960   }
45961   if( pOut!=pIn2 ){
45962     memcpy(pOut->z, pIn2->z, pIn2->n);
45963   }
45964   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
45965   pOut->z[nByte] = 0;
45966   pOut->z[nByte+1] = 0;
45967   pOut->flags |= MEM_Term;
45968   pOut->n = nByte;
45969   pOut->enc = encoding;
45970   UPDATE_MAX_BLOBSIZE(pOut);
45971   break;
45972 }
45973
45974 /* Opcode: Add P1 P2 P3 * *
45975 **
45976 ** Add the value in register P1 to the value in register P2
45977 ** and store the result in register P3.
45978 ** If either input is NULL, the result is NULL.
45979 */
45980 /* Opcode: Multiply P1 P2 P3 * *
45981 **
45982 **
45983 ** Multiply the value in register P1 by the value in register P2
45984 ** and store the result in register P3.
45985 ** If either input is NULL, the result is NULL.
45986 */
45987 /* Opcode: Subtract P1 P2 P3 * *
45988 **
45989 ** Subtract the value in register P1 from the value in register P2
45990 ** and store the result in register P3.
45991 ** If either input is NULL, the result is NULL.
45992 */
45993 /* Opcode: Divide P1 P2 P3 * *
45994 **
45995 ** Divide the value in register P1 by the value in register P2
45996 ** and store the result in register P3.  If the value in register P2
45997 ** is zero, then the result is NULL.
45998 ** If either input is NULL, the result is NULL.
45999 */
46000 /* Opcode: Remainder P1 P2 P3 * *
46001 **
46002 ** Compute the remainder after integer division of the value in
46003 ** register P1 by the value in register P2 and store the result in P3. 
46004 ** If the value in register P2 is zero the result is NULL.
46005 ** If either operand is NULL, the result is NULL.
46006 */
46007 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
46008 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
46009 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
46010 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
46011 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
46012   int flags;
46013   applyNumericAffinity(pIn1);
46014   applyNumericAffinity(pIn2);
46015   flags = pIn1->flags | pIn2->flags;
46016   if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
46017   if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
46018     i64 a, b;
46019     a = pIn1->u.i;
46020     b = pIn2->u.i;
46021     switch( pOp->opcode ){
46022       case OP_Add:         b += a;       break;
46023       case OP_Subtract:    b -= a;       break;
46024       case OP_Multiply:    b *= a;       break;
46025       case OP_Divide: {
46026         if( a==0 ) goto arithmetic_result_is_null;
46027         /* Dividing the largest possible negative 64-bit integer (1<<63) by 
46028         ** -1 returns an integer too large to store in a 64-bit data-type. On
46029         ** some architectures, the value overflows to (1<<63). On others,
46030         ** a SIGFPE is issued. The following statement normalizes this
46031         ** behavior so that all architectures behave as if integer 
46032         ** overflow occurred.
46033         */
46034         if( a==-1 && b==SMALLEST_INT64 ) a = 1;
46035         b /= a;
46036         break;
46037       }
46038       default: {
46039         if( a==0 ) goto arithmetic_result_is_null;
46040         if( a==-1 ) a = 1;
46041         b %= a;
46042         break;
46043       }
46044     }
46045     pOut->u.i = b;
46046     MemSetTypeFlag(pOut, MEM_Int);
46047   }else{
46048     double a, b;
46049     a = sqlite3VdbeRealValue(pIn1);
46050     b = sqlite3VdbeRealValue(pIn2);
46051     switch( pOp->opcode ){
46052       case OP_Add:         b += a;       break;
46053       case OP_Subtract:    b -= a;       break;
46054       case OP_Multiply:    b *= a;       break;
46055       case OP_Divide: {
46056         if( a==0.0 ) goto arithmetic_result_is_null;
46057         b /= a;
46058         break;
46059       }
46060       default: {
46061         i64 ia = (i64)a;
46062         i64 ib = (i64)b;
46063         if( ia==0 ) goto arithmetic_result_is_null;
46064         if( ia==-1 ) ia = 1;
46065         b = ib % ia;
46066         break;
46067       }
46068     }
46069     if( sqlite3IsNaN(b) ){
46070       goto arithmetic_result_is_null;
46071     }
46072     pOut->r = b;
46073     MemSetTypeFlag(pOut, MEM_Real);
46074     if( (flags & MEM_Real)==0 ){
46075       sqlite3VdbeIntegerAffinity(pOut);
46076     }
46077   }
46078   break;
46079
46080 arithmetic_result_is_null:
46081   sqlite3VdbeMemSetNull(pOut);
46082   break;
46083 }
46084
46085 /* Opcode: CollSeq * * P4
46086 **
46087 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
46088 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
46089 ** be returned. This is used by the built-in min(), max() and nullif()
46090 ** functions.
46091 **
46092 ** The interface used by the implementation of the aforementioned functions
46093 ** to retrieve the collation sequence set by this opcode is not available
46094 ** publicly, only to user functions defined in func.c.
46095 */
46096 case OP_CollSeq: {
46097   assert( pOp->p4type==P4_COLLSEQ );
46098   break;
46099 }
46100
46101 /* Opcode: Function P1 P2 P3 P4 P5
46102 **
46103 ** Invoke a user function (P4 is a pointer to a Function structure that
46104 ** defines the function) with P5 arguments taken from register P2 and
46105 ** successors.  The result of the function is stored in register P3.
46106 ** Register P3 must not be one of the function inputs.
46107 **
46108 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
46109 ** function was determined to be constant at compile time. If the first
46110 ** argument was constant then bit 0 of P1 is set. This is used to determine
46111 ** whether meta data associated with a user function argument using the
46112 ** sqlite3_set_auxdata() API may be safely retained until the next
46113 ** invocation of this opcode.
46114 **
46115 ** See also: AggStep and AggFinal
46116 */
46117 case OP_Function: {
46118   int i;
46119   Mem *pArg;
46120   sqlite3_context ctx;
46121   sqlite3_value **apVal;
46122   int n = pOp->p5;
46123
46124   apVal = p->apArg;
46125   assert( apVal || n==0 );
46126
46127   assert( n==0 || (pOp->p2>0 && pOp->p2+n<=p->nMem) );
46128   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
46129   pArg = &p->aMem[pOp->p2];
46130   for(i=0; i<n; i++, pArg++){
46131     apVal[i] = pArg;
46132     storeTypeInfo(pArg, encoding);
46133     REGISTER_TRACE(pOp->p2, pArg);
46134   }
46135
46136   assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
46137   if( pOp->p4type==P4_FUNCDEF ){
46138     ctx.pFunc = pOp->p4.pFunc;
46139     ctx.pVdbeFunc = 0;
46140   }else{
46141     ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
46142     ctx.pFunc = ctx.pVdbeFunc->pFunc;
46143   }
46144
46145   assert( pOp->p3>0 && pOp->p3<=p->nMem );
46146   pOut = &p->aMem[pOp->p3];
46147   ctx.s.flags = MEM_Null;
46148   ctx.s.db = db;
46149   ctx.s.xDel = 0;
46150   ctx.s.zMalloc = 0;
46151
46152   /* The output cell may already have a buffer allocated. Move
46153   ** the pointer to ctx.s so in case the user-function can use
46154   ** the already allocated buffer instead of allocating a new one.
46155   */
46156   sqlite3VdbeMemMove(&ctx.s, pOut);
46157   MemSetTypeFlag(&ctx.s, MEM_Null);
46158
46159   ctx.isError = 0;
46160   if( ctx.pFunc->needCollSeq ){
46161     assert( pOp>p->aOp );
46162     assert( pOp[-1].p4type==P4_COLLSEQ );
46163     assert( pOp[-1].opcode==OP_CollSeq );
46164     ctx.pColl = pOp[-1].p4.pColl;
46165   }
46166   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
46167   (*ctx.pFunc->xFunc)(&ctx, n, apVal);
46168   if( sqlite3SafetyOn(db) ){
46169     sqlite3VdbeMemRelease(&ctx.s);
46170     goto abort_due_to_misuse;
46171   }
46172   if( db->mallocFailed ){
46173     /* Even though a malloc() has failed, the implementation of the
46174     ** user function may have called an sqlite3_result_XXX() function
46175     ** to return a value. The following call releases any resources
46176     ** associated with such a value.
46177     **
46178     ** Note: Maybe MemRelease() should be called if sqlite3SafetyOn()
46179     ** fails also (the if(...) statement above). But if people are
46180     ** misusing sqlite, they have bigger problems than a leaked value.
46181     */
46182     sqlite3VdbeMemRelease(&ctx.s);
46183     goto no_mem;
46184   }
46185
46186   /* If any auxiliary data functions have been called by this user function,
46187   ** immediately call the destructor for any non-static values.
46188   */
46189   if( ctx.pVdbeFunc ){
46190     sqlite3VdbeDeleteAuxData(ctx.pVdbeFunc, pOp->p1);
46191     pOp->p4.pVdbeFunc = ctx.pVdbeFunc;
46192     pOp->p4type = P4_VDBEFUNC;
46193   }
46194
46195   /* If the function returned an error, throw an exception */
46196   if( ctx.isError ){
46197     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s));
46198     rc = ctx.isError;
46199   }
46200
46201   /* Copy the result of the function into register P3 */
46202   sqlite3VdbeChangeEncoding(&ctx.s, encoding);
46203   sqlite3VdbeMemMove(pOut, &ctx.s);
46204   if( sqlite3VdbeMemTooBig(pOut) ){
46205     goto too_big;
46206   }
46207   REGISTER_TRACE(pOp->p3, pOut);
46208   UPDATE_MAX_BLOBSIZE(pOut);
46209   break;
46210 }
46211
46212 /* Opcode: BitAnd P1 P2 P3 * *
46213 **
46214 ** Take the bit-wise AND of the values in register P1 and P2 and
46215 ** store the result in register P3.
46216 ** If either input is NULL, the result is NULL.
46217 */
46218 /* Opcode: BitOr P1 P2 P3 * *
46219 **
46220 ** Take the bit-wise OR of the values in register P1 and P2 and
46221 ** store the result in register P3.
46222 ** If either input is NULL, the result is NULL.
46223 */
46224 /* Opcode: ShiftLeft P1 P2 P3 * *
46225 **
46226 ** Shift the integer value in register P2 to the left by the
46227 ** number of bits specified by the integer in regiser P1.
46228 ** Store the result in register P3.
46229 ** If either input is NULL, the result is NULL.
46230 */
46231 /* Opcode: ShiftRight P1 P2 P3 * *
46232 **
46233 ** Shift the integer value in register P2 to the right by the
46234 ** number of bits specified by the integer in register P1.
46235 ** Store the result in register P3.
46236 ** If either input is NULL, the result is NULL.
46237 */
46238 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
46239 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
46240 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
46241 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
46242   i64 a, b;
46243
46244   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
46245     sqlite3VdbeMemSetNull(pOut);
46246     break;
46247   }
46248   a = sqlite3VdbeIntValue(pIn2);
46249   b = sqlite3VdbeIntValue(pIn1);
46250   switch( pOp->opcode ){
46251     case OP_BitAnd:      a &= b;     break;
46252     case OP_BitOr:       a |= b;     break;
46253     case OP_ShiftLeft:   a <<= b;    break;
46254     default:  assert( pOp->opcode==OP_ShiftRight );
46255                          a >>= b;    break;
46256   }
46257   pOut->u.i = a;
46258   MemSetTypeFlag(pOut, MEM_Int);
46259   break;
46260 }
46261
46262 /* Opcode: AddImm  P1 P2 * * *
46263 ** 
46264 ** Add the constant P2 to the value in register P1.
46265 ** The result is always an integer.
46266 **
46267 ** To force any register to be an integer, just add 0.
46268 */
46269 case OP_AddImm: {            /* in1 */
46270   sqlite3VdbeMemIntegerify(pIn1);
46271   pIn1->u.i += pOp->p2;
46272   break;
46273 }
46274
46275 /* Opcode: ForceInt P1 P2 P3 * *
46276 **
46277 ** Convert value in register P1 into an integer.  If the value 
46278 ** in P1 is not numeric (meaning that is is a NULL or a string that
46279 ** does not look like an integer or floating point number) then
46280 ** jump to P2.  If the value in P1 is numeric then
46281 ** convert it into the least integer that is greater than or equal to its
46282 ** current value if P3==0, or to the least integer that is strictly
46283 ** greater than its current value if P3==1.
46284 */
46285 case OP_ForceInt: {            /* jump, in1 */
46286   i64 v;
46287   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
46288   if( (pIn1->flags & (MEM_Int|MEM_Real))==0 ){
46289     pc = pOp->p2 - 1;
46290     break;
46291   }
46292   if( pIn1->flags & MEM_Int ){
46293     v = pIn1->u.i + (pOp->p3!=0);
46294   }else{
46295     assert( pIn1->flags & MEM_Real );
46296     v = (sqlite3_int64)pIn1->r;
46297     if( pIn1->r>(double)v ) v++;
46298     if( pOp->p3 && pIn1->r==(double)v ) v++;
46299   }
46300   pIn1->u.i = v;
46301   MemSetTypeFlag(pIn1, MEM_Int);
46302   break;
46303 }
46304
46305 /* Opcode: MustBeInt P1 P2 * * *
46306 ** 
46307 ** Force the value in register P1 to be an integer.  If the value
46308 ** in P1 is not an integer and cannot be converted into an integer
46309 ** without data loss, then jump immediately to P2, or if P2==0
46310 ** raise an SQLITE_MISMATCH exception.
46311 */
46312 case OP_MustBeInt: {            /* jump, in1 */
46313   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
46314   if( (pIn1->flags & MEM_Int)==0 ){
46315     if( pOp->p2==0 ){
46316       rc = SQLITE_MISMATCH;
46317       goto abort_due_to_error;
46318     }else{
46319       pc = pOp->p2 - 1;
46320     }
46321   }else{
46322     MemSetTypeFlag(pIn1, MEM_Int);
46323   }
46324   break;
46325 }
46326
46327 /* Opcode: RealAffinity P1 * * * *
46328 **
46329 ** If register P1 holds an integer convert it to a real value.
46330 **
46331 ** This opcode is used when extracting information from a column that
46332 ** has REAL affinity.  Such column values may still be stored as
46333 ** integers, for space efficiency, but after extraction we want them
46334 ** to have only a real value.
46335 */
46336 case OP_RealAffinity: {                  /* in1 */
46337   if( pIn1->flags & MEM_Int ){
46338     sqlite3VdbeMemRealify(pIn1);
46339   }
46340   break;
46341 }
46342
46343 #ifndef SQLITE_OMIT_CAST
46344 /* Opcode: ToText P1 * * * *
46345 **
46346 ** Force the value in register P1 to be text.
46347 ** If the value is numeric, convert it to a string using the
46348 ** equivalent of printf().  Blob values are unchanged and
46349 ** are afterwards simply interpreted as text.
46350 **
46351 ** A NULL value is not changed by this routine.  It remains NULL.
46352 */
46353 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
46354   if( pIn1->flags & MEM_Null ) break;
46355   assert( MEM_Str==(MEM_Blob>>3) );
46356   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
46357   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
46358   rc = ExpandBlob(pIn1);
46359   assert( pIn1->flags & MEM_Str || db->mallocFailed );
46360   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob);
46361   UPDATE_MAX_BLOBSIZE(pIn1);
46362   break;
46363 }
46364
46365 /* Opcode: ToBlob P1 * * * *
46366 **
46367 ** Force the value in register P1 to be a BLOB.
46368 ** If the value is numeric, convert it to a string first.
46369 ** Strings are simply reinterpreted as blobs with no change
46370 ** to the underlying data.
46371 **
46372 ** A NULL value is not changed by this routine.  It remains NULL.
46373 */
46374 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
46375   if( pIn1->flags & MEM_Null ) break;
46376   if( (pIn1->flags & MEM_Blob)==0 ){
46377     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
46378     assert( pIn1->flags & MEM_Str || db->mallocFailed );
46379   }
46380   MemSetTypeFlag(pIn1, MEM_Blob);
46381   UPDATE_MAX_BLOBSIZE(pIn1);
46382   break;
46383 }
46384
46385 /* Opcode: ToNumeric P1 * * * *
46386 **
46387 ** Force the value in register P1 to be numeric (either an
46388 ** integer or a floating-point number.)
46389 ** If the value is text or blob, try to convert it to an using the
46390 ** equivalent of atoi() or atof() and store 0 if no such conversion 
46391 ** is possible.
46392 **
46393 ** A NULL value is not changed by this routine.  It remains NULL.
46394 */
46395 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
46396   if( (pIn1->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
46397     sqlite3VdbeMemNumerify(pIn1);
46398   }
46399   break;
46400 }
46401 #endif /* SQLITE_OMIT_CAST */
46402
46403 /* Opcode: ToInt P1 * * * *
46404 **
46405 ** Force the value in register P1 be an integer.  If
46406 ** The value is currently a real number, drop its fractional part.
46407 ** If the value is text or blob, try to convert it to an integer using the
46408 ** equivalent of atoi() and store 0 if no such conversion is possible.
46409 **
46410 ** A NULL value is not changed by this routine.  It remains NULL.
46411 */
46412 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
46413   if( (pIn1->flags & MEM_Null)==0 ){
46414     sqlite3VdbeMemIntegerify(pIn1);
46415   }
46416   break;
46417 }
46418
46419 #ifndef SQLITE_OMIT_CAST
46420 /* Opcode: ToReal P1 * * * *
46421 **
46422 ** Force the value in register P1 to be a floating point number.
46423 ** If The value is currently an integer, convert it.
46424 ** If the value is text or blob, try to convert it to an integer using the
46425 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
46426 **
46427 ** A NULL value is not changed by this routine.  It remains NULL.
46428 */
46429 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
46430   if( (pIn1->flags & MEM_Null)==0 ){
46431     sqlite3VdbeMemRealify(pIn1);
46432   }
46433   break;
46434 }
46435 #endif /* SQLITE_OMIT_CAST */
46436
46437 /* Opcode: Lt P1 P2 P3 P4 P5
46438 **
46439 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
46440 ** jump to address P2.  
46441 **
46442 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
46443 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL 
46444 ** bit is clear then fall thru if either operand is NULL.
46445 **
46446 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
46447 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
46448 ** to coerce both inputs according to this affinity before the
46449 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
46450 ** affinity is used. Note that the affinity conversions are stored
46451 ** back into the input registers P1 and P3.  So this opcode can cause
46452 ** persistent changes to registers P1 and P3.
46453 **
46454 ** Once any conversions have taken place, and neither value is NULL, 
46455 ** the values are compared. If both values are blobs then memcmp() is
46456 ** used to determine the results of the comparison.  If both values
46457 ** are text, then the appropriate collating function specified in
46458 ** P4 is  used to do the comparison.  If P4 is not specified then
46459 ** memcmp() is used to compare text string.  If both values are
46460 ** numeric, then a numeric comparison is used. If the two values
46461 ** are of different types, then numbers are considered less than
46462 ** strings and strings are considered less than blobs.
46463 **
46464 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
46465 ** store a boolean result (either 0, or 1, or NULL) in register P2.
46466 */
46467 /* Opcode: Ne P1 P2 P3 P4 P5
46468 **
46469 ** This works just like the Lt opcode except that the jump is taken if
46470 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
46471 ** additional information.
46472 */
46473 /* Opcode: Eq P1 P2 P3 P4 P5
46474 **
46475 ** This works just like the Lt opcode except that the jump is taken if
46476 ** the operands in registers P1 and P3 are equal.
46477 ** See the Lt opcode for additional information.
46478 */
46479 /* Opcode: Le P1 P2 P3 P4 P5
46480 **
46481 ** This works just like the Lt opcode except that the jump is taken if
46482 ** the content of register P3 is less than or equal to the content of
46483 ** register P1.  See the Lt opcode for additional information.
46484 */
46485 /* Opcode: Gt P1 P2 P3 P4 P5
46486 **
46487 ** This works just like the Lt opcode except that the jump is taken if
46488 ** the content of register P3 is greater than the content of
46489 ** register P1.  See the Lt opcode for additional information.
46490 */
46491 /* Opcode: Ge P1 P2 P3 P4 P5
46492 **
46493 ** This works just like the Lt opcode except that the jump is taken if
46494 ** the content of register P3 is greater than or equal to the content of
46495 ** register P1.  See the Lt opcode for additional information.
46496 */
46497 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
46498 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
46499 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
46500 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
46501 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
46502 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
46503   int flags;
46504   int res;
46505   char affinity;
46506
46507   flags = pIn1->flags|pIn3->flags;
46508
46509   if( flags&MEM_Null ){
46510     /* If either operand is NULL then the result is always NULL.
46511     ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
46512     */
46513     if( pOp->p5 & SQLITE_STOREP2 ){
46514       pOut = &p->aMem[pOp->p2];
46515       MemSetTypeFlag(pOut, MEM_Null);
46516       REGISTER_TRACE(pOp->p2, pOut);
46517     }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
46518       pc = pOp->p2-1;
46519     }
46520     break;
46521   }
46522
46523   affinity = pOp->p5 & SQLITE_AFF_MASK;
46524   if( affinity ){
46525     applyAffinity(pIn1, affinity, encoding);
46526     applyAffinity(pIn3, affinity, encoding);
46527   }
46528
46529   assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
46530   ExpandBlob(pIn1);
46531   ExpandBlob(pIn3);
46532   res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
46533   switch( pOp->opcode ){
46534     case OP_Eq:    res = res==0;     break;
46535     case OP_Ne:    res = res!=0;     break;
46536     case OP_Lt:    res = res<0;      break;
46537     case OP_Le:    res = res<=0;     break;
46538     case OP_Gt:    res = res>0;      break;
46539     default:       res = res>=0;     break;
46540   }
46541
46542   if( pOp->p5 & SQLITE_STOREP2 ){
46543     pOut = &p->aMem[pOp->p2];
46544     MemSetTypeFlag(pOut, MEM_Int);
46545     pOut->u.i = res;
46546     REGISTER_TRACE(pOp->p2, pOut);
46547   }else if( res ){
46548     pc = pOp->p2-1;
46549   }
46550   break;
46551 }
46552
46553 /* Opcode: Permutation * * * P4 *
46554 **
46555 ** Set the permuation used by the OP_Compare operator to be the array
46556 ** of integers in P4.
46557 **
46558 ** The permutation is only valid until the next OP_Permutation, OP_Compare,
46559 ** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
46560 ** immediately prior to the OP_Compare.
46561 */
46562 case OP_Permutation: {
46563   assert( pOp->p4type==P4_INTARRAY );
46564   assert( pOp->p4.ai );
46565   aPermute = pOp->p4.ai;
46566   break;
46567 }
46568
46569 /* Opcode: Compare P1 P2 P3 P4 *
46570 **
46571 ** Compare to vectors of registers in reg(P1)..reg(P1+P3-1) (all this
46572 ** one "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
46573 ** the comparison for use by the next OP_Jump instruct.
46574 **
46575 ** P4 is a KeyInfo structure that defines collating sequences and sort
46576 ** orders for the comparison.  The permutation applies to registers
46577 ** only.  The KeyInfo elements are used sequentially.
46578 **
46579 ** The comparison is a sort comparison, so NULLs compare equal,
46580 ** NULLs are less than numbers, numbers are less than strings,
46581 ** and strings are less than blobs.
46582 */
46583 case OP_Compare: {
46584   int n = pOp->p3;
46585   int i, p1, p2;
46586   const KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
46587   assert( n>0 );
46588   assert( pKeyInfo!=0 );
46589   p1 = pOp->p1;
46590   assert( p1>0 && p1+n-1<p->nMem );
46591   p2 = pOp->p2;
46592   assert( p2>0 && p2+n-1<p->nMem );
46593   for(i=0; i<n; i++){
46594     int idx = aPermute ? aPermute[i] : i;
46595     CollSeq *pColl;    /* Collating sequence to use on this term */
46596     int bRev;          /* True for DESCENDING sort order */
46597     REGISTER_TRACE(p1+idx, &p->aMem[p1+idx]);
46598     REGISTER_TRACE(p2+idx, &p->aMem[p2+idx]);
46599     assert( i<pKeyInfo->nField );
46600     pColl = pKeyInfo->aColl[i];
46601     bRev = pKeyInfo->aSortOrder[i];
46602     iCompare = sqlite3MemCompare(&p->aMem[p1+idx], &p->aMem[p2+idx], pColl);
46603     if( iCompare ){
46604       if( bRev ) iCompare = -iCompare;
46605       break;
46606     }
46607   }
46608   aPermute = 0;
46609   break;
46610 }
46611
46612 /* Opcode: Jump P1 P2 P3 * *
46613 **
46614 ** Jump to the instruction at address P1, P2, or P3 depending on whether
46615 ** in the most recent OP_Compare instruction the P1 vector was less than
46616 ** equal to, or greater than the P2 vector, respectively.
46617 */
46618 case OP_Jump: {             /* jump */
46619   if( iCompare<0 ){
46620     pc = pOp->p1 - 1;
46621   }else if( iCompare==0 ){
46622     pc = pOp->p2 - 1;
46623   }else{
46624     pc = pOp->p3 - 1;
46625   }
46626   break;
46627 }
46628
46629 /* Opcode: And P1 P2 P3 * *
46630 **
46631 ** Take the logical AND of the values in registers P1 and P2 and
46632 ** write the result into register P3.
46633 **
46634 ** If either P1 or P2 is 0 (false) then the result is 0 even if
46635 ** the other input is NULL.  A NULL and true or two NULLs give
46636 ** a NULL output.
46637 */
46638 /* Opcode: Or P1 P2 P3 * *
46639 **
46640 ** Take the logical OR of the values in register P1 and P2 and
46641 ** store the answer in register P3.
46642 **
46643 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
46644 ** even if the other input is NULL.  A NULL and false or two NULLs
46645 ** give a NULL output.
46646 */
46647 case OP_And:              /* same as TK_AND, in1, in2, out3 */
46648 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
46649   int v1, v2;    /* 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
46650
46651   if( pIn1->flags & MEM_Null ){
46652     v1 = 2;
46653   }else{
46654     v1 = sqlite3VdbeIntValue(pIn1)!=0;
46655   }
46656   if( pIn2->flags & MEM_Null ){
46657     v2 = 2;
46658   }else{
46659     v2 = sqlite3VdbeIntValue(pIn2)!=0;
46660   }
46661   if( pOp->opcode==OP_And ){
46662     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
46663     v1 = and_logic[v1*3+v2];
46664   }else{
46665     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
46666     v1 = or_logic[v1*3+v2];
46667   }
46668   if( v1==2 ){
46669     MemSetTypeFlag(pOut, MEM_Null);
46670   }else{
46671     pOut->u.i = v1;
46672     MemSetTypeFlag(pOut, MEM_Int);
46673   }
46674   break;
46675 }
46676
46677 /* Opcode: Not P1 * * * *
46678 **
46679 ** Interpret the value in register P1 as a boolean value.  Replace it
46680 ** with its complement.  If the value in register P1 is NULL its value
46681 ** is unchanged.
46682 */
46683 case OP_Not: {                /* same as TK_NOT, in1 */
46684   if( pIn1->flags & MEM_Null ) break;  /* Do nothing to NULLs */
46685   sqlite3VdbeMemIntegerify(pIn1);
46686   pIn1->u.i = !pIn1->u.i;
46687   assert( pIn1->flags&MEM_Int );
46688   break;
46689 }
46690
46691 /* Opcode: BitNot P1 * * * *
46692 **
46693 ** Interpret the content of register P1 as an integer.  Replace it
46694 ** with its ones-complement.  If the value is originally NULL, leave
46695 ** it unchanged.
46696 */
46697 case OP_BitNot: {             /* same as TK_BITNOT, in1 */
46698   if( pIn1->flags & MEM_Null ) break;  /* Do nothing to NULLs */
46699   sqlite3VdbeMemIntegerify(pIn1);
46700   pIn1->u.i = ~pIn1->u.i;
46701   assert( pIn1->flags&MEM_Int );
46702   break;
46703 }
46704
46705 /* Opcode: If P1 P2 P3 * *
46706 **
46707 ** Jump to P2 if the value in register P1 is true.  The value is
46708 ** is considered true if it is numeric and non-zero.  If the value
46709 ** in P1 is NULL then take the jump if P3 is true.
46710 */
46711 /* Opcode: IfNot P1 P2 P3 * *
46712 **
46713 ** Jump to P2 if the value in register P1 is False.  The value is
46714 ** is considered true if it has a numeric value of zero.  If the value
46715 ** in P1 is NULL then take the jump if P3 is true.
46716 */
46717 case OP_If:                 /* jump, in1 */
46718 case OP_IfNot: {            /* jump, in1 */
46719   int c;
46720   if( pIn1->flags & MEM_Null ){
46721     c = pOp->p3;
46722   }else{
46723 #ifdef SQLITE_OMIT_FLOATING_POINT
46724     c = sqlite3VdbeIntValue(pIn1);
46725 #else
46726     c = sqlite3VdbeRealValue(pIn1)!=0.0;
46727 #endif
46728     if( pOp->opcode==OP_IfNot ) c = !c;
46729   }
46730   if( c ){
46731     pc = pOp->p2-1;
46732   }
46733   break;
46734 }
46735
46736 /* Opcode: IsNull P1 P2 P3 * *
46737 **
46738 ** Jump to P2 if the value in register P1 is NULL.  If P3 is greater
46739 ** than zero, then check all values reg(P1), reg(P1+1), 
46740 ** reg(P1+2), ..., reg(P1+P3-1).
46741 */
46742 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
46743   int n = pOp->p3;
46744   assert( pOp->p3==0 || pOp->p1>0 );
46745   do{
46746     if( (pIn1->flags & MEM_Null)!=0 ){
46747       pc = pOp->p2 - 1;
46748       break;
46749     }
46750     pIn1++;
46751   }while( --n > 0 );
46752   break;
46753 }
46754
46755 /* Opcode: NotNull P1 P2 * * *
46756 **
46757 ** Jump to P2 if the value in register P1 is not NULL.  
46758 */
46759 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
46760   if( (pIn1->flags & MEM_Null)==0 ){
46761     pc = pOp->p2 - 1;
46762   }
46763   break;
46764 }
46765
46766 /* Opcode: SetNumColumns * P2 * * *
46767 **
46768 ** This opcode sets the number of columns for the cursor opened by the
46769 ** following instruction to P2.
46770 **
46771 ** An OP_SetNumColumns is only useful if it occurs immediately before 
46772 ** one of the following opcodes:
46773 **
46774 **     OpenRead
46775 **     OpenWrite
46776 **     OpenPseudo
46777 **
46778 ** If the OP_Column opcode is to be executed on a cursor, then
46779 ** this opcode must be present immediately before the opcode that
46780 ** opens the cursor.
46781 */
46782 case OP_SetNumColumns: {
46783   break;
46784 }
46785
46786 /* Opcode: Column P1 P2 P3 P4 *
46787 **
46788 ** Interpret the data that cursor P1 points to as a structure built using
46789 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
46790 ** information about the format of the data.)  Extract the P2-th column
46791 ** from this record.  If there are less that (P2+1) 
46792 ** values in the record, extract a NULL.
46793 **
46794 ** The value extracted is stored in register P3.
46795 **
46796 ** If the KeyAsData opcode has previously executed on this cursor, then the
46797 ** field might be extracted from the key rather than the data.
46798 **
46799 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
46800 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
46801 ** the result.
46802 */
46803 case OP_Column: {
46804   u32 payloadSize;   /* Number of bytes in the record */
46805   int p1 = pOp->p1;  /* P1 value of the opcode */
46806   int p2 = pOp->p2;  /* column number to retrieve */
46807   Cursor *pC = 0;    /* The VDBE cursor */
46808   char *zRec;        /* Pointer to complete record-data */
46809   BtCursor *pCrsr;   /* The BTree cursor */
46810   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
46811   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
46812   u32 nField;        /* number of fields in the record */
46813   int len;           /* The length of the serialized data for the column */
46814   int i;             /* Loop counter */
46815   char *zData;       /* Part of the record being decoded */
46816   Mem *pDest;        /* Where to write the extracted value */
46817   Mem sMem;          /* For storing the record being decoded */
46818
46819   sMem.flags = 0;
46820   sMem.db = 0;
46821   sMem.zMalloc = 0;
46822   assert( p1<p->nCursor );
46823   assert( pOp->p3>0 && pOp->p3<=p->nMem );
46824   pDest = &p->aMem[pOp->p3];
46825   MemSetTypeFlag(pDest, MEM_Null);
46826
46827   /* This block sets the variable payloadSize to be the total number of
46828   ** bytes in the record.
46829   **
46830   ** zRec is set to be the complete text of the record if it is available.
46831   ** The complete record text is always available for pseudo-tables
46832   ** If the record is stored in a cursor, the complete record text
46833   ** might be available in the  pC->aRow cache.  Or it might not be.
46834   ** If the data is unavailable,  zRec is set to NULL.
46835   **
46836   ** We also compute the number of columns in the record.  For cursors,
46837   ** the number of columns is stored in the Cursor.nField element.
46838   */
46839   pC = p->apCsr[p1];
46840   assert( pC!=0 );
46841 #ifndef SQLITE_OMIT_VIRTUALTABLE
46842   assert( pC->pVtabCursor==0 );
46843 #endif
46844   if( pC->pCursor!=0 ){
46845     /* The record is stored in a B-Tree */
46846     rc = sqlite3VdbeCursorMoveto(pC);
46847     if( rc ) goto abort_due_to_error;
46848     zRec = 0;
46849     pCrsr = pC->pCursor;
46850     if( pC->nullRow ){
46851       payloadSize = 0;
46852     }else if( pC->cacheStatus==p->cacheCtr ){
46853       payloadSize = pC->payloadSize;
46854       zRec = (char*)pC->aRow;
46855     }else if( pC->isIndex ){
46856       i64 payloadSize64;
46857       sqlite3BtreeKeySize(pCrsr, &payloadSize64);
46858       payloadSize = payloadSize64;
46859     }else{
46860       sqlite3BtreeDataSize(pCrsr, &payloadSize);
46861     }
46862     nField = pC->nField;
46863   }else{
46864     assert( pC->pseudoTable );
46865     /* The record is the sole entry of a pseudo-table */
46866     payloadSize = pC->nData;
46867     zRec = pC->pData;
46868     pC->cacheStatus = CACHE_STALE;
46869     assert( payloadSize==0 || zRec!=0 );
46870     nField = pC->nField;
46871     pCrsr = 0;
46872   }
46873
46874   /* If payloadSize is 0, then just store a NULL */
46875   if( payloadSize==0 ){
46876     assert( pDest->flags&MEM_Null );
46877     goto op_column_out;
46878   }
46879   if( payloadSize>db->aLimit[SQLITE_LIMIT_LENGTH] ){
46880     goto too_big;
46881   }
46882
46883   assert( p2<nField );
46884
46885   /* Read and parse the table header.  Store the results of the parse
46886   ** into the record header cache fields of the cursor.
46887   */
46888   aType = pC->aType;
46889   if( pC->cacheStatus==p->cacheCtr ){
46890     aOffset = pC->aOffset;
46891   }else{
46892     u8 *zIdx;        /* Index into header */
46893     u8 *zEndHdr;     /* Pointer to first byte after the header */
46894     u32 offset;      /* Offset into the data */
46895     int szHdrSz;     /* Size of the header size field at start of record */
46896     int avail;       /* Number of bytes of available data */
46897
46898     assert(aType);
46899     pC->aOffset = aOffset = &aType[nField];
46900     pC->payloadSize = payloadSize;
46901     pC->cacheStatus = p->cacheCtr;
46902
46903     /* Figure out how many bytes are in the header */
46904     if( zRec ){
46905       zData = zRec;
46906     }else{
46907       if( pC->isIndex ){
46908         zData = (char*)sqlite3BtreeKeyFetch(pCrsr, &avail);
46909       }else{
46910         zData = (char*)sqlite3BtreeDataFetch(pCrsr, &avail);
46911       }
46912       /* If KeyFetch()/DataFetch() managed to get the entire payload,
46913       ** save the payload in the pC->aRow cache.  That will save us from
46914       ** having to make additional calls to fetch the content portion of
46915       ** the record.
46916       */
46917       if( avail>=payloadSize ){
46918         zRec = zData;
46919         pC->aRow = (u8*)zData;
46920       }else{
46921         pC->aRow = 0;
46922       }
46923     }
46924     /* The following assert is true in all cases accept when
46925     ** the database file has been corrupted externally.
46926     **    assert( zRec!=0 || avail>=payloadSize || avail>=9 ); */
46927     szHdrSz = getVarint32((u8*)zData, offset);
46928
46929     /* The KeyFetch() or DataFetch() above are fast and will get the entire
46930     ** record header in most cases.  But they will fail to get the complete
46931     ** record header if the record header does not fit on a single page
46932     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
46933     ** acquire the complete header text.
46934     */
46935     if( !zRec && avail<offset ){
46936       sMem.flags = 0;
46937       sMem.db = 0;
46938       rc = sqlite3VdbeMemFromBtree(pCrsr, 0, offset, pC->isIndex, &sMem);
46939       if( rc!=SQLITE_OK ){
46940         goto op_column_out;
46941       }
46942       zData = sMem.z;
46943     }
46944     zEndHdr = (u8 *)&zData[offset];
46945     zIdx = (u8 *)&zData[szHdrSz];
46946
46947     /* Scan the header and use it to fill in the aType[] and aOffset[]
46948     ** arrays.  aType[i] will contain the type integer for the i-th
46949     ** column and aOffset[i] will contain the offset from the beginning
46950     ** of the record to the start of the data for the i-th column
46951     */
46952     for(i=0; i<nField; i++){
46953       if( zIdx<zEndHdr ){
46954         aOffset[i] = offset;
46955         zIdx += getVarint32(zIdx, aType[i]);
46956         offset += sqlite3VdbeSerialTypeLen(aType[i]);
46957       }else{
46958         /* If i is less that nField, then there are less fields in this
46959         ** record than SetNumColumns indicated there are columns in the
46960         ** table. Set the offset for any extra columns not present in
46961         ** the record to 0. This tells code below to store a NULL
46962         ** instead of deserializing a value from the record.
46963         */
46964         aOffset[i] = 0;
46965       }
46966     }
46967     sqlite3VdbeMemRelease(&sMem);
46968     sMem.flags = MEM_Null;
46969
46970     /* If we have read more header data than was contained in the header,
46971     ** or if the end of the last field appears to be past the end of the
46972     ** record, or if the end of the last field appears to be before the end
46973     ** of the record (when all fields present), then we must be dealing 
46974     ** with a corrupt database.
46975     */
46976     if( zIdx>zEndHdr || offset>payloadSize || (zIdx==zEndHdr && offset!=payloadSize) ){
46977       rc = SQLITE_CORRUPT_BKPT;
46978       goto op_column_out;
46979     }
46980   }
46981
46982   /* Get the column information. If aOffset[p2] is non-zero, then 
46983   ** deserialize the value from the record. If aOffset[p2] is zero,
46984   ** then there are not enough fields in the record to satisfy the
46985   ** request.  In this case, set the value NULL or to P4 if P4 is
46986   ** a pointer to a Mem object.
46987   */
46988   if( aOffset[p2] ){
46989     assert( rc==SQLITE_OK );
46990     if( zRec ){
46991       sqlite3VdbeMemReleaseExternal(pDest);
46992       sqlite3VdbeSerialGet((u8 *)&zRec[aOffset[p2]], aType[p2], pDest);
46993     }else{
46994       len = sqlite3VdbeSerialTypeLen(aType[p2]);
46995       sqlite3VdbeMemMove(&sMem, pDest);
46996       rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, pC->isIndex, &sMem);
46997       if( rc!=SQLITE_OK ){
46998         goto op_column_out;
46999       }
47000       zData = sMem.z;
47001       sqlite3VdbeSerialGet((u8*)zData, aType[p2], pDest);
47002     }
47003     pDest->enc = encoding;
47004   }else{
47005     if( pOp->p4type==P4_MEM ){
47006       sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
47007     }else{
47008       assert( pDest->flags&MEM_Null );
47009     }
47010   }
47011
47012   /* If we dynamically allocated space to hold the data (in the
47013   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
47014   ** dynamically allocated space over to the pDest structure.
47015   ** This prevents a memory copy.
47016   */
47017   if( sMem.zMalloc ){
47018     assert( sMem.z==sMem.zMalloc );
47019     assert( !(pDest->flags & MEM_Dyn) );
47020     assert( !(pDest->flags & (MEM_Blob|MEM_Str)) || pDest->z==sMem.z );
47021     pDest->flags &= ~(MEM_Ephem|MEM_Static);
47022     pDest->flags |= MEM_Term;
47023     pDest->z = sMem.z;
47024     pDest->zMalloc = sMem.zMalloc;
47025   }
47026
47027   rc = sqlite3VdbeMemMakeWriteable(pDest);
47028
47029 op_column_out:
47030   UPDATE_MAX_BLOBSIZE(pDest);
47031   REGISTER_TRACE(pOp->p3, pDest);
47032   break;
47033 }
47034
47035 /* Opcode: Affinity P1 P2 * P4 *
47036 **
47037 ** Apply affinities to a range of P2 registers starting with P1.
47038 **
47039 ** P4 is a string that is P2 characters long. The nth character of the
47040 ** string indicates the column affinity that should be used for the nth
47041 ** memory cell in the range.
47042 */
47043 case OP_Affinity: {
47044   char *zAffinity = pOp->p4.z;
47045   Mem *pData0 = &p->aMem[pOp->p1];
47046   Mem *pLast = &pData0[pOp->p2-1];
47047   Mem *pRec;
47048
47049   for(pRec=pData0; pRec<=pLast; pRec++){
47050     ExpandBlob(pRec);
47051     applyAffinity(pRec, zAffinity[pRec-pData0], encoding);
47052   }
47053   break;
47054 }
47055
47056 /* Opcode: MakeRecord P1 P2 P3 P4 *
47057 **
47058 ** Convert P2 registers beginning with P1 into a single entry
47059 ** suitable for use as a data record in a database table or as a key
47060 ** in an index.  The details of the format are irrelevant as long as
47061 ** the OP_Column opcode can decode the record later.
47062 ** Refer to source code comments for the details of the record
47063 ** format.
47064 **
47065 ** P4 may be a string that is P2 characters long.  The nth character of the
47066 ** string indicates the column affinity that should be used for the nth
47067 ** field of the index key.
47068 **
47069 ** The mapping from character to affinity is given by the SQLITE_AFF_
47070 ** macros defined in sqliteInt.h.
47071 **
47072 ** If P4 is NULL then all index fields have the affinity NONE.
47073 */
47074 case OP_MakeRecord: {
47075   /* Assuming the record contains N fields, the record format looks
47076   ** like this:
47077   **
47078   ** ------------------------------------------------------------------------
47079   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 | 
47080   ** ------------------------------------------------------------------------
47081   **
47082   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
47083   ** and so froth.
47084   **
47085   ** Each type field is a varint representing the serial type of the 
47086   ** corresponding data element (see sqlite3VdbeSerialType()). The
47087   ** hdr-size field is also a varint which is the offset from the beginning
47088   ** of the record to data0.
47089   */
47090   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
47091   Mem *pRec;             /* The new record */
47092   u64 nData = 0;         /* Number of bytes of data space */
47093   int nHdr = 0;          /* Number of bytes of header space */
47094   u64 nByte = 0;         /* Data space required for this record */
47095   int nZero = 0;         /* Number of zero bytes at the end of the record */
47096   int nVarint;           /* Number of bytes in a varint */
47097   u32 serial_type;       /* Type field */
47098   Mem *pData0;           /* First field to be combined into the record */
47099   Mem *pLast;            /* Last field of the record */
47100   int nField;            /* Number of fields in the record */
47101   char *zAffinity;       /* The affinity string for the record */
47102   int file_format;       /* File format to use for encoding */
47103   int i;                 /* Space used in zNewRecord[] */
47104
47105   nField = pOp->p1;
47106   zAffinity = pOp->p4.z;
47107   assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=p->nMem );
47108   pData0 = &p->aMem[nField];
47109   nField = pOp->p2;
47110   pLast = &pData0[nField-1];
47111   file_format = p->minWriteFileFormat;
47112
47113   /* Loop through the elements that will make up the record to figure
47114   ** out how much space is required for the new record.
47115   */
47116   for(pRec=pData0; pRec<=pLast; pRec++){
47117     int len;
47118     if( zAffinity ){
47119       applyAffinity(pRec, zAffinity[pRec-pData0], encoding);
47120     }
47121     if( pRec->flags&MEM_Zero && pRec->n>0 ){
47122       sqlite3VdbeMemExpandBlob(pRec);
47123     }
47124     serial_type = sqlite3VdbeSerialType(pRec, file_format);
47125     len = sqlite3VdbeSerialTypeLen(serial_type);
47126     nData += len;
47127     nHdr += sqlite3VarintLen(serial_type);
47128     if( pRec->flags & MEM_Zero ){
47129       /* Only pure zero-filled BLOBs can be input to this Opcode.
47130       ** We do not allow blobs with a prefix and a zero-filled tail. */
47131       nZero += pRec->u.i;
47132     }else if( len ){
47133       nZero = 0;
47134     }
47135   }
47136
47137   /* Add the initial header varint and total the size */
47138   nHdr += nVarint = sqlite3VarintLen(nHdr);
47139   if( nVarint<sqlite3VarintLen(nHdr) ){
47140     nHdr++;
47141   }
47142   nByte = nHdr+nData-nZero;
47143   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
47144     goto too_big;
47145   }
47146
47147   /* Make sure the output register has a buffer large enough to store 
47148   ** the new record. The output register (pOp->p3) is not allowed to
47149   ** be one of the input registers (because the following call to
47150   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
47151   */
47152   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
47153   pOut = &p->aMem[pOp->p3];
47154   if( sqlite3VdbeMemGrow(pOut, nByte, 0) ){
47155     goto no_mem;
47156   }
47157   zNewRecord = (u8 *)pOut->z;
47158
47159   /* Write the record */
47160   i = putVarint32(zNewRecord, nHdr);
47161   for(pRec=pData0; pRec<=pLast; pRec++){
47162     serial_type = sqlite3VdbeSerialType(pRec, file_format);
47163     i += putVarint32(&zNewRecord[i], serial_type);      /* serial type */
47164   }
47165   for(pRec=pData0; pRec<=pLast; pRec++){  /* serial data */
47166     i += sqlite3VdbeSerialPut(&zNewRecord[i], nByte-i, pRec, file_format);
47167   }
47168   assert( i==nByte );
47169
47170   assert( pOp->p3>0 && pOp->p3<=p->nMem );
47171   pOut->n = nByte;
47172   pOut->flags = MEM_Blob | MEM_Dyn;
47173   pOut->xDel = 0;
47174   if( nZero ){
47175     pOut->u.i = nZero;
47176     pOut->flags |= MEM_Zero;
47177   }
47178   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
47179   REGISTER_TRACE(pOp->p3, pOut);
47180   UPDATE_MAX_BLOBSIZE(pOut);
47181   break;
47182 }
47183
47184 /* Opcode: Statement P1 * * * *
47185 **
47186 ** Begin an individual statement transaction which is part of a larger
47187 ** transaction.  This is needed so that the statement
47188 ** can be rolled back after an error without having to roll back the
47189 ** entire transaction.  The statement transaction will automatically
47190 ** commit when the VDBE halts.
47191 **
47192 ** If the database connection is currently in autocommit mode (that 
47193 ** is to say, if it is in between BEGIN and COMMIT)
47194 ** and if there are no other active statements on the same database
47195 ** connection, then this operation is a no-op.  No statement transaction
47196 ** is needed since any error can use the normal ROLLBACK process to
47197 ** undo changes.
47198 **
47199 ** If a statement transaction is started, then a statement journal file
47200 ** will be allocated and initialized.
47201 **
47202 ** The statement is begun on the database file with index P1.  The main
47203 ** database file has an index of 0 and the file used for temporary tables
47204 ** has an index of 1.
47205 */
47206 case OP_Statement: {
47207   if( db->autoCommit==0 || db->activeVdbeCnt>1 ){
47208     int i = pOp->p1;
47209     Btree *pBt;
47210     assert( i>=0 && i<db->nDb );
47211     assert( db->aDb[i].pBt!=0 );
47212     pBt = db->aDb[i].pBt;
47213     assert( sqlite3BtreeIsInTrans(pBt) );
47214     assert( (p->btreeMask & (1<<i))!=0 );
47215     if( !sqlite3BtreeIsInStmt(pBt) ){
47216       rc = sqlite3BtreeBeginStmt(pBt);
47217       p->openedStatement = 1;
47218     }
47219   }
47220   break;
47221 }
47222
47223 /* Opcode: AutoCommit P1 P2 * * *
47224 **
47225 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
47226 ** back any currently active btree transactions. If there are any active
47227 ** VMs (apart from this one), then the COMMIT or ROLLBACK statement fails.
47228 **
47229 ** This instruction causes the VM to halt.
47230 */
47231 case OP_AutoCommit: {
47232   u8 i = pOp->p1;
47233   u8 rollback = pOp->p2;
47234
47235   assert( i==1 || i==0 );
47236   assert( i==1 || rollback==0 );
47237
47238   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
47239
47240   if( db->activeVdbeCnt>1 && i && !db->autoCommit ){
47241     /* If this instruction implements a COMMIT or ROLLBACK, other VMs are
47242     ** still running, and a transaction is active, return an error indicating
47243     ** that the other VMs must complete first. 
47244     */
47245     sqlite3SetString(&p->zErrMsg, db, "cannot %s transaction - "
47246         "SQL statements in progress",
47247         rollback ? "rollback" : "commit");
47248     rc = SQLITE_ERROR;
47249   }else if( i!=db->autoCommit ){
47250     if( pOp->p2 ){
47251       assert( i==1 );
47252       sqlite3RollbackAll(db);
47253       db->autoCommit = 1;
47254     }else{
47255       db->autoCommit = i;
47256       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
47257         p->pc = pc;
47258         db->autoCommit = 1-i;
47259         p->rc = rc = SQLITE_BUSY;
47260         goto vdbe_return;
47261       }
47262     }
47263     if( p->rc==SQLITE_OK ){
47264       rc = SQLITE_DONE;
47265     }else{
47266       rc = SQLITE_ERROR;
47267     }
47268     goto vdbe_return;
47269   }else{
47270     sqlite3SetString(&p->zErrMsg, db,
47271         (!i)?"cannot start a transaction within a transaction":(
47272         (rollback)?"cannot rollback - no transaction is active":
47273                    "cannot commit - no transaction is active"));
47274          
47275     rc = SQLITE_ERROR;
47276   }
47277   break;
47278 }
47279
47280 /* Opcode: Transaction P1 P2 * * *
47281 **
47282 ** Begin a transaction.  The transaction ends when a Commit or Rollback
47283 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
47284 ** transaction might also be rolled back if an error is encountered.
47285 **
47286 ** P1 is the index of the database file on which the transaction is
47287 ** started.  Index 0 is the main database file and index 1 is the
47288 ** file used for temporary tables.  Indices of 2 or more are used for
47289 ** attached databases.
47290 **
47291 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
47292 ** obtained on the database file when a write-transaction is started.  No
47293 ** other process can start another write transaction while this transaction is
47294 ** underway.  Starting a write transaction also creates a rollback journal. A
47295 ** write transaction must be started before any changes can be made to the
47296 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
47297 ** on the file.
47298 **
47299 ** If P2 is zero, then a read-lock is obtained on the database file.
47300 */
47301 case OP_Transaction: {
47302   int i = pOp->p1;
47303   Btree *pBt;
47304
47305   assert( i>=0 && i<db->nDb );
47306   assert( (p->btreeMask & (1<<i))!=0 );
47307   pBt = db->aDb[i].pBt;
47308
47309   if( pBt ){
47310     rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
47311     if( rc==SQLITE_BUSY ){
47312       p->pc = pc;
47313       p->rc = rc = SQLITE_BUSY;
47314       goto vdbe_return;
47315     }
47316     if( rc!=SQLITE_OK && rc!=SQLITE_READONLY /* && rc!=SQLITE_BUSY */ ){
47317       goto abort_due_to_error;
47318     }
47319   }
47320   break;
47321 }
47322
47323 /* Opcode: ReadCookie P1 P2 P3 * *
47324 **
47325 ** Read cookie number P3 from database P1 and write it into register P2.
47326 ** P3==0 is the schema version.  P3==1 is the database format.
47327 ** P3==2 is the recommended pager cache size, and so forth.  P1==0 is
47328 ** the main database file and P1==1 is the database file used to store
47329 ** temporary tables.
47330 **
47331 ** If P1 is negative, then this is a request to read the size of a
47332 ** databases free-list. P3 must be set to 1 in this case. The actual
47333 ** database accessed is ((P1+1)*-1). For example, a P1 parameter of -1
47334 ** corresponds to database 0 ("main"), a P1 of -2 is database 1 ("temp").
47335 **
47336 ** There must be a read-lock on the database (either a transaction
47337 ** must be started or there must be an open cursor) before
47338 ** executing this instruction.
47339 */
47340 case OP_ReadCookie: {               /* out2-prerelease */
47341   int iMeta;
47342   int iDb = pOp->p1;
47343   int iCookie = pOp->p3;
47344
47345   assert( pOp->p3<SQLITE_N_BTREE_META );
47346   if( iDb<0 ){
47347     iDb = (-1*(iDb+1));
47348     iCookie *= -1;
47349   }
47350   assert( iDb>=0 && iDb<db->nDb );
47351   assert( db->aDb[iDb].pBt!=0 );
47352   assert( (p->btreeMask & (1<<iDb))!=0 );
47353   /* The indexing of meta values at the schema layer is off by one from
47354   ** the indexing in the btree layer.  The btree considers meta[0] to
47355   ** be the number of free pages in the database (a read-only value)
47356   ** and meta[1] to be the schema cookie.  The schema layer considers
47357   ** meta[1] to be the schema cookie.  So we have to shift the index
47358   ** by one in the following statement.
47359   */
47360   rc = sqlite3BtreeGetMeta(db->aDb[iDb].pBt, 1 + iCookie, (u32 *)&iMeta);
47361   pOut->u.i = iMeta;
47362   MemSetTypeFlag(pOut, MEM_Int);
47363   break;
47364 }
47365
47366 /* Opcode: SetCookie P1 P2 P3 * *
47367 **
47368 ** Write the content of register P3 (interpreted as an integer)
47369 ** into cookie number P2 of database P1.
47370 ** P2==0 is the schema version.  P2==1 is the database format.
47371 ** P2==2 is the recommended pager cache size, and so forth.  P1==0 is
47372 ** the main database file and P1==1 is the database file used to store
47373 ** temporary tables.
47374 **
47375 ** A transaction must be started before executing this opcode.
47376 */
47377 case OP_SetCookie: {       /* in3 */
47378   Db *pDb;
47379   assert( pOp->p2<SQLITE_N_BTREE_META );
47380   assert( pOp->p1>=0 && pOp->p1<db->nDb );
47381   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
47382   pDb = &db->aDb[pOp->p1];
47383   assert( pDb->pBt!=0 );
47384   sqlite3VdbeMemIntegerify(pIn3);
47385   /* See note about index shifting on OP_ReadCookie */
47386   rc = sqlite3BtreeUpdateMeta(pDb->pBt, 1+pOp->p2, (int)pIn3->u.i);
47387   if( pOp->p2==0 ){
47388     /* When the schema cookie changes, record the new cookie internally */
47389     pDb->pSchema->schema_cookie = pIn3->u.i;
47390     db->flags |= SQLITE_InternChanges;
47391   }else if( pOp->p2==1 ){
47392     /* Record changes in the file format */
47393     pDb->pSchema->file_format = pIn3->u.i;
47394   }
47395   if( pOp->p1==1 ){
47396     /* Invalidate all prepared statements whenever the TEMP database
47397     ** schema is changed.  Ticket #1644 */
47398     sqlite3ExpirePreparedStatements(db);
47399   }
47400   break;
47401 }
47402
47403 /* Opcode: VerifyCookie P1 P2 *
47404 **
47405 ** Check the value of global database parameter number 0 (the
47406 ** schema version) and make sure it is equal to P2.  
47407 ** P1 is the database number which is 0 for the main database file
47408 ** and 1 for the file holding temporary tables and some higher number
47409 ** for auxiliary databases.
47410 **
47411 ** The cookie changes its value whenever the database schema changes.
47412 ** This operation is used to detect when that the cookie has changed
47413 ** and that the current process needs to reread the schema.
47414 **
47415 ** Either a transaction needs to have been started or an OP_Open needs
47416 ** to be executed (to establish a read lock) before this opcode is
47417 ** invoked.
47418 */
47419 case OP_VerifyCookie: {
47420   int iMeta;
47421   Btree *pBt;
47422   assert( pOp->p1>=0 && pOp->p1<db->nDb );
47423   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
47424   pBt = db->aDb[pOp->p1].pBt;
47425   if( pBt ){
47426     rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&iMeta);
47427   }else{
47428     rc = SQLITE_OK;
47429     iMeta = 0;
47430   }
47431   if( rc==SQLITE_OK && iMeta!=pOp->p2 ){
47432     sqlite3DbFree(db, p->zErrMsg);
47433     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
47434     /* If the schema-cookie from the database file matches the cookie 
47435     ** stored with the in-memory representation of the schema, do
47436     ** not reload the schema from the database file.
47437     **
47438     ** If virtual-tables are in use, this is not just an optimization.
47439     ** Often, v-tables store their data in other SQLite tables, which
47440     ** are queried from within xNext() and other v-table methods using
47441     ** prepared queries. If such a query is out-of-date, we do not want to
47442     ** discard the database schema, as the user code implementing the
47443     ** v-table would have to be ready for the sqlite3_vtab structure itself
47444     ** to be invalidated whenever sqlite3_step() is called from within 
47445     ** a v-table method.
47446     */
47447     if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
47448       sqlite3ResetInternalSchema(db, pOp->p1);
47449     }
47450
47451     sqlite3ExpirePreparedStatements(db);
47452     rc = SQLITE_SCHEMA;
47453   }
47454   break;
47455 }
47456
47457 /* Opcode: OpenRead P1 P2 P3 P4 P5
47458 **
47459 ** Open a read-only cursor for the database table whose root page is
47460 ** P2 in a database file.  The database file is determined by P3. 
47461 ** P3==0 means the main database, P3==1 means the database used for 
47462 ** temporary tables, and P3>1 means used the corresponding attached
47463 ** database.  Give the new cursor an identifier of P1.  The P1
47464 ** values need not be contiguous but all P1 values should be small integers.
47465 ** It is an error for P1 to be negative.
47466 **
47467 ** If P5!=0 then use the content of register P2 as the root page, not
47468 ** the value of P2 itself.
47469 **
47470 ** There will be a read lock on the database whenever there is an
47471 ** open cursor.  If the database was unlocked prior to this instruction
47472 ** then a read lock is acquired as part of this instruction.  A read
47473 ** lock allows other processes to read the database but prohibits
47474 ** any other process from modifying the database.  The read lock is
47475 ** released when all cursors are closed.  If this instruction attempts
47476 ** to get a read lock but fails, the script terminates with an
47477 ** SQLITE_BUSY error code.
47478 **
47479 ** The P4 value is a pointer to a KeyInfo structure that defines the
47480 ** content and collating sequence of indices.  P4 is NULL for cursors
47481 ** that are not pointing to indices.
47482 **
47483 ** See also OpenWrite.
47484 */
47485 /* Opcode: OpenWrite P1 P2 P3 P4 P5
47486 **
47487 ** Open a read/write cursor named P1 on the table or index whose root
47488 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
47489 ** root page.
47490 **
47491 ** The P4 value is a pointer to a KeyInfo structure that defines the
47492 ** content and collating sequence of indices.  P4 is NULL for cursors
47493 ** that are not pointing to indices.
47494 **
47495 ** This instruction works just like OpenRead except that it opens the cursor
47496 ** in read/write mode.  For a given table, there can be one or more read-only
47497 ** cursors or a single read/write cursor but not both.
47498 **
47499 ** See also OpenRead.
47500 */
47501 case OP_OpenRead:
47502 case OP_OpenWrite: {
47503   int i = pOp->p1;
47504   int p2 = pOp->p2;
47505   int iDb = pOp->p3;
47506   int wrFlag;
47507   Btree *pX;
47508   Cursor *pCur;
47509   Db *pDb;
47510   
47511   assert( iDb>=0 && iDb<db->nDb );
47512   assert( (p->btreeMask & (1<<iDb))!=0 );
47513   pDb = &db->aDb[iDb];
47514   pX = pDb->pBt;
47515   assert( pX!=0 );
47516   if( pOp->opcode==OP_OpenWrite ){
47517     wrFlag = 1;
47518     if( pDb->pSchema->file_format < p->minWriteFileFormat ){
47519       p->minWriteFileFormat = pDb->pSchema->file_format;
47520     }
47521   }else{
47522     wrFlag = 0;
47523   }
47524   if( pOp->p5 ){
47525     assert( p2>0 );
47526     assert( p2<=p->nMem );
47527     pIn2 = &p->aMem[p2];
47528     sqlite3VdbeMemIntegerify(pIn2);
47529     p2 = pIn2->u.i;
47530     assert( p2>=2 );
47531   }
47532   assert( i>=0 );
47533   pCur = allocateCursor(p, i, &pOp[-1], iDb, 1);
47534   if( pCur==0 ) goto no_mem;
47535   pCur->nullRow = 1;
47536   rc = sqlite3BtreeCursor(pX, p2, wrFlag, pOp->p4.p, pCur->pCursor);
47537   if( pOp->p4type==P4_KEYINFO ){
47538     pCur->pKeyInfo = pOp->p4.pKeyInfo;
47539     pCur->pIncrKey = &pCur->pKeyInfo->incrKey;
47540     pCur->pKeyInfo->enc = ENC(p->db);
47541   }else{
47542     pCur->pKeyInfo = 0;
47543     pCur->pIncrKey = &pCur->bogusIncrKey;
47544   }
47545   switch( rc ){
47546     case SQLITE_BUSY: {
47547       p->pc = pc;
47548       p->rc = rc = SQLITE_BUSY;
47549       goto vdbe_return;
47550     }
47551     case SQLITE_OK: {
47552       int flags = sqlite3BtreeFlags(pCur->pCursor);
47553       /* Sanity checking.  Only the lower four bits of the flags byte should
47554       ** be used.  Bit 3 (mask 0x08) is unpredictable.  The lower 3 bits
47555       ** (mask 0x07) should be either 5 (intkey+leafdata for tables) or
47556       ** 2 (zerodata for indices).  If these conditions are not met it can
47557       ** only mean that we are dealing with a corrupt database file
47558       */
47559       if( (flags & 0xf0)!=0 || ((flags & 0x07)!=5 && (flags & 0x07)!=2) ){
47560         rc = SQLITE_CORRUPT_BKPT;
47561         goto abort_due_to_error;
47562       }
47563       pCur->isTable = (flags & BTREE_INTKEY)!=0;
47564       pCur->isIndex = (flags & BTREE_ZERODATA)!=0;
47565       /* If P4==0 it means we are expected to open a table.  If P4!=0 then
47566       ** we expect to be opening an index.  If this is not what happened,
47567       ** then the database is corrupt
47568       */
47569       if( (pCur->isTable && pOp->p4type==P4_KEYINFO)
47570        || (pCur->isIndex && pOp->p4type!=P4_KEYINFO) ){
47571         rc = SQLITE_CORRUPT_BKPT;
47572         goto abort_due_to_error;
47573       }
47574       break;
47575     }
47576     case SQLITE_EMPTY: {
47577       pCur->isTable = pOp->p4type!=P4_KEYINFO;
47578       pCur->isIndex = !pCur->isTable;
47579       pCur->pCursor = 0;
47580       rc = SQLITE_OK;
47581       break;
47582     }
47583     default: {
47584       goto abort_due_to_error;
47585     }
47586   }
47587   break;
47588 }
47589
47590 /* Opcode: OpenEphemeral P1 P2 * P4 *
47591 **
47592 ** Open a new cursor P1 to a transient table.
47593 ** The cursor is always opened read/write even if 
47594 ** the main database is read-only.  The transient or virtual
47595 ** table is deleted automatically when the cursor is closed.
47596 **
47597 ** P2 is the number of columns in the virtual table.
47598 ** The cursor points to a BTree table if P4==0 and to a BTree index
47599 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
47600 ** that defines the format of keys in the index.
47601 **
47602 ** This opcode was once called OpenTemp.  But that created
47603 ** confusion because the term "temp table", might refer either
47604 ** to a TEMP table at the SQL level, or to a table opened by
47605 ** this opcode.  Then this opcode was call OpenVirtual.  But
47606 ** that created confusion with the whole virtual-table idea.
47607 */
47608 case OP_OpenEphemeral: {
47609   int i = pOp->p1;
47610   Cursor *pCx;
47611   static const int openFlags = 
47612       SQLITE_OPEN_READWRITE |
47613       SQLITE_OPEN_CREATE |
47614       SQLITE_OPEN_EXCLUSIVE |
47615       SQLITE_OPEN_DELETEONCLOSE |
47616       SQLITE_OPEN_TRANSIENT_DB;
47617
47618   assert( i>=0 );
47619   pCx = allocateCursor(p, i, pOp, -1, 1);
47620   if( pCx==0 ) goto no_mem;
47621   pCx->nullRow = 1;
47622   rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, openFlags,
47623                            &pCx->pBt);
47624   if( rc==SQLITE_OK ){
47625     rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
47626   }
47627   if( rc==SQLITE_OK ){
47628     /* If a transient index is required, create it by calling
47629     ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
47630     ** opening it. If a transient table is required, just use the
47631     ** automatically created table with root-page 1 (an INTKEY table).
47632     */
47633     if( pOp->p4.pKeyInfo ){
47634       int pgno;
47635       assert( pOp->p4type==P4_KEYINFO );
47636       rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_ZERODATA); 
47637       if( rc==SQLITE_OK ){
47638         assert( pgno==MASTER_ROOT+1 );
47639         rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, 
47640                                 (KeyInfo*)pOp->p4.z, pCx->pCursor);
47641         pCx->pKeyInfo = pOp->p4.pKeyInfo;
47642         pCx->pKeyInfo->enc = ENC(p->db);
47643         pCx->pIncrKey = &pCx->pKeyInfo->incrKey;
47644       }
47645       pCx->isTable = 0;
47646     }else{
47647       rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, pCx->pCursor);
47648       pCx->isTable = 1;
47649       pCx->pIncrKey = &pCx->bogusIncrKey;
47650     }
47651   }
47652   pCx->isIndex = !pCx->isTable;
47653   break;
47654 }
47655
47656 /* Opcode: OpenPseudo P1 P2 * * *
47657 **
47658 ** Open a new cursor that points to a fake table that contains a single
47659 ** row of data.  Any attempt to write a second row of data causes the
47660 ** first row to be deleted.  All data is deleted when the cursor is
47661 ** closed.
47662 **
47663 ** A pseudo-table created by this opcode is useful for holding the
47664 ** NEW or OLD tables in a trigger.  Also used to hold the a single
47665 ** row output from the sorter so that the row can be decomposed into
47666 ** individual columns using the OP_Column opcode.
47667 **
47668 ** When OP_Insert is executed to insert a row in to the pseudo table,
47669 ** the pseudo-table cursor may or may not make it's own copy of the
47670 ** original row data. If P2 is 0, then the pseudo-table will copy the
47671 ** original row data. Otherwise, a pointer to the original memory cell
47672 ** is stored. In this case, the vdbe program must ensure that the 
47673 ** memory cell containing the row data is not overwritten until the
47674 ** pseudo table is closed (or a new row is inserted into it).
47675 */
47676 case OP_OpenPseudo: {
47677   int i = pOp->p1;
47678   Cursor *pCx;
47679   assert( i>=0 );
47680   pCx = allocateCursor(p, i, &pOp[-1], -1, 0);
47681   if( pCx==0 ) goto no_mem;
47682   pCx->nullRow = 1;
47683   pCx->pseudoTable = 1;
47684   pCx->ephemPseudoTable = pOp->p2;
47685   pCx->pIncrKey = &pCx->bogusIncrKey;
47686   pCx->isTable = 1;
47687   pCx->isIndex = 0;
47688   break;
47689 }
47690
47691 /* Opcode: Close P1 * * * *
47692 **
47693 ** Close a cursor previously opened as P1.  If P1 is not
47694 ** currently open, this instruction is a no-op.
47695 */
47696 case OP_Close: {
47697   int i = pOp->p1;
47698   assert( i>=0 && i<p->nCursor );
47699   sqlite3VdbeFreeCursor(p, p->apCsr[i]);
47700   p->apCsr[i] = 0;
47701   break;
47702 }
47703
47704 /* Opcode: MoveGe P1 P2 P3 P4 *
47705 **
47706 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
47707 ** use the integer value in register P3 as a key. If cursor P1 refers 
47708 ** to an SQL index, then P3 is the first in an array of P4 registers 
47709 ** that are used as an unpacked index key. 
47710 **
47711 ** Reposition cursor P1 so that  it points to the smallest entry that 
47712 ** is greater than or equal to the key value. If there are no records 
47713 ** greater than or equal to the key and P2 is not zero, then jump to P2.
47714 **
47715 ** A special feature of this opcode (and different from the
47716 ** related OP_MoveGt, OP_MoveLt, and OP_MoveLe) is that if P2 is
47717 ** zero and P1 is an SQL table (a b-tree with integer keys) then
47718 ** the seek is deferred until it is actually needed.  It might be
47719 ** the case that the cursor is never accessed.  By deferring the
47720 ** seek, we avoid unnecessary seeks.
47721 **
47722 ** See also: Found, NotFound, Distinct, MoveLt, MoveGt, MoveLe
47723 */
47724 /* Opcode: MoveGt P1 P2 P3 P4 *
47725 **
47726 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
47727 ** use the integer value in register P3 as a key. If cursor P1 refers 
47728 ** to an SQL index, then P3 is the first in an array of P4 registers 
47729 ** that are used as an unpacked index key. 
47730 **
47731 ** Reposition cursor P1 so that  it points to the smallest entry that 
47732 ** is greater than the key value. If there are no records greater than 
47733 ** the key and P2 is not zero, then jump to P2.
47734 **
47735 ** See also: Found, NotFound, Distinct, MoveLt, MoveGe, MoveLe
47736 */
47737 /* Opcode: MoveLt P1 P2 P3 P4 * 
47738 **
47739 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
47740 ** use the integer value in register P3 as a key. If cursor P1 refers 
47741 ** to an SQL index, then P3 is the first in an array of P4 registers 
47742 ** that are used as an unpacked index key. 
47743 **
47744 ** Reposition cursor P1 so that  it points to the largest entry that 
47745 ** is less than the key value. If there are no records less than 
47746 ** the key and P2 is not zero, then jump to P2.
47747 **
47748 ** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLe
47749 */
47750 /* Opcode: MoveLe P1 P2 P3 P4 *
47751 **
47752 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
47753 ** use the integer value in register P3 as a key. If cursor P1 refers 
47754 ** to an SQL index, then P3 is the first in an array of P4 registers 
47755 ** that are used as an unpacked index key. 
47756 **
47757 ** Reposition cursor P1 so that it points to the largest entry that 
47758 ** is less than or equal to the key value. If there are no records 
47759 ** less than or equal to the key and P2 is not zero, then jump to P2.
47760 **
47761 ** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLt
47762 */
47763 case OP_MoveLt:         /* jump, in3 */
47764 case OP_MoveLe:         /* jump, in3 */
47765 case OP_MoveGe:         /* jump, in3 */
47766 case OP_MoveGt: {       /* jump, in3 */
47767   int i = pOp->p1;
47768   Cursor *pC;
47769
47770   assert( i>=0 && i<p->nCursor );
47771   pC = p->apCsr[i];
47772   assert( pC!=0 );
47773   if( pC->pCursor!=0 ){
47774     int res, oc;
47775     oc = pOp->opcode;
47776     pC->nullRow = 0;
47777     *pC->pIncrKey = oc==OP_MoveGt || oc==OP_MoveLe;
47778     if( pC->isTable ){
47779       i64 iKey = sqlite3VdbeIntValue(pIn3);
47780       if( pOp->p2==0 ){
47781         assert( pOp->opcode==OP_MoveGe );
47782         pC->movetoTarget = iKey;
47783         pC->rowidIsValid = 0;
47784         pC->deferredMoveto = 1;
47785         break;
47786       }
47787       rc = sqlite3BtreeMoveto(pC->pCursor, 0, 0, (u64)iKey, 0, &res);
47788       if( rc!=SQLITE_OK ){
47789         goto abort_due_to_error;
47790       }
47791       pC->lastRowid = iKey;
47792       pC->rowidIsValid = res==0;
47793     }else{
47794       UnpackedRecord r;
47795       int nField = pOp->p4.i;
47796       assert( pOp->p4type==P4_INT32 );
47797       assert( nField>0 );
47798       r.pKeyInfo = pC->pKeyInfo;
47799       r.nField = nField;
47800       r.needFree = 0;
47801       r.needDestroy = 0;
47802       r.aMem = &p->aMem[pOp->p3];
47803       rc = sqlite3BtreeMoveto(pC->pCursor, 0, &r, 0, 0, &res);
47804       if( rc!=SQLITE_OK ){
47805         goto abort_due_to_error;
47806       }
47807       pC->rowidIsValid = 0;
47808     }
47809     pC->deferredMoveto = 0;
47810     pC->cacheStatus = CACHE_STALE;
47811     *pC->pIncrKey = 0;
47812 #ifdef SQLITE_TEST
47813     sqlite3_search_count++;
47814 #endif
47815     if( oc==OP_MoveGe || oc==OP_MoveGt ){
47816       if( res<0 ){
47817         rc = sqlite3BtreeNext(pC->pCursor, &res);
47818         if( rc!=SQLITE_OK ) goto abort_due_to_error;
47819         pC->rowidIsValid = 0;
47820       }else{
47821         res = 0;
47822       }
47823     }else{
47824       assert( oc==OP_MoveLt || oc==OP_MoveLe );
47825       if( res>=0 ){
47826         rc = sqlite3BtreePrevious(pC->pCursor, &res);
47827         if( rc!=SQLITE_OK ) goto abort_due_to_error;
47828         pC->rowidIsValid = 0;
47829       }else{
47830         /* res might be negative because the table is empty.  Check to
47831         ** see if this is the case.
47832         */
47833         res = sqlite3BtreeEof(pC->pCursor);
47834       }
47835     }
47836     assert( pOp->p2>0 );
47837     if( res ){
47838       pc = pOp->p2 - 1;
47839     }
47840   }else if( !pC->pseudoTable ){
47841     /* This happens when attempting to open the sqlite3_master table
47842     ** for read access returns SQLITE_EMPTY. In this case always
47843     ** take the jump (since there are no records in the table).
47844     */
47845     pc = pOp->p2 - 1;
47846   }
47847   break;
47848 }
47849
47850 /* Opcode: Found P1 P2 P3 * *
47851 **
47852 ** Register P3 holds a blob constructed by MakeRecord.  P1 is an index.
47853 ** If an entry that matches the value in register p3 exists in P1 then
47854 ** jump to P2.  If the P3 value does not match any entry in P1
47855 ** then fall thru.  The P1 cursor is left pointing at the matching entry
47856 ** if it exists.
47857 **
47858 ** This instruction is used to implement the IN operator where the
47859 ** left-hand side is a SELECT statement.  P1 may be a true index, or it
47860 ** may be a temporary index that holds the results of the SELECT
47861 ** statement.   This instruction is also used to implement the
47862 ** DISTINCT keyword in SELECT statements.
47863 **
47864 ** This instruction checks if index P1 contains a record for which 
47865 ** the first N serialized values exactly match the N serialized values
47866 ** in the record in register P3, where N is the total number of values in
47867 ** the P3 record (the P3 record is a prefix of the P1 record). 
47868 **
47869 ** See also: NotFound, MoveTo, IsUnique, NotExists
47870 */
47871 /* Opcode: NotFound P1 P2 P3 * *
47872 **
47873 ** Register P3 holds a blob constructed by MakeRecord.  P1 is
47874 ** an index.  If no entry exists in P1 that matches the blob then jump
47875 ** to P2.  If an entry does existing, fall through.  The cursor is left
47876 ** pointing to the entry that matches.
47877 **
47878 ** See also: Found, MoveTo, NotExists, IsUnique
47879 */
47880 case OP_NotFound:       /* jump, in3 */
47881 case OP_Found: {        /* jump, in3 */
47882   int i = pOp->p1;
47883   int alreadyExists = 0;
47884   Cursor *pC;
47885   assert( i>=0 && i<p->nCursor );
47886   assert( p->apCsr[i]!=0 );
47887   if( (pC = p->apCsr[i])->pCursor!=0 ){
47888     int res;
47889     assert( pC->isTable==0 );
47890     assert( pIn3->flags & MEM_Blob );
47891     if( pOp->opcode==OP_Found ){
47892       pC->pKeyInfo->prefixIsEqual = 1;
47893     }
47894     rc = sqlite3BtreeMoveto(pC->pCursor, pIn3->z, 0, pIn3->n, 0, &res);
47895     pC->pKeyInfo->prefixIsEqual = 0;
47896     if( rc!=SQLITE_OK ){
47897       break;
47898     }
47899     alreadyExists = (res==0);
47900     pC->deferredMoveto = 0;
47901     pC->cacheStatus = CACHE_STALE;
47902   }
47903   if( pOp->opcode==OP_Found ){
47904     if( alreadyExists ) pc = pOp->p2 - 1;
47905   }else{
47906     if( !alreadyExists ) pc = pOp->p2 - 1;
47907   }
47908   break;
47909 }
47910
47911 /* Opcode: IsUnique P1 P2 P3 P4 *
47912 **
47913 ** The P3 register contains an integer record number.  Call this
47914 ** record number R.  The P4 register contains an index key created
47915 ** using MakeIdxRec.  Call it K.
47916 **
47917 ** P1 is an index.  So it has no data and its key consists of a
47918 ** record generated by OP_MakeRecord where the last field is the 
47919 ** rowid of the entry that the index refers to.
47920 ** 
47921 ** This instruction asks if there is an entry in P1 where the
47922 ** fields matches K but the rowid is different from R.
47923 ** If there is no such entry, then there is an immediate
47924 ** jump to P2.  If any entry does exist where the index string
47925 ** matches K but the record number is not R, then the record
47926 ** number for that entry is written into P3 and control
47927 ** falls through to the next instruction.
47928 **
47929 ** See also: NotFound, NotExists, Found
47930 */
47931 case OP_IsUnique: {        /* jump, in3 */
47932   int i = pOp->p1;
47933   Cursor *pCx;
47934   BtCursor *pCrsr;
47935   Mem *pK;
47936   i64 R;
47937
47938   /* Pop the value R off the top of the stack
47939   */
47940   assert( pOp->p4type==P4_INT32 );
47941   assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
47942   pK = &p->aMem[pOp->p4.i];
47943   sqlite3VdbeMemIntegerify(pIn3);
47944   R = pIn3->u.i;
47945   assert( i>=0 && i<p->nCursor );
47946   pCx = p->apCsr[i];
47947   assert( pCx!=0 );
47948   pCrsr = pCx->pCursor;
47949   if( pCrsr!=0 ){
47950     int res;
47951     i64 v;         /* The record number on the P1 entry that matches K */
47952     char *zKey;    /* The value of K */
47953     int nKey;      /* Number of bytes in K */
47954     int len;       /* Number of bytes in K without the rowid at the end */
47955     int szRowid;   /* Size of the rowid column at the end of zKey */
47956
47957     /* Make sure K is a string and make zKey point to K
47958     */
47959     assert( pK->flags & MEM_Blob );
47960     zKey = pK->z;
47961     nKey = pK->n;
47962
47963     /* sqlite3VdbeIdxRowidLen() only returns other than SQLITE_OK when the
47964     ** record passed as an argument corrupt. Since the record in this case
47965     ** has just been created by an OP_MakeRecord instruction, and not loaded
47966     ** from the database file, it is not possible for it to be corrupt.
47967     ** Therefore, assert(rc==SQLITE_OK).
47968     */
47969     rc = sqlite3VdbeIdxRowidLen((u8*)zKey, nKey, &szRowid);
47970     assert(rc==SQLITE_OK);
47971     len = nKey-szRowid;
47972
47973     /* Search for an entry in P1 where all but the last four bytes match K.
47974     ** If there is no such entry, jump immediately to P2.
47975     */
47976     assert( pCx->deferredMoveto==0 );
47977     pCx->cacheStatus = CACHE_STALE;
47978     rc = sqlite3BtreeMoveto(pCrsr, zKey, 0, len, 0, &res);
47979     if( rc!=SQLITE_OK ){
47980       goto abort_due_to_error;
47981     }
47982     if( res<0 ){
47983       rc = sqlite3BtreeNext(pCrsr, &res);
47984       if( res ){
47985         pc = pOp->p2 - 1;
47986         break;
47987       }
47988     }
47989     rc = sqlite3VdbeIdxKeyCompare(pCx, 0, len, (u8*)zKey, &res); 
47990     if( rc!=SQLITE_OK ) goto abort_due_to_error;
47991     if( res>0 ){
47992       pc = pOp->p2 - 1;
47993       break;
47994     }
47995
47996     /* At this point, pCrsr is pointing to an entry in P1 where all but
47997     ** the final entry (the rowid) matches K.  Check to see if the
47998     ** final rowid column is different from R.  If it equals R then jump
47999     ** immediately to P2.
48000     */
48001     rc = sqlite3VdbeIdxRowid(pCrsr, &v);
48002     if( rc!=SQLITE_OK ){
48003       goto abort_due_to_error;
48004     }
48005     if( v==R ){
48006       pc = pOp->p2 - 1;
48007       break;
48008     }
48009
48010     /* The final varint of the key is different from R.  Store it back
48011     ** into register R3.  (The record number of an entry that violates
48012     ** a UNIQUE constraint.)
48013     */
48014     pIn3->u.i = v;
48015     assert( pIn3->flags&MEM_Int );
48016   }
48017   break;
48018 }
48019
48020 /* Opcode: NotExists P1 P2 P3 * *
48021 **
48022 ** Use the content of register P3 as a integer key.  If a record 
48023 ** with that key does not exist in table of P1, then jump to P2. 
48024 ** If the record does exist, then fall thru.  The cursor is left 
48025 ** pointing to the record if it exists.
48026 **
48027 ** The difference between this operation and NotFound is that this
48028 ** operation assumes the key is an integer and that P1 is a table whereas
48029 ** NotFound assumes key is a blob constructed from MakeRecord and
48030 ** P1 is an index.
48031 **
48032 ** See also: Found, MoveTo, NotFound, IsUnique
48033 */
48034 case OP_NotExists: {        /* jump, in3 */
48035   int i = pOp->p1;
48036   Cursor *pC;
48037   BtCursor *pCrsr;
48038   assert( i>=0 && i<p->nCursor );
48039   assert( p->apCsr[i]!=0 );
48040   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
48041     int res;
48042     u64 iKey;
48043     assert( pIn3->flags & MEM_Int );
48044     assert( p->apCsr[i]->isTable );
48045     iKey = intToKey(pIn3->u.i);
48046     rc = sqlite3BtreeMoveto(pCrsr, 0, 0, iKey, 0,&res);
48047     pC->lastRowid = pIn3->u.i;
48048     pC->rowidIsValid = res==0;
48049     pC->nullRow = 0;
48050     pC->cacheStatus = CACHE_STALE;
48051     /* res might be uninitialized if rc!=SQLITE_OK.  But if rc!=SQLITE_OK
48052     ** processing is about to abort so we really do not care whether or not
48053     ** the following jump is taken.  (In other words, do not stress over
48054     ** the error that valgrind sometimes shows on the next statement when
48055     ** running ioerr.test and similar failure-recovery test scripts.) */
48056     if( res!=0 ){
48057       pc = pOp->p2 - 1;
48058       assert( pC->rowidIsValid==0 );
48059     }
48060   }else if( !pC->pseudoTable ){
48061     /* This happens when an attempt to open a read cursor on the 
48062     ** sqlite_master table returns SQLITE_EMPTY.
48063     */
48064     assert( pC->isTable );
48065     pc = pOp->p2 - 1;
48066     assert( pC->rowidIsValid==0 );
48067   }
48068   break;
48069 }
48070
48071 /* Opcode: Sequence P1 P2 * * *
48072 **
48073 ** Find the next available sequence number for cursor P1.
48074 ** Write the sequence number into register P2.
48075 ** The sequence number on the cursor is incremented after this
48076 ** instruction.  
48077 */
48078 case OP_Sequence: {           /* out2-prerelease */
48079   int i = pOp->p1;
48080   assert( i>=0 && i<p->nCursor );
48081   assert( p->apCsr[i]!=0 );
48082   pOut->u.i = p->apCsr[i]->seqCount++;
48083   MemSetTypeFlag(pOut, MEM_Int);
48084   break;
48085 }
48086
48087
48088 /* Opcode: NewRowid P1 P2 P3 * *
48089 **
48090 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
48091 ** The record number is not previously used as a key in the database
48092 ** table that cursor P1 points to.  The new record number is written
48093 ** written to register P2.
48094 **
48095 ** If P3>0 then P3 is a register that holds the largest previously
48096 ** generated record number.  No new record numbers are allowed to be less
48097 ** than this value.  When this value reaches its maximum, a SQLITE_FULL
48098 ** error is generated.  The P3 register is updated with the generated
48099 ** record number.  This P3 mechanism is used to help implement the
48100 ** AUTOINCREMENT feature.
48101 */
48102 case OP_NewRowid: {           /* out2-prerelease */
48103   int i = pOp->p1;
48104   i64 v = 0;
48105   Cursor *pC;
48106   assert( i>=0 && i<p->nCursor );
48107   assert( p->apCsr[i]!=0 );
48108   if( (pC = p->apCsr[i])->pCursor==0 ){
48109     /* The zero initialization above is all that is needed */
48110   }else{
48111     /* The next rowid or record number (different terms for the same
48112     ** thing) is obtained in a two-step algorithm.
48113     **
48114     ** First we attempt to find the largest existing rowid and add one
48115     ** to that.  But if the largest existing rowid is already the maximum
48116     ** positive integer, we have to fall through to the second
48117     ** probabilistic algorithm
48118     **
48119     ** The second algorithm is to select a rowid at random and see if
48120     ** it already exists in the table.  If it does not exist, we have
48121     ** succeeded.  If the random rowid does exist, we select a new one
48122     ** and try again, up to 1000 times.
48123     **
48124     ** For a table with less than 2 billion entries, the probability
48125     ** of not finding a unused rowid is about 1.0e-300.  This is a 
48126     ** non-zero probability, but it is still vanishingly small and should
48127     ** never cause a problem.  You are much, much more likely to have a
48128     ** hardware failure than for this algorithm to fail.
48129     **
48130     ** The analysis in the previous paragraph assumes that you have a good
48131     ** source of random numbers.  Is a library function like lrand48()
48132     ** good enough?  Maybe. Maybe not. It's hard to know whether there
48133     ** might be subtle bugs is some implementations of lrand48() that
48134     ** could cause problems. To avoid uncertainty, SQLite uses its own 
48135     ** random number generator based on the RC4 algorithm.
48136     **
48137     ** To promote locality of reference for repetitive inserts, the
48138     ** first few attempts at choosing a random rowid pick values just a little
48139     ** larger than the previous rowid.  This has been shown experimentally
48140     ** to double the speed of the COPY operation.
48141     */
48142     int res, rx=SQLITE_OK, cnt;
48143     i64 x;
48144     cnt = 0;
48145     if( (sqlite3BtreeFlags(pC->pCursor)&(BTREE_INTKEY|BTREE_ZERODATA)) !=
48146           BTREE_INTKEY ){
48147       rc = SQLITE_CORRUPT_BKPT;
48148       goto abort_due_to_error;
48149     }
48150     assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_INTKEY)!=0 );
48151     assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_ZERODATA)==0 );
48152
48153 #ifdef SQLITE_32BIT_ROWID
48154 #   define MAX_ROWID 0x7fffffff
48155 #else
48156     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
48157     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
48158     ** to provide the constant while making all compilers happy.
48159     */
48160 #   define MAX_ROWID  ( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
48161 #endif
48162
48163     if( !pC->useRandomRowid ){
48164       if( pC->nextRowidValid ){
48165         v = pC->nextRowid;
48166       }else{
48167         rc = sqlite3BtreeLast(pC->pCursor, &res);
48168         if( rc!=SQLITE_OK ){
48169           goto abort_due_to_error;
48170         }
48171         if( res ){
48172           v = 1;
48173         }else{
48174           sqlite3BtreeKeySize(pC->pCursor, &v);
48175           v = keyToInt(v);
48176           if( v==MAX_ROWID ){
48177             pC->useRandomRowid = 1;
48178           }else{
48179             v++;
48180           }
48181         }
48182       }
48183
48184 #ifndef SQLITE_OMIT_AUTOINCREMENT
48185       if( pOp->p3 ){
48186         Mem *pMem;
48187         assert( pOp->p3>0 && pOp->p3<=p->nMem ); /* P3 is a valid memory cell */
48188         pMem = &p->aMem[pOp->p3];
48189         REGISTER_TRACE(pOp->p3, pMem);
48190         sqlite3VdbeMemIntegerify(pMem);
48191         assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
48192         if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
48193           rc = SQLITE_FULL;
48194           goto abort_due_to_error;
48195         }
48196         if( v<pMem->u.i+1 ){
48197           v = pMem->u.i + 1;
48198         }
48199         pMem->u.i = v;
48200       }
48201 #endif
48202
48203       if( v<MAX_ROWID ){
48204         pC->nextRowidValid = 1;
48205         pC->nextRowid = v+1;
48206       }else{
48207         pC->nextRowidValid = 0;
48208       }
48209     }
48210     if( pC->useRandomRowid ){
48211       assert( pOp->p3==0 );  /* SQLITE_FULL must have occurred prior to this */
48212       v = db->priorNewRowid;
48213       cnt = 0;
48214       do{
48215         if( cnt==0 && (v&0xffffff)==v ){
48216           v++;
48217         }else{
48218           sqlite3_randomness(sizeof(v), &v);
48219           if( cnt<5 ) v &= 0xffffff;
48220         }
48221         if( v==0 ) continue;
48222         x = intToKey(v);
48223         rx = sqlite3BtreeMoveto(pC->pCursor, 0, 0, (u64)x, 0, &res);
48224         cnt++;
48225       }while( cnt<100 && rx==SQLITE_OK && res==0 );
48226       db->priorNewRowid = v;
48227       if( rx==SQLITE_OK && res==0 ){
48228         rc = SQLITE_FULL;
48229         goto abort_due_to_error;
48230       }
48231     }
48232     pC->rowidIsValid = 0;
48233     pC->deferredMoveto = 0;
48234     pC->cacheStatus = CACHE_STALE;
48235   }
48236   MemSetTypeFlag(pOut, MEM_Int);
48237   pOut->u.i = v;
48238   break;
48239 }
48240
48241 /* Opcode: Insert P1 P2 P3 P4 P5
48242 **
48243 ** Write an entry into the table of cursor P1.  A new entry is
48244 ** created if it doesn't already exist or the data for an existing
48245 ** entry is overwritten.  The data is the value stored register
48246 ** number P2. The key is stored in register P3. The key must
48247 ** be an integer.
48248 **
48249 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
48250 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
48251 ** then rowid is stored for subsequent return by the
48252 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
48253 **
48254 ** Parameter P4 may point to a string containing the table-name, or
48255 ** may be NULL. If it is not NULL, then the update-hook 
48256 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
48257 **
48258 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
48259 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
48260 ** and register P2 becomes ephemeral.  If the cursor is changed, the
48261 ** value of register P2 will then change.  Make sure this does not
48262 ** cause any problems.)
48263 **
48264 ** This instruction only works on tables.  The equivalent instruction
48265 ** for indices is OP_IdxInsert.
48266 */
48267 case OP_Insert: {
48268   Mem *pData = &p->aMem[pOp->p2];
48269   Mem *pKey = &p->aMem[pOp->p3];
48270
48271   i64 iKey;   /* The integer ROWID or key for the record to be inserted */
48272   int i = pOp->p1;
48273   Cursor *pC;
48274   assert( i>=0 && i<p->nCursor );
48275   pC = p->apCsr[i];
48276   assert( pC!=0 );
48277   assert( pC->pCursor!=0 || pC->pseudoTable );
48278   assert( pKey->flags & MEM_Int );
48279   assert( pC->isTable );
48280   REGISTER_TRACE(pOp->p2, pData);
48281   REGISTER_TRACE(pOp->p3, pKey);
48282
48283   iKey = intToKey(pKey->u.i);
48284   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
48285   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = pKey->u.i;
48286   if( pC->nextRowidValid && pKey->u.i>=pC->nextRowid ){
48287     pC->nextRowidValid = 0;
48288   }
48289   if( pData->flags & MEM_Null ){
48290     pData->z = 0;
48291     pData->n = 0;
48292   }else{
48293     assert( pData->flags & (MEM_Blob|MEM_Str) );
48294   }
48295   if( pC->pseudoTable ){
48296     if( !pC->ephemPseudoTable ){
48297       sqlite3DbFree(db, pC->pData);
48298     }
48299     pC->iKey = iKey;
48300     pC->nData = pData->n;
48301     if( pData->z==pData->zMalloc || pC->ephemPseudoTable ){
48302       pC->pData = pData->z;
48303       if( !pC->ephemPseudoTable ){
48304         pData->flags &= ~MEM_Dyn;
48305         pData->flags |= MEM_Ephem;
48306         pData->zMalloc = 0;
48307       }
48308     }else{
48309       pC->pData = sqlite3Malloc( pC->nData+2 );
48310       if( !pC->pData ) goto no_mem;
48311       memcpy(pC->pData, pData->z, pC->nData);
48312       pC->pData[pC->nData] = 0;
48313       pC->pData[pC->nData+1] = 0;
48314     }
48315     pC->nullRow = 0;
48316   }else{
48317     int nZero;
48318     if( pData->flags & MEM_Zero ){
48319       nZero = pData->u.i;
48320     }else{
48321       nZero = 0;
48322     }
48323     rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
48324                             pData->z, pData->n, nZero,
48325                             pOp->p5 & OPFLAG_APPEND);
48326   }
48327   
48328   pC->rowidIsValid = 0;
48329   pC->deferredMoveto = 0;
48330   pC->cacheStatus = CACHE_STALE;
48331
48332   /* Invoke the update-hook if required. */
48333   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
48334     const char *zDb = db->aDb[pC->iDb].zName;
48335     const char *zTbl = pOp->p4.z;
48336     int op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
48337     assert( pC->isTable );
48338     db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
48339     assert( pC->iDb>=0 );
48340   }
48341   break;
48342 }
48343
48344 /* Opcode: Delete P1 P2 * P4 *
48345 **
48346 ** Delete the record at which the P1 cursor is currently pointing.
48347 **
48348 ** The cursor will be left pointing at either the next or the previous
48349 ** record in the table. If it is left pointing at the next record, then
48350 ** the next Next instruction will be a no-op.  Hence it is OK to delete
48351 ** a record from within an Next loop.
48352 **
48353 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
48354 ** incremented (otherwise not).
48355 **
48356 ** P1 must not be pseudo-table.  It has to be a real table with
48357 ** multiple rows.
48358 **
48359 ** If P4 is not NULL, then it is the name of the table that P1 is
48360 ** pointing to.  The update hook will be invoked, if it exists.
48361 ** If P4 is not NULL then the P1 cursor must have been positioned
48362 ** using OP_NotFound prior to invoking this opcode.
48363 */
48364 case OP_Delete: {
48365   int i = pOp->p1;
48366   i64 iKey;
48367   Cursor *pC;
48368
48369   assert( i>=0 && i<p->nCursor );
48370   pC = p->apCsr[i];
48371   assert( pC!=0 );
48372   assert( pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
48373
48374   /* If the update-hook will be invoked, set iKey to the rowid of the
48375   ** row being deleted.
48376   */
48377   if( db->xUpdateCallback && pOp->p4.z ){
48378     assert( pC->isTable );
48379     assert( pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
48380     iKey = pC->lastRowid;
48381   }
48382
48383   rc = sqlite3VdbeCursorMoveto(pC);
48384   if( rc ) goto abort_due_to_error;
48385   rc = sqlite3BtreeDelete(pC->pCursor);
48386   pC->nextRowidValid = 0;
48387   pC->cacheStatus = CACHE_STALE;
48388
48389   /* Invoke the update-hook if required. */
48390   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
48391     const char *zDb = db->aDb[pC->iDb].zName;
48392     const char *zTbl = pOp->p4.z;
48393     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey);
48394     assert( pC->iDb>=0 );
48395   }
48396   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
48397   break;
48398 }
48399
48400 /* Opcode: ResetCount P1 * *
48401 **
48402 ** This opcode resets the VMs internal change counter to 0. If P1 is true,
48403 ** then the value of the change counter is copied to the database handle
48404 ** change counter (returned by subsequent calls to sqlite3_changes())
48405 ** before it is reset. This is used by trigger programs.
48406 */
48407 case OP_ResetCount: {
48408   if( pOp->p1 ){
48409     sqlite3VdbeSetChanges(db, p->nChange);
48410   }
48411   p->nChange = 0;
48412   break;
48413 }
48414
48415 /* Opcode: RowData P1 P2 * * *
48416 **
48417 ** Write into register P2 the complete row data for cursor P1.
48418 ** There is no interpretation of the data.  
48419 ** It is just copied onto the P2 register exactly as 
48420 ** it is found in the database file.
48421 **
48422 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
48423 ** of a real table, not a pseudo-table.
48424 */
48425 /* Opcode: RowKey P1 P2 * * *
48426 **
48427 ** Write into register P2 the complete row key for cursor P1.
48428 ** There is no interpretation of the data.  
48429 ** The key is copied onto the P3 register exactly as 
48430 ** it is found in the database file.
48431 **
48432 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
48433 ** of a real table, not a pseudo-table.
48434 */
48435 case OP_RowKey:
48436 case OP_RowData: {
48437   int i = pOp->p1;
48438   Cursor *pC;
48439   BtCursor *pCrsr;
48440   u32 n;
48441
48442   pOut = &p->aMem[pOp->p2];
48443
48444   /* Note that RowKey and RowData are really exactly the same instruction */
48445   assert( i>=0 && i<p->nCursor );
48446   pC = p->apCsr[i];
48447   assert( pC->isTable || pOp->opcode==OP_RowKey );
48448   assert( pC->isIndex || pOp->opcode==OP_RowData );
48449   assert( pC!=0 );
48450   assert( pC->nullRow==0 );
48451   assert( pC->pseudoTable==0 );
48452   assert( pC->pCursor!=0 );
48453   pCrsr = pC->pCursor;
48454   rc = sqlite3VdbeCursorMoveto(pC);
48455   if( rc ) goto abort_due_to_error;
48456   if( pC->isIndex ){
48457     i64 n64;
48458     assert( !pC->isTable );
48459     sqlite3BtreeKeySize(pCrsr, &n64);
48460     if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
48461       goto too_big;
48462     }
48463     n = n64;
48464   }else{
48465     sqlite3BtreeDataSize(pCrsr, &n);
48466     if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
48467       goto too_big;
48468     }
48469   }
48470   if( sqlite3VdbeMemGrow(pOut, n, 0) ){
48471     goto no_mem;
48472   }
48473   pOut->n = n;
48474   MemSetTypeFlag(pOut, MEM_Blob);
48475   if( pC->isIndex ){
48476     rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
48477   }else{
48478     rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
48479   }
48480   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
48481   UPDATE_MAX_BLOBSIZE(pOut);
48482   break;
48483 }
48484
48485 /* Opcode: Rowid P1 P2 * * *
48486 **
48487 ** Store in register P2 an integer which is the key of the table entry that
48488 ** P1 is currently point to.
48489 */
48490 case OP_Rowid: {                 /* out2-prerelease */
48491   int i = pOp->p1;
48492   Cursor *pC;
48493   i64 v;
48494
48495   assert( i>=0 && i<p->nCursor );
48496   pC = p->apCsr[i];
48497   assert( pC!=0 );
48498   rc = sqlite3VdbeCursorMoveto(pC);
48499   if( rc ) goto abort_due_to_error;
48500   if( pC->rowidIsValid ){
48501     v = pC->lastRowid;
48502   }else if( pC->pseudoTable ){
48503     v = keyToInt(pC->iKey);
48504   }else if( pC->nullRow ){
48505     /* Leave the rowid set to a NULL */
48506     break;
48507   }else{
48508     assert( pC->pCursor!=0 );
48509     sqlite3BtreeKeySize(pC->pCursor, &v);
48510     v = keyToInt(v);
48511   }
48512   pOut->u.i = v;
48513   MemSetTypeFlag(pOut, MEM_Int);
48514   break;
48515 }
48516
48517 /* Opcode: NullRow P1 * * * *
48518 **
48519 ** Move the cursor P1 to a null row.  Any OP_Column operations
48520 ** that occur while the cursor is on the null row will always
48521 ** write a NULL.
48522 */
48523 case OP_NullRow: {
48524   int i = pOp->p1;
48525   Cursor *pC;
48526
48527   assert( i>=0 && i<p->nCursor );
48528   pC = p->apCsr[i];
48529   assert( pC!=0 );
48530   pC->nullRow = 1;
48531   pC->rowidIsValid = 0;
48532   break;
48533 }
48534
48535 /* Opcode: Last P1 P2 * * *
48536 **
48537 ** The next use of the Rowid or Column or Next instruction for P1 
48538 ** will refer to the last entry in the database table or index.
48539 ** If the table or index is empty and P2>0, then jump immediately to P2.
48540 ** If P2 is 0 or if the table or index is not empty, fall through
48541 ** to the following instruction.
48542 */
48543 case OP_Last: {        /* jump */
48544   int i = pOp->p1;
48545   Cursor *pC;
48546   BtCursor *pCrsr;
48547   int res;
48548
48549   assert( i>=0 && i<p->nCursor );
48550   pC = p->apCsr[i];
48551   assert( pC!=0 );
48552   pCrsr = pC->pCursor;
48553   assert( pCrsr!=0 );
48554   rc = sqlite3BtreeLast(pCrsr, &res);
48555   pC->nullRow = res;
48556   pC->deferredMoveto = 0;
48557   pC->cacheStatus = CACHE_STALE;
48558   if( res && pOp->p2>0 ){
48559     pc = pOp->p2 - 1;
48560   }
48561   break;
48562 }
48563
48564
48565 /* Opcode: Sort P1 P2 * * *
48566 **
48567 ** This opcode does exactly the same thing as OP_Rewind except that
48568 ** it increments an undocumented global variable used for testing.
48569 **
48570 ** Sorting is accomplished by writing records into a sorting index,
48571 ** then rewinding that index and playing it back from beginning to
48572 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
48573 ** rewinding so that the global variable will be incremented and
48574 ** regression tests can determine whether or not the optimizer is
48575 ** correctly optimizing out sorts.
48576 */
48577 case OP_Sort: {        /* jump */
48578 #ifdef SQLITE_TEST
48579   sqlite3_sort_count++;
48580   sqlite3_search_count--;
48581 #endif
48582   /* Fall through into OP_Rewind */
48583 }
48584 /* Opcode: Rewind P1 P2 * * *
48585 **
48586 ** The next use of the Rowid or Column or Next instruction for P1 
48587 ** will refer to the first entry in the database table or index.
48588 ** If the table or index is empty and P2>0, then jump immediately to P2.
48589 ** If P2 is 0 or if the table or index is not empty, fall through
48590 ** to the following instruction.
48591 */
48592 case OP_Rewind: {        /* jump */
48593   int i = pOp->p1;
48594   Cursor *pC;
48595   BtCursor *pCrsr;
48596   int res;
48597
48598   assert( i>=0 && i<p->nCursor );
48599   pC = p->apCsr[i];
48600   assert( pC!=0 );
48601   if( (pCrsr = pC->pCursor)!=0 ){
48602     rc = sqlite3BtreeFirst(pCrsr, &res);
48603     pC->atFirst = res==0;
48604     pC->deferredMoveto = 0;
48605     pC->cacheStatus = CACHE_STALE;
48606   }else{
48607     res = 1;
48608   }
48609   pC->nullRow = res;
48610   assert( pOp->p2>0 && pOp->p2<p->nOp );
48611   if( res ){
48612     pc = pOp->p2 - 1;
48613   }
48614   break;
48615 }
48616
48617 /* Opcode: Next P1 P2 * * *
48618 **
48619 ** Advance cursor P1 so that it points to the next key/data pair in its
48620 ** table or index.  If there are no more key/value pairs then fall through
48621 ** to the following instruction.  But if the cursor advance was successful,
48622 ** jump immediately to P2.
48623 **
48624 ** The P1 cursor must be for a real table, not a pseudo-table.
48625 **
48626 ** See also: Prev
48627 */
48628 /* Opcode: Prev P1 P2 * * *
48629 **
48630 ** Back up cursor P1 so that it points to the previous key/data pair in its
48631 ** table or index.  If there is no previous key/value pairs then fall through
48632 ** to the following instruction.  But if the cursor backup was successful,
48633 ** jump immediately to P2.
48634 **
48635 ** The P1 cursor must be for a real table, not a pseudo-table.
48636 */
48637 case OP_Prev:          /* jump */
48638 case OP_Next: {        /* jump */
48639   Cursor *pC;
48640   BtCursor *pCrsr;
48641   int res;
48642
48643   CHECK_FOR_INTERRUPT;
48644   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
48645   pC = p->apCsr[pOp->p1];
48646   if( pC==0 ){
48647     break;  /* See ticket #2273 */
48648   }
48649   pCrsr = pC->pCursor;
48650   assert( pCrsr );
48651   res = 1;
48652   assert( pC->deferredMoveto==0 );
48653   rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(pCrsr, &res) :
48654                               sqlite3BtreePrevious(pCrsr, &res);
48655   pC->nullRow = res;
48656   pC->cacheStatus = CACHE_STALE;
48657   if( res==0 ){
48658     pc = pOp->p2 - 1;
48659 #ifdef SQLITE_TEST
48660     sqlite3_search_count++;
48661 #endif
48662   }
48663   pC->rowidIsValid = 0;
48664   break;
48665 }
48666
48667 /* Opcode: IdxInsert P1 P2 P3 * *
48668 **
48669 ** Register P2 holds a SQL index key made using the
48670 ** MakeIdxRec instructions.  This opcode writes that key
48671 ** into the index P1.  Data for the entry is nil.
48672 **
48673 ** P3 is a flag that provides a hint to the b-tree layer that this
48674 ** insert is likely to be an append.
48675 **
48676 ** This instruction only works for indices.  The equivalent instruction
48677 ** for tables is OP_Insert.
48678 */
48679 case OP_IdxInsert: {        /* in2 */
48680   int i = pOp->p1;
48681   Cursor *pC;
48682   BtCursor *pCrsr;
48683   assert( i>=0 && i<p->nCursor );
48684   assert( p->apCsr[i]!=0 );
48685   assert( pIn2->flags & MEM_Blob );
48686   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
48687     assert( pC->isTable==0 );
48688     rc = ExpandBlob(pIn2);
48689     if( rc==SQLITE_OK ){
48690       int nKey = pIn2->n;
48691       const char *zKey = pIn2->z;
48692       rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3);
48693       assert( pC->deferredMoveto==0 );
48694       pC->cacheStatus = CACHE_STALE;
48695     }
48696   }
48697   break;
48698 }
48699
48700 /* Opcode: IdxDeleteM P1 P2 P3 * *
48701 **
48702 ** The content of P3 registers starting at register P2 form
48703 ** an unpacked index key. This opcode removes that entry from the 
48704 ** index opened by cursor P1.
48705 */
48706 case OP_IdxDelete: {
48707   int i = pOp->p1;
48708   Cursor *pC;
48709   BtCursor *pCrsr;
48710   assert( pOp->p3>0 );
48711   assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem );
48712   assert( i>=0 && i<p->nCursor );
48713   assert( p->apCsr[i]!=0 );
48714   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
48715     int res;
48716     UnpackedRecord r;
48717     r.pKeyInfo = pC->pKeyInfo;
48718     r.nField = pOp->p3;
48719     r.needFree = 0;
48720     r.needDestroy = 0;
48721     r.aMem = &p->aMem[pOp->p2];
48722     rc = sqlite3BtreeMoveto(pCrsr, 0, &r, 0, 0, &res);
48723     if( rc==SQLITE_OK && res==0 ){
48724       rc = sqlite3BtreeDelete(pCrsr);
48725     }
48726     assert( pC->deferredMoveto==0 );
48727     pC->cacheStatus = CACHE_STALE;
48728   }
48729   break;
48730 }
48731
48732 /* Opcode: IdxRowid P1 P2 * * *
48733 **
48734 ** Write into register P2 an integer which is the last entry in the record at
48735 ** the end of the index key pointed to by cursor P1.  This integer should be
48736 ** the rowid of the table entry to which this index entry points.
48737 **
48738 ** See also: Rowid, MakeIdxRec.
48739 */
48740 case OP_IdxRowid: {              /* out2-prerelease */
48741   int i = pOp->p1;
48742   BtCursor *pCrsr;
48743   Cursor *pC;
48744
48745   assert( i>=0 && i<p->nCursor );
48746   assert( p->apCsr[i]!=0 );
48747   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
48748     i64 rowid;
48749
48750     assert( pC->deferredMoveto==0 );
48751     assert( pC->isTable==0 );
48752     if( !pC->nullRow ){
48753       rc = sqlite3VdbeIdxRowid(pCrsr, &rowid);
48754       if( rc!=SQLITE_OK ){
48755         goto abort_due_to_error;
48756       }
48757       MemSetTypeFlag(pOut, MEM_Int);
48758       pOut->u.i = rowid;
48759     }
48760   }
48761   break;
48762 }
48763
48764 /* Opcode: IdxGE P1 P2 P3 P4 P5
48765 **
48766 ** The P4 register values beginning with P3 form an unpacked index 
48767 ** key that omits the ROWID.  Compare this key value against the index 
48768 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
48769 **
48770 ** If the P1 index entry is greater than or equal to the key value
48771 ** then jump to P2.  Otherwise fall through to the next instruction.
48772 **
48773 ** If P5 is non-zero then the key value is increased by an epsilon 
48774 ** prior to the comparison.  This make the opcode work like IdxGT except
48775 ** that if the key from register P3 is a prefix of the key in the cursor,
48776 ** the result is false whereas it would be true with IdxGT.
48777 */
48778 /* Opcode: IdxLT P1 P2 P3 * P5
48779 **
48780 ** The P4 register values beginning with P3 form an unpacked index 
48781 ** key that omits the ROWID.  Compare this key value against the index 
48782 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
48783 **
48784 ** If the P1 index entry is less than the key value then jump to P2.
48785 ** Otherwise fall through to the next instruction.
48786 **
48787 ** If P5 is non-zero then the key value is increased by an epsilon prior 
48788 ** to the comparison.  This makes the opcode work like IdxLE.
48789 */
48790 case OP_IdxLT:          /* jump, in3 */
48791 case OP_IdxGE: {        /* jump, in3 */
48792   int i= pOp->p1;
48793   Cursor *pC;
48794
48795   assert( i>=0 && i<p->nCursor );
48796   assert( p->apCsr[i]!=0 );
48797   if( (pC = p->apCsr[i])->pCursor!=0 ){
48798     int res;
48799     UnpackedRecord r;
48800     assert( pC->deferredMoveto==0 );
48801     assert( pOp->p5==0 || pOp->p5==1 );
48802     assert( pOp->p4type==P4_INT32 );
48803     r.pKeyInfo = pC->pKeyInfo;
48804     r.nField = pOp->p4.i;
48805     r.needFree = 0;
48806     r.needDestroy = 0;
48807     r.aMem = &p->aMem[pOp->p3];
48808     *pC->pIncrKey = pOp->p5;
48809     rc = sqlite3VdbeIdxKeyCompare(pC, &r, 0, 0, &res);
48810     *pC->pIncrKey = 0;
48811     if( pOp->opcode==OP_IdxLT ){
48812       res = -res;
48813     }else{
48814       assert( pOp->opcode==OP_IdxGE );
48815       res++;
48816     }
48817     if( res>0 ){
48818       pc = pOp->p2 - 1 ;
48819     }
48820   }
48821   break;
48822 }
48823
48824 /* Opcode: Destroy P1 P2 P3 * *
48825 **
48826 ** Delete an entire database table or index whose root page in the database
48827 ** file is given by P1.
48828 **
48829 ** The table being destroyed is in the main database file if P3==0.  If
48830 ** P3==1 then the table to be clear is in the auxiliary database file
48831 ** that is used to store tables create using CREATE TEMPORARY TABLE.
48832 **
48833 ** If AUTOVACUUM is enabled then it is possible that another root page
48834 ** might be moved into the newly deleted root page in order to keep all
48835 ** root pages contiguous at the beginning of the database.  The former
48836 ** value of the root page that moved - its value before the move occurred -
48837 ** is stored in register P2.  If no page 
48838 ** movement was required (because the table being dropped was already 
48839 ** the last one in the database) then a zero is stored in register P2.
48840 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
48841 **
48842 ** See also: Clear
48843 */
48844 case OP_Destroy: {     /* out2-prerelease */
48845   int iMoved;
48846   int iCnt;
48847 #ifndef SQLITE_OMIT_VIRTUALTABLE
48848   Vdbe *pVdbe;
48849   iCnt = 0;
48850   for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
48851     if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->inVtabMethod<2 && pVdbe->pc>=0 ){
48852       iCnt++;
48853     }
48854   }
48855 #else
48856   iCnt = db->activeVdbeCnt;
48857 #endif
48858   if( iCnt>1 ){
48859     rc = SQLITE_LOCKED;
48860     p->errorAction = OE_Abort;
48861   }else{
48862     int iDb = pOp->p3;
48863     assert( iCnt==1 );
48864     assert( (p->btreeMask & (1<<iDb))!=0 );
48865     rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
48866     MemSetTypeFlag(pOut, MEM_Int);
48867     pOut->u.i = iMoved;
48868 #ifndef SQLITE_OMIT_AUTOVACUUM
48869     if( rc==SQLITE_OK && iMoved!=0 ){
48870       sqlite3RootPageMoved(&db->aDb[iDb], iMoved, pOp->p1);
48871     }
48872 #endif
48873   }
48874   break;
48875 }
48876
48877 /* Opcode: Clear P1 P2 *
48878 **
48879 ** Delete all contents of the database table or index whose root page
48880 ** in the database file is given by P1.  But, unlike Destroy, do not
48881 ** remove the table or index from the database file.
48882 **
48883 ** The table being clear is in the main database file if P2==0.  If
48884 ** P2==1 then the table to be clear is in the auxiliary database file
48885 ** that is used to store tables create using CREATE TEMPORARY TABLE.
48886 **
48887 ** See also: Destroy
48888 */
48889 case OP_Clear: {
48890   assert( (p->btreeMask & (1<<pOp->p2))!=0 );
48891   rc = sqlite3BtreeClearTable(db->aDb[pOp->p2].pBt, pOp->p1);
48892   break;
48893 }
48894
48895 /* Opcode: CreateTable P1 P2 * * *
48896 **
48897 ** Allocate a new table in the main database file if P1==0 or in the
48898 ** auxiliary database file if P1==1 or in an attached database if
48899 ** P1>1.  Write the root page number of the new table into
48900 ** register P2
48901 **
48902 ** The difference between a table and an index is this:  A table must
48903 ** have a 4-byte integer key and can have arbitrary data.  An index
48904 ** has an arbitrary key but no data.
48905 **
48906 ** See also: CreateIndex
48907 */
48908 /* Opcode: CreateIndex P1 P2 * * *
48909 **
48910 ** Allocate a new index in the main database file if P1==0 or in the
48911 ** auxiliary database file if P1==1 or in an attached database if
48912 ** P1>1.  Write the root page number of the new table into
48913 ** register P2.
48914 **
48915 ** See documentation on OP_CreateTable for additional information.
48916 */
48917 case OP_CreateIndex:            /* out2-prerelease */
48918 case OP_CreateTable: {          /* out2-prerelease */
48919   int pgno;
48920   int flags;
48921   Db *pDb;
48922   assert( pOp->p1>=0 && pOp->p1<db->nDb );
48923   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
48924   pDb = &db->aDb[pOp->p1];
48925   assert( pDb->pBt!=0 );
48926   if( pOp->opcode==OP_CreateTable ){
48927     /* flags = BTREE_INTKEY; */
48928     flags = BTREE_LEAFDATA|BTREE_INTKEY;
48929   }else{
48930     flags = BTREE_ZERODATA;
48931   }
48932   rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
48933   if( rc==SQLITE_OK ){
48934     pOut->u.i = pgno;
48935     MemSetTypeFlag(pOut, MEM_Int);
48936   }
48937   break;
48938 }
48939
48940 /* Opcode: ParseSchema P1 P2 * P4 *
48941 **
48942 ** Read and parse all entries from the SQLITE_MASTER table of database P1
48943 ** that match the WHERE clause P4.  P2 is the "force" flag.   Always do
48944 ** the parsing if P2 is true.  If P2 is false, then this routine is a
48945 ** no-op if the schema is not currently loaded.  In other words, if P2
48946 ** is false, the SQLITE_MASTER table is only parsed if the rest of the
48947 ** schema is already loaded into the symbol table.
48948 **
48949 ** This opcode invokes the parser to create a new virtual machine,
48950 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
48951 */
48952 case OP_ParseSchema: {
48953   char *zSql;
48954   int iDb = pOp->p1;
48955   const char *zMaster;
48956   InitData initData;
48957
48958   assert( iDb>=0 && iDb<db->nDb );
48959   if( !pOp->p2 && !DbHasProperty(db, iDb, DB_SchemaLoaded) ){
48960     break;
48961   }
48962   zMaster = SCHEMA_TABLE(iDb);
48963   initData.db = db;
48964   initData.iDb = pOp->p1;
48965   initData.pzErrMsg = &p->zErrMsg;
48966   zSql = sqlite3MPrintf(db,
48967      "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s",
48968      db->aDb[iDb].zName, zMaster, pOp->p4.z);
48969   if( zSql==0 ) goto no_mem;
48970   (void)sqlite3SafetyOff(db);
48971   assert( db->init.busy==0 );
48972   db->init.busy = 1;
48973   assert( !db->mallocFailed );
48974   rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
48975   if( rc==SQLITE_ABORT ) rc = initData.rc;
48976   sqlite3DbFree(db, zSql);
48977   db->init.busy = 0;
48978   (void)sqlite3SafetyOn(db);
48979   if( rc==SQLITE_NOMEM ){
48980     goto no_mem;
48981   }
48982   break;  
48983 }
48984
48985 #if !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER)
48986 /* Opcode: LoadAnalysis P1 * * * *
48987 **
48988 ** Read the sqlite_stat1 table for database P1 and load the content
48989 ** of that table into the internal index hash table.  This will cause
48990 ** the analysis to be used when preparing all subsequent queries.
48991 */
48992 case OP_LoadAnalysis: {
48993   int iDb = pOp->p1;
48994   assert( iDb>=0 && iDb<db->nDb );
48995   rc = sqlite3AnalysisLoad(db, iDb);
48996   break;  
48997 }
48998 #endif /* !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER)  */
48999
49000 /* Opcode: DropTable P1 * * P4 *
49001 **
49002 ** Remove the internal (in-memory) data structures that describe
49003 ** the table named P4 in database P1.  This is called after a table
49004 ** is dropped in order to keep the internal representation of the
49005 ** schema consistent with what is on disk.
49006 */
49007 case OP_DropTable: {
49008   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
49009   break;
49010 }
49011
49012 /* Opcode: DropIndex P1 * * P4 *
49013 **
49014 ** Remove the internal (in-memory) data structures that describe
49015 ** the index named P4 in database P1.  This is called after an index
49016 ** is dropped in order to keep the internal representation of the
49017 ** schema consistent with what is on disk.
49018 */
49019 case OP_DropIndex: {
49020   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
49021   break;
49022 }
49023
49024 /* Opcode: DropTrigger P1 * * P4 *
49025 **
49026 ** Remove the internal (in-memory) data structures that describe
49027 ** the trigger named P4 in database P1.  This is called after a trigger
49028 ** is dropped in order to keep the internal representation of the
49029 ** schema consistent with what is on disk.
49030 */
49031 case OP_DropTrigger: {
49032   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
49033   break;
49034 }
49035
49036
49037 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
49038 /* Opcode: IntegrityCk P1 P2 P3 * P5
49039 **
49040 ** Do an analysis of the currently open database.  Store in
49041 ** register P1 the text of an error message describing any problems.
49042 ** If no problems are found, store a NULL in register P1.
49043 **
49044 ** The register P3 contains the maximum number of allowed errors.
49045 ** At most reg(P3) errors will be reported.
49046 ** In other words, the analysis stops as soon as reg(P1) errors are 
49047 ** seen.  Reg(P1) is updated with the number of errors remaining.
49048 **
49049 ** The root page numbers of all tables in the database are integer
49050 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
49051 ** total.
49052 **
49053 ** If P5 is not zero, the check is done on the auxiliary database
49054 ** file, not the main database file.
49055 **
49056 ** This opcode is used to implement the integrity_check pragma.
49057 */
49058 case OP_IntegrityCk: {
49059   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
49060   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
49061   int j;          /* Loop counter */
49062   int nErr;       /* Number of errors reported */
49063   char *z;        /* Text of the error report */
49064   Mem *pnErr;     /* Register keeping track of errors remaining */
49065   
49066   nRoot = pOp->p2;
49067   assert( nRoot>0 );
49068   aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) );
49069   if( aRoot==0 ) goto no_mem;
49070   assert( pOp->p3>0 && pOp->p3<=p->nMem );
49071   pnErr = &p->aMem[pOp->p3];
49072   assert( (pnErr->flags & MEM_Int)!=0 );
49073   assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
49074   pIn1 = &p->aMem[pOp->p1];
49075   for(j=0; j<nRoot; j++){
49076     aRoot[j] = sqlite3VdbeIntValue(&pIn1[j]);
49077   }
49078   aRoot[j] = 0;
49079   assert( pOp->p5<db->nDb );
49080   assert( (p->btreeMask & (1<<pOp->p5))!=0 );
49081   z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
49082                                  pnErr->u.i, &nErr);
49083   sqlite3DbFree(db, aRoot);
49084   pnErr->u.i -= nErr;
49085   sqlite3VdbeMemSetNull(pIn1);
49086   if( nErr==0 ){
49087     assert( z==0 );
49088   }else if( z==0 ){
49089     goto no_mem;
49090   }else{
49091     sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
49092   }
49093   UPDATE_MAX_BLOBSIZE(pIn1);
49094   sqlite3VdbeChangeEncoding(pIn1, encoding);
49095   break;
49096 }
49097 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
49098
49099 /* Opcode: FifoWrite P1 * * * *
49100 **
49101 ** Write the integer from register P1 into the Fifo.
49102 */
49103 case OP_FifoWrite: {        /* in1 */
49104   p->sFifo.db = db;
49105   if( sqlite3VdbeFifoPush(&p->sFifo, sqlite3VdbeIntValue(pIn1))==SQLITE_NOMEM ){
49106     goto no_mem;
49107   }
49108   break;
49109 }
49110
49111 /* Opcode: FifoRead P1 P2 * * *
49112 **
49113 ** Attempt to read a single integer from the Fifo.  Store that
49114 ** integer in register P1.
49115 ** 
49116 ** If the Fifo is empty jump to P2.
49117 */
49118 case OP_FifoRead: {         /* jump */
49119   CHECK_FOR_INTERRUPT;
49120   assert( pOp->p1>0 && pOp->p1<=p->nMem );
49121   pOut = &p->aMem[pOp->p1];
49122   MemSetTypeFlag(pOut, MEM_Int);
49123   if( sqlite3VdbeFifoPop(&p->sFifo, &pOut->u.i)==SQLITE_DONE ){
49124     pc = pOp->p2 - 1;
49125   }
49126   break;
49127 }
49128
49129 #ifndef SQLITE_OMIT_TRIGGER
49130 /* Opcode: ContextPush * * * 
49131 **
49132 ** Save the current Vdbe context such that it can be restored by a ContextPop
49133 ** opcode. The context stores the last insert row id, the last statement change
49134 ** count, and the current statement change count.
49135 */
49136 case OP_ContextPush: {
49137   int i = p->contextStackTop++;
49138   Context *pContext;
49139
49140   assert( i>=0 );
49141   /* FIX ME: This should be allocated as part of the vdbe at compile-time */
49142   if( i>=p->contextStackDepth ){
49143     p->contextStackDepth = i+1;
49144     p->contextStack = sqlite3DbReallocOrFree(db, p->contextStack,
49145                                           sizeof(Context)*(i+1));
49146     if( p->contextStack==0 ) goto no_mem;
49147   }
49148   pContext = &p->contextStack[i];
49149   pContext->lastRowid = db->lastRowid;
49150   pContext->nChange = p->nChange;
49151   pContext->sFifo = p->sFifo;
49152   sqlite3VdbeFifoInit(&p->sFifo, db);
49153   break;
49154 }
49155
49156 /* Opcode: ContextPop * * * 
49157 **
49158 ** Restore the Vdbe context to the state it was in when contextPush was last
49159 ** executed. The context stores the last insert row id, the last statement
49160 ** change count, and the current statement change count.
49161 */
49162 case OP_ContextPop: {
49163   Context *pContext = &p->contextStack[--p->contextStackTop];
49164   assert( p->contextStackTop>=0 );
49165   db->lastRowid = pContext->lastRowid;
49166   p->nChange = pContext->nChange;
49167   sqlite3VdbeFifoClear(&p->sFifo);
49168   p->sFifo = pContext->sFifo;
49169   break;
49170 }
49171 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
49172
49173 #ifndef SQLITE_OMIT_AUTOINCREMENT
49174 /* Opcode: MemMax P1 P2 * * *
49175 **
49176 ** Set the value of register P1 to the maximum of its current value
49177 ** and the value in register P2.
49178 **
49179 ** This instruction throws an error if the memory cell is not initially
49180 ** an integer.
49181 */
49182 case OP_MemMax: {        /* in1, in2 */
49183   sqlite3VdbeMemIntegerify(pIn1);
49184   sqlite3VdbeMemIntegerify(pIn2);
49185   if( pIn1->u.i<pIn2->u.i){
49186     pIn1->u.i = pIn2->u.i;
49187   }
49188   break;
49189 }
49190 #endif /* SQLITE_OMIT_AUTOINCREMENT */
49191
49192 /* Opcode: IfPos P1 P2 * * *
49193 **
49194 ** If the value of register P1 is 1 or greater, jump to P2.
49195 **
49196 ** It is illegal to use this instruction on a register that does
49197 ** not contain an integer.  An assertion fault will result if you try.
49198 */
49199 case OP_IfPos: {        /* jump, in1 */
49200   assert( pIn1->flags&MEM_Int );
49201   if( pIn1->u.i>0 ){
49202      pc = pOp->p2 - 1;
49203   }
49204   break;
49205 }
49206
49207 /* Opcode: IfNeg P1 P2 * * *
49208 **
49209 ** If the value of register P1 is less than zero, jump to P2. 
49210 **
49211 ** It is illegal to use this instruction on a register that does
49212 ** not contain an integer.  An assertion fault will result if you try.
49213 */
49214 case OP_IfNeg: {        /* jump, in1 */
49215   assert( pIn1->flags&MEM_Int );
49216   if( pIn1->u.i<0 ){
49217      pc = pOp->p2 - 1;
49218   }
49219   break;
49220 }
49221
49222 /* Opcode: IfZero P1 P2 * * *
49223 **
49224 ** If the value of register P1 is exactly 0, jump to P2. 
49225 **
49226 ** It is illegal to use this instruction on a register that does
49227 ** not contain an integer.  An assertion fault will result if you try.
49228 */
49229 case OP_IfZero: {        /* jump, in1 */
49230   assert( pIn1->flags&MEM_Int );
49231   if( pIn1->u.i==0 ){
49232      pc = pOp->p2 - 1;
49233   }
49234   break;
49235 }
49236
49237 /* Opcode: AggStep * P2 P3 P4 P5
49238 **
49239 ** Execute the step function for an aggregate.  The
49240 ** function has P5 arguments.   P4 is a pointer to the FuncDef
49241 ** structure that specifies the function.  Use register
49242 ** P3 as the accumulator.
49243 **
49244 ** The P5 arguments are taken from register P2 and its
49245 ** successors.
49246 */
49247 case OP_AggStep: {
49248   int n = pOp->p5;
49249   int i;
49250   Mem *pMem, *pRec;
49251   sqlite3_context ctx;
49252   sqlite3_value **apVal;
49253
49254   assert( n>=0 );
49255   pRec = &p->aMem[pOp->p2];
49256   apVal = p->apArg;
49257   assert( apVal || n==0 );
49258   for(i=0; i<n; i++, pRec++){
49259     apVal[i] = pRec;
49260     storeTypeInfo(pRec, encoding);
49261   }
49262   ctx.pFunc = pOp->p4.pFunc;
49263   assert( pOp->p3>0 && pOp->p3<=p->nMem );
49264   ctx.pMem = pMem = &p->aMem[pOp->p3];
49265   pMem->n++;
49266   ctx.s.flags = MEM_Null;
49267   ctx.s.z = 0;
49268   ctx.s.zMalloc = 0;
49269   ctx.s.xDel = 0;
49270   ctx.s.db = db;
49271   ctx.isError = 0;
49272   ctx.pColl = 0;
49273   if( ctx.pFunc->needCollSeq ){
49274     assert( pOp>p->aOp );
49275     assert( pOp[-1].p4type==P4_COLLSEQ );
49276     assert( pOp[-1].opcode==OP_CollSeq );
49277     ctx.pColl = pOp[-1].p4.pColl;
49278   }
49279   (ctx.pFunc->xStep)(&ctx, n, apVal);
49280   if( ctx.isError ){
49281     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s));
49282     rc = ctx.isError;
49283   }
49284   sqlite3VdbeMemRelease(&ctx.s);
49285   break;
49286 }
49287
49288 /* Opcode: AggFinal P1 P2 * P4 *
49289 **
49290 ** Execute the finalizer function for an aggregate.  P1 is
49291 ** the memory location that is the accumulator for the aggregate.
49292 **
49293 ** P2 is the number of arguments that the step function takes and
49294 ** P4 is a pointer to the FuncDef for this function.  The P2
49295 ** argument is not used by this opcode.  It is only there to disambiguate
49296 ** functions that can take varying numbers of arguments.  The
49297 ** P4 argument is only needed for the degenerate case where
49298 ** the step function was not previously called.
49299 */
49300 case OP_AggFinal: {
49301   Mem *pMem;
49302   assert( pOp->p1>0 && pOp->p1<=p->nMem );
49303   pMem = &p->aMem[pOp->p1];
49304   assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
49305   rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
49306   if( rc==SQLITE_ERROR ){
49307     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(pMem));
49308   }
49309   sqlite3VdbeChangeEncoding(pMem, encoding);
49310   UPDATE_MAX_BLOBSIZE(pMem);
49311   if( sqlite3VdbeMemTooBig(pMem) ){
49312     goto too_big;
49313   }
49314   break;
49315 }
49316
49317
49318 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
49319 /* Opcode: Vacuum * * * * *
49320 **
49321 ** Vacuum the entire database.  This opcode will cause other virtual
49322 ** machines to be created and run.  It may not be called from within
49323 ** a transaction.
49324 */
49325 case OP_Vacuum: {
49326   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse; 
49327   rc = sqlite3RunVacuum(&p->zErrMsg, db);
49328   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
49329   break;
49330 }
49331 #endif
49332
49333 #if !defined(SQLITE_OMIT_AUTOVACUUM)
49334 /* Opcode: IncrVacuum P1 P2 * * *
49335 **
49336 ** Perform a single step of the incremental vacuum procedure on
49337 ** the P1 database. If the vacuum has finished, jump to instruction
49338 ** P2. Otherwise, fall through to the next instruction.
49339 */
49340 case OP_IncrVacuum: {        /* jump */
49341   Btree *pBt;
49342
49343   assert( pOp->p1>=0 && pOp->p1<db->nDb );
49344   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
49345   pBt = db->aDb[pOp->p1].pBt;
49346   rc = sqlite3BtreeIncrVacuum(pBt);
49347   if( rc==SQLITE_DONE ){
49348     pc = pOp->p2 - 1;
49349     rc = SQLITE_OK;
49350   }
49351   break;
49352 }
49353 #endif
49354
49355 /* Opcode: Expire P1 * * * *
49356 **
49357 ** Cause precompiled statements to become expired. An expired statement
49358 ** fails with an error code of SQLITE_SCHEMA if it is ever executed 
49359 ** (via sqlite3_step()).
49360 ** 
49361 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
49362 ** then only the currently executing statement is affected. 
49363 */
49364 case OP_Expire: {
49365   if( !pOp->p1 ){
49366     sqlite3ExpirePreparedStatements(db);
49367   }else{
49368     p->expired = 1;
49369   }
49370   break;
49371 }
49372
49373 #ifndef SQLITE_OMIT_SHARED_CACHE
49374 /* Opcode: TableLock P1 P2 P3 P4 *
49375 **
49376 ** Obtain a lock on a particular table. This instruction is only used when
49377 ** the shared-cache feature is enabled. 
49378 **
49379 ** If P1 is  the index of the database in sqlite3.aDb[] of the database
49380 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
49381 ** a write lock if P3==1.
49382 **
49383 ** P2 contains the root-page of the table to lock.
49384 **
49385 ** P4 contains a pointer to the name of the table being locked. This is only
49386 ** used to generate an error message if the lock cannot be obtained.
49387 */
49388 case OP_TableLock: {
49389   int p1 = pOp->p1; 
49390   u8 isWriteLock = pOp->p3;
49391   assert( p1>=0 && p1<db->nDb );
49392   assert( (p->btreeMask & (1<<p1))!=0 );
49393   assert( isWriteLock==0 || isWriteLock==1 );
49394   rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
49395   if( rc==SQLITE_LOCKED ){
49396     const char *z = pOp->p4.z;
49397     sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
49398   }
49399   break;
49400 }
49401 #endif /* SQLITE_OMIT_SHARED_CACHE */
49402
49403 #ifndef SQLITE_OMIT_VIRTUALTABLE
49404 /* Opcode: VBegin * * * P4 *
49405 **
49406 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the 
49407 ** xBegin method for that table.
49408 **
49409 ** Also, whether or not P4 is set, check that this is not being called from
49410 ** within a callback to a virtual table xSync() method. If it is, set the
49411 ** error code to SQLITE_LOCKED.
49412 */
49413 case OP_VBegin: {
49414   sqlite3_vtab *pVtab = pOp->p4.pVtab;
49415   rc = sqlite3VtabBegin(db, pVtab);
49416   if( pVtab ){
49417     sqlite3DbFree(db, p->zErrMsg);
49418     p->zErrMsg = pVtab->zErrMsg;
49419     pVtab->zErrMsg = 0;
49420   }
49421   break;
49422 }
49423 #endif /* SQLITE_OMIT_VIRTUALTABLE */
49424
49425 #ifndef SQLITE_OMIT_VIRTUALTABLE
49426 /* Opcode: VCreate P1 * * P4 *
49427 **
49428 ** P4 is the name of a virtual table in database P1. Call the xCreate method
49429 ** for that table.
49430 */
49431 case OP_VCreate: {
49432   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
49433   break;
49434 }
49435 #endif /* SQLITE_OMIT_VIRTUALTABLE */
49436
49437 #ifndef SQLITE_OMIT_VIRTUALTABLE
49438 /* Opcode: VDestroy P1 * * P4 *
49439 **
49440 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
49441 ** of that table.
49442 */
49443 case OP_VDestroy: {
49444   p->inVtabMethod = 2;
49445   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
49446   p->inVtabMethod = 0;
49447   break;
49448 }
49449 #endif /* SQLITE_OMIT_VIRTUALTABLE */
49450
49451 #ifndef SQLITE_OMIT_VIRTUALTABLE
49452 /* Opcode: VOpen P1 * * P4 *
49453 **
49454 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
49455 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
49456 ** table and stores that cursor in P1.
49457 */
49458 case OP_VOpen: {
49459   Cursor *pCur = 0;
49460   sqlite3_vtab_cursor *pVtabCursor = 0;
49461
49462   sqlite3_vtab *pVtab = pOp->p4.pVtab;
49463   sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
49464
49465   assert(pVtab && pModule);
49466   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
49467   rc = pModule->xOpen(pVtab, &pVtabCursor);
49468   sqlite3DbFree(db, p->zErrMsg);
49469   p->zErrMsg = pVtab->zErrMsg;
49470   pVtab->zErrMsg = 0;
49471   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
49472   if( SQLITE_OK==rc ){
49473     /* Initialize sqlite3_vtab_cursor base class */
49474     pVtabCursor->pVtab = pVtab;
49475
49476     /* Initialise vdbe cursor object */
49477     pCur = allocateCursor(p, pOp->p1, &pOp[-1], -1, 0);
49478     if( pCur ){
49479       pCur->pVtabCursor = pVtabCursor;
49480       pCur->pModule = pVtabCursor->pVtab->pModule;
49481     }else{
49482       db->mallocFailed = 1;
49483       pModule->xClose(pVtabCursor);
49484     }
49485   }
49486   break;
49487 }
49488 #endif /* SQLITE_OMIT_VIRTUALTABLE */
49489
49490 #ifndef SQLITE_OMIT_VIRTUALTABLE
49491 /* Opcode: VFilter P1 P2 P3 P4 *
49492 **
49493 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
49494 ** the filtered result set is empty.
49495 **
49496 ** P4 is either NULL or a string that was generated by the xBestIndex
49497 ** method of the module.  The interpretation of the P4 string is left
49498 ** to the module implementation.
49499 **
49500 ** This opcode invokes the xFilter method on the virtual table specified
49501 ** by P1.  The integer query plan parameter to xFilter is stored in register
49502 ** P3. Register P3+1 stores the argc parameter to be passed to the
49503 ** xFilter method. Registers P3+2..P3+1+argc are the argc
49504 ** additional parameters which are passed to
49505 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
49506 **
49507 ** A jump is made to P2 if the result set after filtering would be empty.
49508 */
49509 case OP_VFilter: {   /* jump */
49510   int nArg;
49511   int iQuery;
49512   const sqlite3_module *pModule;
49513   Mem *pQuery = &p->aMem[pOp->p3];
49514   Mem *pArgc = &pQuery[1];
49515   sqlite3_vtab_cursor *pVtabCursor;
49516   sqlite3_vtab *pVtab;
49517
49518   Cursor *pCur = p->apCsr[pOp->p1];
49519
49520   REGISTER_TRACE(pOp->p3, pQuery);
49521   assert( pCur->pVtabCursor );
49522   pVtabCursor = pCur->pVtabCursor;
49523   pVtab = pVtabCursor->pVtab;
49524   pModule = pVtab->pModule;
49525
49526   /* Grab the index number and argc parameters */
49527   assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
49528   nArg = pArgc->u.i;
49529   iQuery = pQuery->u.i;
49530
49531   /* Invoke the xFilter method */
49532   {
49533     int res = 0;
49534     int i;
49535     Mem **apArg = p->apArg;
49536     for(i = 0; i<nArg; i++){
49537       apArg[i] = &pArgc[i+1];
49538       storeTypeInfo(apArg[i], 0);
49539     }
49540
49541     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
49542     sqlite3VtabLock(pVtab);
49543     p->inVtabMethod = 1;
49544     rc = pModule->xFilter(pVtabCursor, iQuery, pOp->p4.z, nArg, apArg);
49545     p->inVtabMethod = 0;
49546     sqlite3DbFree(db, p->zErrMsg);
49547     p->zErrMsg = pVtab->zErrMsg;
49548     pVtab->zErrMsg = 0;
49549     sqlite3VtabUnlock(db, pVtab);
49550     if( rc==SQLITE_OK ){
49551       res = pModule->xEof(pVtabCursor);
49552     }
49553     if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
49554
49555     if( res ){
49556       pc = pOp->p2 - 1;
49557     }
49558   }
49559   pCur->nullRow = 0;
49560
49561   break;
49562 }
49563 #endif /* SQLITE_OMIT_VIRTUALTABLE */
49564
49565 #ifndef SQLITE_OMIT_VIRTUALTABLE
49566 /* Opcode: VRowid P1 P2 * * *
49567 **
49568 ** Store into register P2  the rowid of
49569 ** the virtual-table that the P1 cursor is pointing to.
49570 */
49571 case OP_VRowid: {             /* out2-prerelease */
49572   sqlite3_vtab *pVtab;
49573   const sqlite3_module *pModule;
49574   sqlite_int64 iRow;
49575   Cursor *pCur = p->apCsr[pOp->p1];
49576
49577   assert( pCur->pVtabCursor );
49578   if( pCur->nullRow ){
49579     break;
49580   }
49581   pVtab = pCur->pVtabCursor->pVtab;
49582   pModule = pVtab->pModule;
49583   assert( pModule->xRowid );
49584   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
49585   rc = pModule->xRowid(pCur->pVtabCursor, &iRow);
49586   sqlite3DbFree(db, p->zErrMsg);
49587   p->zErrMsg = pVtab->zErrMsg;
49588   pVtab->zErrMsg = 0;
49589   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
49590   MemSetTypeFlag(pOut, MEM_Int);
49591   pOut->u.i = iRow;
49592   break;
49593 }
49594 #endif /* SQLITE_OMIT_VIRTUALTABLE */
49595
49596 #ifndef SQLITE_OMIT_VIRTUALTABLE
49597 /* Opcode: VColumn P1 P2 P3 * *
49598 **
49599 ** Store the value of the P2-th column of
49600 ** the row of the virtual-table that the 
49601 ** P1 cursor is pointing to into register P3.
49602 */
49603 case OP_VColumn: {
49604   sqlite3_vtab *pVtab;
49605   const sqlite3_module *pModule;
49606   Mem *pDest;
49607   sqlite3_context sContext;
49608
49609   Cursor *pCur = p->apCsr[pOp->p1];
49610   assert( pCur->pVtabCursor );
49611   assert( pOp->p3>0 && pOp->p3<=p->nMem );
49612   pDest = &p->aMem[pOp->p3];
49613   if( pCur->nullRow ){
49614     sqlite3VdbeMemSetNull(pDest);
49615     break;
49616   }
49617   pVtab = pCur->pVtabCursor->pVtab;
49618   pModule = pVtab->pModule;
49619   assert( pModule->xColumn );
49620   memset(&sContext, 0, sizeof(sContext));
49621
49622   /* The output cell may already have a buffer allocated. Move
49623   ** the current contents to sContext.s so in case the user-function 
49624   ** can use the already allocated buffer instead of allocating a 
49625   ** new one.
49626   */
49627   sqlite3VdbeMemMove(&sContext.s, pDest);
49628   MemSetTypeFlag(&sContext.s, MEM_Null);
49629
49630   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
49631   rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
49632   sqlite3DbFree(db, p->zErrMsg);
49633   p->zErrMsg = pVtab->zErrMsg;
49634   pVtab->zErrMsg = 0;
49635
49636   /* Copy the result of the function to the P3 register. We
49637   ** do this regardless of whether or not an error occured to ensure any
49638   ** dynamic allocation in sContext.s (a Mem struct) is  released.
49639   */
49640   sqlite3VdbeChangeEncoding(&sContext.s, encoding);
49641   REGISTER_TRACE(pOp->p3, pDest);
49642   sqlite3VdbeMemMove(pDest, &sContext.s);
49643   UPDATE_MAX_BLOBSIZE(pDest);
49644
49645   if( sqlite3SafetyOn(db) ){
49646     goto abort_due_to_misuse;
49647   }
49648   if( sqlite3VdbeMemTooBig(pDest) ){
49649     goto too_big;
49650   }
49651   break;
49652 }
49653 #endif /* SQLITE_OMIT_VIRTUALTABLE */
49654
49655 #ifndef SQLITE_OMIT_VIRTUALTABLE
49656 /* Opcode: VNext P1 P2 * * *
49657 **
49658 ** Advance virtual table P1 to the next row in its result set and
49659 ** jump to instruction P2.  Or, if the virtual table has reached
49660 ** the end of its result set, then fall through to the next instruction.
49661 */
49662 case OP_VNext: {   /* jump */
49663   sqlite3_vtab *pVtab;
49664   const sqlite3_module *pModule;
49665   int res = 0;
49666
49667   Cursor *pCur = p->apCsr[pOp->p1];
49668   assert( pCur->pVtabCursor );
49669   if( pCur->nullRow ){
49670     break;
49671   }
49672   pVtab = pCur->pVtabCursor->pVtab;
49673   pModule = pVtab->pModule;
49674   assert( pModule->xNext );
49675
49676   /* Invoke the xNext() method of the module. There is no way for the
49677   ** underlying implementation to return an error if one occurs during
49678   ** xNext(). Instead, if an error occurs, true is returned (indicating that 
49679   ** data is available) and the error code returned when xColumn or
49680   ** some other method is next invoked on the save virtual table cursor.
49681   */
49682   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
49683   sqlite3VtabLock(pVtab);
49684   p->inVtabMethod = 1;
49685   rc = pModule->xNext(pCur->pVtabCursor);
49686   p->inVtabMethod = 0;
49687   sqlite3DbFree(db, p->zErrMsg);
49688   p->zErrMsg = pVtab->zErrMsg;
49689   pVtab->zErrMsg = 0;
49690   sqlite3VtabUnlock(db, pVtab);
49691   if( rc==SQLITE_OK ){
49692     res = pModule->xEof(pCur->pVtabCursor);
49693   }
49694   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
49695
49696   if( !res ){
49697     /* If there is data, jump to P2 */
49698     pc = pOp->p2 - 1;
49699   }
49700   break;
49701 }
49702 #endif /* SQLITE_OMIT_VIRTUALTABLE */
49703
49704 #ifndef SQLITE_OMIT_VIRTUALTABLE
49705 /* Opcode: VRename P1 * * P4 *
49706 **
49707 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
49708 ** This opcode invokes the corresponding xRename method. The value
49709 ** in register P1 is passed as the zName argument to the xRename method.
49710 */
49711 case OP_VRename: {
49712   sqlite3_vtab *pVtab = pOp->p4.pVtab;
49713   Mem *pName = &p->aMem[pOp->p1];
49714   assert( pVtab->pModule->xRename );
49715   REGISTER_TRACE(pOp->p1, pName);
49716
49717   Stringify(pName, encoding);
49718
49719   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
49720   sqlite3VtabLock(pVtab);
49721   rc = pVtab->pModule->xRename(pVtab, pName->z);
49722   sqlite3DbFree(db, p->zErrMsg);
49723   p->zErrMsg = pVtab->zErrMsg;
49724   pVtab->zErrMsg = 0;
49725   sqlite3VtabUnlock(db, pVtab);
49726   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
49727
49728   break;
49729 }
49730 #endif
49731
49732 #ifndef SQLITE_OMIT_VIRTUALTABLE
49733 /* Opcode: VUpdate P1 P2 P3 P4 *
49734 **
49735 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
49736 ** This opcode invokes the corresponding xUpdate method. P2 values
49737 ** are contiguous memory cells starting at P3 to pass to the xUpdate 
49738 ** invocation. The value in register (P3+P2-1) corresponds to the 
49739 ** p2th element of the argv array passed to xUpdate.
49740 **
49741 ** The xUpdate method will do a DELETE or an INSERT or both.
49742 ** The argv[0] element (which corresponds to memory cell P3)
49743 ** is the rowid of a row to delete.  If argv[0] is NULL then no 
49744 ** deletion occurs.  The argv[1] element is the rowid of the new 
49745 ** row.  This can be NULL to have the virtual table select the new 
49746 ** rowid for itself.  The subsequent elements in the array are 
49747 ** the values of columns in the new row.
49748 **
49749 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
49750 ** a row to delete.
49751 **
49752 ** P1 is a boolean flag. If it is set to true and the xUpdate call
49753 ** is successful, then the value returned by sqlite3_last_insert_rowid() 
49754 ** is set to the value of the rowid for the row just inserted.
49755 */
49756 case OP_VUpdate: {
49757   sqlite3_vtab *pVtab = pOp->p4.pVtab;
49758   sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
49759   int nArg = pOp->p2;
49760   assert( pOp->p4type==P4_VTAB );
49761   if( pModule->xUpdate==0 ){
49762     sqlite3SetString(&p->zErrMsg, db, "read-only table");
49763     rc = SQLITE_ERROR;
49764   }else{
49765     int i;
49766     sqlite_int64 rowid;
49767     Mem **apArg = p->apArg;
49768     Mem *pX = &p->aMem[pOp->p3];
49769     for(i=0; i<nArg; i++){
49770       storeTypeInfo(pX, 0);
49771       apArg[i] = pX;
49772       pX++;
49773     }
49774     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
49775     sqlite3VtabLock(pVtab);
49776     rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
49777     sqlite3DbFree(db, p->zErrMsg);
49778     p->zErrMsg = pVtab->zErrMsg;
49779     pVtab->zErrMsg = 0;
49780     sqlite3VtabUnlock(db, pVtab);
49781     if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
49782     if( pOp->p1 && rc==SQLITE_OK ){
49783       assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
49784       db->lastRowid = rowid;
49785     }
49786     p->nChange++;
49787   }
49788   break;
49789 }
49790 #endif /* SQLITE_OMIT_VIRTUALTABLE */
49791
49792 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
49793 /* Opcode: Pagecount P1 P2 * * *
49794 **
49795 ** Write the current number of pages in database P1 to memory cell P2.
49796 */
49797 case OP_Pagecount: {            /* out2-prerelease */
49798   int p1 = pOp->p1; 
49799   int nPage;
49800   Pager *pPager = sqlite3BtreePager(db->aDb[p1].pBt);
49801
49802   rc = sqlite3PagerPagecount(pPager, &nPage);
49803   if( rc==SQLITE_OK ){
49804     pOut->flags = MEM_Int;
49805     pOut->u.i = nPage;
49806   }
49807   break;
49808 }
49809 #endif
49810
49811 #ifndef SQLITE_OMIT_TRACE
49812 /* Opcode: Trace * * * P4 *
49813 **
49814 ** If tracing is enabled (by the sqlite3_trace()) interface, then
49815 ** the UTF-8 string contained in P4 is emitted on the trace callback.
49816 */
49817 case OP_Trace: {
49818   if( pOp->p4.z ){
49819     if( db->xTrace ){
49820       db->xTrace(db->pTraceArg, pOp->p4.z);
49821     }
49822 #ifdef SQLITE_DEBUG
49823     if( (db->flags & SQLITE_SqlTrace)!=0 ){
49824       sqlite3DebugPrintf("SQL-trace: %s\n", pOp->p4.z);
49825     }
49826 #endif /* SQLITE_DEBUG */
49827   }
49828   break;
49829 }
49830 #endif
49831
49832
49833 /* Opcode: Noop * * * * *
49834 **
49835 ** Do nothing.  This instruction is often useful as a jump
49836 ** destination.
49837 */
49838 /*
49839 ** The magic Explain opcode are only inserted when explain==2 (which
49840 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
49841 ** This opcode records information from the optimizer.  It is the
49842 ** the same as a no-op.  This opcodesnever appears in a real VM program.
49843 */
49844 default: {          /* This is really OP_Noop and OP_Explain */
49845   break;
49846 }
49847
49848 /*****************************************************************************
49849 ** The cases of the switch statement above this line should all be indented
49850 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
49851 ** readability.  From this point on down, the normal indentation rules are
49852 ** restored.
49853 *****************************************************************************/
49854     }
49855
49856 #ifdef VDBE_PROFILE
49857     {
49858       u64 elapsed = sqlite3Hwtime() - start;
49859       pOp->cycles += elapsed;
49860       pOp->cnt++;
49861 #if 0
49862         fprintf(stdout, "%10llu ", elapsed);
49863         sqlite3VdbePrintOp(stdout, origPc, &p->aOp[origPc]);
49864 #endif
49865     }
49866 #endif
49867
49868     /* The following code adds nothing to the actual functionality
49869     ** of the program.  It is only here for testing and debugging.
49870     ** On the other hand, it does burn CPU cycles every time through
49871     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
49872     */
49873 #ifndef NDEBUG
49874     assert( pc>=-1 && pc<p->nOp );
49875
49876 #ifdef SQLITE_DEBUG
49877     if( p->trace ){
49878       if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
49879       if( opProperty & OPFLG_OUT2_PRERELEASE ){
49880         registerTrace(p->trace, pOp->p2, pOut);
49881       }
49882       if( opProperty & OPFLG_OUT3 ){
49883         registerTrace(p->trace, pOp->p3, pOut);
49884       }
49885     }
49886 #endif  /* SQLITE_DEBUG */
49887 #endif  /* NDEBUG */
49888   }  /* The end of the for(;;) loop the loops through opcodes */
49889
49890   /* If we reach this point, it means that execution is finished with
49891   ** an error of some kind.
49892   */
49893 vdbe_error_halt:
49894   assert( rc );
49895   p->rc = rc;
49896   sqlite3VdbeHalt(p);
49897   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
49898   rc = SQLITE_ERROR;
49899
49900   /* This is the only way out of this procedure.  We have to
49901   ** release the mutexes on btrees that were acquired at the
49902   ** top. */
49903 vdbe_return:
49904   sqlite3BtreeMutexArrayLeave(&p->aMutex);
49905   return rc;
49906
49907   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
49908   ** is encountered.
49909   */
49910 too_big:
49911   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
49912   rc = SQLITE_TOOBIG;
49913   goto vdbe_error_halt;
49914
49915   /* Jump to here if a malloc() fails.
49916   */
49917 no_mem:
49918   db->mallocFailed = 1;
49919   sqlite3SetString(&p->zErrMsg, db, "out of memory");
49920   rc = SQLITE_NOMEM;
49921   goto vdbe_error_halt;
49922
49923   /* Jump to here for an SQLITE_MISUSE error.
49924   */
49925 abort_due_to_misuse:
49926   rc = SQLITE_MISUSE;
49927   /* Fall thru into abort_due_to_error */
49928
49929   /* Jump to here for any other kind of fatal error.  The "rc" variable
49930   ** should hold the error number.
49931   */
49932 abort_due_to_error:
49933   assert( p->zErrMsg==0 );
49934   if( db->mallocFailed ) rc = SQLITE_NOMEM;
49935   if( rc!=SQLITE_IOERR_NOMEM ){
49936     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
49937   }
49938   goto vdbe_error_halt;
49939
49940   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
49941   ** flag.
49942   */
49943 abort_due_to_interrupt:
49944   assert( db->u1.isInterrupted );
49945   rc = SQLITE_INTERRUPT;
49946   p->rc = rc;
49947   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
49948   goto vdbe_error_halt;
49949 }
49950
49951 /************** End of vdbe.c ************************************************/
49952 /************** Begin file vdbeblob.c ****************************************/
49953 /*
49954 ** 2007 May 1
49955 **
49956 ** The author disclaims copyright to this source code.  In place of
49957 ** a legal notice, here is a blessing:
49958 **
49959 **    May you do good and not evil.
49960 **    May you find forgiveness for yourself and forgive others.
49961 **    May you share freely, never taking more than you give.
49962 **
49963 *************************************************************************
49964 **
49965 ** This file contains code used to implement incremental BLOB I/O.
49966 **
49967 ** $Id: vdbeblob.c,v 1.25 2008/07/28 19:34:54 drh Exp $
49968 */
49969
49970
49971 #ifndef SQLITE_OMIT_INCRBLOB
49972
49973 /*
49974 ** Valid sqlite3_blob* handles point to Incrblob structures.
49975 */
49976 typedef struct Incrblob Incrblob;
49977 struct Incrblob {
49978   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
49979   int nByte;              /* Size of open blob, in bytes */
49980   int iOffset;            /* Byte offset of blob in cursor data */
49981   BtCursor *pCsr;         /* Cursor pointing at blob row */
49982   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
49983   sqlite3 *db;            /* The associated database */
49984 };
49985
49986 /*
49987 ** Open a blob handle.
49988 */
49989 SQLITE_API int sqlite3_blob_open(
49990   sqlite3* db,            /* The database connection */
49991   const char *zDb,        /* The attached database containing the blob */
49992   const char *zTable,     /* The table containing the blob */
49993   const char *zColumn,    /* The column containing the blob */
49994   sqlite_int64 iRow,      /* The row containing the glob */
49995   int flags,              /* True -> read/write access, false -> read-only */
49996   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
49997 ){
49998   int nAttempt = 0;
49999   int iCol;               /* Index of zColumn in row-record */
50000
50001   /* This VDBE program seeks a btree cursor to the identified 
50002   ** db/table/row entry. The reason for using a vdbe program instead
50003   ** of writing code to use the b-tree layer directly is that the
50004   ** vdbe program will take advantage of the various transaction,
50005   ** locking and error handling infrastructure built into the vdbe.
50006   **
50007   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
50008   ** Code external to the Vdbe then "borrows" the b-tree cursor and
50009   ** uses it to implement the blob_read(), blob_write() and 
50010   ** blob_bytes() functions.
50011   **
50012   ** The sqlite3_blob_close() function finalizes the vdbe program,
50013   ** which closes the b-tree cursor and (possibly) commits the 
50014   ** transaction.
50015   */
50016   static const VdbeOpList openBlob[] = {
50017     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
50018     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
50019
50020     /* One of the following two instructions is replaced by an
50021     ** OP_Noop before exection.
50022     */
50023     {OP_SetNumColumns, 0, 0, 0},   /* 2: Num cols for cursor */
50024     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
50025     {OP_SetNumColumns, 0, 0, 0},   /* 4: Num cols for cursor */
50026     {OP_OpenWrite, 0, 0, 0},       /* 5: Open cursor 0 for read/write */
50027
50028     {OP_Variable, 1, 1, 0},        /* 6: Push the rowid to the stack */
50029     {OP_NotExists, 0, 10, 1},      /* 7: Seek the cursor */
50030     {OP_Column, 0, 0, 1},          /* 8  */
50031     {OP_ResultRow, 1, 0, 0},       /* 9  */
50032     {OP_Close, 0, 0, 0},           /* 10  */
50033     {OP_Halt, 0, 0, 0},            /* 11 */
50034   };
50035
50036   Vdbe *v = 0;
50037   int rc = SQLITE_OK;
50038   char zErr[128];
50039
50040   zErr[0] = 0;
50041   sqlite3_mutex_enter(db->mutex);
50042   do {
50043     Parse sParse;
50044     Table *pTab;
50045
50046     memset(&sParse, 0, sizeof(Parse));
50047     sParse.db = db;
50048
50049     if( sqlite3SafetyOn(db) ){
50050       sqlite3_mutex_leave(db->mutex);
50051       return SQLITE_MISUSE;
50052     }
50053
50054     sqlite3BtreeEnterAll(db);
50055     pTab = sqlite3LocateTable(&sParse, 0, zTable, zDb);
50056     if( pTab && IsVirtual(pTab) ){
50057       pTab = 0;
50058       sqlite3ErrorMsg(&sParse, "cannot open virtual table: %s", zTable);
50059     }
50060 #ifndef SQLITE_OMIT_VIEW
50061     if( pTab && pTab->pSelect ){
50062       pTab = 0;
50063       sqlite3ErrorMsg(&sParse, "cannot open view: %s", zTable);
50064     }
50065 #endif
50066     if( !pTab ){
50067       if( sParse.zErrMsg ){
50068         sqlite3_snprintf(sizeof(zErr), zErr, "%s", sParse.zErrMsg);
50069       }
50070       sqlite3DbFree(db, sParse.zErrMsg);
50071       rc = SQLITE_ERROR;
50072       (void)sqlite3SafetyOff(db);
50073       sqlite3BtreeLeaveAll(db);
50074       goto blob_open_out;
50075     }
50076
50077     /* Now search pTab for the exact column. */
50078     for(iCol=0; iCol < pTab->nCol; iCol++) {
50079       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
50080         break;
50081       }
50082     }
50083     if( iCol==pTab->nCol ){
50084       sqlite3_snprintf(sizeof(zErr), zErr, "no such column: \"%s\"", zColumn);
50085       rc = SQLITE_ERROR;
50086       (void)sqlite3SafetyOff(db);
50087       sqlite3BtreeLeaveAll(db);
50088       goto blob_open_out;
50089     }
50090
50091     /* If the value is being opened for writing, check that the
50092     ** column is not indexed. It is against the rules to open an
50093     ** indexed column for writing.
50094     */
50095     if( flags ){
50096       Index *pIdx;
50097       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
50098         int j;
50099         for(j=0; j<pIdx->nColumn; j++){
50100           if( pIdx->aiColumn[j]==iCol ){
50101             sqlite3_snprintf(sizeof(zErr), zErr,
50102                              "cannot open indexed column for writing");
50103             rc = SQLITE_ERROR;
50104             (void)sqlite3SafetyOff(db);
50105             sqlite3BtreeLeaveAll(db);
50106             goto blob_open_out;
50107           }
50108         }
50109       }
50110     }
50111
50112     v = sqlite3VdbeCreate(db);
50113     if( v ){
50114       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
50115       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
50116
50117       /* Configure the OP_Transaction */
50118       sqlite3VdbeChangeP1(v, 0, iDb);
50119       sqlite3VdbeChangeP2(v, 0, (flags ? 1 : 0));
50120
50121       /* Configure the OP_VerifyCookie */
50122       sqlite3VdbeChangeP1(v, 1, iDb);
50123       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
50124
50125       /* Make sure a mutex is held on the table to be accessed */
50126       sqlite3VdbeUsesBtree(v, iDb); 
50127
50128       /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
50129       ** parameter of the other to pTab->tnum. 
50130       */
50131       sqlite3VdbeChangeToNoop(v, (flags ? 3 : 5), 1);
50132       sqlite3VdbeChangeP2(v, (flags ? 5 : 3), pTab->tnum);
50133       sqlite3VdbeChangeP3(v, (flags ? 5 : 3), iDb);
50134
50135       /* Configure the OP_SetNumColumns. Configure the cursor to
50136       ** think that the table has one more column than it really
50137       ** does. An OP_Column to retrieve this imaginary column will
50138       ** always return an SQL NULL. This is useful because it means
50139       ** we can invoke OP_Column to fill in the vdbe cursors type 
50140       ** and offset cache without causing any IO.
50141       */
50142       sqlite3VdbeChangeP2(v, flags ? 4 : 2, pTab->nCol+1);
50143       sqlite3VdbeChangeP2(v, 8, pTab->nCol);
50144       if( !db->mallocFailed ){
50145         sqlite3VdbeMakeReady(v, 1, 1, 1, 0);
50146       }
50147     }
50148    
50149     sqlite3BtreeLeaveAll(db);
50150     rc = sqlite3SafetyOff(db);
50151     if( rc!=SQLITE_OK || db->mallocFailed ){
50152       goto blob_open_out;
50153     }
50154
50155     sqlite3_bind_int64((sqlite3_stmt *)v, 1, iRow);
50156     rc = sqlite3_step((sqlite3_stmt *)v);
50157     if( rc!=SQLITE_ROW ){
50158       nAttempt++;
50159       rc = sqlite3_finalize((sqlite3_stmt *)v);
50160       sqlite3_snprintf(sizeof(zErr), zErr, sqlite3_errmsg(db));
50161       v = 0;
50162     }
50163   } while( nAttempt<5 && rc==SQLITE_SCHEMA );
50164
50165   if( rc==SQLITE_ROW ){
50166     /* The row-record has been opened successfully. Check that the
50167     ** column in question contains text or a blob. If it contains
50168     ** text, it is up to the caller to get the encoding right.
50169     */
50170     Incrblob *pBlob;
50171     u32 type = v->apCsr[0]->aType[iCol];
50172
50173     if( type<12 ){
50174       sqlite3_snprintf(sizeof(zErr), zErr, "cannot open value of type %s",
50175           type==0?"null": type==7?"real": "integer"
50176       );
50177       rc = SQLITE_ERROR;
50178       goto blob_open_out;
50179     }
50180     pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
50181     if( db->mallocFailed ){
50182       sqlite3DbFree(db, pBlob);
50183       goto blob_open_out;
50184     }
50185     pBlob->flags = flags;
50186     pBlob->pCsr =  v->apCsr[0]->pCursor;
50187     sqlite3BtreeEnterCursor(pBlob->pCsr);
50188     sqlite3BtreeCacheOverflow(pBlob->pCsr);
50189     sqlite3BtreeLeaveCursor(pBlob->pCsr);
50190     pBlob->pStmt = (sqlite3_stmt *)v;
50191     pBlob->iOffset = v->apCsr[0]->aOffset[iCol];
50192     pBlob->nByte = sqlite3VdbeSerialTypeLen(type);
50193     pBlob->db = db;
50194     *ppBlob = (sqlite3_blob *)pBlob;
50195     rc = SQLITE_OK;
50196   }else if( rc==SQLITE_OK ){
50197     sqlite3_snprintf(sizeof(zErr), zErr, "no such rowid: %lld", iRow);
50198     rc = SQLITE_ERROR;
50199   }
50200
50201 blob_open_out:
50202   zErr[sizeof(zErr)-1] = '\0';
50203   if( rc!=SQLITE_OK || db->mallocFailed ){
50204     sqlite3_finalize((sqlite3_stmt *)v);
50205   }
50206   sqlite3Error(db, rc, (rc==SQLITE_OK?0:zErr));
50207   rc = sqlite3ApiExit(db, rc);
50208   sqlite3_mutex_leave(db->mutex);
50209   return rc;
50210 }
50211
50212 /*
50213 ** Close a blob handle that was previously created using
50214 ** sqlite3_blob_open().
50215 */
50216 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
50217   Incrblob *p = (Incrblob *)pBlob;
50218   int rc;
50219
50220   rc = sqlite3_finalize(p->pStmt);
50221   sqlite3DbFree(p->db, p);
50222   return rc;
50223 }
50224
50225 /*
50226 ** Perform a read or write operation on a blob
50227 */
50228 static int blobReadWrite(
50229   sqlite3_blob *pBlob, 
50230   void *z, 
50231   int n, 
50232   int iOffset, 
50233   int (*xCall)(BtCursor*, u32, u32, void*)
50234 ){
50235   int rc;
50236   Incrblob *p = (Incrblob *)pBlob;
50237   Vdbe *v;
50238   sqlite3 *db = p->db;  
50239
50240   /* Request is out of range. Return a transient error. */
50241   if( (iOffset+n)>p->nByte ){
50242     return SQLITE_ERROR;
50243   }
50244   sqlite3_mutex_enter(db->mutex);
50245
50246   /* If there is no statement handle, then the blob-handle has
50247   ** already been invalidated. Return SQLITE_ABORT in this case.
50248   */
50249   v = (Vdbe*)p->pStmt;
50250   if( v==0 ){
50251     rc = SQLITE_ABORT;
50252   }else{
50253     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
50254     ** returned, clean-up the statement handle.
50255     */
50256     assert( db == v->db );
50257     sqlite3BtreeEnterCursor(p->pCsr);
50258     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
50259     sqlite3BtreeLeaveCursor(p->pCsr);
50260     if( rc==SQLITE_ABORT ){
50261       sqlite3VdbeFinalize(v);
50262       p->pStmt = 0;
50263     }else{
50264       db->errCode = rc;
50265       v->rc = rc;
50266     }
50267   }
50268   rc = sqlite3ApiExit(db, rc);
50269   sqlite3_mutex_leave(db->mutex);
50270   return rc;
50271 }
50272
50273 /*
50274 ** Read data from a blob handle.
50275 */
50276 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
50277   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
50278 }
50279
50280 /*
50281 ** Write data to a blob handle.
50282 */
50283 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
50284   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
50285 }
50286
50287 /*
50288 ** Query a blob handle for the size of the data.
50289 **
50290 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
50291 ** so no mutex is required for access.
50292 */
50293 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
50294   Incrblob *p = (Incrblob *)pBlob;
50295   return p->nByte;
50296 }
50297
50298 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
50299
50300 /************** End of vdbeblob.c ********************************************/
50301 /************** Begin file journal.c *****************************************/
50302 /*
50303 ** 2007 August 22
50304 **
50305 ** The author disclaims copyright to this source code.  In place of
50306 ** a legal notice, here is a blessing:
50307 **
50308 **    May you do good and not evil.
50309 **    May you find forgiveness for yourself and forgive others.
50310 **    May you share freely, never taking more than you give.
50311 **
50312 *************************************************************************
50313 **
50314 ** @(#) $Id: journal.c,v 1.8 2008/05/01 18:01:47 drh Exp $
50315 */
50316
50317 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
50318
50319 /*
50320 ** This file implements a special kind of sqlite3_file object used
50321 ** by SQLite to create journal files if the atomic-write optimization
50322 ** is enabled.
50323 **
50324 ** The distinctive characteristic of this sqlite3_file is that the
50325 ** actual on disk file is created lazily. When the file is created,
50326 ** the caller specifies a buffer size for an in-memory buffer to
50327 ** be used to service read() and write() requests. The actual file
50328 ** on disk is not created or populated until either:
50329 **
50330 **   1) The in-memory representation grows too large for the allocated 
50331 **      buffer, or
50332 **   2) The xSync() method is called.
50333 */
50334
50335
50336
50337 /*
50338 ** A JournalFile object is a subclass of sqlite3_file used by
50339 ** as an open file handle for journal files.
50340 */
50341 struct JournalFile {
50342   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
50343   int nBuf;                       /* Size of zBuf[] in bytes */
50344   char *zBuf;                     /* Space to buffer journal writes */
50345   int iSize;                      /* Amount of zBuf[] currently used */
50346   int flags;                      /* xOpen flags */
50347   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
50348   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
50349   const char *zJournal;           /* Name of the journal file */
50350 };
50351 typedef struct JournalFile JournalFile;
50352
50353 /*
50354 ** If it does not already exists, create and populate the on-disk file 
50355 ** for JournalFile p.
50356 */
50357 static int createFile(JournalFile *p){
50358   int rc = SQLITE_OK;
50359   if( !p->pReal ){
50360     sqlite3_file *pReal = (sqlite3_file *)&p[1];
50361     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
50362     if( rc==SQLITE_OK ){
50363       p->pReal = pReal;
50364       if( p->iSize>0 ){
50365         assert(p->iSize<=p->nBuf);
50366         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
50367       }
50368     }
50369   }
50370   return rc;
50371 }
50372
50373 /*
50374 ** Close the file.
50375 */
50376 static int jrnlClose(sqlite3_file *pJfd){
50377   JournalFile *p = (JournalFile *)pJfd;
50378   if( p->pReal ){
50379     sqlite3OsClose(p->pReal);
50380   }
50381   sqlite3_free(p->zBuf);
50382   return SQLITE_OK;
50383 }
50384
50385 /*
50386 ** Read data from the file.
50387 */
50388 static int jrnlRead(
50389   sqlite3_file *pJfd,    /* The journal file from which to read */
50390   void *zBuf,            /* Put the results here */
50391   int iAmt,              /* Number of bytes to read */
50392   sqlite_int64 iOfst     /* Begin reading at this offset */
50393 ){
50394   int rc = SQLITE_OK;
50395   JournalFile *p = (JournalFile *)pJfd;
50396   if( p->pReal ){
50397     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
50398   }else{
50399     assert( iAmt+iOfst<=p->iSize );
50400     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
50401   }
50402   return rc;
50403 }
50404
50405 /*
50406 ** Write data to the file.
50407 */
50408 static int jrnlWrite(
50409   sqlite3_file *pJfd,    /* The journal file into which to write */
50410   const void *zBuf,      /* Take data to be written from here */
50411   int iAmt,              /* Number of bytes to write */
50412   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
50413 ){
50414   int rc = SQLITE_OK;
50415   JournalFile *p = (JournalFile *)pJfd;
50416   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
50417     rc = createFile(p);
50418   }
50419   if( rc==SQLITE_OK ){
50420     if( p->pReal ){
50421       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
50422     }else{
50423       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
50424       if( p->iSize<(iOfst+iAmt) ){
50425         p->iSize = (iOfst+iAmt);
50426       }
50427     }
50428   }
50429   return rc;
50430 }
50431
50432 /*
50433 ** Truncate the file.
50434 */
50435 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
50436   int rc = SQLITE_OK;
50437   JournalFile *p = (JournalFile *)pJfd;
50438   if( p->pReal ){
50439     rc = sqlite3OsTruncate(p->pReal, size);
50440   }else if( size<p->iSize ){
50441     p->iSize = size;
50442   }
50443   return rc;
50444 }
50445
50446 /*
50447 ** Sync the file.
50448 */
50449 static int jrnlSync(sqlite3_file *pJfd, int flags){
50450   int rc;
50451   JournalFile *p = (JournalFile *)pJfd;
50452   if( p->pReal ){
50453     rc = sqlite3OsSync(p->pReal, flags);
50454   }else{
50455     rc = SQLITE_OK;
50456   }
50457   return rc;
50458 }
50459
50460 /*
50461 ** Query the size of the file in bytes.
50462 */
50463 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
50464   int rc = SQLITE_OK;
50465   JournalFile *p = (JournalFile *)pJfd;
50466   if( p->pReal ){
50467     rc = sqlite3OsFileSize(p->pReal, pSize);
50468   }else{
50469     *pSize = (sqlite_int64) p->iSize;
50470   }
50471   return rc;
50472 }
50473
50474 /*
50475 ** Table of methods for JournalFile sqlite3_file object.
50476 */
50477 static struct sqlite3_io_methods JournalFileMethods = {
50478   1,             /* iVersion */
50479   jrnlClose,     /* xClose */
50480   jrnlRead,      /* xRead */
50481   jrnlWrite,     /* xWrite */
50482   jrnlTruncate,  /* xTruncate */
50483   jrnlSync,      /* xSync */
50484   jrnlFileSize,  /* xFileSize */
50485   0,             /* xLock */
50486   0,             /* xUnlock */
50487   0,             /* xCheckReservedLock */
50488   0,             /* xFileControl */
50489   0,             /* xSectorSize */
50490   0              /* xDeviceCharacteristics */
50491 };
50492
50493 /* 
50494 ** Open a journal file.
50495 */
50496 SQLITE_PRIVATE int sqlite3JournalOpen(
50497   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
50498   const char *zName,         /* Name of the journal file */
50499   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
50500   int flags,                 /* Opening flags */
50501   int nBuf                   /* Bytes buffered before opening the file */
50502 ){
50503   JournalFile *p = (JournalFile *)pJfd;
50504   memset(p, 0, sqlite3JournalSize(pVfs));
50505   if( nBuf>0 ){
50506     p->zBuf = sqlite3MallocZero(nBuf);
50507     if( !p->zBuf ){
50508       return SQLITE_NOMEM;
50509     }
50510   }else{
50511     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
50512   }
50513   p->pMethod = &JournalFileMethods;
50514   p->nBuf = nBuf;
50515   p->flags = flags;
50516   p->zJournal = zName;
50517   p->pVfs = pVfs;
50518   return SQLITE_OK;
50519 }
50520
50521 /*
50522 ** If the argument p points to a JournalFile structure, and the underlying
50523 ** file has not yet been created, create it now.
50524 */
50525 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
50526   if( p->pMethods!=&JournalFileMethods ){
50527     return SQLITE_OK;
50528   }
50529   return createFile((JournalFile *)p);
50530 }
50531
50532 /* 
50533 ** Return the number of bytes required to store a JournalFile that uses vfs
50534 ** pVfs to create the underlying on-disk files.
50535 */
50536 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
50537   return (pVfs->szOsFile+sizeof(JournalFile));
50538 }
50539 #endif
50540
50541 /************** End of journal.c *********************************************/
50542 /************** Begin file expr.c ********************************************/
50543 /*
50544 ** 2001 September 15
50545 **
50546 ** The author disclaims copyright to this source code.  In place of
50547 ** a legal notice, here is a blessing:
50548 **
50549 **    May you do good and not evil.
50550 **    May you find forgiveness for yourself and forgive others.
50551 **    May you share freely, never taking more than you give.
50552 **
50553 *************************************************************************
50554 ** This file contains routines used for analyzing expressions and
50555 ** for generating VDBE code that evaluates expressions in SQLite.
50556 **
50557 ** $Id: expr.c,v 1.387 2008/07/28 19:34:53 drh Exp $
50558 */
50559
50560 /*
50561 ** Return the 'affinity' of the expression pExpr if any.
50562 **
50563 ** If pExpr is a column, a reference to a column via an 'AS' alias,
50564 ** or a sub-select with a column as the return value, then the 
50565 ** affinity of that column is returned. Otherwise, 0x00 is returned,
50566 ** indicating no affinity for the expression.
50567 **
50568 ** i.e. the WHERE clause expresssions in the following statements all
50569 ** have an affinity:
50570 **
50571 ** CREATE TABLE t1(a);
50572 ** SELECT * FROM t1 WHERE a;
50573 ** SELECT a AS b FROM t1 WHERE b;
50574 ** SELECT * FROM t1 WHERE (select a from t1);
50575 */
50576 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
50577   int op = pExpr->op;
50578   if( op==TK_SELECT ){
50579     return sqlite3ExprAffinity(pExpr->pSelect->pEList->a[0].pExpr);
50580   }
50581 #ifndef SQLITE_OMIT_CAST
50582   if( op==TK_CAST ){
50583     return sqlite3AffinityType(&pExpr->token);
50584   }
50585 #endif
50586   return pExpr->affinity;
50587 }
50588
50589 /*
50590 ** Set the collating sequence for expression pExpr to be the collating
50591 ** sequence named by pToken.   Return a pointer to the revised expression.
50592 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
50593 ** flag.  An explicit collating sequence will override implicit
50594 ** collating sequences.
50595 */
50596 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pName){
50597   char *zColl = 0;            /* Dequoted name of collation sequence */
50598   CollSeq *pColl;
50599   sqlite3 *db = pParse->db;
50600   zColl = sqlite3NameFromToken(db, pName);
50601   if( pExpr && zColl ){
50602     pColl = sqlite3LocateCollSeq(pParse, zColl, -1);
50603     if( pColl ){
50604       pExpr->pColl = pColl;
50605       pExpr->flags |= EP_ExpCollate;
50606     }
50607   }
50608   sqlite3DbFree(db, zColl);
50609   return pExpr;
50610 }
50611
50612 /*
50613 ** Return the default collation sequence for the expression pExpr. If
50614 ** there is no default collation type, return 0.
50615 */
50616 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
50617   CollSeq *pColl = 0;
50618   if( pExpr ){
50619     int op;
50620     pColl = pExpr->pColl;
50621     op = pExpr->op;
50622     if( (op==TK_CAST || op==TK_UPLUS) && !pColl ){
50623       return sqlite3ExprCollSeq(pParse, pExpr->pLeft);
50624     }
50625   }
50626   if( sqlite3CheckCollSeq(pParse, pColl) ){ 
50627     pColl = 0;
50628   }
50629   return pColl;
50630 }
50631
50632 /*
50633 ** pExpr is an operand of a comparison operator.  aff2 is the
50634 ** type affinity of the other operand.  This routine returns the
50635 ** type affinity that should be used for the comparison operator.
50636 */
50637 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
50638   char aff1 = sqlite3ExprAffinity(pExpr);
50639   if( aff1 && aff2 ){
50640     /* Both sides of the comparison are columns. If one has numeric
50641     ** affinity, use that. Otherwise use no affinity.
50642     */
50643     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
50644       return SQLITE_AFF_NUMERIC;
50645     }else{
50646       return SQLITE_AFF_NONE;
50647     }
50648   }else if( !aff1 && !aff2 ){
50649     /* Neither side of the comparison is a column.  Compare the
50650     ** results directly.
50651     */
50652     return SQLITE_AFF_NONE;
50653   }else{
50654     /* One side is a column, the other is not. Use the columns affinity. */
50655     assert( aff1==0 || aff2==0 );
50656     return (aff1 + aff2);
50657   }
50658 }
50659
50660 /*
50661 ** pExpr is a comparison operator.  Return the type affinity that should
50662 ** be applied to both operands prior to doing the comparison.
50663 */
50664 static char comparisonAffinity(Expr *pExpr){
50665   char aff;
50666   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
50667           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
50668           pExpr->op==TK_NE );
50669   assert( pExpr->pLeft );
50670   aff = sqlite3ExprAffinity(pExpr->pLeft);
50671   if( pExpr->pRight ){
50672     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
50673   }
50674   else if( pExpr->pSelect ){
50675     aff = sqlite3CompareAffinity(pExpr->pSelect->pEList->a[0].pExpr, aff);
50676   }
50677   else if( !aff ){
50678     aff = SQLITE_AFF_NONE;
50679   }
50680   return aff;
50681 }
50682
50683 /*
50684 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
50685 ** idx_affinity is the affinity of an indexed column. Return true
50686 ** if the index with affinity idx_affinity may be used to implement
50687 ** the comparison in pExpr.
50688 */
50689 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
50690   char aff = comparisonAffinity(pExpr);
50691   switch( aff ){
50692     case SQLITE_AFF_NONE:
50693       return 1;
50694     case SQLITE_AFF_TEXT:
50695       return idx_affinity==SQLITE_AFF_TEXT;
50696     default:
50697       return sqlite3IsNumericAffinity(idx_affinity);
50698   }
50699 }
50700
50701 /*
50702 ** Return the P5 value that should be used for a binary comparison
50703 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
50704 */
50705 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
50706   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
50707   aff = sqlite3CompareAffinity(pExpr1, aff) | jumpIfNull;
50708   return aff;
50709 }
50710
50711 /*
50712 ** Return a pointer to the collation sequence that should be used by
50713 ** a binary comparison operator comparing pLeft and pRight.
50714 **
50715 ** If the left hand expression has a collating sequence type, then it is
50716 ** used. Otherwise the collation sequence for the right hand expression
50717 ** is used, or the default (BINARY) if neither expression has a collating
50718 ** type.
50719 **
50720 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
50721 ** it is not considered.
50722 */
50723 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
50724   Parse *pParse, 
50725   Expr *pLeft, 
50726   Expr *pRight
50727 ){
50728   CollSeq *pColl;
50729   assert( pLeft );
50730   if( pLeft->flags & EP_ExpCollate ){
50731     assert( pLeft->pColl );
50732     pColl = pLeft->pColl;
50733   }else if( pRight && pRight->flags & EP_ExpCollate ){
50734     assert( pRight->pColl );
50735     pColl = pRight->pColl;
50736   }else{
50737     pColl = sqlite3ExprCollSeq(pParse, pLeft);
50738     if( !pColl ){
50739       pColl = sqlite3ExprCollSeq(pParse, pRight);
50740     }
50741   }
50742   return pColl;
50743 }
50744
50745 /*
50746 ** Generate the operands for a comparison operation.  Before
50747 ** generating the code for each operand, set the EP_AnyAff
50748 ** flag on the expression so that it will be able to used a
50749 ** cached column value that has previously undergone an
50750 ** affinity change.
50751 */
50752 static void codeCompareOperands(
50753   Parse *pParse,    /* Parsing and code generating context */
50754   Expr *pLeft,      /* The left operand */
50755   int *pRegLeft,    /* Register where left operand is stored */
50756   int *pFreeLeft,   /* Free this register when done */
50757   Expr *pRight,     /* The right operand */
50758   int *pRegRight,   /* Register where right operand is stored */
50759   int *pFreeRight   /* Write temp register for right operand there */
50760 ){
50761   while( pLeft->op==TK_UPLUS ) pLeft = pLeft->pLeft;
50762   pLeft->flags |= EP_AnyAff;
50763   *pRegLeft = sqlite3ExprCodeTemp(pParse, pLeft, pFreeLeft);
50764   while( pRight->op==TK_UPLUS ) pRight = pRight->pLeft;
50765   pRight->flags |= EP_AnyAff;
50766   *pRegRight = sqlite3ExprCodeTemp(pParse, pRight, pFreeRight);
50767 }
50768
50769 /*
50770 ** Generate code for a comparison operator.
50771 */
50772 static int codeCompare(
50773   Parse *pParse,    /* The parsing (and code generating) context */
50774   Expr *pLeft,      /* The left operand */
50775   Expr *pRight,     /* The right operand */
50776   int opcode,       /* The comparison opcode */
50777   int in1, int in2, /* Register holding operands */
50778   int dest,         /* Jump here if true.  */
50779   int jumpIfNull    /* If true, jump if either operand is NULL */
50780 ){
50781   int p5;
50782   int addr;
50783   CollSeq *p4;
50784
50785   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
50786   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
50787   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
50788                            (void*)p4, P4_COLLSEQ);
50789   sqlite3VdbeChangeP5(pParse->pVdbe, p5);
50790   if( (p5 & SQLITE_AFF_MASK)!=SQLITE_AFF_NONE ){
50791     sqlite3ExprCacheAffinityChange(pParse, in1, 1);
50792     sqlite3ExprCacheAffinityChange(pParse, in2, 1);
50793   }
50794   return addr;
50795 }
50796
50797 #if SQLITE_MAX_EXPR_DEPTH>0
50798 /*
50799 ** Check that argument nHeight is less than or equal to the maximum
50800 ** expression depth allowed. If it is not, leave an error message in
50801 ** pParse.
50802 */
50803 static int checkExprHeight(Parse *pParse, int nHeight){
50804   int rc = SQLITE_OK;
50805   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
50806   if( nHeight>mxHeight ){
50807     sqlite3ErrorMsg(pParse, 
50808        "Expression tree is too large (maximum depth %d)", mxHeight
50809     );
50810     rc = SQLITE_ERROR;
50811   }
50812   return rc;
50813 }
50814
50815 /* The following three functions, heightOfExpr(), heightOfExprList()
50816 ** and heightOfSelect(), are used to determine the maximum height
50817 ** of any expression tree referenced by the structure passed as the
50818 ** first argument.
50819 **
50820 ** If this maximum height is greater than the current value pointed
50821 ** to by pnHeight, the second parameter, then set *pnHeight to that
50822 ** value.
50823 */
50824 static void heightOfExpr(Expr *p, int *pnHeight){
50825   if( p ){
50826     if( p->nHeight>*pnHeight ){
50827       *pnHeight = p->nHeight;
50828     }
50829   }
50830 }
50831 static void heightOfExprList(ExprList *p, int *pnHeight){
50832   if( p ){
50833     int i;
50834     for(i=0; i<p->nExpr; i++){
50835       heightOfExpr(p->a[i].pExpr, pnHeight);
50836     }
50837   }
50838 }
50839 static void heightOfSelect(Select *p, int *pnHeight){
50840   if( p ){
50841     heightOfExpr(p->pWhere, pnHeight);
50842     heightOfExpr(p->pHaving, pnHeight);
50843     heightOfExpr(p->pLimit, pnHeight);
50844     heightOfExpr(p->pOffset, pnHeight);
50845     heightOfExprList(p->pEList, pnHeight);
50846     heightOfExprList(p->pGroupBy, pnHeight);
50847     heightOfExprList(p->pOrderBy, pnHeight);
50848     heightOfSelect(p->pPrior, pnHeight);
50849   }
50850 }
50851
50852 /*
50853 ** Set the Expr.nHeight variable in the structure passed as an 
50854 ** argument. An expression with no children, Expr.pList or 
50855 ** Expr.pSelect member has a height of 1. Any other expression
50856 ** has a height equal to the maximum height of any other 
50857 ** referenced Expr plus one.
50858 */
50859 static void exprSetHeight(Expr *p){
50860   int nHeight = 0;
50861   heightOfExpr(p->pLeft, &nHeight);
50862   heightOfExpr(p->pRight, &nHeight);
50863   heightOfExprList(p->pList, &nHeight);
50864   heightOfSelect(p->pSelect, &nHeight);
50865   p->nHeight = nHeight + 1;
50866 }
50867
50868 /*
50869 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
50870 ** the height is greater than the maximum allowed expression depth,
50871 ** leave an error in pParse.
50872 */
50873 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
50874   exprSetHeight(p);
50875   checkExprHeight(pParse, p->nHeight);
50876 }
50877
50878 /*
50879 ** Return the maximum height of any expression tree referenced
50880 ** by the select statement passed as an argument.
50881 */
50882 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
50883   int nHeight = 0;
50884   heightOfSelect(p, &nHeight);
50885   return nHeight;
50886 }
50887 #else
50888   #define checkExprHeight(x,y)
50889   #define exprSetHeight(y)
50890 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
50891
50892 /*
50893 ** Construct a new expression node and return a pointer to it.  Memory
50894 ** for this node is obtained from sqlite3_malloc().  The calling function
50895 ** is responsible for making sure the node eventually gets freed.
50896 */
50897 SQLITE_PRIVATE Expr *sqlite3Expr(
50898   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
50899   int op,                 /* Expression opcode */
50900   Expr *pLeft,            /* Left operand */
50901   Expr *pRight,           /* Right operand */
50902   const Token *pToken     /* Argument token */
50903 ){
50904   Expr *pNew;
50905   pNew = sqlite3DbMallocZero(db, sizeof(Expr));
50906   if( pNew==0 ){
50907     /* When malloc fails, delete pLeft and pRight. Expressions passed to 
50908     ** this function must always be allocated with sqlite3Expr() for this 
50909     ** reason. 
50910     */
50911     sqlite3ExprDelete(db, pLeft);
50912     sqlite3ExprDelete(db, pRight);
50913     return 0;
50914   }
50915   pNew->op = op;
50916   pNew->pLeft = pLeft;
50917   pNew->pRight = pRight;
50918   pNew->iAgg = -1;
50919   pNew->span.z = (u8*)"";
50920   if( pToken ){
50921     assert( pToken->dyn==0 );
50922     pNew->span = pNew->token = *pToken;
50923   }else if( pLeft ){
50924     if( pRight ){
50925       if( pRight->span.dyn==0 && pLeft->span.dyn==0 ){
50926         sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
50927       }
50928       if( pRight->flags & EP_ExpCollate ){
50929         pNew->flags |= EP_ExpCollate;
50930         pNew->pColl = pRight->pColl;
50931       }
50932     }
50933     if( pLeft->flags & EP_ExpCollate ){
50934       pNew->flags |= EP_ExpCollate;
50935       pNew->pColl = pLeft->pColl;
50936     }
50937   }
50938
50939   exprSetHeight(pNew);
50940   return pNew;
50941 }
50942
50943 /*
50944 ** Works like sqlite3Expr() except that it takes an extra Parse*
50945 ** argument and notifies the associated connection object if malloc fails.
50946 */
50947 SQLITE_PRIVATE Expr *sqlite3PExpr(
50948   Parse *pParse,          /* Parsing context */
50949   int op,                 /* Expression opcode */
50950   Expr *pLeft,            /* Left operand */
50951   Expr *pRight,           /* Right operand */
50952   const Token *pToken     /* Argument token */
50953 ){
50954   Expr *p = sqlite3Expr(pParse->db, op, pLeft, pRight, pToken);
50955   if( p ){
50956     checkExprHeight(pParse, p->nHeight);
50957   }
50958   return p;
50959 }
50960
50961 /*
50962 ** When doing a nested parse, you can include terms in an expression
50963 ** that look like this:   #1 #2 ...  These terms refer to registers
50964 ** in the virtual machine.  #N is the N-th register.
50965 **
50966 ** This routine is called by the parser to deal with on of those terms.
50967 ** It immediately generates code to store the value in a memory location.
50968 ** The returns an expression that will code to extract the value from
50969 ** that memory location as needed.
50970 */
50971 SQLITE_PRIVATE Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
50972   Vdbe *v = pParse->pVdbe;
50973   Expr *p;
50974   if( pParse->nested==0 ){
50975     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
50976     return sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
50977   }
50978   if( v==0 ) return 0;
50979   p = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, pToken);
50980   if( p==0 ){
50981     return 0;  /* Malloc failed */
50982   }
50983   p->iTable = atoi((char*)&pToken->z[1]);
50984   return p;
50985 }
50986
50987 /*
50988 ** Join two expressions using an AND operator.  If either expression is
50989 ** NULL, then just return the other expression.
50990 */
50991 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
50992   if( pLeft==0 ){
50993     return pRight;
50994   }else if( pRight==0 ){
50995     return pLeft;
50996   }else{
50997     return sqlite3Expr(db, TK_AND, pLeft, pRight, 0);
50998   }
50999 }
51000
51001 /*
51002 ** Set the Expr.span field of the given expression to span all
51003 ** text between the two given tokens.  Both tokens must be pointing
51004 ** at the same string.
51005 */
51006 SQLITE_PRIVATE void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
51007   assert( pRight!=0 );
51008   assert( pLeft!=0 );
51009   if( pExpr ){
51010     pExpr->span.z = pLeft->z;
51011     pExpr->span.n = pRight->n + (pRight->z - pLeft->z);
51012   }
51013 }
51014
51015 /*
51016 ** Construct a new expression node for a function with multiple
51017 ** arguments.
51018 */
51019 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
51020   Expr *pNew;
51021   sqlite3 *db = pParse->db;
51022   assert( pToken );
51023   pNew = sqlite3DbMallocZero(db, sizeof(Expr) );
51024   if( pNew==0 ){
51025     sqlite3ExprListDelete(db, pList); /* Avoid leaking memory when malloc fails */
51026     return 0;
51027   }
51028   pNew->op = TK_FUNCTION;
51029   pNew->pList = pList;
51030   assert( pToken->dyn==0 );
51031   pNew->token = *pToken;
51032   pNew->span = pNew->token;
51033
51034   sqlite3ExprSetHeight(pParse, pNew);
51035   return pNew;
51036 }
51037
51038 /*
51039 ** Assign a variable number to an expression that encodes a wildcard
51040 ** in the original SQL statement.  
51041 **
51042 ** Wildcards consisting of a single "?" are assigned the next sequential
51043 ** variable number.
51044 **
51045 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
51046 ** sure "nnn" is not too be to avoid a denial of service attack when
51047 ** the SQL statement comes from an external source.
51048 **
51049 ** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
51050 ** as the previous instance of the same wildcard.  Or if this is the first
51051 ** instance of the wildcard, the next sequenial variable number is
51052 ** assigned.
51053 */
51054 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
51055   Token *pToken;
51056   sqlite3 *db = pParse->db;
51057
51058   if( pExpr==0 ) return;
51059   pToken = &pExpr->token;
51060   assert( pToken->n>=1 );
51061   assert( pToken->z!=0 );
51062   assert( pToken->z[0]!=0 );
51063   if( pToken->n==1 ){
51064     /* Wildcard of the form "?".  Assign the next variable number */
51065     pExpr->iTable = ++pParse->nVar;
51066   }else if( pToken->z[0]=='?' ){
51067     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
51068     ** use it as the variable number */
51069     int i;
51070     pExpr->iTable = i = atoi((char*)&pToken->z[1]);
51071     testcase( i==0 );
51072     testcase( i==1 );
51073     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
51074     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
51075     if( i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
51076       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
51077           db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
51078     }
51079     if( i>pParse->nVar ){
51080       pParse->nVar = i;
51081     }
51082   }else{
51083     /* Wildcards of the form ":aaa" or "$aaa".  Reuse the same variable
51084     ** number as the prior appearance of the same name, or if the name
51085     ** has never appeared before, reuse the same variable number
51086     */
51087     int i, n;
51088     n = pToken->n;
51089     for(i=0; i<pParse->nVarExpr; i++){
51090       Expr *pE;
51091       if( (pE = pParse->apVarExpr[i])!=0
51092           && pE->token.n==n
51093           && memcmp(pE->token.z, pToken->z, n)==0 ){
51094         pExpr->iTable = pE->iTable;
51095         break;
51096       }
51097     }
51098     if( i>=pParse->nVarExpr ){
51099       pExpr->iTable = ++pParse->nVar;
51100       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
51101         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
51102         pParse->apVarExpr =
51103             sqlite3DbReallocOrFree(
51104               db,
51105               pParse->apVarExpr,
51106               pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
51107             );
51108       }
51109       if( !db->mallocFailed ){
51110         assert( pParse->apVarExpr!=0 );
51111         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
51112       }
51113     }
51114   } 
51115   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
51116     sqlite3ErrorMsg(pParse, "too many SQL variables");
51117   }
51118 }
51119
51120 /*
51121 ** Recursively delete an expression tree.
51122 */
51123 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
51124   if( p==0 ) return;
51125   if( p->span.dyn ) sqlite3DbFree(db, (char*)p->span.z);
51126   if( p->token.dyn ) sqlite3DbFree(db, (char*)p->token.z);
51127   sqlite3ExprDelete(db, p->pLeft);
51128   sqlite3ExprDelete(db, p->pRight);
51129   sqlite3ExprListDelete(db, p->pList);
51130   sqlite3SelectDelete(db, p->pSelect);
51131   sqlite3DbFree(db, p);
51132 }
51133
51134 /*
51135 ** The Expr.token field might be a string literal that is quoted.
51136 ** If so, remove the quotation marks.
51137 */
51138 SQLITE_PRIVATE void sqlite3DequoteExpr(sqlite3 *db, Expr *p){
51139   if( ExprHasAnyProperty(p, EP_Dequoted) ){
51140     return;
51141   }
51142   ExprSetProperty(p, EP_Dequoted);
51143   if( p->token.dyn==0 ){
51144     sqlite3TokenCopy(db, &p->token, &p->token);
51145   }
51146   sqlite3Dequote((char*)p->token.z);
51147 }
51148
51149
51150 /*
51151 ** The following group of routines make deep copies of expressions,
51152 ** expression lists, ID lists, and select statements.  The copies can
51153 ** be deleted (by being passed to their respective ...Delete() routines)
51154 ** without effecting the originals.
51155 **
51156 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
51157 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
51158 ** by subsequent calls to sqlite*ListAppend() routines.
51159 **
51160 ** Any tables that the SrcList might point to are not duplicated.
51161 */
51162 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p){
51163   Expr *pNew;
51164   if( p==0 ) return 0;
51165   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
51166   if( pNew==0 ) return 0;
51167   memcpy(pNew, p, sizeof(*pNew));
51168   if( p->token.z!=0 ){
51169     pNew->token.z = (u8*)sqlite3DbStrNDup(db, (char*)p->token.z, p->token.n);
51170     pNew->token.dyn = 1;
51171   }else{
51172     assert( pNew->token.z==0 );
51173   }
51174   pNew->span.z = 0;
51175   pNew->pLeft = sqlite3ExprDup(db, p->pLeft);
51176   pNew->pRight = sqlite3ExprDup(db, p->pRight);
51177   pNew->pList = sqlite3ExprListDup(db, p->pList);
51178   pNew->pSelect = sqlite3SelectDup(db, p->pSelect);
51179   return pNew;
51180 }
51181 SQLITE_PRIVATE void sqlite3TokenCopy(sqlite3 *db, Token *pTo, Token *pFrom){
51182   if( pTo->dyn ) sqlite3DbFree(db, (char*)pTo->z);
51183   if( pFrom->z ){
51184     pTo->n = pFrom->n;
51185     pTo->z = (u8*)sqlite3DbStrNDup(db, (char*)pFrom->z, pFrom->n);
51186     pTo->dyn = 1;
51187   }else{
51188     pTo->z = 0;
51189   }
51190 }
51191 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p){
51192   ExprList *pNew;
51193   struct ExprList_item *pItem, *pOldItem;
51194   int i;
51195   if( p==0 ) return 0;
51196   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
51197   if( pNew==0 ) return 0;
51198   pNew->iECursor = 0;
51199   pNew->nExpr = pNew->nAlloc = p->nExpr;
51200   pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
51201   if( pItem==0 ){
51202     sqlite3DbFree(db, pNew);
51203     return 0;
51204   } 
51205   pOldItem = p->a;
51206   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
51207     Expr *pNewExpr, *pOldExpr;
51208     pItem->pExpr = pNewExpr = sqlite3ExprDup(db, pOldExpr = pOldItem->pExpr);
51209     if( pOldExpr->span.z!=0 && pNewExpr ){
51210       /* Always make a copy of the span for top-level expressions in the
51211       ** expression list.  The logic in SELECT processing that determines
51212       ** the names of columns in the result set needs this information */
51213       sqlite3TokenCopy(db, &pNewExpr->span, &pOldExpr->span);
51214     }
51215     assert( pNewExpr==0 || pNewExpr->span.z!=0 
51216             || pOldExpr->span.z==0
51217             || db->mallocFailed );
51218     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
51219     pItem->sortOrder = pOldItem->sortOrder;
51220     pItem->isAgg = pOldItem->isAgg;
51221     pItem->done = 0;
51222   }
51223   return pNew;
51224 }
51225
51226 /*
51227 ** If cursors, triggers, views and subqueries are all omitted from
51228 ** the build, then none of the following routines, except for 
51229 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
51230 ** called with a NULL argument.
51231 */
51232 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
51233  || !defined(SQLITE_OMIT_SUBQUERY)
51234 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p){
51235   SrcList *pNew;
51236   int i;
51237   int nByte;
51238   if( p==0 ) return 0;
51239   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
51240   pNew = sqlite3DbMallocRaw(db, nByte );
51241   if( pNew==0 ) return 0;
51242   pNew->nSrc = pNew->nAlloc = p->nSrc;
51243   for(i=0; i<p->nSrc; i++){
51244     struct SrcList_item *pNewItem = &pNew->a[i];
51245     struct SrcList_item *pOldItem = &p->a[i];
51246     Table *pTab;
51247     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
51248     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
51249     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
51250     pNewItem->jointype = pOldItem->jointype;
51251     pNewItem->iCursor = pOldItem->iCursor;
51252     pNewItem->isPopulated = pOldItem->isPopulated;
51253     pTab = pNewItem->pTab = pOldItem->pTab;
51254     if( pTab ){
51255       pTab->nRef++;
51256     }
51257     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect);
51258     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn);
51259     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
51260     pNewItem->colUsed = pOldItem->colUsed;
51261   }
51262   return pNew;
51263 }
51264 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
51265   IdList *pNew;
51266   int i;
51267   if( p==0 ) return 0;
51268   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
51269   if( pNew==0 ) return 0;
51270   pNew->nId = pNew->nAlloc = p->nId;
51271   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
51272   if( pNew->a==0 ){
51273     sqlite3DbFree(db, pNew);
51274     return 0;
51275   }
51276   for(i=0; i<p->nId; i++){
51277     struct IdList_item *pNewItem = &pNew->a[i];
51278     struct IdList_item *pOldItem = &p->a[i];
51279     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
51280     pNewItem->idx = pOldItem->idx;
51281   }
51282   return pNew;
51283 }
51284 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p){
51285   Select *pNew;
51286   if( p==0 ) return 0;
51287   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
51288   if( pNew==0 ) return 0;
51289   pNew->isDistinct = p->isDistinct;
51290   pNew->pEList = sqlite3ExprListDup(db, p->pEList);
51291   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc);
51292   pNew->pWhere = sqlite3ExprDup(db, p->pWhere);
51293   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy);
51294   pNew->pHaving = sqlite3ExprDup(db, p->pHaving);
51295   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy);
51296   pNew->op = p->op;
51297   pNew->pPrior = sqlite3SelectDup(db, p->pPrior);
51298   pNew->pLimit = sqlite3ExprDup(db, p->pLimit);
51299   pNew->pOffset = sqlite3ExprDup(db, p->pOffset);
51300   pNew->iLimit = 0;
51301   pNew->iOffset = 0;
51302   pNew->isResolved = p->isResolved;
51303   pNew->isAgg = p->isAgg;
51304   pNew->usesEphm = 0;
51305   pNew->disallowOrderBy = 0;
51306   pNew->pRightmost = 0;
51307   pNew->addrOpenEphm[0] = -1;
51308   pNew->addrOpenEphm[1] = -1;
51309   pNew->addrOpenEphm[2] = -1;
51310   return pNew;
51311 }
51312 #else
51313 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p){
51314   assert( p==0 );
51315   return 0;
51316 }
51317 #endif
51318
51319
51320 /*
51321 ** Add a new element to the end of an expression list.  If pList is
51322 ** initially NULL, then create a new expression list.
51323 */
51324 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
51325   Parse *pParse,          /* Parsing context */
51326   ExprList *pList,        /* List to which to append. Might be NULL */
51327   Expr *pExpr,            /* Expression to be appended */
51328   Token *pName            /* AS keyword for the expression */
51329 ){
51330   sqlite3 *db = pParse->db;
51331   if( pList==0 ){
51332     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
51333     if( pList==0 ){
51334       goto no_mem;
51335     }
51336     assert( pList->nAlloc==0 );
51337   }
51338   if( pList->nAlloc<=pList->nExpr ){
51339     struct ExprList_item *a;
51340     int n = pList->nAlloc*2 + 4;
51341     a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
51342     if( a==0 ){
51343       goto no_mem;
51344     }
51345     pList->a = a;
51346     pList->nAlloc = n;
51347   }
51348   assert( pList->a!=0 );
51349   if( pExpr || pName ){
51350     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
51351     memset(pItem, 0, sizeof(*pItem));
51352     pItem->zName = sqlite3NameFromToken(db, pName);
51353     pItem->pExpr = pExpr;
51354   }
51355   return pList;
51356
51357 no_mem:     
51358   /* Avoid leaking memory if malloc has failed. */
51359   sqlite3ExprDelete(db, pExpr);
51360   sqlite3ExprListDelete(db, pList);
51361   return 0;
51362 }
51363
51364 /*
51365 ** If the expression list pEList contains more than iLimit elements,
51366 ** leave an error message in pParse.
51367 */
51368 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
51369   Parse *pParse,
51370   ExprList *pEList,
51371   const char *zObject
51372 ){
51373   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
51374   testcase( pEList && pEList->nExpr==mx );
51375   testcase( pEList && pEList->nExpr==mx+1 );
51376   if( pEList && pEList->nExpr>mx ){
51377     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
51378   }
51379 }
51380
51381 /*
51382 ** Delete an entire expression list.
51383 */
51384 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
51385   int i;
51386   struct ExprList_item *pItem;
51387   if( pList==0 ) return;
51388   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
51389   assert( pList->nExpr<=pList->nAlloc );
51390   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
51391     sqlite3ExprDelete(db, pItem->pExpr);
51392     sqlite3DbFree(db, pItem->zName);
51393   }
51394   sqlite3DbFree(db, pList->a);
51395   sqlite3DbFree(db, pList);
51396 }
51397
51398 /*
51399 ** Walk an expression tree.  Call xFunc for each node visited.  xFunc
51400 ** is called on the node before xFunc is called on the nodes children.
51401 **
51402 ** The return value from xFunc determines whether the tree walk continues.
51403 ** 0 means continue walking the tree.  1 means do not walk children
51404 ** of the current node but continue with siblings.  2 means abandon
51405 ** the tree walk completely.
51406 **
51407 ** The return value from this routine is 1 to abandon the tree walk
51408 ** and 0 to continue.
51409 **
51410 ** NOTICE:  This routine does *not* descend into subqueries.
51411 */
51412 static int walkExprList(ExprList *, int (*)(void *, Expr*), void *);
51413 static int walkExprTree(Expr *pExpr, int (*xFunc)(void*,Expr*), void *pArg){
51414   int rc;
51415   if( pExpr==0 ) return 0;
51416   rc = (*xFunc)(pArg, pExpr);
51417   if( rc==0 ){
51418     if( walkExprTree(pExpr->pLeft, xFunc, pArg) ) return 1;
51419     if( walkExprTree(pExpr->pRight, xFunc, pArg) ) return 1;
51420     if( walkExprList(pExpr->pList, xFunc, pArg) ) return 1;
51421   }
51422   return rc>1;
51423 }
51424
51425 /*
51426 ** Call walkExprTree() for every expression in list p.
51427 */
51428 static int walkExprList(ExprList *p, int (*xFunc)(void *, Expr*), void *pArg){
51429   int i;
51430   struct ExprList_item *pItem;
51431   if( !p ) return 0;
51432   for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
51433     if( walkExprTree(pItem->pExpr, xFunc, pArg) ) return 1;
51434   }
51435   return 0;
51436 }
51437
51438 /*
51439 ** Call walkExprTree() for every expression in Select p, not including
51440 ** expressions that are part of sub-selects in any FROM clause or the LIMIT
51441 ** or OFFSET expressions..
51442 */
51443 static int walkSelectExpr(Select *p, int (*xFunc)(void *, Expr*), void *pArg){
51444   walkExprList(p->pEList, xFunc, pArg);
51445   walkExprTree(p->pWhere, xFunc, pArg);
51446   walkExprList(p->pGroupBy, xFunc, pArg);
51447   walkExprTree(p->pHaving, xFunc, pArg);
51448   walkExprList(p->pOrderBy, xFunc, pArg);
51449   if( p->pPrior ){
51450     walkSelectExpr(p->pPrior, xFunc, pArg);
51451   }
51452   return 0;
51453 }
51454
51455
51456 /*
51457 ** This routine is designed as an xFunc for walkExprTree().
51458 **
51459 ** pArg is really a pointer to an integer.  If we can tell by looking
51460 ** at pExpr that the expression that contains pExpr is not a constant
51461 ** expression, then set *pArg to 0 and return 2 to abandon the tree walk.
51462 ** If pExpr does does not disqualify the expression from being a constant
51463 ** then do nothing.
51464 **
51465 ** After walking the whole tree, if no nodes are found that disqualify
51466 ** the expression as constant, then we assume the whole expression
51467 ** is constant.  See sqlite3ExprIsConstant() for additional information.
51468 */
51469 static int exprNodeIsConstant(void *pArg, Expr *pExpr){
51470   int *pN = (int*)pArg;
51471
51472   /* If *pArg is 3 then any term of the expression that comes from
51473   ** the ON or USING clauses of a join disqualifies the expression
51474   ** from being considered constant. */
51475   if( (*pN)==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
51476     *pN = 0;
51477     return 2;
51478   }
51479
51480   switch( pExpr->op ){
51481     /* Consider functions to be constant if all their arguments are constant
51482     ** and *pArg==2 */
51483     case TK_FUNCTION:
51484       if( (*pN)==2 ) return 0;
51485       /* Fall through */
51486     case TK_ID:
51487     case TK_COLUMN:
51488     case TK_DOT:
51489     case TK_AGG_FUNCTION:
51490     case TK_AGG_COLUMN:
51491 #ifndef SQLITE_OMIT_SUBQUERY
51492     case TK_SELECT:
51493     case TK_EXISTS:
51494       testcase( pExpr->op==TK_SELECT );
51495       testcase( pExpr->op==TK_EXISTS );
51496 #endif
51497       testcase( pExpr->op==TK_ID );
51498       testcase( pExpr->op==TK_COLUMN );
51499       testcase( pExpr->op==TK_DOT );
51500       testcase( pExpr->op==TK_AGG_FUNCTION );
51501       testcase( pExpr->op==TK_AGG_COLUMN );
51502       *pN = 0;
51503       return 2;
51504     case TK_IN:
51505       if( pExpr->pSelect ){
51506         *pN = 0;
51507         return 2;
51508       }
51509     default:
51510       return 0;
51511   }
51512 }
51513
51514 /*
51515 ** Walk an expression tree.  Return 1 if the expression is constant
51516 ** and 0 if it involves variables or function calls.
51517 **
51518 ** For the purposes of this function, a double-quoted string (ex: "abc")
51519 ** is considered a variable but a single-quoted string (ex: 'abc') is
51520 ** a constant.
51521 */
51522 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
51523   int isConst = 1;
51524   walkExprTree(p, exprNodeIsConstant, &isConst);
51525   return isConst;
51526 }
51527
51528 /*
51529 ** Walk an expression tree.  Return 1 if the expression is constant
51530 ** that does no originate from the ON or USING clauses of a join.
51531 ** Return 0 if it involves variables or function calls or terms from
51532 ** an ON or USING clause.
51533 */
51534 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
51535   int isConst = 3;
51536   walkExprTree(p, exprNodeIsConstant, &isConst);
51537   return isConst!=0;
51538 }
51539
51540 /*
51541 ** Walk an expression tree.  Return 1 if the expression is constant
51542 ** or a function call with constant arguments.  Return and 0 if there
51543 ** are any variables.
51544 **
51545 ** For the purposes of this function, a double-quoted string (ex: "abc")
51546 ** is considered a variable but a single-quoted string (ex: 'abc') is
51547 ** a constant.
51548 */
51549 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
51550   int isConst = 2;
51551   walkExprTree(p, exprNodeIsConstant, &isConst);
51552   return isConst!=0;
51553 }
51554
51555 /*
51556 ** If the expression p codes a constant integer that is small enough
51557 ** to fit in a 32-bit integer, return 1 and put the value of the integer
51558 ** in *pValue.  If the expression is not an integer or if it is too big
51559 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
51560 */
51561 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
51562   int rc = 0;
51563   if( p->flags & EP_IntValue ){
51564     *pValue = p->iTable;
51565     return 1;
51566   }
51567   switch( p->op ){
51568     case TK_INTEGER: {
51569       rc = sqlite3GetInt32((char*)p->token.z, pValue);
51570       break;
51571     }
51572     case TK_UPLUS: {
51573       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
51574       break;
51575     }
51576     case TK_UMINUS: {
51577       int v;
51578       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
51579         *pValue = -v;
51580         rc = 1;
51581       }
51582       break;
51583     }
51584     default: break;
51585   }
51586   if( rc ){
51587     p->op = TK_INTEGER;
51588     p->flags |= EP_IntValue;
51589     p->iTable = *pValue;
51590   }
51591   return rc;
51592 }
51593
51594 /*
51595 ** Return TRUE if the given string is a row-id column name.
51596 */
51597 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
51598   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
51599   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
51600   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
51601   return 0;
51602 }
51603
51604 /*
51605 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
51606 ** that name in the set of source tables in pSrcList and make the pExpr 
51607 ** expression node refer back to that source column.  The following changes
51608 ** are made to pExpr:
51609 **
51610 **    pExpr->iDb           Set the index in db->aDb[] of the database holding
51611 **                         the table.
51612 **    pExpr->iTable        Set to the cursor number for the table obtained
51613 **                         from pSrcList.
51614 **    pExpr->iColumn       Set to the column number within the table.
51615 **    pExpr->op            Set to TK_COLUMN.
51616 **    pExpr->pLeft         Any expression this points to is deleted
51617 **    pExpr->pRight        Any expression this points to is deleted.
51618 **
51619 ** The pDbToken is the name of the database (the "X").  This value may be
51620 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
51621 ** can be used.  The pTableToken is the name of the table (the "Y").  This
51622 ** value can be NULL if pDbToken is also NULL.  If pTableToken is NULL it
51623 ** means that the form of the name is Z and that columns from any table
51624 ** can be used.
51625 **
51626 ** If the name cannot be resolved unambiguously, leave an error message
51627 ** in pParse and return non-zero.  Return zero on success.
51628 */
51629 static int lookupName(
51630   Parse *pParse,       /* The parsing context */
51631   Token *pDbToken,     /* Name of the database containing table, or NULL */
51632   Token *pTableToken,  /* Name of table containing column, or NULL */
51633   Token *pColumnToken, /* Name of the column. */
51634   NameContext *pNC,    /* The name context used to resolve the name */
51635   Expr *pExpr          /* Make this EXPR node point to the selected column */
51636 ){
51637   char *zDb = 0;       /* Name of the database.  The "X" in X.Y.Z */
51638   char *zTab = 0;      /* Name of the table.  The "Y" in X.Y.Z or Y.Z */
51639   char *zCol = 0;      /* Name of the column.  The "Z" */
51640   int i, j;            /* Loop counters */
51641   int cnt = 0;         /* Number of matching column names */
51642   int cntTab = 0;      /* Number of matching table names */
51643   sqlite3 *db = pParse->db;  /* The database */
51644   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
51645   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
51646   NameContext *pTopNC = pNC;        /* First namecontext in the list */
51647   Schema *pSchema = 0;              /* Schema of the expression */
51648
51649   assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
51650   zDb = sqlite3NameFromToken(db, pDbToken);
51651   zTab = sqlite3NameFromToken(db, pTableToken);
51652   zCol = sqlite3NameFromToken(db, pColumnToken);
51653   if( db->mallocFailed ){
51654     goto lookupname_end;
51655   }
51656
51657   pExpr->iTable = -1;
51658   while( pNC && cnt==0 ){
51659     ExprList *pEList;
51660     SrcList *pSrcList = pNC->pSrcList;
51661
51662     if( pSrcList ){
51663       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
51664         Table *pTab;
51665         int iDb;
51666         Column *pCol;
51667   
51668         pTab = pItem->pTab;
51669         assert( pTab!=0 );
51670         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
51671         assert( pTab->nCol>0 );
51672         if( zTab ){
51673           if( pItem->zAlias ){
51674             char *zTabName = pItem->zAlias;
51675             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
51676           }else{
51677             char *zTabName = pTab->zName;
51678             if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
51679             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
51680               continue;
51681             }
51682           }
51683         }
51684         if( 0==(cntTab++) ){
51685           pExpr->iTable = pItem->iCursor;
51686           pSchema = pTab->pSchema;
51687           pMatch = pItem;
51688         }
51689         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
51690           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
51691             const char *zColl = pTab->aCol[j].zColl;
51692             IdList *pUsing;
51693             cnt++;
51694             pExpr->iTable = pItem->iCursor;
51695             pMatch = pItem;
51696             pSchema = pTab->pSchema;
51697             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
51698             pExpr->iColumn = j==pTab->iPKey ? -1 : j;
51699             pExpr->affinity = pTab->aCol[j].affinity;
51700             if( (pExpr->flags & EP_ExpCollate)==0 ){
51701               pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
51702             }
51703             if( i<pSrcList->nSrc-1 ){
51704               if( pItem[1].jointype & JT_NATURAL ){
51705                 /* If this match occurred in the left table of a natural join,
51706                 ** then skip the right table to avoid a duplicate match */
51707                 pItem++;
51708                 i++;
51709               }else if( (pUsing = pItem[1].pUsing)!=0 ){
51710                 /* If this match occurs on a column that is in the USING clause
51711                 ** of a join, skip the search of the right table of the join
51712                 ** to avoid a duplicate match there. */
51713                 int k;
51714                 for(k=0; k<pUsing->nId; k++){
51715                   if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
51716                     pItem++;
51717                     i++;
51718                     break;
51719                   }
51720                 }
51721               }
51722             }
51723             break;
51724           }
51725         }
51726       }
51727     }
51728
51729 #ifndef SQLITE_OMIT_TRIGGER
51730     /* If we have not already resolved the name, then maybe 
51731     ** it is a new.* or old.* trigger argument reference
51732     */
51733     if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
51734       TriggerStack *pTriggerStack = pParse->trigStack;
51735       Table *pTab = 0;
51736       u32 *piColMask;
51737       if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
51738         pExpr->iTable = pTriggerStack->newIdx;
51739         assert( pTriggerStack->pTab );
51740         pTab = pTriggerStack->pTab;
51741         piColMask = &(pTriggerStack->newColMask);
51742       }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
51743         pExpr->iTable = pTriggerStack->oldIdx;
51744         assert( pTriggerStack->pTab );
51745         pTab = pTriggerStack->pTab;
51746         piColMask = &(pTriggerStack->oldColMask);
51747       }
51748
51749       if( pTab ){ 
51750         int iCol;
51751         Column *pCol = pTab->aCol;
51752
51753         pSchema = pTab->pSchema;
51754         cntTab++;
51755         for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) {
51756           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
51757             const char *zColl = pTab->aCol[iCol].zColl;
51758             cnt++;
51759             pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
51760             pExpr->affinity = pTab->aCol[iCol].affinity;
51761             if( (pExpr->flags & EP_ExpCollate)==0 ){
51762               pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
51763             }
51764             pExpr->pTab = pTab;
51765             if( iCol>=0 ){
51766               testcase( iCol==31 );
51767               testcase( iCol==32 );
51768               *piColMask |= ((u32)1<<iCol) | (iCol>=32?0xffffffff:0);
51769             }
51770             break;
51771           }
51772         }
51773       }
51774     }
51775 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
51776
51777     /*
51778     ** Perhaps the name is a reference to the ROWID
51779     */
51780     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
51781       cnt = 1;
51782       pExpr->iColumn = -1;
51783       pExpr->affinity = SQLITE_AFF_INTEGER;
51784     }
51785
51786     /*
51787     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
51788     ** might refer to an result-set alias.  This happens, for example, when
51789     ** we are resolving names in the WHERE clause of the following command:
51790     **
51791     **     SELECT a+b AS x FROM table WHERE x<10;
51792     **
51793     ** In cases like this, replace pExpr with a copy of the expression that
51794     ** forms the result set entry ("a+b" in the example) and return immediately.
51795     ** Note that the expression in the result set should have already been
51796     ** resolved by the time the WHERE clause is resolved.
51797     */
51798     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
51799       for(j=0; j<pEList->nExpr; j++){
51800         char *zAs = pEList->a[j].zName;
51801         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
51802           Expr *pDup, *pOrig;
51803           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
51804           assert( pExpr->pList==0 );
51805           assert( pExpr->pSelect==0 );
51806           pOrig = pEList->a[j].pExpr;
51807           if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
51808             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
51809             sqlite3DbFree(db, zCol);
51810             return 2;
51811           }
51812           pDup = sqlite3ExprDup(db, pOrig);
51813           if( pExpr->flags & EP_ExpCollate ){
51814             pDup->pColl = pExpr->pColl;
51815             pDup->flags |= EP_ExpCollate;
51816           }
51817           if( pExpr->span.dyn ) sqlite3DbFree(db, (char*)pExpr->span.z);
51818           if( pExpr->token.dyn ) sqlite3DbFree(db, (char*)pExpr->token.z);
51819           memcpy(pExpr, pDup, sizeof(*pExpr));
51820           sqlite3DbFree(db, pDup);
51821           cnt = 1;
51822           pMatch = 0;
51823           assert( zTab==0 && zDb==0 );
51824           goto lookupname_end_2;
51825         }
51826       } 
51827     }
51828
51829     /* Advance to the next name context.  The loop will exit when either
51830     ** we have a match (cnt>0) or when we run out of name contexts.
51831     */
51832     if( cnt==0 ){
51833       pNC = pNC->pNext;
51834     }
51835   }
51836
51837   /*
51838   ** If X and Y are NULL (in other words if only the column name Z is
51839   ** supplied) and the value of Z is enclosed in double-quotes, then
51840   ** Z is a string literal if it doesn't match any column names.  In that
51841   ** case, we need to return right away and not make any changes to
51842   ** pExpr.
51843   **
51844   ** Because no reference was made to outer contexts, the pNC->nRef
51845   ** fields are not changed in any context.
51846   */
51847   if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
51848     sqlite3DbFree(db, zCol);
51849     return 0;
51850   }
51851
51852   /*
51853   ** cnt==0 means there was not match.  cnt>1 means there were two or
51854   ** more matches.  Either way, we have an error.
51855   */
51856   if( cnt!=1 ){
51857     const char *zErr;
51858     zErr = cnt==0 ? "no such column" : "ambiguous column name";
51859     if( zDb ){
51860       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
51861     }else if( zTab ){
51862       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
51863     }else{
51864       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
51865     }
51866     pTopNC->nErr++;
51867   }
51868
51869   /* If a column from a table in pSrcList is referenced, then record
51870   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
51871   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
51872   ** column number is greater than the number of bits in the bitmask
51873   ** then set the high-order bit of the bitmask.
51874   */
51875   if( pExpr->iColumn>=0 && pMatch!=0 ){
51876     int n = pExpr->iColumn;
51877     testcase( n==sizeof(Bitmask)*8-1 );
51878     if( n>=sizeof(Bitmask)*8 ){
51879       n = sizeof(Bitmask)*8-1;
51880     }
51881     assert( pMatch->iCursor==pExpr->iTable );
51882     pMatch->colUsed |= ((Bitmask)1)<<n;
51883   }
51884
51885 lookupname_end:
51886   /* Clean up and return
51887   */
51888   sqlite3DbFree(db, zDb);
51889   sqlite3DbFree(db, zTab);
51890   sqlite3ExprDelete(db, pExpr->pLeft);
51891   pExpr->pLeft = 0;
51892   sqlite3ExprDelete(db, pExpr->pRight);
51893   pExpr->pRight = 0;
51894   pExpr->op = TK_COLUMN;
51895 lookupname_end_2:
51896   sqlite3DbFree(db, zCol);
51897   if( cnt==1 ){
51898     assert( pNC!=0 );
51899     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
51900     if( pMatch && !pMatch->pSelect ){
51901       pExpr->pTab = pMatch->pTab;
51902     }
51903     /* Increment the nRef value on all name contexts from TopNC up to
51904     ** the point where the name matched. */
51905     for(;;){
51906       assert( pTopNC!=0 );
51907       pTopNC->nRef++;
51908       if( pTopNC==pNC ) break;
51909       pTopNC = pTopNC->pNext;
51910     }
51911     return 0;
51912   } else {
51913     return 1;
51914   }
51915 }
51916
51917 /*
51918 ** This routine is designed as an xFunc for walkExprTree().
51919 **
51920 ** Resolve symbolic names into TK_COLUMN operators for the current
51921 ** node in the expression tree.  Return 0 to continue the search down
51922 ** the tree or 2 to abort the tree walk.
51923 **
51924 ** This routine also does error checking and name resolution for
51925 ** function names.  The operator for aggregate functions is changed
51926 ** to TK_AGG_FUNCTION.
51927 */
51928 static int nameResolverStep(void *pArg, Expr *pExpr){
51929   NameContext *pNC = (NameContext*)pArg;
51930   Parse *pParse;
51931
51932   if( pExpr==0 ) return 1;
51933   assert( pNC!=0 );
51934   pParse = pNC->pParse;
51935
51936   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return 1;
51937   ExprSetProperty(pExpr, EP_Resolved);
51938 #ifndef NDEBUG
51939   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
51940     SrcList *pSrcList = pNC->pSrcList;
51941     int i;
51942     for(i=0; i<pNC->pSrcList->nSrc; i++){
51943       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
51944     }
51945   }
51946 #endif
51947   switch( pExpr->op ){
51948     /* Double-quoted strings (ex: "abc") are used as identifiers if
51949     ** possible.  Otherwise they remain as strings.  Single-quoted
51950     ** strings (ex: 'abc') are always string literals.
51951     */
51952     case TK_STRING: {
51953       if( pExpr->token.z[0]=='\'' ) break;
51954       /* Fall thru into the TK_ID case if this is a double-quoted string */
51955     }
51956     /* A lone identifier is the name of a column.
51957     */
51958     case TK_ID: {
51959       lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr);
51960       return 1;
51961     }
51962   
51963     /* A table name and column name:     ID.ID
51964     ** Or a database, table and column:  ID.ID.ID
51965     */
51966     case TK_DOT: {
51967       Token *pColumn;
51968       Token *pTable;
51969       Token *pDb;
51970       Expr *pRight;
51971
51972       /* if( pSrcList==0 ) break; */
51973       pRight = pExpr->pRight;
51974       if( pRight->op==TK_ID ){
51975         pDb = 0;
51976         pTable = &pExpr->pLeft->token;
51977         pColumn = &pRight->token;
51978       }else{
51979         assert( pRight->op==TK_DOT );
51980         pDb = &pExpr->pLeft->token;
51981         pTable = &pRight->pLeft->token;
51982         pColumn = &pRight->pRight->token;
51983       }
51984       lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr);
51985       return 1;
51986     }
51987
51988     /* Resolve function names
51989     */
51990     case TK_CONST_FUNC:
51991     case TK_FUNCTION: {
51992       ExprList *pList = pExpr->pList;    /* The argument list */
51993       int n = pList ? pList->nExpr : 0;  /* Number of arguments */
51994       int no_such_func = 0;       /* True if no such function exists */
51995       int wrong_num_args = 0;     /* True if wrong number of arguments */
51996       int is_agg = 0;             /* True if is an aggregate function */
51997       int i;
51998       int auth;                   /* Authorization to use the function */
51999       int nId;                    /* Number of characters in function name */
52000       const char *zId;            /* The function name. */
52001       FuncDef *pDef;              /* Information about the function */
52002       int enc = ENC(pParse->db);  /* The database encoding */
52003
52004       zId = (char*)pExpr->token.z;
52005       nId = pExpr->token.n;
52006       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
52007       if( pDef==0 ){
52008         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
52009         if( pDef==0 ){
52010           no_such_func = 1;
52011         }else{
52012           wrong_num_args = 1;
52013         }
52014       }else{
52015         is_agg = pDef->xFunc==0;
52016       }
52017 #ifndef SQLITE_OMIT_AUTHORIZATION
52018       if( pDef ){
52019         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
52020         if( auth!=SQLITE_OK ){
52021           if( auth==SQLITE_DENY ){
52022             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
52023                                     pDef->zName);
52024             pNC->nErr++;
52025           }
52026           pExpr->op = TK_NULL;
52027           return 1;
52028         }
52029       }
52030 #endif
52031       if( is_agg && !pNC->allowAgg ){
52032         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
52033         pNC->nErr++;
52034         is_agg = 0;
52035       }else if( no_such_func ){
52036         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
52037         pNC->nErr++;
52038       }else if( wrong_num_args ){
52039         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
52040              nId, zId);
52041         pNC->nErr++;
52042       }
52043       if( is_agg ){
52044         pExpr->op = TK_AGG_FUNCTION;
52045         pNC->hasAgg = 1;
52046       }
52047       if( is_agg ) pNC->allowAgg = 0;
52048       for(i=0; pNC->nErr==0 && i<n; i++){
52049         walkExprTree(pList->a[i].pExpr, nameResolverStep, pNC);
52050       }
52051       if( is_agg ) pNC->allowAgg = 1;
52052       /* FIX ME:  Compute pExpr->affinity based on the expected return
52053       ** type of the function 
52054       */
52055       return is_agg;
52056     }
52057 #ifndef SQLITE_OMIT_SUBQUERY
52058     case TK_SELECT:
52059     case TK_EXISTS:
52060 #endif
52061     case TK_IN: {
52062       if( pExpr->pSelect ){
52063         int nRef = pNC->nRef;
52064 #ifndef SQLITE_OMIT_CHECK
52065         if( pNC->isCheck ){
52066           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
52067         }
52068 #endif
52069         sqlite3SelectResolve(pParse, pExpr->pSelect, pNC);
52070         assert( pNC->nRef>=nRef );
52071         if( nRef!=pNC->nRef ){
52072           ExprSetProperty(pExpr, EP_VarSelect);
52073         }
52074       }
52075       break;
52076     }
52077 #ifndef SQLITE_OMIT_CHECK
52078     case TK_VARIABLE: {
52079       if( pNC->isCheck ){
52080         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
52081       }
52082       break;
52083     }
52084 #endif
52085   }
52086   return 0;
52087 }
52088
52089 /*
52090 ** This routine walks an expression tree and resolves references to
52091 ** table columns.  Nodes of the form ID.ID or ID resolve into an
52092 ** index to the table in the table list and a column offset.  The 
52093 ** Expr.opcode for such nodes is changed to TK_COLUMN.  The Expr.iTable
52094 ** value is changed to the index of the referenced table in pTabList
52095 ** plus the "base" value.  The base value will ultimately become the
52096 ** VDBE cursor number for a cursor that is pointing into the referenced
52097 ** table.  The Expr.iColumn value is changed to the index of the column 
52098 ** of the referenced table.  The Expr.iColumn value for the special
52099 ** ROWID column is -1.  Any INTEGER PRIMARY KEY column is tried as an
52100 ** alias for ROWID.
52101 **
52102 ** Also resolve function names and check the functions for proper
52103 ** usage.  Make sure all function names are recognized and all functions
52104 ** have the correct number of arguments.  Leave an error message
52105 ** in pParse->zErrMsg if anything is amiss.  Return the number of errors.
52106 **
52107 ** If the expression contains aggregate functions then set the EP_Agg
52108 ** property on the expression.
52109 */
52110 SQLITE_PRIVATE int sqlite3ExprResolveNames( 
52111   NameContext *pNC,       /* Namespace to resolve expressions in. */
52112   Expr *pExpr             /* The expression to be analyzed. */
52113 ){
52114   int savedHasAgg;
52115
52116   if( pExpr==0 ) return 0;
52117 #if SQLITE_MAX_EXPR_DEPTH>0
52118   {
52119     if( checkExprHeight(pNC->pParse, pExpr->nHeight + pNC->pParse->nHeight) ){
52120       return 1;
52121     }
52122     pNC->pParse->nHeight += pExpr->nHeight;
52123   }
52124 #endif
52125   savedHasAgg = pNC->hasAgg;
52126   pNC->hasAgg = 0;
52127   walkExprTree(pExpr, nameResolverStep, pNC);
52128 #if SQLITE_MAX_EXPR_DEPTH>0
52129   pNC->pParse->nHeight -= pExpr->nHeight;
52130 #endif
52131   if( pNC->nErr>0 ){
52132     ExprSetProperty(pExpr, EP_Error);
52133   }
52134   if( pNC->hasAgg ){
52135     ExprSetProperty(pExpr, EP_Agg);
52136   }else if( savedHasAgg ){
52137     pNC->hasAgg = 1;
52138   }
52139   return ExprHasProperty(pExpr, EP_Error);
52140 }
52141
52142 /*
52143 ** A pointer instance of this structure is used to pass information
52144 ** through walkExprTree into codeSubqueryStep().
52145 */
52146 typedef struct QueryCoder QueryCoder;
52147 struct QueryCoder {
52148   Parse *pParse;       /* The parsing context */
52149   NameContext *pNC;    /* Namespace of first enclosing query */
52150 };
52151
52152 #ifdef SQLITE_TEST
52153   int sqlite3_enable_in_opt = 1;
52154 #else
52155   #define sqlite3_enable_in_opt 1
52156 #endif
52157
52158 /*
52159 ** Return true if the IN operator optimization is enabled and
52160 ** the SELECT statement p exists and is of the
52161 ** simple form:
52162 **
52163 **     SELECT <column> FROM <table>
52164 **
52165 ** If this is the case, it may be possible to use an existing table
52166 ** or index instead of generating an epheremal table.
52167 */
52168 #ifndef SQLITE_OMIT_SUBQUERY
52169 static int isCandidateForInOpt(Select *p){
52170   SrcList *pSrc;
52171   ExprList *pEList;
52172   Table *pTab;
52173   if( !sqlite3_enable_in_opt ) return 0; /* IN optimization must be enabled */
52174   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
52175   if( p->pPrior ) return 0;              /* Not a compound SELECT */
52176   if( p->isDistinct ) return 0;          /* No DISTINCT keyword */
52177   if( p->isAgg ) return 0;               /* Contains no aggregate functions */
52178   if( p->pGroupBy ) return 0;            /* Has no GROUP BY clause */
52179   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
52180   if( p->pOffset ) return 0;
52181   if( p->pWhere ) return 0;              /* Has no WHERE clause */
52182   pSrc = p->pSrc;
52183   if( pSrc==0 ) return 0;                /* A single table in the FROM clause */
52184   if( pSrc->nSrc!=1 ) return 0;
52185   if( pSrc->a[0].pSelect ) return 0;     /* FROM clause is not a subquery */
52186   pTab = pSrc->a[0].pTab;
52187   if( pTab==0 ) return 0;
52188   if( pTab->pSelect ) return 0;          /* FROM clause is not a view */
52189   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
52190   pEList = p->pEList;
52191   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
52192   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
52193   return 1;
52194 }
52195 #endif /* SQLITE_OMIT_SUBQUERY */
52196
52197 /*
52198 ** This function is used by the implementation of the IN (...) operator.
52199 ** It's job is to find or create a b-tree structure that may be used
52200 ** either to test for membership of the (...) set or to iterate through
52201 ** its members, skipping duplicates.
52202 **
52203 ** The cursor opened on the structure (database table, database index 
52204 ** or ephermal table) is stored in pX->iTable before this function returns.
52205 ** The returned value indicates the structure type, as follows:
52206 **
52207 **   IN_INDEX_ROWID - The cursor was opened on a database table.
52208 **   IN_INDEX_INDEX - The cursor was opened on a database index.
52209 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
52210 **                    populated epheremal table.
52211 **
52212 ** An existing structure may only be used if the SELECT is of the simple
52213 ** form:
52214 **
52215 **     SELECT <column> FROM <table>
52216 **
52217 ** If prNotFound parameter is 0, then the structure will be used to iterate
52218 ** through the set members, skipping any duplicates. In this case an
52219 ** epheremal table must be used unless the selected <column> is guaranteed
52220 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
52221 ** is unique by virtue of a constraint or implicit index.
52222 **
52223 ** If the prNotFound parameter is not 0, then the structure will be used 
52224 ** for fast set membership tests. In this case an epheremal table must 
52225 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can 
52226 ** be found with <column> as its left-most column.
52227 **
52228 ** When the structure is being used for set membership tests, the user
52229 ** needs to know whether or not the structure contains an SQL NULL 
52230 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
52231 ** If there is a chance that the structure may contain a NULL value at
52232 ** runtime, then a register is allocated and the register number written
52233 ** to *prNotFound. If there is no chance that the structure contains a
52234 ** NULL value, then *prNotFound is left unchanged.
52235 **
52236 ** If a register is allocated and its location stored in *prNotFound, then
52237 ** its initial value is NULL. If the structure does not remain constant
52238 ** for the duration of the query (i.e. the set is a correlated sub-select), 
52239 ** the value of the allocated register is reset to NULL each time the 
52240 ** structure is repopulated. This allows the caller to use vdbe code 
52241 ** equivalent to the following:
52242 **
52243 **   if( register==NULL ){
52244 **     has_null = <test if data structure contains null>
52245 **     register = 1
52246 **   }
52247 **
52248 ** in order to avoid running the <test if data structure contains null>
52249 ** test more often than is necessary.
52250 */
52251 #ifndef SQLITE_OMIT_SUBQUERY
52252 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
52253   Select *p;
52254   int eType = 0;
52255   int iTab = pParse->nTab++;
52256   int mustBeUnique = !prNotFound;
52257
52258   /* The follwing if(...) expression is true if the SELECT is of the 
52259   ** simple form:
52260   **
52261   **     SELECT <column> FROM <table>
52262   **
52263   ** If this is the case, it may be possible to use an existing table
52264   ** or index instead of generating an epheremal table.
52265   */
52266   p = pX->pSelect;
52267   if( isCandidateForInOpt(p) ){
52268     sqlite3 *db = pParse->db;
52269     Index *pIdx;
52270     Expr *pExpr = p->pEList->a[0].pExpr;
52271     int iCol = pExpr->iColumn;
52272     Vdbe *v = sqlite3GetVdbe(pParse);
52273
52274     /* This function is only called from two places. In both cases the vdbe
52275     ** has already been allocated. So assume sqlite3GetVdbe() is always
52276     ** successful here.
52277     */
52278     assert(v);
52279     if( iCol<0 ){
52280       int iMem = ++pParse->nMem;
52281       int iAddr;
52282       Table *pTab = p->pSrc->a[0].pTab;
52283       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
52284       sqlite3VdbeUsesBtree(v, iDb);
52285
52286       iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
52287       sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
52288
52289       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
52290       eType = IN_INDEX_ROWID;
52291
52292       sqlite3VdbeJumpHere(v, iAddr);
52293     }else{
52294       /* The collation sequence used by the comparison. If an index is to 
52295       ** be used in place of a temp-table, it must be ordered according
52296       ** to this collation sequence.
52297       */
52298       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
52299
52300       /* Check that the affinity that will be used to perform the 
52301       ** comparison is the same as the affinity of the column. If
52302       ** it is not, it is not possible to use any index.
52303       */
52304       Table *pTab = p->pSrc->a[0].pTab;
52305       char aff = comparisonAffinity(pX);
52306       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
52307
52308       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
52309         if( (pIdx->aiColumn[0]==iCol)
52310          && (pReq==sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], -1, 0))
52311          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
52312         ){
52313           int iDb;
52314           int iMem = ++pParse->nMem;
52315           int iAddr;
52316           char *pKey;
52317   
52318           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
52319           iDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
52320           sqlite3VdbeUsesBtree(v, iDb);
52321
52322           iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
52323           sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
52324   
52325           sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pIdx->nColumn);
52326           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
52327                                pKey,P4_KEYINFO_HANDOFF);
52328           VdbeComment((v, "%s", pIdx->zName));
52329           eType = IN_INDEX_INDEX;
52330
52331           sqlite3VdbeJumpHere(v, iAddr);
52332           if( prNotFound && !pTab->aCol[iCol].notNull ){
52333             *prNotFound = ++pParse->nMem;
52334           }
52335         }
52336       }
52337     }
52338   }
52339
52340   if( eType==0 ){
52341     int rMayHaveNull = 0;
52342     if( prNotFound ){
52343       *prNotFound = rMayHaveNull = ++pParse->nMem;
52344     }
52345     sqlite3CodeSubselect(pParse, pX, rMayHaveNull);
52346     eType = IN_INDEX_EPH;
52347   }else{
52348     pX->iTable = iTab;
52349   }
52350   return eType;
52351 }
52352 #endif
52353
52354 /*
52355 ** Generate code for scalar subqueries used as an expression
52356 ** and IN operators.  Examples:
52357 **
52358 **     (SELECT a FROM b)          -- subquery
52359 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
52360 **     x IN (4,5,11)              -- IN operator with list on right-hand side
52361 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
52362 **
52363 ** The pExpr parameter describes the expression that contains the IN
52364 ** operator or subquery.
52365 */
52366 #ifndef SQLITE_OMIT_SUBQUERY
52367 SQLITE_PRIVATE void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr, int rMayHaveNull){
52368   int testAddr = 0;                       /* One-time test address */
52369   Vdbe *v = sqlite3GetVdbe(pParse);
52370   if( v==0 ) return;
52371
52372
52373   /* This code must be run in its entirety every time it is encountered
52374   ** if any of the following is true:
52375   **
52376   **    *  The right-hand side is a correlated subquery
52377   **    *  The right-hand side is an expression list containing variables
52378   **    *  We are inside a trigger
52379   **
52380   ** If all of the above are false, then we can run this code just once
52381   ** save the results, and reuse the same result on subsequent invocations.
52382   */
52383   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
52384     int mem = ++pParse->nMem;
52385     sqlite3VdbeAddOp1(v, OP_If, mem);
52386     testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
52387     assert( testAddr>0 || pParse->db->mallocFailed );
52388   }
52389
52390   switch( pExpr->op ){
52391     case TK_IN: {
52392       char affinity;
52393       KeyInfo keyInfo;
52394       int addr;        /* Address of OP_OpenEphemeral instruction */
52395
52396       if( rMayHaveNull ){
52397         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
52398       }
52399
52400       affinity = sqlite3ExprAffinity(pExpr->pLeft);
52401
52402       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
52403       ** expression it is handled the same way. A virtual table is 
52404       ** filled with single-field index keys representing the results
52405       ** from the SELECT or the <exprlist>.
52406       **
52407       ** If the 'x' expression is a column value, or the SELECT...
52408       ** statement returns a column value, then the affinity of that
52409       ** column is used to build the index keys. If both 'x' and the
52410       ** SELECT... statement are columns, then numeric affinity is used
52411       ** if either column has NUMERIC or INTEGER affinity. If neither
52412       ** 'x' nor the SELECT... statement are columns, then numeric affinity
52413       ** is used.
52414       */
52415       pExpr->iTable = pParse->nTab++;
52416       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, 1);
52417       memset(&keyInfo, 0, sizeof(keyInfo));
52418       keyInfo.nField = 1;
52419
52420       if( pExpr->pSelect ){
52421         /* Case 1:     expr IN (SELECT ...)
52422         **
52423         ** Generate code to write the results of the select into the temporary
52424         ** table allocated and opened above.
52425         */
52426         SelectDest dest;
52427         ExprList *pEList;
52428
52429         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
52430         dest.affinity = (int)affinity;
52431         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
52432         if( sqlite3Select(pParse, pExpr->pSelect, &dest, 0, 0, 0) ){
52433           return;
52434         }
52435         pEList = pExpr->pSelect->pEList;
52436         if( pEList && pEList->nExpr>0 ){ 
52437           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
52438               pEList->a[0].pExpr);
52439         }
52440       }else if( pExpr->pList ){
52441         /* Case 2:     expr IN (exprlist)
52442         **
52443         ** For each expression, build an index key from the evaluation and
52444         ** store it in the temporary table. If <expr> is a column, then use
52445         ** that columns affinity when building index keys. If <expr> is not
52446         ** a column, use numeric affinity.
52447         */
52448         int i;
52449         ExprList *pList = pExpr->pList;
52450         struct ExprList_item *pItem;
52451         int r1, r2, r3;
52452
52453         if( !affinity ){
52454           affinity = SQLITE_AFF_NONE;
52455         }
52456         keyInfo.aColl[0] = pExpr->pLeft->pColl;
52457
52458         /* Loop through each expression in <exprlist>. */
52459         r1 = sqlite3GetTempReg(pParse);
52460         r2 = sqlite3GetTempReg(pParse);
52461         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
52462           Expr *pE2 = pItem->pExpr;
52463
52464           /* If the expression is not constant then we will need to
52465           ** disable the test that was generated above that makes sure
52466           ** this code only executes once.  Because for a non-constant
52467           ** expression we need to rerun this code each time.
52468           */
52469           if( testAddr && !sqlite3ExprIsConstant(pE2) ){
52470             sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
52471             testAddr = 0;
52472           }
52473
52474           /* Evaluate the expression and insert it into the temp table */
52475           pParse->disableColCache++;
52476           r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
52477           assert( pParse->disableColCache>0 );
52478           pParse->disableColCache--;
52479           sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
52480           sqlite3ExprCacheAffinityChange(pParse, r3, 1);
52481           sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
52482         }
52483         sqlite3ReleaseTempReg(pParse, r1);
52484         sqlite3ReleaseTempReg(pParse, r2);
52485       }
52486       sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
52487       break;
52488     }
52489
52490     case TK_EXISTS:
52491     case TK_SELECT: {
52492       /* This has to be a scalar SELECT.  Generate code to put the
52493       ** value of this select in a memory cell and record the number
52494       ** of the memory cell in iColumn.
52495       */
52496       static const Token one = { (u8*)"1", 0, 1 };
52497       Select *pSel;
52498       SelectDest dest;
52499
52500       pSel = pExpr->pSelect;
52501       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
52502       if( pExpr->op==TK_SELECT ){
52503         dest.eDest = SRT_Mem;
52504         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
52505         VdbeComment((v, "Init subquery result"));
52506       }else{
52507         dest.eDest = SRT_Exists;
52508         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
52509         VdbeComment((v, "Init EXISTS result"));
52510       }
52511       sqlite3ExprDelete(pParse->db, pSel->pLimit);
52512       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one);
52513       if( sqlite3Select(pParse, pSel, &dest, 0, 0, 0) ){
52514         return;
52515       }
52516       pExpr->iColumn = dest.iParm;
52517       break;
52518     }
52519   }
52520
52521   if( testAddr ){
52522     sqlite3VdbeJumpHere(v, testAddr-1);
52523   }
52524
52525   return;
52526 }
52527 #endif /* SQLITE_OMIT_SUBQUERY */
52528
52529 /*
52530 ** Duplicate an 8-byte value
52531 */
52532 static char *dup8bytes(Vdbe *v, const char *in){
52533   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
52534   if( out ){
52535     memcpy(out, in, 8);
52536   }
52537   return out;
52538 }
52539
52540 /*
52541 ** Generate an instruction that will put the floating point
52542 ** value described by z[0..n-1] into register iMem.
52543 **
52544 ** The z[] string will probably not be zero-terminated.  But the 
52545 ** z[n] character is guaranteed to be something that does not look
52546 ** like the continuation of the number.
52547 */
52548 static void codeReal(Vdbe *v, const char *z, int n, int negateFlag, int iMem){
52549   assert( z || v==0 || sqlite3VdbeDb(v)->mallocFailed );
52550   if( z ){
52551     double value;
52552     char *zV;
52553     assert( !isdigit(z[n]) );
52554     sqlite3AtoF(z, &value);
52555     if( sqlite3IsNaN(value) ){
52556       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem);
52557     }else{
52558       if( negateFlag ) value = -value;
52559       zV = dup8bytes(v, (char*)&value);
52560       sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
52561     }
52562   }
52563 }
52564
52565
52566 /*
52567 ** Generate an instruction that will put the integer describe by
52568 ** text z[0..n-1] into register iMem.
52569 **
52570 ** The z[] string will probably not be zero-terminated.  But the 
52571 ** z[n] character is guaranteed to be something that does not look
52572 ** like the continuation of the number.
52573 */
52574 static void codeInteger(Vdbe *v, Expr *pExpr, int negFlag, int iMem){
52575   const char *z;
52576   if( pExpr->flags & EP_IntValue ){
52577     int i = pExpr->iTable;
52578     if( negFlag ) i = -i;
52579     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
52580   }else if( (z = (char*)pExpr->token.z)!=0 ){
52581     int i;
52582     int n = pExpr->token.n;
52583     assert( !isdigit(z[n]) );
52584     if( sqlite3GetInt32(z, &i) ){
52585       if( negFlag ) i = -i;
52586       sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
52587     }else if( sqlite3FitsIn64Bits(z, negFlag) ){
52588       i64 value;
52589       char *zV;
52590       sqlite3Atoi64(z, &value);
52591       if( negFlag ) value = -value;
52592       zV = dup8bytes(v, (char*)&value);
52593       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
52594     }else{
52595       codeReal(v, z, n, negFlag, iMem);
52596     }
52597   }
52598 }
52599
52600
52601 /*
52602 ** Generate code that will extract the iColumn-th column from
52603 ** table pTab and store the column value in a register.  An effort
52604 ** is made to store the column value in register iReg, but this is
52605 ** not guaranteed.  The location of the column value is returned.
52606 **
52607 ** There must be an open cursor to pTab in iTable when this routine
52608 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
52609 **
52610 ** This routine might attempt to reuse the value of the column that
52611 ** has already been loaded into a register.  The value will always
52612 ** be used if it has not undergone any affinity changes.  But if
52613 ** an affinity change has occurred, then the cached value will only be
52614 ** used if allowAffChng is true.
52615 */
52616 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
52617   Parse *pParse,   /* Parsing and code generating context */
52618   Table *pTab,     /* Description of the table we are reading from */
52619   int iColumn,     /* Index of the table column */
52620   int iTable,      /* The cursor pointing to the table */
52621   int iReg,        /* Store results here */
52622   int allowAffChng /* True if prior affinity changes are OK */
52623 ){
52624   Vdbe *v = pParse->pVdbe;
52625   int i;
52626   struct yColCache *p;
52627
52628   for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
52629     if( p->iTable==iTable && p->iColumn==iColumn
52630            && (!p->affChange || allowAffChng) ){
52631 #if 0
52632       sqlite3VdbeAddOp0(v, OP_Noop);
52633       VdbeComment((v, "OPT: tab%d.col%d -> r%d", iTable, iColumn, p->iReg));
52634 #endif
52635       return p->iReg;
52636     }
52637   }  
52638   assert( v!=0 );
52639   if( iColumn<0 ){
52640     int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid;
52641     sqlite3VdbeAddOp2(v, op, iTable, iReg);
52642   }else if( pTab==0 ){
52643     sqlite3VdbeAddOp3(v, OP_Column, iTable, iColumn, iReg);
52644   }else{
52645     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
52646     sqlite3VdbeAddOp3(v, op, iTable, iColumn, iReg);
52647     sqlite3ColumnDefault(v, pTab, iColumn);
52648 #ifndef SQLITE_OMIT_FLOATING_POINT
52649     if( pTab->aCol[iColumn].affinity==SQLITE_AFF_REAL ){
52650       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
52651     }
52652 #endif
52653   }
52654   if( pParse->disableColCache==0 ){
52655     i = pParse->iColCache;
52656     p = &pParse->aColCache[i];
52657     p->iTable = iTable;
52658     p->iColumn = iColumn;
52659     p->iReg = iReg;
52660     p->affChange = 0;
52661     i++;
52662     if( i>=ArraySize(pParse->aColCache) ) i = 0;
52663     if( i>pParse->nColCache ) pParse->nColCache = i;
52664     pParse->iColCache = i;
52665   }
52666   return iReg;
52667 }
52668
52669 /*
52670 ** Clear all column cache entries associated with the vdbe
52671 ** cursor with cursor number iTable.
52672 */
52673 SQLITE_PRIVATE void sqlite3ExprClearColumnCache(Parse *pParse, int iTable){
52674   if( iTable<0 ){
52675     pParse->nColCache = 0;
52676     pParse->iColCache = 0;
52677   }else{
52678     int i;
52679     for(i=0; i<pParse->nColCache; i++){
52680       if( pParse->aColCache[i].iTable==iTable ){
52681         testcase( i==pParse->nColCache-1 );
52682         pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache];
52683         pParse->iColCache = pParse->nColCache;
52684       }
52685     }
52686   }
52687 }
52688
52689 /*
52690 ** Record the fact that an affinity change has occurred on iCount
52691 ** registers starting with iStart.
52692 */
52693 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
52694   int iEnd = iStart + iCount - 1;
52695   int i;
52696   for(i=0; i<pParse->nColCache; i++){
52697     int r = pParse->aColCache[i].iReg;
52698     if( r>=iStart && r<=iEnd ){
52699       pParse->aColCache[i].affChange = 1;
52700     }
52701   }
52702 }
52703
52704 /*
52705 ** Generate code to move content from registers iFrom...iFrom+nReg-1
52706 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
52707 */
52708 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
52709   int i;
52710   if( iFrom==iTo ) return;
52711   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
52712   for(i=0; i<pParse->nColCache; i++){
52713     int x = pParse->aColCache[i].iReg;
52714     if( x>=iFrom && x<iFrom+nReg ){
52715       pParse->aColCache[i].iReg += iTo-iFrom;
52716     }
52717   }
52718 }
52719
52720 /*
52721 ** Generate code to copy content from registers iFrom...iFrom+nReg-1
52722 ** over to iTo..iTo+nReg-1.
52723 */
52724 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
52725   int i;
52726   if( iFrom==iTo ) return;
52727   for(i=0; i<nReg; i++){
52728     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
52729   }
52730 }
52731
52732 /*
52733 ** Return true if any register in the range iFrom..iTo (inclusive)
52734 ** is used as part of the column cache.
52735 */
52736 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
52737   int i;
52738   for(i=0; i<pParse->nColCache; i++){
52739     int r = pParse->aColCache[i].iReg;
52740     if( r>=iFrom && r<=iTo ) return 1;
52741   }
52742   return 0;
52743 }
52744
52745 /*
52746 ** Theres is a value in register iCurrent.  We ultimately want
52747 ** the value to be in register iTarget.  It might be that
52748 ** iCurrent and iTarget are the same register.
52749 **
52750 ** We are going to modify the value, so we need to make sure it
52751 ** is not a cached register.  If iCurrent is a cached register,
52752 ** then try to move the value over to iTarget.  If iTarget is a
52753 ** cached register, then clear the corresponding cache line.
52754 **
52755 ** Return the register that the value ends up in.
52756 */
52757 SQLITE_PRIVATE int sqlite3ExprWritableRegister(Parse *pParse, int iCurrent, int iTarget){
52758   int i;
52759   assert( pParse->pVdbe!=0 );
52760   if( !usedAsColumnCache(pParse, iCurrent, iCurrent) ){
52761     return iCurrent;
52762   }
52763   if( iCurrent!=iTarget ){
52764     sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, iCurrent, iTarget);
52765   }
52766   for(i=0; i<pParse->nColCache; i++){
52767     if( pParse->aColCache[i].iReg==iTarget ){
52768       pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache];
52769       pParse->iColCache = pParse->nColCache;
52770     }
52771   }
52772   return iTarget;
52773 }
52774
52775 /*
52776 ** If the last instruction coded is an ephemeral copy of any of
52777 ** the registers in the nReg registers beginning with iReg, then
52778 ** convert the last instruction from OP_SCopy to OP_Copy.
52779 */
52780 SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){
52781   int addr;
52782   VdbeOp *pOp;
52783   Vdbe *v;
52784
52785   v = pParse->pVdbe;
52786   addr = sqlite3VdbeCurrentAddr(v);
52787   pOp = sqlite3VdbeGetOp(v, addr-1);
52788   assert( pOp || pParse->db->mallocFailed );
52789   if( pOp && pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1<iReg+nReg ){
52790     pOp->opcode = OP_Copy;
52791   }
52792 }
52793
52794 /*
52795 ** Generate code into the current Vdbe to evaluate the given
52796 ** expression.  Attempt to store the results in register "target".
52797 ** Return the register where results are stored.
52798 **
52799 ** With this routine, there is no guaranteed that results will
52800 ** be stored in target.  The result might be stored in some other
52801 ** register if it is convenient to do so.  The calling function
52802 ** must check the return code and move the results to the desired
52803 ** register.
52804 */
52805 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
52806   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
52807   int op;                   /* The opcode being coded */
52808   int inReg = target;       /* Results stored in register inReg */
52809   int regFree1 = 0;         /* If non-zero free this temporary register */
52810   int regFree2 = 0;         /* If non-zero free this temporary register */
52811   int r1, r2, r3, r4;       /* Various register numbers */
52812
52813   assert( v!=0 || pParse->db->mallocFailed );
52814   assert( target>0 && target<=pParse->nMem );
52815   if( v==0 ) return 0;
52816
52817   if( pExpr==0 ){
52818     op = TK_NULL;
52819   }else{
52820     op = pExpr->op;
52821   }
52822   switch( op ){
52823     case TK_AGG_COLUMN: {
52824       AggInfo *pAggInfo = pExpr->pAggInfo;
52825       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
52826       if( !pAggInfo->directMode ){
52827         assert( pCol->iMem>0 );
52828         inReg = pCol->iMem;
52829         break;
52830       }else if( pAggInfo->useSortingIdx ){
52831         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
52832                               pCol->iSorterColumn, target);
52833         break;
52834       }
52835       /* Otherwise, fall thru into the TK_COLUMN case */
52836     }
52837     case TK_COLUMN: {
52838       if( pExpr->iTable<0 ){
52839         /* This only happens when coding check constraints */
52840         assert( pParse->ckBase>0 );
52841         inReg = pExpr->iColumn + pParse->ckBase;
52842       }else{
52843         testcase( (pExpr->flags & EP_AnyAff)!=0 );
52844         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
52845                                  pExpr->iColumn, pExpr->iTable, target,
52846                                  pExpr->flags & EP_AnyAff);
52847       }
52848       break;
52849     }
52850     case TK_INTEGER: {
52851       codeInteger(v, pExpr, 0, target);
52852       break;
52853     }
52854     case TK_FLOAT: {
52855       codeReal(v, (char*)pExpr->token.z, pExpr->token.n, 0, target);
52856       break;
52857     }
52858     case TK_STRING: {
52859       sqlite3DequoteExpr(pParse->db, pExpr);
52860       sqlite3VdbeAddOp4(v,OP_String8, 0, target, 0,
52861                         (char*)pExpr->token.z, pExpr->token.n);
52862       break;
52863     }
52864     case TK_NULL: {
52865       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
52866       break;
52867     }
52868 #ifndef SQLITE_OMIT_BLOB_LITERAL
52869     case TK_BLOB: {
52870       int n;
52871       const char *z;
52872       char *zBlob;
52873       assert( pExpr->token.n>=3 );
52874       assert( pExpr->token.z[0]=='x' || pExpr->token.z[0]=='X' );
52875       assert( pExpr->token.z[1]=='\'' );
52876       assert( pExpr->token.z[pExpr->token.n-1]=='\'' );
52877       n = pExpr->token.n - 3;
52878       z = (char*)pExpr->token.z + 2;
52879       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
52880       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
52881       break;
52882     }
52883 #endif
52884     case TK_VARIABLE: {
52885       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iTable, target);
52886       if( pExpr->token.n>1 ){
52887         sqlite3VdbeChangeP4(v, -1, (char*)pExpr->token.z, pExpr->token.n);
52888       }
52889       break;
52890     }
52891     case TK_REGISTER: {
52892       inReg = pExpr->iTable;
52893       break;
52894     }
52895 #ifndef SQLITE_OMIT_CAST
52896     case TK_CAST: {
52897       /* Expressions of the form:   CAST(pLeft AS token) */
52898       int aff, to_op;
52899       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
52900       aff = sqlite3AffinityType(&pExpr->token);
52901       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
52902       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
52903       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
52904       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
52905       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
52906       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
52907       testcase( to_op==OP_ToText );
52908       testcase( to_op==OP_ToBlob );
52909       testcase( to_op==OP_ToNumeric );
52910       testcase( to_op==OP_ToInt );
52911       testcase( to_op==OP_ToReal );
52912       sqlite3VdbeAddOp1(v, to_op, inReg);
52913       testcase( usedAsColumnCache(pParse, inReg, inReg) );
52914       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
52915       break;
52916     }
52917 #endif /* SQLITE_OMIT_CAST */
52918     case TK_LT:
52919     case TK_LE:
52920     case TK_GT:
52921     case TK_GE:
52922     case TK_NE:
52923     case TK_EQ: {
52924       assert( TK_LT==OP_Lt );
52925       assert( TK_LE==OP_Le );
52926       assert( TK_GT==OP_Gt );
52927       assert( TK_GE==OP_Ge );
52928       assert( TK_EQ==OP_Eq );
52929       assert( TK_NE==OP_Ne );
52930       testcase( op==TK_LT );
52931       testcase( op==TK_LE );
52932       testcase( op==TK_GT );
52933       testcase( op==TK_GE );
52934       testcase( op==TK_EQ );
52935       testcase( op==TK_NE );
52936       codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
52937                                   pExpr->pRight, &r2, &regFree2);
52938       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
52939                   r1, r2, inReg, SQLITE_STOREP2);
52940       testcase( regFree1==0 );
52941       testcase( regFree2==0 );
52942       break;
52943     }
52944     case TK_AND:
52945     case TK_OR:
52946     case TK_PLUS:
52947     case TK_STAR:
52948     case TK_MINUS:
52949     case TK_REM:
52950     case TK_BITAND:
52951     case TK_BITOR:
52952     case TK_SLASH:
52953     case TK_LSHIFT:
52954     case TK_RSHIFT: 
52955     case TK_CONCAT: {
52956       assert( TK_AND==OP_And );
52957       assert( TK_OR==OP_Or );
52958       assert( TK_PLUS==OP_Add );
52959       assert( TK_MINUS==OP_Subtract );
52960       assert( TK_REM==OP_Remainder );
52961       assert( TK_BITAND==OP_BitAnd );
52962       assert( TK_BITOR==OP_BitOr );
52963       assert( TK_SLASH==OP_Divide );
52964       assert( TK_LSHIFT==OP_ShiftLeft );
52965       assert( TK_RSHIFT==OP_ShiftRight );
52966       assert( TK_CONCAT==OP_Concat );
52967       testcase( op==TK_AND );
52968       testcase( op==TK_OR );
52969       testcase( op==TK_PLUS );
52970       testcase( op==TK_MINUS );
52971       testcase( op==TK_REM );
52972       testcase( op==TK_BITAND );
52973       testcase( op==TK_BITOR );
52974       testcase( op==TK_SLASH );
52975       testcase( op==TK_LSHIFT );
52976       testcase( op==TK_RSHIFT );
52977       testcase( op==TK_CONCAT );
52978       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
52979       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
52980       sqlite3VdbeAddOp3(v, op, r2, r1, target);
52981       testcase( regFree1==0 );
52982       testcase( regFree2==0 );
52983       break;
52984     }
52985     case TK_UMINUS: {
52986       Expr *pLeft = pExpr->pLeft;
52987       assert( pLeft );
52988       if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){
52989         if( pLeft->op==TK_FLOAT ){
52990           codeReal(v, (char*)pLeft->token.z, pLeft->token.n, 1, target);
52991         }else{
52992           codeInteger(v, pLeft, 1, target);
52993         }
52994       }else{
52995         regFree1 = r1 = sqlite3GetTempReg(pParse);
52996         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
52997         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
52998         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
52999         testcase( regFree2==0 );
53000       }
53001       inReg = target;
53002       break;
53003     }
53004     case TK_BITNOT:
53005     case TK_NOT: {
53006       assert( TK_BITNOT==OP_BitNot );
53007       assert( TK_NOT==OP_Not );
53008       testcase( op==TK_BITNOT );
53009       testcase( op==TK_NOT );
53010       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
53011       testcase( inReg==target );
53012       testcase( usedAsColumnCache(pParse, inReg, inReg) );
53013       inReg = sqlite3ExprWritableRegister(pParse, inReg, target);
53014       sqlite3VdbeAddOp1(v, op, inReg);
53015       break;
53016     }
53017     case TK_ISNULL:
53018     case TK_NOTNULL: {
53019       int addr;
53020       assert( TK_ISNULL==OP_IsNull );
53021       assert( TK_NOTNULL==OP_NotNull );
53022       testcase( op==TK_ISNULL );
53023       testcase( op==TK_NOTNULL );
53024       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
53025       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
53026       testcase( regFree1==0 );
53027       addr = sqlite3VdbeAddOp1(v, op, r1);
53028       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
53029       sqlite3VdbeJumpHere(v, addr);
53030       break;
53031     }
53032     case TK_AGG_FUNCTION: {
53033       AggInfo *pInfo = pExpr->pAggInfo;
53034       if( pInfo==0 ){
53035         sqlite3ErrorMsg(pParse, "misuse of aggregate: %T",
53036             &pExpr->span);
53037       }else{
53038         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
53039       }
53040       break;
53041     }
53042     case TK_CONST_FUNC:
53043     case TK_FUNCTION: {
53044       ExprList *pList = pExpr->pList;
53045       int nExpr = pList ? pList->nExpr : 0;
53046       FuncDef *pDef;
53047       int nId;
53048       const char *zId;
53049       int constMask = 0;
53050       int i;
53051       sqlite3 *db = pParse->db;
53052       u8 enc = ENC(db);
53053       CollSeq *pColl = 0;
53054
53055       testcase( op==TK_CONST_FUNC );
53056       testcase( op==TK_FUNCTION );
53057       zId = (char*)pExpr->token.z;
53058       nId = pExpr->token.n;
53059       pDef = sqlite3FindFunction(pParse->db, zId, nId, nExpr, enc, 0);
53060       assert( pDef!=0 );
53061       if( pList ){
53062         nExpr = pList->nExpr;
53063         r1 = sqlite3GetTempRange(pParse, nExpr);
53064         sqlite3ExprCodeExprList(pParse, pList, r1, 1);
53065       }else{
53066         nExpr = r1 = 0;
53067       }
53068 #ifndef SQLITE_OMIT_VIRTUALTABLE
53069       /* Possibly overload the function if the first argument is
53070       ** a virtual table column.
53071       **
53072       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
53073       ** second argument, not the first, as the argument to test to
53074       ** see if it is a column in a virtual table.  This is done because
53075       ** the left operand of infix functions (the operand we want to
53076       ** control overloading) ends up as the second argument to the
53077       ** function.  The expression "A glob B" is equivalent to 
53078       ** "glob(B,A).  We want to use the A in "A glob B" to test
53079       ** for function overloading.  But we use the B term in "glob(B,A)".
53080       */
53081       if( nExpr>=2 && (pExpr->flags & EP_InfixFunc) ){
53082         pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[1].pExpr);
53083       }else if( nExpr>0 ){
53084         pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[0].pExpr);
53085       }
53086 #endif
53087       for(i=0; i<nExpr && i<32; i++){
53088         if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
53089           constMask |= (1<<i);
53090         }
53091         if( pDef->needCollSeq && !pColl ){
53092           pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
53093         }
53094       }
53095       if( pDef->needCollSeq ){
53096         if( !pColl ) pColl = pParse->db->pDfltColl; 
53097         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
53098       }
53099       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
53100                         (char*)pDef, P4_FUNCDEF);
53101       sqlite3VdbeChangeP5(v, nExpr);
53102       if( nExpr ){
53103         sqlite3ReleaseTempRange(pParse, r1, nExpr);
53104       }
53105       sqlite3ExprCacheAffinityChange(pParse, r1, nExpr);
53106       break;
53107     }
53108 #ifndef SQLITE_OMIT_SUBQUERY
53109     case TK_EXISTS:
53110     case TK_SELECT: {
53111       testcase( op==TK_EXISTS );
53112       testcase( op==TK_SELECT );
53113       if( pExpr->iColumn==0 ){
53114         sqlite3CodeSubselect(pParse, pExpr, 0);
53115       }
53116       inReg = pExpr->iColumn;
53117       break;
53118     }
53119     case TK_IN: {
53120       int rNotFound = 0;
53121       int rMayHaveNull = 0;
53122       int j2, j3, j4, j5;
53123       char affinity;
53124       int eType;
53125
53126       VdbeNoopComment((v, "begin IN expr r%d", target));
53127       eType = sqlite3FindInIndex(pParse, pExpr, &rMayHaveNull);
53128       if( rMayHaveNull ){
53129         rNotFound = ++pParse->nMem;
53130       }
53131
53132       /* Figure out the affinity to use to create a key from the results
53133       ** of the expression. affinityStr stores a static string suitable for
53134       ** P4 of OP_MakeRecord.
53135       */
53136       affinity = comparisonAffinity(pExpr);
53137
53138
53139       /* Code the <expr> from "<expr> IN (...)". The temporary table
53140       ** pExpr->iTable contains the values that make up the (...) set.
53141       */
53142       pParse->disableColCache++;
53143       sqlite3ExprCode(pParse, pExpr->pLeft, target);
53144       pParse->disableColCache--;
53145       j2 = sqlite3VdbeAddOp1(v, OP_IsNull, target);
53146       if( eType==IN_INDEX_ROWID ){
53147         j3 = sqlite3VdbeAddOp1(v, OP_MustBeInt, target);
53148         j4 = sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, 0, target);
53149         sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
53150         j5 = sqlite3VdbeAddOp0(v, OP_Goto);
53151         sqlite3VdbeJumpHere(v, j3);
53152         sqlite3VdbeJumpHere(v, j4);
53153         sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
53154       }else{
53155         r2 = regFree2 = sqlite3GetTempReg(pParse);
53156
53157         /* Create a record and test for set membership. If the set contains
53158         ** the value, then jump to the end of the test code. The target
53159         ** register still contains the true (1) value written to it earlier.
53160         */
53161         sqlite3VdbeAddOp4(v, OP_MakeRecord, target, 1, r2, &affinity, 1);
53162         sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
53163         j5 = sqlite3VdbeAddOp3(v, OP_Found, pExpr->iTable, 0, r2);
53164
53165         /* If the set membership test fails, then the result of the 
53166         ** "x IN (...)" expression must be either 0 or NULL. If the set
53167         ** contains no NULL values, then the result is 0. If the set 
53168         ** contains one or more NULL values, then the result of the
53169         ** expression is also NULL.
53170         */
53171         if( rNotFound==0 ){
53172           /* This branch runs if it is known at compile time (now) that 
53173           ** the set contains no NULL values. This happens as the result
53174           ** of a "NOT NULL" constraint in the database schema. No need
53175           ** to test the data structure at runtime in this case.
53176           */
53177           sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
53178         }else{
53179           /* This block populates the rNotFound register with either NULL
53180           ** or 0 (an integer value). If the data structure contains one
53181           ** or more NULLs, then set rNotFound to NULL. Otherwise, set it
53182           ** to 0. If register rMayHaveNull is already set to some value
53183           ** other than NULL, then the test has already been run and 
53184           ** rNotFound is already populated.
53185           */
53186           static const char nullRecord[] = { 0x02, 0x00 };
53187           j3 = sqlite3VdbeAddOp1(v, OP_NotNull, rMayHaveNull);
53188           sqlite3VdbeAddOp2(v, OP_Null, 0, rNotFound);
53189           sqlite3VdbeAddOp4(v, OP_Blob, 2, rMayHaveNull, 0, 
53190                              nullRecord, P4_STATIC);
53191           j4 = sqlite3VdbeAddOp3(v, OP_Found, pExpr->iTable, 0, rMayHaveNull);
53192           sqlite3VdbeAddOp2(v, OP_Integer, 0, rNotFound);
53193           sqlite3VdbeJumpHere(v, j4);
53194           sqlite3VdbeJumpHere(v, j3);
53195
53196           /* Copy the value of register rNotFound (which is either NULL or 0)
53197           ** into the target register. This will be the result of the
53198           ** expression.
53199           */
53200           sqlite3VdbeAddOp2(v, OP_Copy, rNotFound, target);
53201         }
53202       }
53203       sqlite3VdbeJumpHere(v, j2);
53204       sqlite3VdbeJumpHere(v, j5);
53205       VdbeComment((v, "end IN expr r%d", target));
53206       break;
53207     }
53208 #endif
53209     /*
53210     **    x BETWEEN y AND z
53211     **
53212     ** This is equivalent to
53213     **
53214     **    x>=y AND x<=z
53215     **
53216     ** X is stored in pExpr->pLeft.
53217     ** Y is stored in pExpr->pList->a[0].pExpr.
53218     ** Z is stored in pExpr->pList->a[1].pExpr.
53219     */
53220     case TK_BETWEEN: {
53221       Expr *pLeft = pExpr->pLeft;
53222       struct ExprList_item *pLItem = pExpr->pList->a;
53223       Expr *pRight = pLItem->pExpr;
53224
53225       codeCompareOperands(pParse, pLeft, &r1, &regFree1,
53226                                   pRight, &r2, &regFree2);
53227       testcase( regFree1==0 );
53228       testcase( regFree2==0 );
53229       r3 = sqlite3GetTempReg(pParse);
53230       r4 = sqlite3GetTempReg(pParse);
53231       codeCompare(pParse, pLeft, pRight, OP_Ge,
53232                   r1, r2, r3, SQLITE_STOREP2);
53233       pLItem++;
53234       pRight = pLItem->pExpr;
53235       sqlite3ReleaseTempReg(pParse, regFree2);
53236       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
53237       testcase( regFree2==0 );
53238       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
53239       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
53240       sqlite3ReleaseTempReg(pParse, r3);
53241       sqlite3ReleaseTempReg(pParse, r4);
53242       break;
53243     }
53244     case TK_UPLUS: {
53245       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
53246       break;
53247     }
53248
53249     /*
53250     ** Form A:
53251     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
53252     **
53253     ** Form B:
53254     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
53255     **
53256     ** Form A is can be transformed into the equivalent form B as follows:
53257     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
53258     **        WHEN x=eN THEN rN ELSE y END
53259     **
53260     ** X (if it exists) is in pExpr->pLeft.
53261     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
53262     ** ELSE clause and no other term matches, then the result of the
53263     ** exprssion is NULL.
53264     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
53265     **
53266     ** The result of the expression is the Ri for the first matching Ei,
53267     ** or if there is no matching Ei, the ELSE term Y, or if there is
53268     ** no ELSE term, NULL.
53269     */
53270     case TK_CASE: {
53271       int endLabel;                     /* GOTO label for end of CASE stmt */
53272       int nextCase;                     /* GOTO label for next WHEN clause */
53273       int nExpr;                        /* 2x number of WHEN terms */
53274       int i;                            /* Loop counter */
53275       ExprList *pEList;                 /* List of WHEN terms */
53276       struct ExprList_item *aListelem;  /* Array of WHEN terms */
53277       Expr opCompare;                   /* The X==Ei expression */
53278       Expr cacheX;                      /* Cached expression X */
53279       Expr *pX;                         /* The X expression */
53280       Expr *pTest;                      /* X==Ei (form A) or just Ei (form B) */
53281
53282       assert(pExpr->pList);
53283       assert((pExpr->pList->nExpr % 2) == 0);
53284       assert(pExpr->pList->nExpr > 0);
53285       pEList = pExpr->pList;
53286       aListelem = pEList->a;
53287       nExpr = pEList->nExpr;
53288       endLabel = sqlite3VdbeMakeLabel(v);
53289       if( (pX = pExpr->pLeft)!=0 ){
53290         cacheX = *pX;
53291         testcase( pX->op==TK_COLUMN || pX->op==TK_REGISTER );
53292         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
53293         testcase( regFree1==0 );
53294         cacheX.op = TK_REGISTER;
53295         cacheX.iColumn = 0;
53296         opCompare.op = TK_EQ;
53297         opCompare.pLeft = &cacheX;
53298         pTest = &opCompare;
53299       }
53300       pParse->disableColCache++;
53301       for(i=0; i<nExpr; i=i+2){
53302         if( pX ){
53303           opCompare.pRight = aListelem[i].pExpr;
53304         }else{
53305           pTest = aListelem[i].pExpr;
53306         }
53307         nextCase = sqlite3VdbeMakeLabel(v);
53308         testcase( pTest->op==TK_COLUMN || pTest->op==TK_REGISTER );
53309         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
53310         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
53311         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
53312         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
53313         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
53314         sqlite3VdbeResolveLabel(v, nextCase);
53315       }
53316       if( pExpr->pRight ){
53317         sqlite3ExprCode(pParse, pExpr->pRight, target);
53318       }else{
53319         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
53320       }
53321       sqlite3VdbeResolveLabel(v, endLabel);
53322       assert( pParse->disableColCache>0 );
53323       pParse->disableColCache--;
53324       break;
53325     }
53326 #ifndef SQLITE_OMIT_TRIGGER
53327     case TK_RAISE: {
53328       if( !pParse->trigStack ){
53329         sqlite3ErrorMsg(pParse,
53330                        "RAISE() may only be used within a trigger-program");
53331         return 0;
53332       }
53333       if( pExpr->iColumn!=OE_Ignore ){
53334          assert( pExpr->iColumn==OE_Rollback ||
53335                  pExpr->iColumn == OE_Abort ||
53336                  pExpr->iColumn == OE_Fail );
53337          sqlite3DequoteExpr(pParse->db, pExpr);
53338          sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn, 0,
53339                         (char*)pExpr->token.z, pExpr->token.n);
53340       } else {
53341          assert( pExpr->iColumn == OE_Ignore );
53342          sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0);
53343          sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
53344          VdbeComment((v, "raise(IGNORE)"));
53345       }
53346       break;
53347     }
53348 #endif
53349   }
53350   sqlite3ReleaseTempReg(pParse, regFree1);
53351   sqlite3ReleaseTempReg(pParse, regFree2);
53352   return inReg;
53353 }
53354
53355 /*
53356 ** Generate code to evaluate an expression and store the results
53357 ** into a register.  Return the register number where the results
53358 ** are stored.
53359 **
53360 ** If the register is a temporary register that can be deallocated,
53361 ** then write its number into *pReg.  If the result register is not
53362 ** a temporary, then set *pReg to zero.
53363 */
53364 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
53365   int r1 = sqlite3GetTempReg(pParse);
53366   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
53367   if( r2==r1 ){
53368     *pReg = r1;
53369   }else{
53370     sqlite3ReleaseTempReg(pParse, r1);
53371     *pReg = 0;
53372   }
53373   return r2;
53374 }
53375
53376 /*
53377 ** Generate code that will evaluate expression pExpr and store the
53378 ** results in register target.  The results are guaranteed to appear
53379 ** in register target.
53380 */
53381 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
53382   int inReg;
53383
53384   assert( target>0 && target<=pParse->nMem );
53385   inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
53386   assert( pParse->pVdbe || pParse->db->mallocFailed );
53387   if( inReg!=target && pParse->pVdbe ){
53388     sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
53389   }
53390   return target;
53391 }
53392
53393 /*
53394 ** Generate code that evalutes the given expression and puts the result
53395 ** in register target.
53396 **
53397 ** Also make a copy of the expression results into another "cache" register
53398 ** and modify the expression so that the next time it is evaluated,
53399 ** the result is a copy of the cache register.
53400 **
53401 ** This routine is used for expressions that are used multiple 
53402 ** times.  They are evaluated once and the results of the expression
53403 ** are reused.
53404 */
53405 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
53406   Vdbe *v = pParse->pVdbe;
53407   int inReg;
53408   inReg = sqlite3ExprCode(pParse, pExpr, target);
53409   assert( target>0 );
53410   if( pExpr->op!=TK_REGISTER ){  
53411     int iMem;
53412     iMem = ++pParse->nMem;
53413     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
53414     pExpr->iTable = iMem;
53415     pExpr->iColumn = pExpr->op;
53416     pExpr->op = TK_REGISTER;
53417   }
53418   return inReg;
53419 }
53420
53421 /*
53422 ** Return TRUE if pExpr is an constant expression that is appropriate
53423 ** for factoring out of a loop.  Appropriate expressions are:
53424 **
53425 **    *  Any expression that evaluates to two or more opcodes.
53426 **
53427 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, 
53428 **       or OP_Variable that does not need to be placed in a 
53429 **       specific register.
53430 **
53431 ** There is no point in factoring out single-instruction constant
53432 ** expressions that need to be placed in a particular register.  
53433 ** We could factor them out, but then we would end up adding an
53434 ** OP_SCopy instruction to move the value into the correct register
53435 ** later.  We might as well just use the original instruction and
53436 ** avoid the OP_SCopy.
53437 */
53438 static int isAppropriateForFactoring(Expr *p){
53439   if( !sqlite3ExprIsConstantNotJoin(p) ){
53440     return 0;  /* Only constant expressions are appropriate for factoring */
53441   }
53442   if( (p->flags & EP_FixedDest)==0 ){
53443     return 1;  /* Any constant without a fixed destination is appropriate */
53444   }
53445   while( p->op==TK_UPLUS ) p = p->pLeft;
53446   switch( p->op ){
53447 #ifndef SQLITE_OMIT_BLOB_LITERAL
53448     case TK_BLOB:
53449 #endif
53450     case TK_VARIABLE:
53451     case TK_INTEGER:
53452     case TK_FLOAT:
53453     case TK_NULL:
53454     case TK_STRING: {
53455       testcase( p->op==TK_BLOB );
53456       testcase( p->op==TK_VARIABLE );
53457       testcase( p->op==TK_INTEGER );
53458       testcase( p->op==TK_FLOAT );
53459       testcase( p->op==TK_NULL );
53460       testcase( p->op==TK_STRING );
53461       /* Single-instruction constants with a fixed destination are
53462       ** better done in-line.  If we factor them, they will just end
53463       ** up generating an OP_SCopy to move the value to the destination
53464       ** register. */
53465       return 0;
53466     }
53467     case TK_UMINUS: {
53468        if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
53469          return 0;
53470        }
53471        break;
53472     }
53473     default: {
53474       break;
53475     }
53476   }
53477   return 1;
53478 }
53479
53480 /*
53481 ** If pExpr is a constant expression that is appropriate for
53482 ** factoring out of a loop, then evaluate the expression
53483 ** into a register and convert the expression into a TK_REGISTER
53484 ** expression.
53485 */
53486 static int evalConstExpr(void *pArg, Expr *pExpr){
53487   Parse *pParse = (Parse*)pArg;
53488   switch( pExpr->op ){
53489     case TK_REGISTER: {
53490       return 1;
53491     }
53492     case TK_FUNCTION:
53493     case TK_AGG_FUNCTION:
53494     case TK_CONST_FUNC: {
53495       /* The arguments to a function have a fixed destination.
53496       ** Mark them this way to avoid generated unneeded OP_SCopy
53497       ** instructions. 
53498       */
53499       ExprList *pList = pExpr->pList;
53500       if( pList ){
53501         int i = pList->nExpr;
53502         struct ExprList_item *pItem = pList->a;
53503         for(; i>0; i--, pItem++){
53504           if( pItem->pExpr ) pItem->pExpr->flags |= EP_FixedDest;
53505         }
53506       }
53507       break;
53508     }
53509   }
53510   if( isAppropriateForFactoring(pExpr) ){
53511     int r1 = ++pParse->nMem;
53512     int r2;
53513     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
53514     if( r1!=r2 ) sqlite3ReleaseTempReg(pParse, r1);
53515     pExpr->iColumn = pExpr->op;
53516     pExpr->op = TK_REGISTER;
53517     pExpr->iTable = r2;
53518     return 1;
53519   }
53520   return 0;
53521 }
53522
53523 /*
53524 ** Preevaluate constant subexpressions within pExpr and store the
53525 ** results in registers.  Modify pExpr so that the constant subexpresions
53526 ** are TK_REGISTER opcodes that refer to the precomputed values.
53527 */
53528 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
53529    walkExprTree(pExpr, evalConstExpr, pParse);
53530 }
53531
53532
53533 /*
53534 ** Generate code that pushes the value of every element of the given
53535 ** expression list into a sequence of registers beginning at target.
53536 **
53537 ** Return the number of elements evaluated.
53538 */
53539 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
53540   Parse *pParse,     /* Parsing context */
53541   ExprList *pList,   /* The expression list to be coded */
53542   int target,        /* Where to write results */
53543   int doHardCopy     /* Call sqlite3ExprHardCopy on each element if true */
53544 ){
53545   struct ExprList_item *pItem;
53546   int i, n;
53547   assert( pList!=0 || pParse->db->mallocFailed );
53548   if( pList==0 ){
53549     return 0;
53550   }
53551   assert( target>0 );
53552   n = pList->nExpr;
53553   for(pItem=pList->a, i=0; i<n; i++, pItem++){
53554     sqlite3ExprCode(pParse, pItem->pExpr, target+i);
53555     if( doHardCopy ) sqlite3ExprHardCopy(pParse, target, n);
53556   }
53557   return n;
53558 }
53559
53560 /*
53561 ** Generate code for a boolean expression such that a jump is made
53562 ** to the label "dest" if the expression is true but execution
53563 ** continues straight thru if the expression is false.
53564 **
53565 ** If the expression evaluates to NULL (neither true nor false), then
53566 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
53567 **
53568 ** This code depends on the fact that certain token values (ex: TK_EQ)
53569 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
53570 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
53571 ** the make process cause these values to align.  Assert()s in the code
53572 ** below verify that the numbers are aligned correctly.
53573 */
53574 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
53575   Vdbe *v = pParse->pVdbe;
53576   int op = 0;
53577   int regFree1 = 0;
53578   int regFree2 = 0;
53579   int r1, r2;
53580
53581   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
53582   if( v==0 || pExpr==0 ) return;
53583   op = pExpr->op;
53584   switch( op ){
53585     case TK_AND: {
53586       int d2 = sqlite3VdbeMakeLabel(v);
53587       testcase( jumpIfNull==0 );
53588       testcase( pParse->disableColCache==0 );
53589       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
53590       pParse->disableColCache++;
53591       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
53592       assert( pParse->disableColCache>0 );
53593       pParse->disableColCache--;
53594       sqlite3VdbeResolveLabel(v, d2);
53595       break;
53596     }
53597     case TK_OR: {
53598       testcase( jumpIfNull==0 );
53599       testcase( pParse->disableColCache==0 );
53600       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
53601       pParse->disableColCache++;
53602       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
53603       assert( pParse->disableColCache>0 );
53604       pParse->disableColCache--;
53605       break;
53606     }
53607     case TK_NOT: {
53608       testcase( jumpIfNull==0 );
53609       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
53610       break;
53611     }
53612     case TK_LT:
53613     case TK_LE:
53614     case TK_GT:
53615     case TK_GE:
53616     case TK_NE:
53617     case TK_EQ: {
53618       assert( TK_LT==OP_Lt );
53619       assert( TK_LE==OP_Le );
53620       assert( TK_GT==OP_Gt );
53621       assert( TK_GE==OP_Ge );
53622       assert( TK_EQ==OP_Eq );
53623       assert( TK_NE==OP_Ne );
53624       testcase( op==TK_LT );
53625       testcase( op==TK_LE );
53626       testcase( op==TK_GT );
53627       testcase( op==TK_GE );
53628       testcase( op==TK_EQ );
53629       testcase( op==TK_NE );
53630       testcase( jumpIfNull==0 );
53631       codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
53632                                   pExpr->pRight, &r2, &regFree2);
53633       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
53634                   r1, r2, dest, jumpIfNull);
53635       testcase( regFree1==0 );
53636       testcase( regFree2==0 );
53637       break;
53638     }
53639     case TK_ISNULL:
53640     case TK_NOTNULL: {
53641       assert( TK_ISNULL==OP_IsNull );
53642       assert( TK_NOTNULL==OP_NotNull );
53643       testcase( op==TK_ISNULL );
53644       testcase( op==TK_NOTNULL );
53645       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
53646       sqlite3VdbeAddOp2(v, op, r1, dest);
53647       testcase( regFree1==0 );
53648       break;
53649     }
53650     case TK_BETWEEN: {
53651       /*    x BETWEEN y AND z
53652       **
53653       ** Is equivalent to 
53654       **
53655       **    x>=y AND x<=z
53656       **
53657       ** Code it as such, taking care to do the common subexpression
53658       ** elementation of x.
53659       */
53660       Expr exprAnd;
53661       Expr compLeft;
53662       Expr compRight;
53663       Expr exprX;
53664
53665       exprX = *pExpr->pLeft;
53666       exprAnd.op = TK_AND;
53667       exprAnd.pLeft = &compLeft;
53668       exprAnd.pRight = &compRight;
53669       compLeft.op = TK_GE;
53670       compLeft.pLeft = &exprX;
53671       compLeft.pRight = pExpr->pList->a[0].pExpr;
53672       compRight.op = TK_LE;
53673       compRight.pLeft = &exprX;
53674       compRight.pRight = pExpr->pList->a[1].pExpr;
53675       exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
53676       testcase( regFree1==0 );
53677       exprX.op = TK_REGISTER;
53678       testcase( jumpIfNull==0 );
53679       sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
53680       break;
53681     }
53682     default: {
53683       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
53684       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
53685       testcase( regFree1==0 );
53686       testcase( jumpIfNull==0 );
53687       break;
53688     }
53689   }
53690   sqlite3ReleaseTempReg(pParse, regFree1);
53691   sqlite3ReleaseTempReg(pParse, regFree2);  
53692 }
53693
53694 /*
53695 ** Generate code for a boolean expression such that a jump is made
53696 ** to the label "dest" if the expression is false but execution
53697 ** continues straight thru if the expression is true.
53698 **
53699 ** If the expression evaluates to NULL (neither true nor false) then
53700 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
53701 ** is 0.
53702 */
53703 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
53704   Vdbe *v = pParse->pVdbe;
53705   int op = 0;
53706   int regFree1 = 0;
53707   int regFree2 = 0;
53708   int r1, r2;
53709
53710   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
53711   if( v==0 || pExpr==0 ) return;
53712
53713   /* The value of pExpr->op and op are related as follows:
53714   **
53715   **       pExpr->op            op
53716   **       ---------          ----------
53717   **       TK_ISNULL          OP_NotNull
53718   **       TK_NOTNULL         OP_IsNull
53719   **       TK_NE              OP_Eq
53720   **       TK_EQ              OP_Ne
53721   **       TK_GT              OP_Le
53722   **       TK_LE              OP_Gt
53723   **       TK_GE              OP_Lt
53724   **       TK_LT              OP_Ge
53725   **
53726   ** For other values of pExpr->op, op is undefined and unused.
53727   ** The value of TK_ and OP_ constants are arranged such that we
53728   ** can compute the mapping above using the following expression.
53729   ** Assert()s verify that the computation is correct.
53730   */
53731   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
53732
53733   /* Verify correct alignment of TK_ and OP_ constants
53734   */
53735   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
53736   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
53737   assert( pExpr->op!=TK_NE || op==OP_Eq );
53738   assert( pExpr->op!=TK_EQ || op==OP_Ne );
53739   assert( pExpr->op!=TK_LT || op==OP_Ge );
53740   assert( pExpr->op!=TK_LE || op==OP_Gt );
53741   assert( pExpr->op!=TK_GT || op==OP_Le );
53742   assert( pExpr->op!=TK_GE || op==OP_Lt );
53743
53744   switch( pExpr->op ){
53745     case TK_AND: {
53746       testcase( jumpIfNull==0 );
53747       testcase( pParse->disableColCache==0 );
53748       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
53749       pParse->disableColCache++;
53750       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
53751       assert( pParse->disableColCache>0 );
53752       pParse->disableColCache--;
53753       break;
53754     }
53755     case TK_OR: {
53756       int d2 = sqlite3VdbeMakeLabel(v);
53757       testcase( jumpIfNull==0 );
53758       testcase( pParse->disableColCache==0 );
53759       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
53760       pParse->disableColCache++;
53761       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
53762       assert( pParse->disableColCache>0 );
53763       pParse->disableColCache--;
53764       sqlite3VdbeResolveLabel(v, d2);
53765       break;
53766     }
53767     case TK_NOT: {
53768       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
53769       break;
53770     }
53771     case TK_LT:
53772     case TK_LE:
53773     case TK_GT:
53774     case TK_GE:
53775     case TK_NE:
53776     case TK_EQ: {
53777       testcase( op==TK_LT );
53778       testcase( op==TK_LE );
53779       testcase( op==TK_GT );
53780       testcase( op==TK_GE );
53781       testcase( op==TK_EQ );
53782       testcase( op==TK_NE );
53783       testcase( jumpIfNull==0 );
53784       codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
53785                                   pExpr->pRight, &r2, &regFree2);
53786       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
53787                   r1, r2, dest, jumpIfNull);
53788       testcase( regFree1==0 );
53789       testcase( regFree2==0 );
53790       break;
53791     }
53792     case TK_ISNULL:
53793     case TK_NOTNULL: {
53794       testcase( op==TK_ISNULL );
53795       testcase( op==TK_NOTNULL );
53796       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
53797       sqlite3VdbeAddOp2(v, op, r1, dest);
53798       testcase( regFree1==0 );
53799       break;
53800     }
53801     case TK_BETWEEN: {
53802       /*    x BETWEEN y AND z
53803       **
53804       ** Is equivalent to 
53805       **
53806       **    x>=y AND x<=z
53807       **
53808       ** Code it as such, taking care to do the common subexpression
53809       ** elementation of x.
53810       */
53811       Expr exprAnd;
53812       Expr compLeft;
53813       Expr compRight;
53814       Expr exprX;
53815
53816       exprX = *pExpr->pLeft;
53817       exprAnd.op = TK_AND;
53818       exprAnd.pLeft = &compLeft;
53819       exprAnd.pRight = &compRight;
53820       compLeft.op = TK_GE;
53821       compLeft.pLeft = &exprX;
53822       compLeft.pRight = pExpr->pList->a[0].pExpr;
53823       compRight.op = TK_LE;
53824       compRight.pLeft = &exprX;
53825       compRight.pRight = pExpr->pList->a[1].pExpr;
53826       exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
53827       testcase( regFree1==0 );
53828       exprX.op = TK_REGISTER;
53829       testcase( jumpIfNull==0 );
53830       sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
53831       break;
53832     }
53833     default: {
53834       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
53835       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
53836       testcase( regFree1==0 );
53837       testcase( jumpIfNull==0 );
53838       break;
53839     }
53840   }
53841   sqlite3ReleaseTempReg(pParse, regFree1);
53842   sqlite3ReleaseTempReg(pParse, regFree2);
53843 }
53844
53845 /*
53846 ** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
53847 ** if they are identical and return FALSE if they differ in any way.
53848 **
53849 ** Sometimes this routine will return FALSE even if the two expressions
53850 ** really are equivalent.  If we cannot prove that the expressions are
53851 ** identical, we return FALSE just to be safe.  So if this routine
53852 ** returns false, then you do not really know for certain if the two
53853 ** expressions are the same.  But if you get a TRUE return, then you
53854 ** can be sure the expressions are the same.  In the places where
53855 ** this routine is used, it does not hurt to get an extra FALSE - that
53856 ** just might result in some slightly slower code.  But returning
53857 ** an incorrect TRUE could lead to a malfunction.
53858 */
53859 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
53860   int i;
53861   if( pA==0||pB==0 ){
53862     return pB==pA;
53863   }
53864   if( pA->op!=pB->op ) return 0;
53865   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
53866   if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
53867   if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
53868   if( pA->pList ){
53869     if( pB->pList==0 ) return 0;
53870     if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
53871     for(i=0; i<pA->pList->nExpr; i++){
53872       if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
53873         return 0;
53874       }
53875     }
53876   }else if( pB->pList ){
53877     return 0;
53878   }
53879   if( pA->pSelect || pB->pSelect ) return 0;
53880   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
53881   if( pA->op!=TK_COLUMN && pA->token.z ){
53882     if( pB->token.z==0 ) return 0;
53883     if( pB->token.n!=pA->token.n ) return 0;
53884     if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){
53885       return 0;
53886     }
53887   }
53888   return 1;
53889 }
53890
53891
53892 /*
53893 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
53894 ** the new element.  Return a negative number if malloc fails.
53895 */
53896 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
53897   int i;
53898   pInfo->aCol = sqlite3ArrayAllocate(
53899        db,
53900        pInfo->aCol,
53901        sizeof(pInfo->aCol[0]),
53902        3,
53903        &pInfo->nColumn,
53904        &pInfo->nColumnAlloc,
53905        &i
53906   );
53907   return i;
53908 }    
53909
53910 /*
53911 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
53912 ** the new element.  Return a negative number if malloc fails.
53913 */
53914 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
53915   int i;
53916   pInfo->aFunc = sqlite3ArrayAllocate(
53917        db, 
53918        pInfo->aFunc,
53919        sizeof(pInfo->aFunc[0]),
53920        3,
53921        &pInfo->nFunc,
53922        &pInfo->nFuncAlloc,
53923        &i
53924   );
53925   return i;
53926 }    
53927
53928 /*
53929 ** This is an xFunc for walkExprTree() used to implement 
53930 ** sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
53931 ** for additional information.
53932 **
53933 ** This routine analyzes the aggregate function at pExpr.
53934 */
53935 static int analyzeAggregate(void *pArg, Expr *pExpr){
53936   int i;
53937   NameContext *pNC = (NameContext *)pArg;
53938   Parse *pParse = pNC->pParse;
53939   SrcList *pSrcList = pNC->pSrcList;
53940   AggInfo *pAggInfo = pNC->pAggInfo;
53941
53942   switch( pExpr->op ){
53943     case TK_AGG_COLUMN:
53944     case TK_COLUMN: {
53945       /* Check to see if the column is in one of the tables in the FROM
53946       ** clause of the aggregate query */
53947       if( pSrcList ){
53948         struct SrcList_item *pItem = pSrcList->a;
53949         for(i=0; i<pSrcList->nSrc; i++, pItem++){
53950           struct AggInfo_col *pCol;
53951           if( pExpr->iTable==pItem->iCursor ){
53952             /* If we reach this point, it means that pExpr refers to a table
53953             ** that is in the FROM clause of the aggregate query.  
53954             **
53955             ** Make an entry for the column in pAggInfo->aCol[] if there
53956             ** is not an entry there already.
53957             */
53958             int k;
53959             pCol = pAggInfo->aCol;
53960             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
53961               if( pCol->iTable==pExpr->iTable &&
53962                   pCol->iColumn==pExpr->iColumn ){
53963                 break;
53964               }
53965             }
53966             if( (k>=pAggInfo->nColumn)
53967              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
53968             ){
53969               pCol = &pAggInfo->aCol[k];
53970               pCol->pTab = pExpr->pTab;
53971               pCol->iTable = pExpr->iTable;
53972               pCol->iColumn = pExpr->iColumn;
53973               pCol->iMem = ++pParse->nMem;
53974               pCol->iSorterColumn = -1;
53975               pCol->pExpr = pExpr;
53976               if( pAggInfo->pGroupBy ){
53977                 int j, n;
53978                 ExprList *pGB = pAggInfo->pGroupBy;
53979                 struct ExprList_item *pTerm = pGB->a;
53980                 n = pGB->nExpr;
53981                 for(j=0; j<n; j++, pTerm++){
53982                   Expr *pE = pTerm->pExpr;
53983                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
53984                       pE->iColumn==pExpr->iColumn ){
53985                     pCol->iSorterColumn = j;
53986                     break;
53987                   }
53988                 }
53989               }
53990               if( pCol->iSorterColumn<0 ){
53991                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
53992               }
53993             }
53994             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
53995             ** because it was there before or because we just created it).
53996             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
53997             ** pAggInfo->aCol[] entry.
53998             */
53999             pExpr->pAggInfo = pAggInfo;
54000             pExpr->op = TK_AGG_COLUMN;
54001             pExpr->iAgg = k;
54002             break;
54003           } /* endif pExpr->iTable==pItem->iCursor */
54004         } /* end loop over pSrcList */
54005       }
54006       return 1;
54007     }
54008     case TK_AGG_FUNCTION: {
54009       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
54010       ** to be ignored */
54011       if( pNC->nDepth==0 ){
54012         /* Check to see if pExpr is a duplicate of another aggregate 
54013         ** function that is already in the pAggInfo structure
54014         */
54015         struct AggInfo_func *pItem = pAggInfo->aFunc;
54016         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
54017           if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
54018             break;
54019           }
54020         }
54021         if( i>=pAggInfo->nFunc ){
54022           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
54023           */
54024           u8 enc = ENC(pParse->db);
54025           i = addAggInfoFunc(pParse->db, pAggInfo);
54026           if( i>=0 ){
54027             pItem = &pAggInfo->aFunc[i];
54028             pItem->pExpr = pExpr;
54029             pItem->iMem = ++pParse->nMem;
54030             pItem->pFunc = sqlite3FindFunction(pParse->db,
54031                    (char*)pExpr->token.z, pExpr->token.n,
54032                    pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
54033             if( pExpr->flags & EP_Distinct ){
54034               pItem->iDistinct = pParse->nTab++;
54035             }else{
54036               pItem->iDistinct = -1;
54037             }
54038           }
54039         }
54040         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
54041         */
54042         pExpr->iAgg = i;
54043         pExpr->pAggInfo = pAggInfo;
54044         return 1;
54045       }
54046     }
54047   }
54048
54049   /* Recursively walk subqueries looking for TK_COLUMN nodes that need
54050   ** to be changed to TK_AGG_COLUMN.  But increment nDepth so that
54051   ** TK_AGG_FUNCTION nodes in subqueries will be unchanged.
54052   */
54053   if( pExpr->pSelect ){
54054     pNC->nDepth++;
54055     walkSelectExpr(pExpr->pSelect, analyzeAggregate, pNC);
54056     pNC->nDepth--;
54057   }
54058   return 0;
54059 }
54060
54061 /*
54062 ** Analyze the given expression looking for aggregate functions and
54063 ** for variables that need to be added to the pParse->aAgg[] array.
54064 ** Make additional entries to the pParse->aAgg[] array as necessary.
54065 **
54066 ** This routine should only be called after the expression has been
54067 ** analyzed by sqlite3ExprResolveNames().
54068 */
54069 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
54070   walkExprTree(pExpr, analyzeAggregate, pNC);
54071 }
54072
54073 /*
54074 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
54075 ** expression list.  Return the number of errors.
54076 **
54077 ** If an error is found, the analysis is cut short.
54078 */
54079 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
54080   struct ExprList_item *pItem;
54081   int i;
54082   if( pList ){
54083     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
54084       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
54085     }
54086   }
54087 }
54088
54089 /*
54090 ** Allocate or deallocate temporary use registers during code generation.
54091 */
54092 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
54093   if( pParse->nTempReg==0 ){
54094     return ++pParse->nMem;
54095   }
54096   return pParse->aTempReg[--pParse->nTempReg];
54097 }
54098 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
54099   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
54100     sqlite3ExprWritableRegister(pParse, iReg, iReg);
54101     pParse->aTempReg[pParse->nTempReg++] = iReg;
54102   }
54103 }
54104
54105 /*
54106 ** Allocate or deallocate a block of nReg consecutive registers
54107 */
54108 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
54109   int i, n;
54110   i = pParse->iRangeReg;
54111   n = pParse->nRangeReg;
54112   if( nReg<=n && !usedAsColumnCache(pParse, i, i+n-1) ){
54113     pParse->iRangeReg += nReg;
54114     pParse->nRangeReg -= nReg;
54115   }else{
54116     i = pParse->nMem+1;
54117     pParse->nMem += nReg;
54118   }
54119   return i;
54120 }
54121 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
54122   if( nReg>pParse->nRangeReg ){
54123     pParse->nRangeReg = nReg;
54124     pParse->iRangeReg = iReg;
54125   }
54126 }
54127
54128 /************** End of expr.c ************************************************/
54129 /************** Begin file alter.c *******************************************/
54130 /*
54131 ** 2005 February 15
54132 **
54133 ** The author disclaims copyright to this source code.  In place of
54134 ** a legal notice, here is a blessing:
54135 **
54136 **    May you do good and not evil.
54137 **    May you find forgiveness for yourself and forgive others.
54138 **    May you share freely, never taking more than you give.
54139 **
54140 *************************************************************************
54141 ** This file contains C code routines that used to generate VDBE code
54142 ** that implements the ALTER TABLE command.
54143 **
54144 ** $Id: alter.c,v 1.47 2008/07/28 19:34:53 drh Exp $
54145 */
54146
54147 /*
54148 ** The code in this file only exists if we are not omitting the
54149 ** ALTER TABLE logic from the build.
54150 */
54151 #ifndef SQLITE_OMIT_ALTERTABLE
54152
54153
54154 /*
54155 ** This function is used by SQL generated to implement the 
54156 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
54157 ** CREATE INDEX command. The second is a table name. The table name in 
54158 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
54159 ** argument and the result returned. Examples:
54160 **
54161 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
54162 **     -> 'CREATE TABLE def(a, b, c)'
54163 **
54164 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
54165 **     -> 'CREATE INDEX i ON def(a, b, c)'
54166 */
54167 static void renameTableFunc(
54168   sqlite3_context *context,
54169   int argc,
54170   sqlite3_value **argv
54171 ){
54172   unsigned char const *zSql = sqlite3_value_text(argv[0]);
54173   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
54174
54175   int token;
54176   Token tname;
54177   unsigned char const *zCsr = zSql;
54178   int len = 0;
54179   char *zRet;
54180
54181   sqlite3 *db = sqlite3_context_db_handle(context);
54182
54183   /* The principle used to locate the table name in the CREATE TABLE 
54184   ** statement is that the table name is the first non-space token that
54185   ** is immediately followed by a TK_LP or TK_USING token.
54186   */
54187   if( zSql ){
54188     do {
54189       if( !*zCsr ){
54190         /* Ran out of input before finding an opening bracket. Return NULL. */
54191         return;
54192       }
54193
54194       /* Store the token that zCsr points to in tname. */
54195       tname.z = zCsr;
54196       tname.n = len;
54197
54198       /* Advance zCsr to the next token. Store that token type in 'token',
54199       ** and its length in 'len' (to be used next iteration of this loop).
54200       */
54201       do {
54202         zCsr += len;
54203         len = sqlite3GetToken(zCsr, &token);
54204       } while( token==TK_SPACE || token==TK_COMMENT );
54205       assert( len>0 );
54206     } while( token!=TK_LP && token!=TK_USING );
54207
54208     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", tname.z - zSql, zSql, 
54209        zTableName, tname.z+tname.n);
54210     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
54211   }
54212 }
54213
54214 #ifndef SQLITE_OMIT_TRIGGER
54215 /* This function is used by SQL generated to implement the
54216 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
54217 ** statement. The second is a table name. The table name in the CREATE 
54218 ** TRIGGER statement is replaced with the third argument and the result 
54219 ** returned. This is analagous to renameTableFunc() above, except for CREATE
54220 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
54221 */
54222 static void renameTriggerFunc(
54223   sqlite3_context *context,
54224   int argc,
54225   sqlite3_value **argv
54226 ){
54227   unsigned char const *zSql = sqlite3_value_text(argv[0]);
54228   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
54229
54230   int token;
54231   Token tname;
54232   int dist = 3;
54233   unsigned char const *zCsr = zSql;
54234   int len = 0;
54235   char *zRet;
54236
54237   sqlite3 *db = sqlite3_context_db_handle(context);
54238
54239   /* The principle used to locate the table name in the CREATE TRIGGER 
54240   ** statement is that the table name is the first token that is immediatedly
54241   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
54242   ** of TK_WHEN, TK_BEGIN or TK_FOR.
54243   */
54244   if( zSql ){
54245     do {
54246
54247       if( !*zCsr ){
54248         /* Ran out of input before finding the table name. Return NULL. */
54249         return;
54250       }
54251
54252       /* Store the token that zCsr points to in tname. */
54253       tname.z = zCsr;
54254       tname.n = len;
54255
54256       /* Advance zCsr to the next token. Store that token type in 'token',
54257       ** and its length in 'len' (to be used next iteration of this loop).
54258       */
54259       do {
54260         zCsr += len;
54261         len = sqlite3GetToken(zCsr, &token);
54262       }while( token==TK_SPACE );
54263       assert( len>0 );
54264
54265       /* Variable 'dist' stores the number of tokens read since the most
54266       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN 
54267       ** token is read and 'dist' equals 2, the condition stated above
54268       ** to be met.
54269       **
54270       ** Note that ON cannot be a database, table or column name, so
54271       ** there is no need to worry about syntax like 
54272       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
54273       */
54274       dist++;
54275       if( token==TK_DOT || token==TK_ON ){
54276         dist = 0;
54277       }
54278     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
54279
54280     /* Variable tname now contains the token that is the old table-name
54281     ** in the CREATE TRIGGER statement.
54282     */
54283     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", tname.z - zSql, zSql, 
54284        zTableName, tname.z+tname.n);
54285     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
54286   }
54287 }
54288 #endif   /* !SQLITE_OMIT_TRIGGER */
54289
54290 /*
54291 ** Register built-in functions used to help implement ALTER TABLE
54292 */
54293 SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3 *db){
54294   sqlite3CreateFunc(db, "sqlite_rename_table", 2, SQLITE_UTF8, 0,
54295                          renameTableFunc, 0, 0);
54296 #ifndef SQLITE_OMIT_TRIGGER
54297   sqlite3CreateFunc(db, "sqlite_rename_trigger", 2, SQLITE_UTF8, 0,
54298                          renameTriggerFunc, 0, 0);
54299 #endif
54300 }
54301
54302 /*
54303 ** Generate the text of a WHERE expression which can be used to select all
54304 ** temporary triggers on table pTab from the sqlite_temp_master table. If
54305 ** table pTab has no temporary triggers, or is itself stored in the 
54306 ** temporary database, NULL is returned.
54307 */
54308 static char *whereTempTriggers(Parse *pParse, Table *pTab){
54309   Trigger *pTrig;
54310   char *zWhere = 0;
54311   char *tmp = 0;
54312   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
54313
54314   /* If the table is not located in the temp-db (in which case NULL is 
54315   ** returned, loop through the tables list of triggers. For each trigger
54316   ** that is not part of the temp-db schema, add a clause to the WHERE 
54317   ** expression being built up in zWhere.
54318   */
54319   if( pTab->pSchema!=pTempSchema ){
54320     sqlite3 *db = pParse->db;
54321     for( pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext ){
54322       if( pTrig->pSchema==pTempSchema ){
54323         if( !zWhere ){
54324           zWhere = sqlite3MPrintf(db, "name=%Q", pTrig->name);
54325         }else{
54326           tmp = zWhere;
54327           zWhere = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, pTrig->name);
54328           sqlite3DbFree(db, tmp);
54329         }
54330       }
54331     }
54332   }
54333   return zWhere;
54334 }
54335
54336 /*
54337 ** Generate code to drop and reload the internal representation of table
54338 ** pTab from the database, including triggers and temporary triggers.
54339 ** Argument zName is the name of the table in the database schema at
54340 ** the time the generated code is executed. This can be different from
54341 ** pTab->zName if this function is being called to code part of an 
54342 ** "ALTER TABLE RENAME TO" statement.
54343 */
54344 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
54345   Vdbe *v;
54346   char *zWhere;
54347   int iDb;                   /* Index of database containing pTab */
54348 #ifndef SQLITE_OMIT_TRIGGER
54349   Trigger *pTrig;
54350 #endif
54351
54352   v = sqlite3GetVdbe(pParse);
54353   if( !v ) return;
54354   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
54355   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
54356   assert( iDb>=0 );
54357
54358 #ifndef SQLITE_OMIT_TRIGGER
54359   /* Drop any table triggers from the internal schema. */
54360   for(pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext){
54361     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
54362     assert( iTrigDb==iDb || iTrigDb==1 );
54363     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->name, 0);
54364   }
54365 #endif
54366
54367   /* Drop the table and index from the internal schema */
54368   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
54369
54370   /* Reload the table, index and permanent trigger schemas. */
54371   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
54372   if( !zWhere ) return;
54373   sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
54374
54375 #ifndef SQLITE_OMIT_TRIGGER
54376   /* Now, if the table is not stored in the temp database, reload any temp 
54377   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. 
54378   */
54379   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
54380     sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
54381   }
54382 #endif
54383 }
54384
54385 /*
54386 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
54387 ** command. 
54388 */
54389 SQLITE_PRIVATE void sqlite3AlterRenameTable(
54390   Parse *pParse,            /* Parser context. */
54391   SrcList *pSrc,            /* The table to rename. */
54392   Token *pName              /* The new table name. */
54393 ){
54394   int iDb;                  /* Database that contains the table */
54395   char *zDb;                /* Name of database iDb */
54396   Table *pTab;              /* Table being renamed */
54397   char *zName = 0;          /* NULL-terminated version of pName */ 
54398   sqlite3 *db = pParse->db; /* Database connection */
54399   int nTabName;             /* Number of UTF-8 characters in zTabName */
54400   const char *zTabName;     /* Original name of the table */
54401   Vdbe *v;
54402 #ifndef SQLITE_OMIT_TRIGGER
54403   char *zWhere = 0;         /* Where clause to locate temp triggers */
54404 #endif
54405   int isVirtualRename = 0;  /* True if this is a v-table with an xRename() */
54406   
54407   if( db->mallocFailed ) goto exit_rename_table;
54408   assert( pSrc->nSrc==1 );
54409   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
54410
54411   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
54412   if( !pTab ) goto exit_rename_table;
54413   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
54414   zDb = db->aDb[iDb].zName;
54415
54416   /* Get a NULL terminated version of the new table name. */
54417   zName = sqlite3NameFromToken(db, pName);
54418   if( !zName ) goto exit_rename_table;
54419
54420   /* Check that a table or index named 'zName' does not already exist
54421   ** in database iDb. If so, this is an error.
54422   */
54423   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
54424     sqlite3ErrorMsg(pParse, 
54425         "there is already another table or index with this name: %s", zName);
54426     goto exit_rename_table;
54427   }
54428
54429   /* Make sure it is not a system table being altered, or a reserved name
54430   ** that the table is being renamed to.
54431   */
54432   if( strlen(pTab->zName)>6 && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7) ){
54433     sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
54434     goto exit_rename_table;
54435   }
54436   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
54437     goto exit_rename_table;
54438   }
54439
54440 #ifndef SQLITE_OMIT_VIEW
54441   if( pTab->pSelect ){
54442     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
54443     goto exit_rename_table;
54444   }
54445 #endif
54446
54447 #ifndef SQLITE_OMIT_AUTHORIZATION
54448   /* Invoke the authorization callback. */
54449   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
54450     goto exit_rename_table;
54451   }
54452 #endif
54453
54454 #ifndef SQLITE_OMIT_VIRTUALTABLE
54455   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
54456     goto exit_rename_table;
54457   }
54458   if( IsVirtual(pTab) && pTab->pMod->pModule->xRename ){
54459     isVirtualRename = 1;
54460   }
54461 #endif
54462
54463   /* Begin a transaction and code the VerifyCookie for database iDb. 
54464   ** Then modify the schema cookie (since the ALTER TABLE modifies the
54465   ** schema). Open a statement transaction if the table is a virtual
54466   ** table.
54467   */
54468   v = sqlite3GetVdbe(pParse);
54469   if( v==0 ){
54470     goto exit_rename_table;
54471   }
54472   sqlite3BeginWriteOperation(pParse, isVirtualRename, iDb);
54473   sqlite3ChangeCookie(pParse, iDb);
54474
54475   /* If this is a virtual table, invoke the xRename() function if
54476   ** one is defined. The xRename() callback will modify the names
54477   ** of any resources used by the v-table implementation (including other
54478   ** SQLite tables) that are identified by the name of the virtual table.
54479   */
54480 #ifndef SQLITE_OMIT_VIRTUALTABLE
54481   if( isVirtualRename ){
54482     int i = ++pParse->nMem;
54483     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
54484     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pTab->pVtab, P4_VTAB);
54485   }
54486 #endif
54487
54488   /* figure out how many UTF-8 characters are in zName */
54489   zTabName = pTab->zName;
54490   nTabName = sqlite3Utf8CharLen(zTabName, -1);
54491
54492   /* Modify the sqlite_master table to use the new table name. */
54493   sqlite3NestedParse(pParse,
54494       "UPDATE %Q.%s SET "
54495 #ifdef SQLITE_OMIT_TRIGGER
54496           "sql = sqlite_rename_table(sql, %Q), "
54497 #else
54498           "sql = CASE "
54499             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
54500             "ELSE sqlite_rename_table(sql, %Q) END, "
54501 #endif
54502           "tbl_name = %Q, "
54503           "name = CASE "
54504             "WHEN type='table' THEN %Q "
54505             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
54506              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
54507             "ELSE name END "
54508       "WHERE tbl_name=%Q AND "
54509           "(type='table' OR type='index' OR type='trigger');", 
54510       zDb, SCHEMA_TABLE(iDb), zName, zName, zName, 
54511 #ifndef SQLITE_OMIT_TRIGGER
54512       zName,
54513 #endif
54514       zName, nTabName, zTabName
54515   );
54516
54517 #ifndef SQLITE_OMIT_AUTOINCREMENT
54518   /* If the sqlite_sequence table exists in this database, then update 
54519   ** it with the new table name.
54520   */
54521   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
54522     sqlite3NestedParse(pParse,
54523         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
54524         zDb, zName, pTab->zName);
54525   }
54526 #endif
54527
54528 #ifndef SQLITE_OMIT_TRIGGER
54529   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
54530   ** table. Don't do this if the table being ALTERed is itself located in
54531   ** the temp database.
54532   */
54533   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
54534     sqlite3NestedParse(pParse, 
54535         "UPDATE sqlite_temp_master SET "
54536             "sql = sqlite_rename_trigger(sql, %Q), "
54537             "tbl_name = %Q "
54538             "WHERE %s;", zName, zName, zWhere);
54539     sqlite3DbFree(db, zWhere);
54540   }
54541 #endif
54542
54543   /* Drop and reload the internal table schema. */
54544   reloadTableSchema(pParse, pTab, zName);
54545
54546 exit_rename_table:
54547   sqlite3SrcListDelete(db, pSrc);
54548   sqlite3DbFree(db, zName);
54549 }
54550
54551
54552 /*
54553 ** This function is called after an "ALTER TABLE ... ADD" statement
54554 ** has been parsed. Argument pColDef contains the text of the new
54555 ** column definition.
54556 **
54557 ** The Table structure pParse->pNewTable was extended to include
54558 ** the new column during parsing.
54559 */
54560 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
54561   Table *pNew;              /* Copy of pParse->pNewTable */
54562   Table *pTab;              /* Table being altered */
54563   int iDb;                  /* Database number */
54564   const char *zDb;          /* Database name */
54565   const char *zTab;         /* Table name */
54566   char *zCol;               /* Null-terminated column definition */
54567   Column *pCol;             /* The new column */
54568   Expr *pDflt;              /* Default value for the new column */
54569   sqlite3 *db;              /* The database connection; */
54570
54571   if( pParse->nErr ) return;
54572   pNew = pParse->pNewTable;
54573   assert( pNew );
54574
54575   db = pParse->db;
54576   assert( sqlite3BtreeHoldsAllMutexes(db) );
54577   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
54578   zDb = db->aDb[iDb].zName;
54579   zTab = pNew->zName;
54580   pCol = &pNew->aCol[pNew->nCol-1];
54581   pDflt = pCol->pDflt;
54582   pTab = sqlite3FindTable(db, zTab, zDb);
54583   assert( pTab );
54584
54585 #ifndef SQLITE_OMIT_AUTHORIZATION
54586   /* Invoke the authorization callback. */
54587   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
54588     return;
54589   }
54590 #endif
54591
54592   /* If the default value for the new column was specified with a 
54593   ** literal NULL, then set pDflt to 0. This simplifies checking
54594   ** for an SQL NULL default below.
54595   */
54596   if( pDflt && pDflt->op==TK_NULL ){
54597     pDflt = 0;
54598   }
54599
54600   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
54601   ** If there is a NOT NULL constraint, then the default value for the
54602   ** column must not be NULL.
54603   */
54604   if( pCol->isPrimKey ){
54605     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
54606     return;
54607   }
54608   if( pNew->pIndex ){
54609     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
54610     return;
54611   }
54612   if( pCol->notNull && !pDflt ){
54613     sqlite3ErrorMsg(pParse, 
54614         "Cannot add a NOT NULL column with default value NULL");
54615     return;
54616   }
54617
54618   /* Ensure the default expression is something that sqlite3ValueFromExpr()
54619   ** can handle (i.e. not CURRENT_TIME etc.)
54620   */
54621   if( pDflt ){
54622     sqlite3_value *pVal;
54623     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
54624       db->mallocFailed = 1;
54625       return;
54626     }
54627     if( !pVal ){
54628       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
54629       return;
54630     }
54631     sqlite3ValueFree(pVal);
54632   }
54633
54634   /* Modify the CREATE TABLE statement. */
54635   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
54636   if( zCol ){
54637     char *zEnd = &zCol[pColDef->n-1];
54638     while( (zEnd>zCol && *zEnd==';') || isspace(*(unsigned char *)zEnd) ){
54639       *zEnd-- = '\0';
54640     }
54641     sqlite3NestedParse(pParse, 
54642         "UPDATE \"%w\".%s SET "
54643           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
54644         "WHERE type = 'table' AND name = %Q", 
54645       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
54646       zTab
54647     );
54648     sqlite3DbFree(db, zCol);
54649   }
54650
54651   /* If the default value of the new column is NULL, then set the file
54652   ** format to 2. If the default value of the new column is not NULL,
54653   ** the file format becomes 3.
54654   */
54655   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
54656
54657   /* Reload the schema of the modified table. */
54658   reloadTableSchema(pParse, pTab, pTab->zName);
54659 }
54660
54661 /*
54662 ** This function is called by the parser after the table-name in
54663 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
54664 ** pSrc is the full-name of the table being altered.
54665 **
54666 ** This routine makes a (partial) copy of the Table structure
54667 ** for the table being altered and sets Parse.pNewTable to point
54668 ** to it. Routines called by the parser as the column definition
54669 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
54670 ** the copy. The copy of the Table structure is deleted by tokenize.c 
54671 ** after parsing is finished.
54672 **
54673 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
54674 ** coding the "ALTER TABLE ... ADD" statement.
54675 */
54676 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
54677   Table *pNew;
54678   Table *pTab;
54679   Vdbe *v;
54680   int iDb;
54681   int i;
54682   int nAlloc;
54683   sqlite3 *db = pParse->db;
54684
54685   /* Look up the table being altered. */
54686   assert( pParse->pNewTable==0 );
54687   assert( sqlite3BtreeHoldsAllMutexes(db) );
54688   if( db->mallocFailed ) goto exit_begin_add_column;
54689   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
54690   if( !pTab ) goto exit_begin_add_column;
54691
54692 #ifndef SQLITE_OMIT_VIRTUALTABLE
54693   if( IsVirtual(pTab) ){
54694     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
54695     goto exit_begin_add_column;
54696   }
54697 #endif
54698
54699   /* Make sure this is not an attempt to ALTER a view. */
54700   if( pTab->pSelect ){
54701     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
54702     goto exit_begin_add_column;
54703   }
54704
54705   assert( pTab->addColOffset>0 );
54706   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
54707
54708   /* Put a copy of the Table struct in Parse.pNewTable for the
54709   ** sqlite3AddColumn() function and friends to modify.
54710   */
54711   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
54712   if( !pNew ) goto exit_begin_add_column;
54713   pParse->pNewTable = pNew;
54714   pNew->nRef = 1;
54715   pNew->db = db;
54716   pNew->nCol = pTab->nCol;
54717   assert( pNew->nCol>0 );
54718   nAlloc = (((pNew->nCol-1)/8)*8)+8;
54719   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
54720   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
54721   pNew->zName = sqlite3DbStrDup(db, pTab->zName);
54722   if( !pNew->aCol || !pNew->zName ){
54723     db->mallocFailed = 1;
54724     goto exit_begin_add_column;
54725   }
54726   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
54727   for(i=0; i<pNew->nCol; i++){
54728     Column *pCol = &pNew->aCol[i];
54729     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
54730     pCol->zColl = 0;
54731     pCol->zType = 0;
54732     pCol->pDflt = 0;
54733   }
54734   pNew->pSchema = db->aDb[iDb].pSchema;
54735   pNew->addColOffset = pTab->addColOffset;
54736   pNew->nRef = 1;
54737
54738   /* Begin a transaction and increment the schema cookie.  */
54739   sqlite3BeginWriteOperation(pParse, 0, iDb);
54740   v = sqlite3GetVdbe(pParse);
54741   if( !v ) goto exit_begin_add_column;
54742   sqlite3ChangeCookie(pParse, iDb);
54743
54744 exit_begin_add_column:
54745   sqlite3SrcListDelete(db, pSrc);
54746   return;
54747 }
54748 #endif  /* SQLITE_ALTER_TABLE */
54749
54750 /************** End of alter.c ***********************************************/
54751 /************** Begin file analyze.c *****************************************/
54752 /*
54753 ** 2005 July 8
54754 **
54755 ** The author disclaims copyright to this source code.  In place of
54756 ** a legal notice, here is a blessing:
54757 **
54758 **    May you do good and not evil.
54759 **    May you find forgiveness for yourself and forgive others.
54760 **    May you share freely, never taking more than you give.
54761 **
54762 *************************************************************************
54763 ** This file contains code associated with the ANALYZE command.
54764 **
54765 ** @(#) $Id: analyze.c,v 1.43 2008/07/28 19:34:53 drh Exp $
54766 */
54767 #ifndef SQLITE_OMIT_ANALYZE
54768
54769 /*
54770 ** This routine generates code that opens the sqlite_stat1 table on cursor
54771 ** iStatCur.
54772 **
54773 ** If the sqlite_stat1 tables does not previously exist, it is created.
54774 ** If it does previously exist, all entires associated with table zWhere
54775 ** are removed.  If zWhere==0 then all entries are removed.
54776 */
54777 static void openStatTable(
54778   Parse *pParse,          /* Parsing context */
54779   int iDb,                /* The database we are looking in */
54780   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
54781   const char *zWhere      /* Delete entries associated with this table */
54782 ){
54783   sqlite3 *db = pParse->db;
54784   Db *pDb;
54785   int iRootPage;
54786   int createStat1 = 0;
54787   Table *pStat;
54788   Vdbe *v = sqlite3GetVdbe(pParse);
54789
54790   if( v==0 ) return;
54791   assert( sqlite3BtreeHoldsAllMutexes(db) );
54792   assert( sqlite3VdbeDb(v)==db );
54793   pDb = &db->aDb[iDb];
54794   if( (pStat = sqlite3FindTable(db, "sqlite_stat1", pDb->zName))==0 ){
54795     /* The sqlite_stat1 tables does not exist.  Create it.  
54796     ** Note that a side-effect of the CREATE TABLE statement is to leave
54797     ** the rootpage of the new table in register pParse->regRoot.  This is
54798     ** important because the OpenWrite opcode below will be needing it. */
54799     sqlite3NestedParse(pParse,
54800       "CREATE TABLE %Q.sqlite_stat1(tbl,idx,stat)",
54801       pDb->zName
54802     );
54803     iRootPage = pParse->regRoot;
54804     createStat1 = 1;  /* Cause rootpage to be taken from top of stack */
54805   }else if( zWhere ){
54806     /* The sqlite_stat1 table exists.  Delete all entries associated with
54807     ** the table zWhere. */
54808     sqlite3NestedParse(pParse,
54809        "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q",
54810        pDb->zName, zWhere
54811     );
54812     iRootPage = pStat->tnum;
54813   }else{
54814     /* The sqlite_stat1 table already exists.  Delete all rows. */
54815     iRootPage = pStat->tnum;
54816     sqlite3VdbeAddOp2(v, OP_Clear, pStat->tnum, iDb);
54817   }
54818
54819   /* Open the sqlite_stat1 table for writing. Unless it was created
54820   ** by this vdbe program, lock it for writing at the shared-cache level. 
54821   ** If this vdbe did create the sqlite_stat1 table, then it must have 
54822   ** already obtained a schema-lock, making the write-lock redundant.
54823   */
54824   if( !createStat1 ){
54825     sqlite3TableLock(pParse, iDb, iRootPage, 1, "sqlite_stat1");
54826   }
54827   sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, 3);
54828   sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur, iRootPage, iDb);
54829   sqlite3VdbeChangeP5(v, createStat1);
54830 }
54831
54832 /*
54833 ** Generate code to do an analysis of all indices associated with
54834 ** a single table.
54835 */
54836 static void analyzeOneTable(
54837   Parse *pParse,   /* Parser context */
54838   Table *pTab,     /* Table whose indices are to be analyzed */
54839   int iStatCur,    /* Cursor that writes to the sqlite_stat1 table */
54840   int iMem         /* Available memory locations begin here */
54841 ){
54842   Index *pIdx;     /* An index to being analyzed */
54843   int iIdxCur;     /* Cursor number for index being analyzed */
54844   int nCol;        /* Number of columns in the index */
54845   Vdbe *v;         /* The virtual machine being built up */
54846   int i;           /* Loop counter */
54847   int topOfLoop;   /* The top of the loop */
54848   int endOfLoop;   /* The end of the loop */
54849   int addr;        /* The address of an instruction */
54850   int iDb;         /* Index of database containing pTab */
54851
54852   v = sqlite3GetVdbe(pParse);
54853   if( v==0 || pTab==0 || pTab->pIndex==0 ){
54854     /* Do no analysis for tables that have no indices */
54855     return;
54856   }
54857   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
54858   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
54859   assert( iDb>=0 );
54860 #ifndef SQLITE_OMIT_AUTHORIZATION
54861   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
54862       pParse->db->aDb[iDb].zName ) ){
54863     return;
54864   }
54865 #endif
54866
54867   /* Establish a read-lock on the table at the shared-cache level. */
54868   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
54869
54870   iIdxCur = pParse->nTab;
54871   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
54872     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
54873     int regFields;    /* Register block for building records */
54874     int regRec;       /* Register holding completed record */
54875     int regTemp;      /* Temporary use register */
54876     int regCol;       /* Content of a column from the table being analyzed */
54877     int regRowid;     /* Rowid for the inserted record */
54878     int regF2;
54879
54880     /* Open a cursor to the index to be analyzed
54881     */
54882     assert( iDb==sqlite3SchemaToIndex(pParse->db, pIdx->pSchema) );
54883     nCol = pIdx->nColumn;
54884     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, nCol+1);
54885     sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
54886         (char *)pKey, P4_KEYINFO_HANDOFF);
54887     VdbeComment((v, "%s", pIdx->zName));
54888     regFields = iMem+nCol*2;
54889     regTemp = regRowid = regCol = regFields+3;
54890     regRec = regCol+1;
54891     if( regRec>pParse->nMem ){
54892       pParse->nMem = regRec;
54893     }
54894
54895     /* Memory cells are used as follows:
54896     **
54897     **    mem[iMem]:             The total number of rows in the table.
54898     **    mem[iMem+1]:           Number of distinct values in column 1
54899     **    ...
54900     **    mem[iMem+nCol]:        Number of distinct values in column N
54901     **    mem[iMem+nCol+1]       Last observed value of column 1
54902     **    ...
54903     **    mem[iMem+nCol+nCol]:   Last observed value of column N
54904     **
54905     ** Cells iMem through iMem+nCol are initialized to 0.  The others
54906     ** are initialized to NULL.
54907     */
54908     for(i=0; i<=nCol; i++){
54909       sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
54910     }
54911     for(i=0; i<nCol; i++){
54912       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
54913     }
54914
54915     /* Do the analysis.
54916     */
54917     endOfLoop = sqlite3VdbeMakeLabel(v);
54918     sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
54919     topOfLoop = sqlite3VdbeCurrentAddr(v);
54920     sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
54921     for(i=0; i<nCol; i++){
54922       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
54923       sqlite3VdbeAddOp3(v, OP_Ne, regCol, 0, iMem+nCol+i+1);
54924       /**** TODO:  add collating sequence *****/
54925       sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
54926     }
54927     sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
54928     for(i=0; i<nCol; i++){
54929       sqlite3VdbeJumpHere(v, topOfLoop + 2*(i + 1));
54930       sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
54931       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
54932     }
54933     sqlite3VdbeResolveLabel(v, endOfLoop);
54934     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
54935     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
54936
54937     /* Store the results.  
54938     **
54939     ** The result is a single row of the sqlite_stat1 table.  The first
54940     ** two columns are the names of the table and index.  The third column
54941     ** is a string composed of a list of integer statistics about the
54942     ** index.  The first integer in the list is the total number of entires
54943     ** in the index.  There is one additional integer in the list for each
54944     ** column of the table.  This additional integer is a guess of how many
54945     ** rows of the table the index will select.  If D is the count of distinct
54946     ** values and K is the total number of rows, then the integer is computed
54947     ** as:
54948     **
54949     **        I = (K+D-1)/D
54950     **
54951     ** If K==0 then no entry is made into the sqlite_stat1 table.  
54952     ** If K>0 then it is always the case the D>0 so division by zero
54953     ** is never possible.
54954     */
54955     addr = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
54956     sqlite3VdbeAddOp4(v, OP_String8, 0, regFields, 0, pTab->zName, 0);
54957     sqlite3VdbeAddOp4(v, OP_String8, 0, regFields+1, 0, pIdx->zName, 0);
54958     regF2 = regFields+2;
54959     sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regF2);
54960     for(i=0; i<nCol; i++){
54961       sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
54962       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regF2, regF2);
54963       sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
54964       sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
54965       sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
54966       sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
54967       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regF2, regF2);
54968     }
54969     sqlite3VdbeAddOp4(v, OP_MakeRecord, regFields, 3, regRec, "aaa", 0);
54970     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
54971     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
54972     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
54973     sqlite3VdbeJumpHere(v, addr);
54974   }
54975 }
54976
54977 /*
54978 ** Generate code that will cause the most recent index analysis to
54979 ** be laoded into internal hash tables where is can be used.
54980 */
54981 static void loadAnalysis(Parse *pParse, int iDb){
54982   Vdbe *v = sqlite3GetVdbe(pParse);
54983   if( v ){
54984     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
54985   }
54986 }
54987
54988 /*
54989 ** Generate code that will do an analysis of an entire database
54990 */
54991 static void analyzeDatabase(Parse *pParse, int iDb){
54992   sqlite3 *db = pParse->db;
54993   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
54994   HashElem *k;
54995   int iStatCur;
54996   int iMem;
54997
54998   sqlite3BeginWriteOperation(pParse, 0, iDb);
54999   iStatCur = pParse->nTab++;
55000   openStatTable(pParse, iDb, iStatCur, 0);
55001   iMem = pParse->nMem+1;
55002   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
55003     Table *pTab = (Table*)sqliteHashData(k);
55004     analyzeOneTable(pParse, pTab, iStatCur, iMem);
55005   }
55006   loadAnalysis(pParse, iDb);
55007 }
55008
55009 /*
55010 ** Generate code that will do an analysis of a single table in
55011 ** a database.
55012 */
55013 static void analyzeTable(Parse *pParse, Table *pTab){
55014   int iDb;
55015   int iStatCur;
55016
55017   assert( pTab!=0 );
55018   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
55019   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
55020   sqlite3BeginWriteOperation(pParse, 0, iDb);
55021   iStatCur = pParse->nTab++;
55022   openStatTable(pParse, iDb, iStatCur, pTab->zName);
55023   analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem+1);
55024   loadAnalysis(pParse, iDb);
55025 }
55026
55027 /*
55028 ** Generate code for the ANALYZE command.  The parser calls this routine
55029 ** when it recognizes an ANALYZE command.
55030 **
55031 **        ANALYZE                            -- 1
55032 **        ANALYZE  <database>                -- 2
55033 **        ANALYZE  ?<database>.?<tablename>  -- 3
55034 **
55035 ** Form 1 causes all indices in all attached databases to be analyzed.
55036 ** Form 2 analyzes all indices the single database named.
55037 ** Form 3 analyzes all indices associated with the named table.
55038 */
55039 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
55040   sqlite3 *db = pParse->db;
55041   int iDb;
55042   int i;
55043   char *z, *zDb;
55044   Table *pTab;
55045   Token *pTableName;
55046
55047   /* Read the database schema. If an error occurs, leave an error message
55048   ** and code in pParse and return NULL. */
55049   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
55050   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
55051     return;
55052   }
55053
55054   if( pName1==0 ){
55055     /* Form 1:  Analyze everything */
55056     for(i=0; i<db->nDb; i++){
55057       if( i==1 ) continue;  /* Do not analyze the TEMP database */
55058       analyzeDatabase(pParse, i);
55059     }
55060   }else if( pName2==0 || pName2->n==0 ){
55061     /* Form 2:  Analyze the database or table named */
55062     iDb = sqlite3FindDb(db, pName1);
55063     if( iDb>=0 ){
55064       analyzeDatabase(pParse, iDb);
55065     }else{
55066       z = sqlite3NameFromToken(db, pName1);
55067       if( z ){
55068         pTab = sqlite3LocateTable(pParse, 0, z, 0);
55069         sqlite3DbFree(db, z);
55070         if( pTab ){
55071           analyzeTable(pParse, pTab);
55072         }
55073       }
55074     }
55075   }else{
55076     /* Form 3: Analyze the fully qualified table name */
55077     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
55078     if( iDb>=0 ){
55079       zDb = db->aDb[iDb].zName;
55080       z = sqlite3NameFromToken(db, pTableName);
55081       if( z ){
55082         pTab = sqlite3LocateTable(pParse, 0, z, zDb);
55083         sqlite3DbFree(db, z);
55084         if( pTab ){
55085           analyzeTable(pParse, pTab);
55086         }
55087       }
55088     }   
55089   }
55090 }
55091
55092 /*
55093 ** Used to pass information from the analyzer reader through to the
55094 ** callback routine.
55095 */
55096 typedef struct analysisInfo analysisInfo;
55097 struct analysisInfo {
55098   sqlite3 *db;
55099   const char *zDatabase;
55100 };
55101
55102 /*
55103 ** This callback is invoked once for each index when reading the
55104 ** sqlite_stat1 table.  
55105 **
55106 **     argv[0] = name of the index
55107 **     argv[1] = results of analysis - on integer for each column
55108 */
55109 static int analysisLoader(void *pData, int argc, char **argv, char **azNotUsed){
55110   analysisInfo *pInfo = (analysisInfo*)pData;
55111   Index *pIndex;
55112   int i, c;
55113   unsigned int v;
55114   const char *z;
55115
55116   assert( argc==2 );
55117   if( argv==0 || argv[0]==0 || argv[1]==0 ){
55118     return 0;
55119   }
55120   pIndex = sqlite3FindIndex(pInfo->db, argv[0], pInfo->zDatabase);
55121   if( pIndex==0 ){
55122     return 0;
55123   }
55124   z = argv[1];
55125   for(i=0; *z && i<=pIndex->nColumn; i++){
55126     v = 0;
55127     while( (c=z[0])>='0' && c<='9' ){
55128       v = v*10 + c - '0';
55129       z++;
55130     }
55131     pIndex->aiRowEst[i] = v;
55132     if( *z==' ' ) z++;
55133   }
55134   return 0;
55135 }
55136
55137 /*
55138 ** Load the content of the sqlite_stat1 table into the index hash tables.
55139 */
55140 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
55141   analysisInfo sInfo;
55142   HashElem *i;
55143   char *zSql;
55144   int rc;
55145
55146   assert( iDb>=0 && iDb<db->nDb );
55147   assert( db->aDb[iDb].pBt!=0 );
55148   assert( sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
55149
55150   /* Clear any prior statistics */
55151   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
55152     Index *pIdx = sqliteHashData(i);
55153     sqlite3DefaultRowEst(pIdx);
55154   }
55155
55156   /* Check to make sure the sqlite_stat1 table existss */
55157   sInfo.db = db;
55158   sInfo.zDatabase = db->aDb[iDb].zName;
55159   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
55160      return SQLITE_ERROR;
55161   }
55162
55163
55164   /* Load new statistics out of the sqlite_stat1 table */
55165   zSql = sqlite3MPrintf(db, "SELECT idx, stat FROM %Q.sqlite_stat1",
55166                         sInfo.zDatabase);
55167   (void)sqlite3SafetyOff(db);
55168   rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
55169   (void)sqlite3SafetyOn(db);
55170   sqlite3DbFree(db, zSql);
55171   return rc;
55172 }
55173
55174
55175 #endif /* SQLITE_OMIT_ANALYZE */
55176
55177 /************** End of analyze.c *********************************************/
55178 /************** Begin file attach.c ******************************************/
55179 /*
55180 ** 2003 April 6
55181 **
55182 ** The author disclaims copyright to this source code.  In place of
55183 ** a legal notice, here is a blessing:
55184 **
55185 **    May you do good and not evil.
55186 **    May you find forgiveness for yourself and forgive others.
55187 **    May you share freely, never taking more than you give.
55188 **
55189 *************************************************************************
55190 ** This file contains code used to implement the ATTACH and DETACH commands.
55191 **
55192 ** $Id: attach.c,v 1.77 2008/07/28 19:34:53 drh Exp $
55193 */
55194
55195 #ifndef SQLITE_OMIT_ATTACH
55196 /*
55197 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
55198 ** is slightly different from resolving a normal SQL expression, because simple
55199 ** identifiers are treated as strings, not possible column names or aliases.
55200 **
55201 ** i.e. if the parser sees:
55202 **
55203 **     ATTACH DATABASE abc AS def
55204 **
55205 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
55206 ** looking for columns of the same name.
55207 **
55208 ** This only applies to the root node of pExpr, so the statement:
55209 **
55210 **     ATTACH DATABASE abc||def AS 'db2'
55211 **
55212 ** will fail because neither abc or def can be resolved.
55213 */
55214 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
55215 {
55216   int rc = SQLITE_OK;
55217   if( pExpr ){
55218     if( pExpr->op!=TK_ID ){
55219       rc = sqlite3ExprResolveNames(pName, pExpr);
55220       if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
55221         sqlite3ErrorMsg(pName->pParse, "invalid name: \"%T\"", &pExpr->span);
55222         return SQLITE_ERROR;
55223       }
55224     }else{
55225       pExpr->op = TK_STRING;
55226     }
55227   }
55228   return rc;
55229 }
55230
55231 /*
55232 ** An SQL user-function registered to do the work of an ATTACH statement. The
55233 ** three arguments to the function come directly from an attach statement:
55234 **
55235 **     ATTACH DATABASE x AS y KEY z
55236 **
55237 **     SELECT sqlite_attach(x, y, z)
55238 **
55239 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
55240 ** third argument.
55241 */
55242 static void attachFunc(
55243   sqlite3_context *context,
55244   int argc,
55245   sqlite3_value **argv
55246 ){
55247   int i;
55248   int rc = 0;
55249   sqlite3 *db = sqlite3_context_db_handle(context);
55250   const char *zName;
55251   const char *zFile;
55252   Db *aNew;
55253   char *zErrDyn = 0;
55254   char zErr[128];
55255
55256   zFile = (const char *)sqlite3_value_text(argv[0]);
55257   zName = (const char *)sqlite3_value_text(argv[1]);
55258   if( zFile==0 ) zFile = "";
55259   if( zName==0 ) zName = "";
55260
55261   /* Check for the following errors:
55262   **
55263   **     * Too many attached databases,
55264   **     * Transaction currently open
55265   **     * Specified database name already being used.
55266   */
55267   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
55268     sqlite3_snprintf(
55269       sizeof(zErr), zErr, "too many attached databases - max %d", 
55270       db->aLimit[SQLITE_LIMIT_ATTACHED]
55271     );
55272     goto attach_error;
55273   }
55274   if( !db->autoCommit ){
55275     sqlite3_snprintf(sizeof(zErr), zErr,
55276                      "cannot ATTACH database within transaction");
55277     goto attach_error;
55278   }
55279   for(i=0; i<db->nDb; i++){
55280     char *z = db->aDb[i].zName;
55281     if( z && zName && sqlite3StrICmp(z, zName)==0 ){
55282       sqlite3_snprintf(sizeof(zErr), zErr, 
55283                        "database %s is already in use", zName);
55284       goto attach_error;
55285     }
55286   }
55287
55288   /* Allocate the new entry in the db->aDb[] array and initialise the schema
55289   ** hash tables.
55290   */
55291   if( db->aDb==db->aDbStatic ){
55292     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
55293     if( aNew==0 ) return;
55294     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
55295   }else{
55296     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
55297     if( aNew==0 ) return;
55298   }
55299   db->aDb = aNew;
55300   aNew = &db->aDb[db->nDb++];
55301   memset(aNew, 0, sizeof(*aNew));
55302
55303   /* Open the database file. If the btree is successfully opened, use
55304   ** it to obtain the database schema. At this point the schema may
55305   ** or may not be initialised.
55306   */
55307   rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE,
55308                            db->openFlags | SQLITE_OPEN_MAIN_DB,
55309                            &aNew->pBt);
55310   if( rc==SQLITE_OK ){
55311     Pager *pPager;
55312     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
55313     if( !aNew->pSchema ){
55314       rc = SQLITE_NOMEM;
55315     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
55316       sqlite3_snprintf(sizeof(zErr), zErr, 
55317         "attached databases must use the same text encoding as main database");
55318       goto attach_error;
55319     }
55320     pPager = sqlite3BtreePager(aNew->pBt);
55321     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
55322     sqlite3PagerJournalMode(pPager, db->dfltJournalMode);
55323   }
55324   aNew->zName = sqlite3DbStrDup(db, zName);
55325   aNew->safety_level = 3;
55326
55327 #if SQLITE_HAS_CODEC
55328   {
55329     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
55330     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
55331     int nKey;
55332     char *zKey;
55333     int t = sqlite3_value_type(argv[2]);
55334     switch( t ){
55335       case SQLITE_INTEGER:
55336       case SQLITE_FLOAT:
55337         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
55338         rc = SQLITE_ERROR;
55339         break;
55340         
55341       case SQLITE_TEXT:
55342       case SQLITE_BLOB:
55343         nKey = sqlite3_value_bytes(argv[2]);
55344         zKey = (char *)sqlite3_value_blob(argv[2]);
55345         sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
55346         break;
55347
55348       case SQLITE_NULL:
55349         /* No key specified.  Use the key from the main database */
55350         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
55351         sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
55352         break;
55353     }
55354   }
55355 #endif
55356
55357   /* If the file was opened successfully, read the schema for the new database.
55358   ** If this fails, or if opening the file failed, then close the file and 
55359   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
55360   ** we found it.
55361   */
55362   if( rc==SQLITE_OK ){
55363     (void)sqlite3SafetyOn(db);
55364     sqlite3BtreeEnterAll(db);
55365     rc = sqlite3Init(db, &zErrDyn);
55366     sqlite3BtreeLeaveAll(db);
55367     (void)sqlite3SafetyOff(db);
55368   }
55369   if( rc ){
55370     int iDb = db->nDb - 1;
55371     assert( iDb>=2 );
55372     if( db->aDb[iDb].pBt ){
55373       sqlite3BtreeClose(db->aDb[iDb].pBt);
55374       db->aDb[iDb].pBt = 0;
55375       db->aDb[iDb].pSchema = 0;
55376     }
55377     sqlite3ResetInternalSchema(db, 0);
55378     db->nDb = iDb;
55379     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
55380       db->mallocFailed = 1;
55381       sqlite3_snprintf(sizeof(zErr),zErr, "out of memory");
55382     }else{
55383       sqlite3_snprintf(sizeof(zErr),zErr, "unable to open database: %s", zFile);
55384     }
55385     goto attach_error;
55386   }
55387   
55388   return;
55389
55390 attach_error:
55391   /* Return an error if we get here */
55392   if( zErrDyn ){
55393     sqlite3_result_error(context, zErrDyn, -1);
55394     sqlite3DbFree(db, zErrDyn);
55395   }else{
55396     zErr[sizeof(zErr)-1] = 0;
55397     sqlite3_result_error(context, zErr, -1);
55398   }
55399   if( rc ) sqlite3_result_error_code(context, rc);
55400 }
55401
55402 /*
55403 ** An SQL user-function registered to do the work of an DETACH statement. The
55404 ** three arguments to the function come directly from a detach statement:
55405 **
55406 **     DETACH DATABASE x
55407 **
55408 **     SELECT sqlite_detach(x)
55409 */
55410 static void detachFunc(
55411   sqlite3_context *context,
55412   int argc,
55413   sqlite3_value **argv
55414 ){
55415   const char *zName = (const char *)sqlite3_value_text(argv[0]);
55416   sqlite3 *db = sqlite3_context_db_handle(context);
55417   int i;
55418   Db *pDb = 0;
55419   char zErr[128];
55420
55421   if( zName==0 ) zName = "";
55422   for(i=0; i<db->nDb; i++){
55423     pDb = &db->aDb[i];
55424     if( pDb->pBt==0 ) continue;
55425     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
55426   }
55427
55428   if( i>=db->nDb ){
55429     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
55430     goto detach_error;
55431   }
55432   if( i<2 ){
55433     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
55434     goto detach_error;
55435   }
55436   if( !db->autoCommit ){
55437     sqlite3_snprintf(sizeof(zErr), zErr,
55438                      "cannot DETACH database within transaction");
55439     goto detach_error;
55440   }
55441   if( sqlite3BtreeIsInReadTrans(pDb->pBt) ){
55442     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
55443     goto detach_error;
55444   }
55445
55446   sqlite3BtreeClose(pDb->pBt);
55447   pDb->pBt = 0;
55448   pDb->pSchema = 0;
55449   sqlite3ResetInternalSchema(db, 0);
55450   return;
55451
55452 detach_error:
55453   sqlite3_result_error(context, zErr, -1);
55454 }
55455
55456 /*
55457 ** This procedure generates VDBE code for a single invocation of either the
55458 ** sqlite_detach() or sqlite_attach() SQL user functions.
55459 */
55460 static void codeAttach(
55461   Parse *pParse,       /* The parser context */
55462   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
55463   const char *zFunc,   /* Either "sqlite_attach" or "sqlite_detach */
55464   int nFunc,           /* Number of args to pass to zFunc */
55465   Expr *pAuthArg,      /* Expression to pass to authorization callback */
55466   Expr *pFilename,     /* Name of database file */
55467   Expr *pDbname,       /* Name of the database to use internally */
55468   Expr *pKey           /* Database key for encryption extension */
55469 ){
55470   int rc;
55471   NameContext sName;
55472   Vdbe *v;
55473   FuncDef *pFunc;
55474   sqlite3* db = pParse->db;
55475   int regArgs;
55476
55477 #ifndef SQLITE_OMIT_AUTHORIZATION
55478   assert( db->mallocFailed || pAuthArg );
55479   if( pAuthArg ){
55480     char *zAuthArg = sqlite3NameFromToken(db, &pAuthArg->span);
55481     if( !zAuthArg ){
55482       goto attach_end;
55483     }
55484     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
55485     sqlite3DbFree(db, zAuthArg);
55486     if(rc!=SQLITE_OK ){
55487       goto attach_end;
55488     }
55489   }
55490 #endif /* SQLITE_OMIT_AUTHORIZATION */
55491
55492   memset(&sName, 0, sizeof(NameContext));
55493   sName.pParse = pParse;
55494
55495   if( 
55496       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
55497       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
55498       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
55499   ){
55500     pParse->nErr++;
55501     goto attach_end;
55502   }
55503
55504   v = sqlite3GetVdbe(pParse);
55505   regArgs = sqlite3GetTempRange(pParse, 4);
55506   sqlite3ExprCode(pParse, pFilename, regArgs);
55507   sqlite3ExprCode(pParse, pDbname, regArgs+1);
55508   sqlite3ExprCode(pParse, pKey, regArgs+2);
55509
55510   assert( v || db->mallocFailed );
55511   if( v ){
55512     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-nFunc, regArgs+3);
55513     sqlite3VdbeChangeP5(v, nFunc);
55514     pFunc = sqlite3FindFunction(db, zFunc, strlen(zFunc), nFunc, SQLITE_UTF8,0);
55515     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
55516
55517     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
55518     ** statement only). For DETACH, set it to false (expire all existing
55519     ** statements).
55520     */
55521     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
55522   }
55523   
55524 attach_end:
55525   sqlite3ExprDelete(db, pFilename);
55526   sqlite3ExprDelete(db, pDbname);
55527   sqlite3ExprDelete(db, pKey);
55528 }
55529
55530 /*
55531 ** Called by the parser to compile a DETACH statement.
55532 **
55533 **     DETACH pDbname
55534 */
55535 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
55536   codeAttach(pParse, SQLITE_DETACH, "sqlite_detach", 1, pDbname, 0, 0, pDbname);
55537 }
55538
55539 /*
55540 ** Called by the parser to compile an ATTACH statement.
55541 **
55542 **     ATTACH p AS pDbname KEY pKey
55543 */
55544 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
55545   codeAttach(pParse, SQLITE_ATTACH, "sqlite_attach", 3, p, p, pDbname, pKey);
55546 }
55547 #endif /* SQLITE_OMIT_ATTACH */
55548
55549 /*
55550 ** Register the functions sqlite_attach and sqlite_detach.
55551 */
55552 SQLITE_PRIVATE void sqlite3AttachFunctions(sqlite3 *db){
55553 #ifndef SQLITE_OMIT_ATTACH
55554   static const int enc = SQLITE_UTF8;
55555   sqlite3CreateFunc(db, "sqlite_attach", 3, enc, 0, attachFunc, 0, 0);
55556   sqlite3CreateFunc(db, "sqlite_detach", 1, enc, 0, detachFunc, 0, 0);
55557 #endif
55558 }
55559
55560 /*
55561 ** Initialize a DbFixer structure.  This routine must be called prior
55562 ** to passing the structure to one of the sqliteFixAAAA() routines below.
55563 **
55564 ** The return value indicates whether or not fixation is required.  TRUE
55565 ** means we do need to fix the database references, FALSE means we do not.
55566 */
55567 SQLITE_PRIVATE int sqlite3FixInit(
55568   DbFixer *pFix,      /* The fixer to be initialized */
55569   Parse *pParse,      /* Error messages will be written here */
55570   int iDb,            /* This is the database that must be used */
55571   const char *zType,  /* "view", "trigger", or "index" */
55572   const Token *pName  /* Name of the view, trigger, or index */
55573 ){
55574   sqlite3 *db;
55575
55576   if( iDb<0 || iDb==1 ) return 0;
55577   db = pParse->db;
55578   assert( db->nDb>iDb );
55579   pFix->pParse = pParse;
55580   pFix->zDb = db->aDb[iDb].zName;
55581   pFix->zType = zType;
55582   pFix->pName = pName;
55583   return 1;
55584 }
55585
55586 /*
55587 ** The following set of routines walk through the parse tree and assign
55588 ** a specific database to all table references where the database name
55589 ** was left unspecified in the original SQL statement.  The pFix structure
55590 ** must have been initialized by a prior call to sqlite3FixInit().
55591 **
55592 ** These routines are used to make sure that an index, trigger, or
55593 ** view in one database does not refer to objects in a different database.
55594 ** (Exception: indices, triggers, and views in the TEMP database are
55595 ** allowed to refer to anything.)  If a reference is explicitly made
55596 ** to an object in a different database, an error message is added to
55597 ** pParse->zErrMsg and these routines return non-zero.  If everything
55598 ** checks out, these routines return 0.
55599 */
55600 SQLITE_PRIVATE int sqlite3FixSrcList(
55601   DbFixer *pFix,       /* Context of the fixation */
55602   SrcList *pList       /* The Source list to check and modify */
55603 ){
55604   int i;
55605   const char *zDb;
55606   struct SrcList_item *pItem;
55607
55608   if( pList==0 ) return 0;
55609   zDb = pFix->zDb;
55610   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
55611     if( pItem->zDatabase==0 ){
55612       pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
55613     }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
55614       sqlite3ErrorMsg(pFix->pParse,
55615          "%s %T cannot reference objects in database %s",
55616          pFix->zType, pFix->pName, pItem->zDatabase);
55617       return 1;
55618     }
55619 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
55620     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
55621     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
55622 #endif
55623   }
55624   return 0;
55625 }
55626 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
55627 SQLITE_PRIVATE int sqlite3FixSelect(
55628   DbFixer *pFix,       /* Context of the fixation */
55629   Select *pSelect      /* The SELECT statement to be fixed to one database */
55630 ){
55631   while( pSelect ){
55632     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
55633       return 1;
55634     }
55635     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
55636       return 1;
55637     }
55638     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
55639       return 1;
55640     }
55641     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
55642       return 1;
55643     }
55644     pSelect = pSelect->pPrior;
55645   }
55646   return 0;
55647 }
55648 SQLITE_PRIVATE int sqlite3FixExpr(
55649   DbFixer *pFix,     /* Context of the fixation */
55650   Expr *pExpr        /* The expression to be fixed to one database */
55651 ){
55652   while( pExpr ){
55653     if( sqlite3FixSelect(pFix, pExpr->pSelect) ){
55654       return 1;
55655     }
55656     if( sqlite3FixExprList(pFix, pExpr->pList) ){
55657       return 1;
55658     }
55659     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
55660       return 1;
55661     }
55662     pExpr = pExpr->pLeft;
55663   }
55664   return 0;
55665 }
55666 SQLITE_PRIVATE int sqlite3FixExprList(
55667   DbFixer *pFix,     /* Context of the fixation */
55668   ExprList *pList    /* The expression to be fixed to one database */
55669 ){
55670   int i;
55671   struct ExprList_item *pItem;
55672   if( pList==0 ) return 0;
55673   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
55674     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
55675       return 1;
55676     }
55677   }
55678   return 0;
55679 }
55680 #endif
55681
55682 #ifndef SQLITE_OMIT_TRIGGER
55683 SQLITE_PRIVATE int sqlite3FixTriggerStep(
55684   DbFixer *pFix,     /* Context of the fixation */
55685   TriggerStep *pStep /* The trigger step be fixed to one database */
55686 ){
55687   while( pStep ){
55688     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
55689       return 1;
55690     }
55691     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
55692       return 1;
55693     }
55694     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
55695       return 1;
55696     }
55697     pStep = pStep->pNext;
55698   }
55699   return 0;
55700 }
55701 #endif
55702
55703 /************** End of attach.c **********************************************/
55704 /************** Begin file auth.c ********************************************/
55705 /*
55706 ** 2003 January 11
55707 **
55708 ** The author disclaims copyright to this source code.  In place of
55709 ** a legal notice, here is a blessing:
55710 **
55711 **    May you do good and not evil.
55712 **    May you find forgiveness for yourself and forgive others.
55713 **    May you share freely, never taking more than you give.
55714 **
55715 *************************************************************************
55716 ** This file contains code used to implement the sqlite3_set_authorizer()
55717 ** API.  This facility is an optional feature of the library.  Embedded
55718 ** systems that do not need this facility may omit it by recompiling
55719 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
55720 **
55721 ** $Id: auth.c,v 1.29 2007/09/18 15:55:07 drh Exp $
55722 */
55723
55724 /*
55725 ** All of the code in this file may be omitted by defining a single
55726 ** macro.
55727 */
55728 #ifndef SQLITE_OMIT_AUTHORIZATION
55729
55730 /*
55731 ** Set or clear the access authorization function.
55732 **
55733 ** The access authorization function is be called during the compilation
55734 ** phase to verify that the user has read and/or write access permission on
55735 ** various fields of the database.  The first argument to the auth function
55736 ** is a copy of the 3rd argument to this routine.  The second argument
55737 ** to the auth function is one of these constants:
55738 **
55739 **       SQLITE_CREATE_INDEX
55740 **       SQLITE_CREATE_TABLE
55741 **       SQLITE_CREATE_TEMP_INDEX
55742 **       SQLITE_CREATE_TEMP_TABLE
55743 **       SQLITE_CREATE_TEMP_TRIGGER
55744 **       SQLITE_CREATE_TEMP_VIEW
55745 **       SQLITE_CREATE_TRIGGER
55746 **       SQLITE_CREATE_VIEW
55747 **       SQLITE_DELETE
55748 **       SQLITE_DROP_INDEX
55749 **       SQLITE_DROP_TABLE
55750 **       SQLITE_DROP_TEMP_INDEX
55751 **       SQLITE_DROP_TEMP_TABLE
55752 **       SQLITE_DROP_TEMP_TRIGGER
55753 **       SQLITE_DROP_TEMP_VIEW
55754 **       SQLITE_DROP_TRIGGER
55755 **       SQLITE_DROP_VIEW
55756 **       SQLITE_INSERT
55757 **       SQLITE_PRAGMA
55758 **       SQLITE_READ
55759 **       SQLITE_SELECT
55760 **       SQLITE_TRANSACTION
55761 **       SQLITE_UPDATE
55762 **
55763 ** The third and fourth arguments to the auth function are the name of
55764 ** the table and the column that are being accessed.  The auth function
55765 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
55766 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
55767 ** means that the SQL statement will never-run - the sqlite3_exec() call
55768 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
55769 ** should run but attempts to read the specified column will return NULL
55770 ** and attempts to write the column will be ignored.
55771 **
55772 ** Setting the auth function to NULL disables this hook.  The default
55773 ** setting of the auth function is NULL.
55774 */
55775 SQLITE_API int sqlite3_set_authorizer(
55776   sqlite3 *db,
55777   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
55778   void *pArg
55779 ){
55780   sqlite3_mutex_enter(db->mutex);
55781   db->xAuth = xAuth;
55782   db->pAuthArg = pArg;
55783   sqlite3ExpirePreparedStatements(db);
55784   sqlite3_mutex_leave(db->mutex);
55785   return SQLITE_OK;
55786 }
55787
55788 /*
55789 ** Write an error message into pParse->zErrMsg that explains that the
55790 ** user-supplied authorization function returned an illegal value.
55791 */
55792 static void sqliteAuthBadReturnCode(Parse *pParse, int rc){
55793   sqlite3ErrorMsg(pParse, "illegal return value (%d) from the "
55794     "authorization function - should be SQLITE_OK, SQLITE_IGNORE, "
55795     "or SQLITE_DENY", rc);
55796   pParse->rc = SQLITE_ERROR;
55797 }
55798
55799 /*
55800 ** The pExpr should be a TK_COLUMN expression.  The table referred to
55801 ** is in pTabList or else it is the NEW or OLD table of a trigger.  
55802 ** Check to see if it is OK to read this particular column.
55803 **
55804 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
55805 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
55806 ** then generate an error.
55807 */
55808 SQLITE_PRIVATE void sqlite3AuthRead(
55809   Parse *pParse,        /* The parser context */
55810   Expr *pExpr,          /* The expression to check authorization on */
55811   Schema *pSchema,      /* The schema of the expression */
55812   SrcList *pTabList     /* All table that pExpr might refer to */
55813 ){
55814   sqlite3 *db = pParse->db;
55815   int rc;
55816   Table *pTab = 0;      /* The table being read */
55817   const char *zCol;     /* Name of the column of the table */
55818   int iSrc;             /* Index in pTabList->a[] of table being read */
55819   const char *zDBase;   /* Name of database being accessed */
55820   TriggerStack *pStack; /* The stack of current triggers */
55821   int iDb;              /* The index of the database the expression refers to */
55822
55823   if( db->xAuth==0 ) return;
55824   if( pExpr->op!=TK_COLUMN ) return;
55825   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
55826   if( iDb<0 ){
55827     /* An attempt to read a column out of a subquery or other
55828     ** temporary table. */
55829     return;
55830   }
55831   for(iSrc=0; pTabList && iSrc<pTabList->nSrc; iSrc++){
55832     if( pExpr->iTable==pTabList->a[iSrc].iCursor ) break;
55833   }
55834   if( iSrc>=0 && pTabList && iSrc<pTabList->nSrc ){
55835     pTab = pTabList->a[iSrc].pTab;
55836   }else if( (pStack = pParse->trigStack)!=0 ){
55837     /* This must be an attempt to read the NEW or OLD pseudo-tables
55838     ** of a trigger.
55839     */
55840     assert( pExpr->iTable==pStack->newIdx || pExpr->iTable==pStack->oldIdx );
55841     pTab = pStack->pTab;
55842   }
55843   if( pTab==0 ) return;
55844   if( pExpr->iColumn>=0 ){
55845     assert( pExpr->iColumn<pTab->nCol );
55846     zCol = pTab->aCol[pExpr->iColumn].zName;
55847   }else if( pTab->iPKey>=0 ){
55848     assert( pTab->iPKey<pTab->nCol );
55849     zCol = pTab->aCol[pTab->iPKey].zName;
55850   }else{
55851     zCol = "ROWID";
55852   }
55853   assert( iDb>=0 && iDb<db->nDb );
55854   zDBase = db->aDb[iDb].zName;
55855   rc = db->xAuth(db->pAuthArg, SQLITE_READ, pTab->zName, zCol, zDBase, 
55856                  pParse->zAuthContext);
55857   if( rc==SQLITE_IGNORE ){
55858     pExpr->op = TK_NULL;
55859   }else if( rc==SQLITE_DENY ){
55860     if( db->nDb>2 || iDb!=0 ){
55861       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited", 
55862          zDBase, pTab->zName, zCol);
55863     }else{
55864       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited",pTab->zName,zCol);
55865     }
55866     pParse->rc = SQLITE_AUTH;
55867   }else if( rc!=SQLITE_OK ){
55868     sqliteAuthBadReturnCode(pParse, rc);
55869   }
55870 }
55871
55872 /*
55873 ** Do an authorization check using the code and arguments given.  Return
55874 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
55875 ** is returned, then the error count and error message in pParse are
55876 ** modified appropriately.
55877 */
55878 SQLITE_PRIVATE int sqlite3AuthCheck(
55879   Parse *pParse,
55880   int code,
55881   const char *zArg1,
55882   const char *zArg2,
55883   const char *zArg3
55884 ){
55885   sqlite3 *db = pParse->db;
55886   int rc;
55887
55888   /* Don't do any authorization checks if the database is initialising
55889   ** or if the parser is being invoked from within sqlite3_declare_vtab.
55890   */
55891   if( db->init.busy || IN_DECLARE_VTAB ){
55892     return SQLITE_OK;
55893   }
55894
55895   if( db->xAuth==0 ){
55896     return SQLITE_OK;
55897   }
55898   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
55899   if( rc==SQLITE_DENY ){
55900     sqlite3ErrorMsg(pParse, "not authorized");
55901     pParse->rc = SQLITE_AUTH;
55902   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
55903     rc = SQLITE_DENY;
55904     sqliteAuthBadReturnCode(pParse, rc);
55905   }
55906   return rc;
55907 }
55908
55909 /*
55910 ** Push an authorization context.  After this routine is called, the
55911 ** zArg3 argument to authorization callbacks will be zContext until
55912 ** popped.  Or if pParse==0, this routine is a no-op.
55913 */
55914 SQLITE_PRIVATE void sqlite3AuthContextPush(
55915   Parse *pParse,
55916   AuthContext *pContext, 
55917   const char *zContext
55918 ){
55919   pContext->pParse = pParse;
55920   if( pParse ){
55921     pContext->zAuthContext = pParse->zAuthContext;
55922     pParse->zAuthContext = zContext;
55923   }
55924 }
55925
55926 /*
55927 ** Pop an authorization context that was previously pushed
55928 ** by sqlite3AuthContextPush
55929 */
55930 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
55931   if( pContext->pParse ){
55932     pContext->pParse->zAuthContext = pContext->zAuthContext;
55933     pContext->pParse = 0;
55934   }
55935 }
55936
55937 #endif /* SQLITE_OMIT_AUTHORIZATION */
55938
55939 /************** End of auth.c ************************************************/
55940 /************** Begin file build.c *******************************************/
55941 /*
55942 ** 2001 September 15
55943 **
55944 ** The author disclaims copyright to this source code.  In place of
55945 ** a legal notice, here is a blessing:
55946 **
55947 **    May you do good and not evil.
55948 **    May you find forgiveness for yourself and forgive others.
55949 **    May you share freely, never taking more than you give.
55950 **
55951 *************************************************************************
55952 ** This file contains C code routines that are called by the SQLite parser
55953 ** when syntax rules are reduced.  The routines in this file handle the
55954 ** following kinds of SQL syntax:
55955 **
55956 **     CREATE TABLE
55957 **     DROP TABLE
55958 **     CREATE INDEX
55959 **     DROP INDEX
55960 **     creating ID lists
55961 **     BEGIN TRANSACTION
55962 **     COMMIT
55963 **     ROLLBACK
55964 **
55965 ** $Id: build.c,v 1.493 2008/08/04 04:39:49 danielk1977 Exp $
55966 */
55967
55968 /*
55969 ** This routine is called when a new SQL statement is beginning to
55970 ** be parsed.  Initialize the pParse structure as needed.
55971 */
55972 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
55973   pParse->explain = explainFlag;
55974   pParse->nVar = 0;
55975 }
55976
55977 #ifndef SQLITE_OMIT_SHARED_CACHE
55978 /*
55979 ** The TableLock structure is only used by the sqlite3TableLock() and
55980 ** codeTableLocks() functions.
55981 */
55982 struct TableLock {
55983   int iDb;             /* The database containing the table to be locked */
55984   int iTab;            /* The root page of the table to be locked */
55985   u8 isWriteLock;      /* True for write lock.  False for a read lock */
55986   const char *zName;   /* Name of the table */
55987 };
55988
55989 /*
55990 ** Record the fact that we want to lock a table at run-time.  
55991 **
55992 ** The table to be locked has root page iTab and is found in database iDb.
55993 ** A read or a write lock can be taken depending on isWritelock.
55994 **
55995 ** This routine just records the fact that the lock is desired.  The
55996 ** code to make the lock occur is generated by a later call to
55997 ** codeTableLocks() which occurs during sqlite3FinishCoding().
55998 */
55999 SQLITE_PRIVATE void sqlite3TableLock(
56000   Parse *pParse,     /* Parsing context */
56001   int iDb,           /* Index of the database containing the table to lock */
56002   int iTab,          /* Root page number of the table to be locked */
56003   u8 isWriteLock,    /* True for a write lock */
56004   const char *zName  /* Name of the table to be locked */
56005 ){
56006   int i;
56007   int nBytes;
56008   TableLock *p;
56009
56010   if( iDb<0 ){
56011     return;
56012   }
56013
56014   for(i=0; i<pParse->nTableLock; i++){
56015     p = &pParse->aTableLock[i];
56016     if( p->iDb==iDb && p->iTab==iTab ){
56017       p->isWriteLock = (p->isWriteLock || isWriteLock);
56018       return;
56019     }
56020   }
56021
56022   nBytes = sizeof(TableLock) * (pParse->nTableLock+1);
56023   pParse->aTableLock = 
56024       sqlite3DbReallocOrFree(pParse->db, pParse->aTableLock, nBytes);
56025   if( pParse->aTableLock ){
56026     p = &pParse->aTableLock[pParse->nTableLock++];
56027     p->iDb = iDb;
56028     p->iTab = iTab;
56029     p->isWriteLock = isWriteLock;
56030     p->zName = zName;
56031   }else{
56032     pParse->nTableLock = 0;
56033     pParse->db->mallocFailed = 1;
56034   }
56035 }
56036
56037 /*
56038 ** Code an OP_TableLock instruction for each table locked by the
56039 ** statement (configured by calls to sqlite3TableLock()).
56040 */
56041 static void codeTableLocks(Parse *pParse){
56042   int i;
56043   Vdbe *pVdbe; 
56044
56045   if( 0==(pVdbe = sqlite3GetVdbe(pParse)) ){
56046     return;
56047   }
56048
56049   for(i=0; i<pParse->nTableLock; i++){
56050     TableLock *p = &pParse->aTableLock[i];
56051     int p1 = p->iDb;
56052     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
56053                       p->zName, P4_STATIC);
56054   }
56055 }
56056 #else
56057   #define codeTableLocks(x)
56058 #endif
56059
56060 /*
56061 ** This routine is called after a single SQL statement has been
56062 ** parsed and a VDBE program to execute that statement has been
56063 ** prepared.  This routine puts the finishing touches on the
56064 ** VDBE program and resets the pParse structure for the next
56065 ** parse.
56066 **
56067 ** Note that if an error occurred, it might be the case that
56068 ** no VDBE code was generated.
56069 */
56070 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
56071   sqlite3 *db;
56072   Vdbe *v;
56073
56074   db = pParse->db;
56075   if( db->mallocFailed ) return;
56076   if( pParse->nested ) return;
56077   if( pParse->nErr ) return;
56078
56079   /* Begin by generating some termination code at the end of the
56080   ** vdbe program
56081   */
56082   v = sqlite3GetVdbe(pParse);
56083   if( v ){
56084     sqlite3VdbeAddOp0(v, OP_Halt);
56085
56086     /* The cookie mask contains one bit for each database file open.
56087     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
56088     ** set for each database that is used.  Generate code to start a
56089     ** transaction on each used database and to verify the schema cookie
56090     ** on each used database.
56091     */
56092     if( pParse->cookieGoto>0 ){
56093       u32 mask;
56094       int iDb;
56095       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
56096       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
56097         if( (mask & pParse->cookieMask)==0 ) continue;
56098         sqlite3VdbeUsesBtree(v, iDb);
56099         sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
56100         sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
56101       }
56102 #ifndef SQLITE_OMIT_VIRTUALTABLE
56103       {
56104         int i;
56105         for(i=0; i<pParse->nVtabLock; i++){
56106           char *vtab = (char *)pParse->apVtabLock[i]->pVtab;
56107           sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
56108         }
56109         pParse->nVtabLock = 0;
56110       }
56111 #endif
56112
56113       /* Once all the cookies have been verified and transactions opened, 
56114       ** obtain the required table-locks. This is a no-op unless the 
56115       ** shared-cache feature is enabled.
56116       */
56117       codeTableLocks(pParse);
56118       sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
56119     }
56120
56121 #ifndef SQLITE_OMIT_TRACE
56122     if( !db->init.busy ){
56123       /* Change the P4 argument of the first opcode (which will always be
56124       ** an OP_Trace) to be the complete text of the current SQL statement.
56125       */
56126       VdbeOp *pOp = sqlite3VdbeGetOp(v, 0);
56127       if( pOp && pOp->opcode==OP_Trace ){
56128         sqlite3VdbeChangeP4(v, 0, pParse->zSql, pParse->zTail-pParse->zSql);
56129       }
56130     }
56131 #endif /* SQLITE_OMIT_TRACE */
56132   }
56133
56134
56135   /* Get the VDBE program ready for execution
56136   */
56137   if( v && pParse->nErr==0 && !db->mallocFailed ){
56138 #ifdef SQLITE_DEBUG
56139     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
56140     sqlite3VdbeTrace(v, trace);
56141 #endif
56142     assert( pParse->disableColCache==0 );  /* Disables and re-enables match */
56143     sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem+3,
56144                          pParse->nTab+3, pParse->explain);
56145     pParse->rc = SQLITE_DONE;
56146     pParse->colNamesSet = 0;
56147   }else if( pParse->rc==SQLITE_OK ){
56148     pParse->rc = SQLITE_ERROR;
56149   }
56150   pParse->nTab = 0;
56151   pParse->nMem = 0;
56152   pParse->nSet = 0;
56153   pParse->nVar = 0;
56154   pParse->cookieMask = 0;
56155   pParse->cookieGoto = 0;
56156 }
56157
56158 /*
56159 ** Run the parser and code generator recursively in order to generate
56160 ** code for the SQL statement given onto the end of the pParse context
56161 ** currently under construction.  When the parser is run recursively
56162 ** this way, the final OP_Halt is not appended and other initialization
56163 ** and finalization steps are omitted because those are handling by the
56164 ** outermost parser.
56165 **
56166 ** Not everything is nestable.  This facility is designed to permit
56167 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
56168 ** care if you decide to try to use this routine for some other purposes.
56169 */
56170 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
56171   va_list ap;
56172   char *zSql;
56173   char *zErrMsg = 0;
56174   sqlite3 *db = pParse->db;
56175 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
56176   char saveBuf[SAVE_SZ];
56177
56178   if( pParse->nErr ) return;
56179   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
56180   va_start(ap, zFormat);
56181   zSql = sqlite3VMPrintf(db, zFormat, ap);
56182   va_end(ap);
56183   if( zSql==0 ){
56184     return;   /* A malloc must have failed */
56185   }
56186   pParse->nested++;
56187   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
56188   memset(&pParse->nVar, 0, SAVE_SZ);
56189   sqlite3RunParser(pParse, zSql, &zErrMsg);
56190   sqlite3DbFree(db, zErrMsg);
56191   sqlite3DbFree(db, zSql);
56192   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
56193   pParse->nested--;
56194 }
56195
56196 /*
56197 ** Locate the in-memory structure that describes a particular database
56198 ** table given the name of that table and (optionally) the name of the
56199 ** database containing the table.  Return NULL if not found.
56200 **
56201 ** If zDatabase is 0, all databases are searched for the table and the
56202 ** first matching table is returned.  (No checking for duplicate table
56203 ** names is done.)  The search order is TEMP first, then MAIN, then any
56204 ** auxiliary databases added using the ATTACH command.
56205 **
56206 ** See also sqlite3LocateTable().
56207 */
56208 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
56209   Table *p = 0;
56210   int i;
56211   int nName;
56212   assert( zName!=0 );
56213   nName = sqlite3Strlen(db, zName) + 1;
56214   for(i=OMIT_TEMPDB; i<db->nDb; i++){
56215     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
56216     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
56217     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
56218     if( p ) break;
56219   }
56220   return p;
56221 }
56222
56223 /*
56224 ** Locate the in-memory structure that describes a particular database
56225 ** table given the name of that table and (optionally) the name of the
56226 ** database containing the table.  Return NULL if not found.  Also leave an
56227 ** error message in pParse->zErrMsg.
56228 **
56229 ** The difference between this routine and sqlite3FindTable() is that this
56230 ** routine leaves an error message in pParse->zErrMsg where
56231 ** sqlite3FindTable() does not.
56232 */
56233 SQLITE_PRIVATE Table *sqlite3LocateTable(
56234   Parse *pParse,         /* context in which to report errors */
56235   int isView,            /* True if looking for a VIEW rather than a TABLE */
56236   const char *zName,     /* Name of the table we are looking for */
56237   const char *zDbase     /* Name of the database.  Might be NULL */
56238 ){
56239   Table *p;
56240
56241   /* Read the database schema. If an error occurs, leave an error message
56242   ** and code in pParse and return NULL. */
56243   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
56244     return 0;
56245   }
56246
56247   p = sqlite3FindTable(pParse->db, zName, zDbase);
56248   if( p==0 ){
56249     const char *zMsg = isView ? "no such view" : "no such table";
56250     if( zDbase ){
56251       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
56252     }else{
56253       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
56254     }
56255     pParse->checkSchema = 1;
56256   }
56257   return p;
56258 }
56259
56260 /*
56261 ** Locate the in-memory structure that describes 
56262 ** a particular index given the name of that index
56263 ** and the name of the database that contains the index.
56264 ** Return NULL if not found.
56265 **
56266 ** If zDatabase is 0, all databases are searched for the
56267 ** table and the first matching index is returned.  (No checking
56268 ** for duplicate index names is done.)  The search order is
56269 ** TEMP first, then MAIN, then any auxiliary databases added
56270 ** using the ATTACH command.
56271 */
56272 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
56273   Index *p = 0;
56274   int i;
56275   int nName = sqlite3Strlen(db, zName)+1;
56276   for(i=OMIT_TEMPDB; i<db->nDb; i++){
56277     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
56278     Schema *pSchema = db->aDb[j].pSchema;
56279     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
56280     assert( pSchema || (j==1 && !db->aDb[1].pBt) );
56281     if( pSchema ){
56282       p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
56283     }
56284     if( p ) break;
56285   }
56286   return p;
56287 }
56288
56289 /*
56290 ** Reclaim the memory used by an index
56291 */
56292 static void freeIndex(Index *p){
56293   sqlite3 *db = p->pTable->db;
56294   sqlite3DbFree(db, p->zColAff);
56295   sqlite3DbFree(db, p);
56296 }
56297
56298 /*
56299 ** Remove the given index from the index hash table, and free
56300 ** its memory structures.
56301 **
56302 ** The index is removed from the database hash tables but
56303 ** it is not unlinked from the Table that it indexes.
56304 ** Unlinking from the Table must be done by the calling function.
56305 */
56306 static void sqliteDeleteIndex(Index *p){
56307   Index *pOld;
56308   const char *zName = p->zName;
56309
56310   pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName, strlen(zName)+1, 0);
56311   assert( pOld==0 || pOld==p );
56312   freeIndex(p);
56313 }
56314
56315 /*
56316 ** For the index called zIdxName which is found in the database iDb,
56317 ** unlike that index from its Table then remove the index from
56318 ** the index hash table and free all memory structures associated
56319 ** with the index.
56320 */
56321 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
56322   Index *pIndex;
56323   int len;
56324   Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
56325
56326   len = sqlite3Strlen(db, zIdxName);
56327   pIndex = sqlite3HashInsert(pHash, zIdxName, len+1, 0);
56328   if( pIndex ){
56329     if( pIndex->pTable->pIndex==pIndex ){
56330       pIndex->pTable->pIndex = pIndex->pNext;
56331     }else{
56332       Index *p;
56333       for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
56334       if( p && p->pNext==pIndex ){
56335         p->pNext = pIndex->pNext;
56336       }
56337     }
56338     freeIndex(pIndex);
56339   }
56340   db->flags |= SQLITE_InternChanges;
56341 }
56342
56343 /*
56344 ** Erase all schema information from the in-memory hash tables of
56345 ** a single database.  This routine is called to reclaim memory
56346 ** before the database closes.  It is also called during a rollback
56347 ** if there were schema changes during the transaction or if a
56348 ** schema-cookie mismatch occurs.
56349 **
56350 ** If iDb<=0 then reset the internal schema tables for all database
56351 ** files.  If iDb>=2 then reset the internal schema for only the
56352 ** single file indicated.
56353 */
56354 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
56355   int i, j;
56356   assert( iDb>=0 && iDb<db->nDb );
56357
56358   if( iDb==0 ){
56359     sqlite3BtreeEnterAll(db);
56360   }
56361   for(i=iDb; i<db->nDb; i++){
56362     Db *pDb = &db->aDb[i];
56363     if( pDb->pSchema ){
56364       assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
56365       sqlite3SchemaFree(pDb->pSchema);
56366     }
56367     if( iDb>0 ) return;
56368   }
56369   assert( iDb==0 );
56370   db->flags &= ~SQLITE_InternChanges;
56371   sqlite3BtreeLeaveAll(db);
56372
56373   /* If one or more of the auxiliary database files has been closed,
56374   ** then remove them from the auxiliary database list.  We take the
56375   ** opportunity to do this here since we have just deleted all of the
56376   ** schema hash tables and therefore do not have to make any changes
56377   ** to any of those tables.
56378   */
56379   for(i=0; i<db->nDb; i++){
56380     struct Db *pDb = &db->aDb[i];
56381     if( pDb->pBt==0 ){
56382       if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
56383       pDb->pAux = 0;
56384     }
56385   }
56386   for(i=j=2; i<db->nDb; i++){
56387     struct Db *pDb = &db->aDb[i];
56388     if( pDb->pBt==0 ){
56389       sqlite3DbFree(db, pDb->zName);
56390       pDb->zName = 0;
56391       continue;
56392     }
56393     if( j<i ){
56394       db->aDb[j] = db->aDb[i];
56395     }
56396     j++;
56397   }
56398   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
56399   db->nDb = j;
56400   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
56401     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
56402     sqlite3DbFree(db, db->aDb);
56403     db->aDb = db->aDbStatic;
56404   }
56405 }
56406
56407 /*
56408 ** This routine is called when a commit occurs.
56409 */
56410 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
56411   db->flags &= ~SQLITE_InternChanges;
56412 }
56413
56414 /*
56415 ** Clear the column names from a table or view.
56416 */
56417 static void sqliteResetColumnNames(Table *pTable){
56418   int i;
56419   Column *pCol;
56420   sqlite3 *db = pTable->db;
56421   assert( pTable!=0 );
56422   if( (pCol = pTable->aCol)!=0 ){
56423     for(i=0; i<pTable->nCol; i++, pCol++){
56424       sqlite3DbFree(db, pCol->zName);
56425       sqlite3ExprDelete(db, pCol->pDflt);
56426       sqlite3DbFree(db, pCol->zType);
56427       sqlite3DbFree(db, pCol->zColl);
56428     }
56429     sqlite3DbFree(db, pTable->aCol);
56430   }
56431   pTable->aCol = 0;
56432   pTable->nCol = 0;
56433 }
56434
56435 /*
56436 ** Remove the memory data structures associated with the given
56437 ** Table.  No changes are made to disk by this routine.
56438 **
56439 ** This routine just deletes the data structure.  It does not unlink
56440 ** the table data structure from the hash table.  Nor does it remove
56441 ** foreign keys from the sqlite.aFKey hash table.  But it does destroy
56442 ** memory structures of the indices and foreign keys associated with 
56443 ** the table.
56444 */
56445 SQLITE_PRIVATE void sqlite3DeleteTable(Table *pTable){
56446   Index *pIndex, *pNext;
56447   FKey *pFKey, *pNextFKey;
56448   sqlite3 *db;
56449
56450   if( pTable==0 ) return;
56451   db = pTable->db;
56452
56453   /* Do not delete the table until the reference count reaches zero. */
56454   pTable->nRef--;
56455   if( pTable->nRef>0 ){
56456     return;
56457   }
56458   assert( pTable->nRef==0 );
56459
56460   /* Delete all indices associated with this table
56461   */
56462   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
56463     pNext = pIndex->pNext;
56464     assert( pIndex->pSchema==pTable->pSchema );
56465     sqliteDeleteIndex(pIndex);
56466   }
56467
56468 #ifndef SQLITE_OMIT_FOREIGN_KEY
56469   /* Delete all foreign keys associated with this table.  The keys
56470   ** should have already been unlinked from the pSchema->aFKey hash table 
56471   */
56472   for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
56473     pNextFKey = pFKey->pNextFrom;
56474     assert( sqlite3HashFind(&pTable->pSchema->aFKey,
56475                            pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey );
56476     sqlite3DbFree(db, pFKey);
56477   }
56478 #endif
56479
56480   /* Delete the Table structure itself.
56481   */
56482   sqliteResetColumnNames(pTable);
56483   sqlite3DbFree(db, pTable->zName);
56484   sqlite3DbFree(db, pTable->zColAff);
56485   sqlite3SelectDelete(db, pTable->pSelect);
56486 #ifndef SQLITE_OMIT_CHECK
56487   sqlite3ExprDelete(db, pTable->pCheck);
56488 #endif
56489   sqlite3VtabClear(pTable);
56490   sqlite3DbFree(db, pTable);
56491 }
56492
56493 /*
56494 ** Unlink the given table from the hash tables and the delete the
56495 ** table structure with all its indices and foreign keys.
56496 */
56497 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
56498   Table *p;
56499   FKey *pF1, *pF2;
56500   Db *pDb;
56501
56502   assert( db!=0 );
56503   assert( iDb>=0 && iDb<db->nDb );
56504   assert( zTabName && zTabName[0] );
56505   pDb = &db->aDb[iDb];
56506   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, strlen(zTabName)+1,0);
56507   if( p ){
56508 #ifndef SQLITE_OMIT_FOREIGN_KEY
56509     for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
56510       int nTo = strlen(pF1->zTo) + 1;
56511       pF2 = sqlite3HashFind(&pDb->pSchema->aFKey, pF1->zTo, nTo);
56512       if( pF2==pF1 ){
56513         sqlite3HashInsert(&pDb->pSchema->aFKey, pF1->zTo, nTo, pF1->pNextTo);
56514       }else{
56515         while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
56516         if( pF2 ){
56517           pF2->pNextTo = pF1->pNextTo;
56518         }
56519       }
56520     }
56521 #endif
56522     sqlite3DeleteTable(p);
56523   }
56524   db->flags |= SQLITE_InternChanges;
56525 }
56526
56527 /*
56528 ** Given a token, return a string that consists of the text of that
56529 ** token with any quotations removed.  Space to hold the returned string
56530 ** is obtained from sqliteMalloc() and must be freed by the calling
56531 ** function.
56532 **
56533 ** Tokens are often just pointers into the original SQL text and so
56534 ** are not \000 terminated and are not persistent.  The returned string
56535 ** is \000 terminated and is persistent.
56536 */
56537 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
56538   char *zName;
56539   if( pName ){
56540     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
56541     sqlite3Dequote(zName);
56542   }else{
56543     zName = 0;
56544   }
56545   return zName;
56546 }
56547
56548 /*
56549 ** Open the sqlite_master table stored in database number iDb for
56550 ** writing. The table is opened using cursor 0.
56551 */
56552 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
56553   Vdbe *v = sqlite3GetVdbe(p);
56554   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
56555   sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, 5);/* sqlite_master has 5 columns */
56556   sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
56557 }
56558
56559 /*
56560 ** The token *pName contains the name of a database (either "main" or
56561 ** "temp" or the name of an attached db). This routine returns the
56562 ** index of the named database in db->aDb[], or -1 if the named db 
56563 ** does not exist.
56564 */
56565 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
56566   int i = -1;    /* Database number */
56567   int n;         /* Number of characters in the name */
56568   Db *pDb;       /* A database whose name space is being searched */
56569   char *zName;   /* Name we are searching for */
56570
56571   zName = sqlite3NameFromToken(db, pName);
56572   if( zName ){
56573     n = strlen(zName);
56574     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
56575       if( (!OMIT_TEMPDB || i!=1 ) && n==strlen(pDb->zName) && 
56576           0==sqlite3StrICmp(pDb->zName, zName) ){
56577         break;
56578       }
56579     }
56580     sqlite3DbFree(db, zName);
56581   }
56582   return i;
56583 }
56584
56585 /* The table or view or trigger name is passed to this routine via tokens
56586 ** pName1 and pName2. If the table name was fully qualified, for example:
56587 **
56588 ** CREATE TABLE xxx.yyy (...);
56589 ** 
56590 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
56591 ** the table name is not fully qualified, i.e.:
56592 **
56593 ** CREATE TABLE yyy(...);
56594 **
56595 ** Then pName1 is set to "yyy" and pName2 is "".
56596 **
56597 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
56598 ** pName2) that stores the unqualified table name.  The index of the
56599 ** database "xxx" is returned.
56600 */
56601 SQLITE_PRIVATE int sqlite3TwoPartName(
56602   Parse *pParse,      /* Parsing and code generating context */
56603   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
56604   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
56605   Token **pUnqual     /* Write the unqualified object name here */
56606 ){
56607   int iDb;                    /* Database holding the object */
56608   sqlite3 *db = pParse->db;
56609
56610   if( pName2 && pName2->n>0 ){
56611     assert( !db->init.busy );
56612     *pUnqual = pName2;
56613     iDb = sqlite3FindDb(db, pName1);
56614     if( iDb<0 ){
56615       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
56616       pParse->nErr++;
56617       return -1;
56618     }
56619   }else{
56620     assert( db->init.iDb==0 || db->init.busy );
56621     iDb = db->init.iDb;
56622     *pUnqual = pName1;
56623   }
56624   return iDb;
56625 }
56626
56627 /*
56628 ** This routine is used to check if the UTF-8 string zName is a legal
56629 ** unqualified name for a new schema object (table, index, view or
56630 ** trigger). All names are legal except those that begin with the string
56631 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
56632 ** is reserved for internal use.
56633 */
56634 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
56635   if( !pParse->db->init.busy && pParse->nested==0 
56636           && (pParse->db->flags & SQLITE_WriteSchema)==0
56637           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
56638     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
56639     return SQLITE_ERROR;
56640   }
56641   return SQLITE_OK;
56642 }
56643
56644 /*
56645 ** Begin constructing a new table representation in memory.  This is
56646 ** the first of several action routines that get called in response
56647 ** to a CREATE TABLE statement.  In particular, this routine is called
56648 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
56649 ** flag is true if the table should be stored in the auxiliary database
56650 ** file instead of in the main database file.  This is normally the case
56651 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
56652 ** CREATE and TABLE.
56653 **
56654 ** The new table record is initialized and put in pParse->pNewTable.
56655 ** As more of the CREATE TABLE statement is parsed, additional action
56656 ** routines will be called to add more information to this record.
56657 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
56658 ** is called to complete the construction of the new table record.
56659 */
56660 SQLITE_PRIVATE void sqlite3StartTable(
56661   Parse *pParse,   /* Parser context */
56662   Token *pName1,   /* First part of the name of the table or view */
56663   Token *pName2,   /* Second part of the name of the table or view */
56664   int isTemp,      /* True if this is a TEMP table */
56665   int isView,      /* True if this is a VIEW */
56666   int isVirtual,   /* True if this is a VIRTUAL table */
56667   int noErr        /* Do nothing if table already exists */
56668 ){
56669   Table *pTable;
56670   char *zName = 0; /* The name of the new table */
56671   sqlite3 *db = pParse->db;
56672   Vdbe *v;
56673   int iDb;         /* Database number to create the table in */
56674   Token *pName;    /* Unqualified name of the table to create */
56675
56676   /* The table or view name to create is passed to this routine via tokens
56677   ** pName1 and pName2. If the table name was fully qualified, for example:
56678   **
56679   ** CREATE TABLE xxx.yyy (...);
56680   ** 
56681   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
56682   ** the table name is not fully qualified, i.e.:
56683   **
56684   ** CREATE TABLE yyy(...);
56685   **
56686   ** Then pName1 is set to "yyy" and pName2 is "".
56687   **
56688   ** The call below sets the pName pointer to point at the token (pName1 or
56689   ** pName2) that stores the unqualified table name. The variable iDb is
56690   ** set to the index of the database that the table or view is to be
56691   ** created in.
56692   */
56693   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
56694   if( iDb<0 ) return;
56695   if( !OMIT_TEMPDB && isTemp && iDb>1 ){
56696     /* If creating a temp table, the name may not be qualified */
56697     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
56698     return;
56699   }
56700   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
56701
56702   pParse->sNameToken = *pName;
56703   zName = sqlite3NameFromToken(db, pName);
56704   if( zName==0 ) return;
56705   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
56706     goto begin_table_error;
56707   }
56708   if( db->init.iDb==1 ) isTemp = 1;
56709 #ifndef SQLITE_OMIT_AUTHORIZATION
56710   assert( (isTemp & 1)==isTemp );
56711   {
56712     int code;
56713     char *zDb = db->aDb[iDb].zName;
56714     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
56715       goto begin_table_error;
56716     }
56717     if( isView ){
56718       if( !OMIT_TEMPDB && isTemp ){
56719         code = SQLITE_CREATE_TEMP_VIEW;
56720       }else{
56721         code = SQLITE_CREATE_VIEW;
56722       }
56723     }else{
56724       if( !OMIT_TEMPDB && isTemp ){
56725         code = SQLITE_CREATE_TEMP_TABLE;
56726       }else{
56727         code = SQLITE_CREATE_TABLE;
56728       }
56729     }
56730     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
56731       goto begin_table_error;
56732     }
56733   }
56734 #endif
56735
56736   /* Make sure the new table name does not collide with an existing
56737   ** index or table name in the same database.  Issue an error message if
56738   ** it does. The exception is if the statement being parsed was passed
56739   ** to an sqlite3_declare_vtab() call. In that case only the column names
56740   ** and types will be used, so there is no need to test for namespace
56741   ** collisions.
56742   */
56743   if( !IN_DECLARE_VTAB ){
56744     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
56745       goto begin_table_error;
56746     }
56747     pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
56748     if( pTable ){
56749       if( !noErr ){
56750         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
56751       }
56752       goto begin_table_error;
56753     }
56754     if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
56755       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
56756       goto begin_table_error;
56757     }
56758   }
56759
56760   pTable = sqlite3DbMallocZero(db, sizeof(Table));
56761   if( pTable==0 ){
56762     db->mallocFailed = 1;
56763     pParse->rc = SQLITE_NOMEM;
56764     pParse->nErr++;
56765     goto begin_table_error;
56766   }
56767   pTable->zName = zName;
56768   pTable->iPKey = -1;
56769   pTable->pSchema = db->aDb[iDb].pSchema;
56770   pTable->nRef = 1;
56771   pTable->db = db;
56772   if( pParse->pNewTable ) sqlite3DeleteTable(pParse->pNewTable);
56773   pParse->pNewTable = pTable;
56774
56775   /* If this is the magic sqlite_sequence table used by autoincrement,
56776   ** then record a pointer to this table in the main database structure
56777   ** so that INSERT can find the table easily.
56778   */
56779 #ifndef SQLITE_OMIT_AUTOINCREMENT
56780   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
56781     pTable->pSchema->pSeqTab = pTable;
56782   }
56783 #endif
56784
56785   /* Begin generating the code that will insert the table record into
56786   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
56787   ** and allocate the record number for the table entry now.  Before any
56788   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
56789   ** indices to be created and the table record must come before the 
56790   ** indices.  Hence, the record number for the table must be allocated
56791   ** now.
56792   */
56793   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
56794     int j1;
56795     int fileFormat;
56796     int reg1, reg2, reg3;
56797     sqlite3BeginWriteOperation(pParse, 0, iDb);
56798
56799 #ifndef SQLITE_OMIT_VIRTUALTABLE
56800     if( isVirtual ){
56801       sqlite3VdbeAddOp0(v, OP_VBegin);
56802     }
56803 #endif
56804
56805     /* If the file format and encoding in the database have not been set, 
56806     ** set them now.
56807     */
56808     reg1 = pParse->regRowid = ++pParse->nMem;
56809     reg2 = pParse->regRoot = ++pParse->nMem;
56810     reg3 = ++pParse->nMem;
56811     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, 1);   /* file_format */
56812     sqlite3VdbeUsesBtree(v, iDb);
56813     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
56814     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
56815                   1 : SQLITE_MAX_FILE_FORMAT;
56816     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
56817     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, reg3);
56818     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
56819     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 4, reg3);
56820     sqlite3VdbeJumpHere(v, j1);
56821
56822     /* This just creates a place-holder record in the sqlite_master table.
56823     ** The record created does not contain anything yet.  It will be replaced
56824     ** by the real entry in code generated at sqlite3EndTable().
56825     **
56826     ** The rowid for the new entry is left on the top of the stack.
56827     ** The rowid value is needed by the code that sqlite3EndTable will
56828     ** generate.
56829     */
56830 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
56831     if( isView || isVirtual ){
56832       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
56833     }else
56834 #endif
56835     {
56836       sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
56837     }
56838     sqlite3OpenMasterTable(pParse, iDb);
56839     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
56840     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
56841     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
56842     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
56843     sqlite3VdbeAddOp0(v, OP_Close);
56844   }
56845
56846   /* Normal (non-error) return. */
56847   return;
56848
56849   /* If an error occurs, we jump here */
56850 begin_table_error:
56851   sqlite3DbFree(db, zName);
56852   return;
56853 }
56854
56855 /*
56856 ** This macro is used to compare two strings in a case-insensitive manner.
56857 ** It is slightly faster than calling sqlite3StrICmp() directly, but
56858 ** produces larger code.
56859 **
56860 ** WARNING: This macro is not compatible with the strcmp() family. It
56861 ** returns true if the two strings are equal, otherwise false.
56862 */
56863 #define STRICMP(x, y) (\
56864 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
56865 sqlite3UpperToLower[*(unsigned char *)(y)]     \
56866 && sqlite3StrICmp((x)+1,(y)+1)==0 )
56867
56868 /*
56869 ** Add a new column to the table currently being constructed.
56870 **
56871 ** The parser calls this routine once for each column declaration
56872 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
56873 ** first to get things going.  Then this routine is called for each
56874 ** column.
56875 */
56876 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
56877   Table *p;
56878   int i;
56879   char *z;
56880   Column *pCol;
56881   sqlite3 *db = pParse->db;
56882   if( (p = pParse->pNewTable)==0 ) return;
56883 #if SQLITE_MAX_COLUMN
56884   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
56885     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
56886     return;
56887   }
56888 #endif
56889   z = sqlite3NameFromToken(pParse->db, pName);
56890   if( z==0 ) return;
56891   for(i=0; i<p->nCol; i++){
56892     if( STRICMP(z, p->aCol[i].zName) ){
56893       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
56894       sqlite3DbFree(db, z);
56895       return;
56896     }
56897   }
56898   if( (p->nCol & 0x7)==0 ){
56899     Column *aNew;
56900     aNew = sqlite3DbRealloc(pParse->db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
56901     if( aNew==0 ){
56902       sqlite3DbFree(db, z);
56903       return;
56904     }
56905     p->aCol = aNew;
56906   }
56907   pCol = &p->aCol[p->nCol];
56908   memset(pCol, 0, sizeof(p->aCol[0]));
56909   pCol->zName = z;
56910  
56911   /* If there is no type specified, columns have the default affinity
56912   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
56913   ** be called next to set pCol->affinity correctly.
56914   */
56915   pCol->affinity = SQLITE_AFF_NONE;
56916   p->nCol++;
56917 }
56918
56919 /*
56920 ** This routine is called by the parser while in the middle of
56921 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
56922 ** been seen on a column.  This routine sets the notNull flag on
56923 ** the column currently under construction.
56924 */
56925 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
56926   Table *p;
56927   int i;
56928   if( (p = pParse->pNewTable)==0 ) return;
56929   i = p->nCol-1;
56930   if( i>=0 ) p->aCol[i].notNull = onError;
56931 }
56932
56933 /*
56934 ** Scan the column type name zType (length nType) and return the
56935 ** associated affinity type.
56936 **
56937 ** This routine does a case-independent search of zType for the 
56938 ** substrings in the following table. If one of the substrings is
56939 ** found, the corresponding affinity is returned. If zType contains
56940 ** more than one of the substrings, entries toward the top of 
56941 ** the table take priority. For example, if zType is 'BLOBINT', 
56942 ** SQLITE_AFF_INTEGER is returned.
56943 **
56944 ** Substring     | Affinity
56945 ** --------------------------------
56946 ** 'INT'         | SQLITE_AFF_INTEGER
56947 ** 'CHAR'        | SQLITE_AFF_TEXT
56948 ** 'CLOB'        | SQLITE_AFF_TEXT
56949 ** 'TEXT'        | SQLITE_AFF_TEXT
56950 ** 'BLOB'        | SQLITE_AFF_NONE
56951 ** 'REAL'        | SQLITE_AFF_REAL
56952 ** 'FLOA'        | SQLITE_AFF_REAL
56953 ** 'DOUB'        | SQLITE_AFF_REAL
56954 **
56955 ** If none of the substrings in the above table are found,
56956 ** SQLITE_AFF_NUMERIC is returned.
56957 */
56958 SQLITE_PRIVATE char sqlite3AffinityType(const Token *pType){
56959   u32 h = 0;
56960   char aff = SQLITE_AFF_NUMERIC;
56961   const unsigned char *zIn = pType->z;
56962   const unsigned char *zEnd = &pType->z[pType->n];
56963
56964   while( zIn!=zEnd ){
56965     h = (h<<8) + sqlite3UpperToLower[*zIn];
56966     zIn++;
56967     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
56968       aff = SQLITE_AFF_TEXT; 
56969     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
56970       aff = SQLITE_AFF_TEXT;
56971     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
56972       aff = SQLITE_AFF_TEXT;
56973     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
56974         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
56975       aff = SQLITE_AFF_NONE;
56976 #ifndef SQLITE_OMIT_FLOATING_POINT
56977     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
56978         && aff==SQLITE_AFF_NUMERIC ){
56979       aff = SQLITE_AFF_REAL;
56980     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
56981         && aff==SQLITE_AFF_NUMERIC ){
56982       aff = SQLITE_AFF_REAL;
56983     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
56984         && aff==SQLITE_AFF_NUMERIC ){
56985       aff = SQLITE_AFF_REAL;
56986 #endif
56987     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
56988       aff = SQLITE_AFF_INTEGER;
56989       break;
56990     }
56991   }
56992
56993   return aff;
56994 }
56995
56996 /*
56997 ** This routine is called by the parser while in the middle of
56998 ** parsing a CREATE TABLE statement.  The pFirst token is the first
56999 ** token in the sequence of tokens that describe the type of the
57000 ** column currently under construction.   pLast is the last token
57001 ** in the sequence.  Use this information to construct a string
57002 ** that contains the typename of the column and store that string
57003 ** in zType.
57004 */ 
57005 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
57006   Table *p;
57007   int i;
57008   Column *pCol;
57009   sqlite3 *db;
57010
57011   if( (p = pParse->pNewTable)==0 ) return;
57012   i = p->nCol-1;
57013   if( i<0 ) return;
57014   pCol = &p->aCol[i];
57015   db = pParse->db;
57016   sqlite3DbFree(db, pCol->zType);
57017   pCol->zType = sqlite3NameFromToken(db, pType);
57018   pCol->affinity = sqlite3AffinityType(pType);
57019 }
57020
57021 /*
57022 ** The expression is the default value for the most recently added column
57023 ** of the table currently under construction.
57024 **
57025 ** Default value expressions must be constant.  Raise an exception if this
57026 ** is not the case.
57027 **
57028 ** This routine is called by the parser while in the middle of
57029 ** parsing a CREATE TABLE statement.
57030 */
57031 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){
57032   Table *p;
57033   Column *pCol;
57034   sqlite3 *db = pParse->db;
57035   if( (p = pParse->pNewTable)!=0 ){
57036     pCol = &(p->aCol[p->nCol-1]);
57037     if( !sqlite3ExprIsConstantOrFunction(pExpr) ){
57038       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
57039           pCol->zName);
57040     }else{
57041       Expr *pCopy;
57042       sqlite3ExprDelete(db, pCol->pDflt);
57043       pCol->pDflt = pCopy = sqlite3ExprDup(db, pExpr);
57044       if( pCopy ){
57045         sqlite3TokenCopy(db, &pCopy->span, &pExpr->span);
57046       }
57047     }
57048   }
57049   sqlite3ExprDelete(db, pExpr);
57050 }
57051
57052 /*
57053 ** Designate the PRIMARY KEY for the table.  pList is a list of names 
57054 ** of columns that form the primary key.  If pList is NULL, then the
57055 ** most recently added column of the table is the primary key.
57056 **
57057 ** A table can have at most one primary key.  If the table already has
57058 ** a primary key (and this is the second primary key) then create an
57059 ** error.
57060 **
57061 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
57062 ** then we will try to use that column as the rowid.  Set the Table.iPKey
57063 ** field of the table under construction to be the index of the
57064 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
57065 ** no INTEGER PRIMARY KEY.
57066 **
57067 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
57068 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
57069 */
57070 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
57071   Parse *pParse,    /* Parsing context */
57072   ExprList *pList,  /* List of field names to be indexed */
57073   int onError,      /* What to do with a uniqueness conflict */
57074   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
57075   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
57076 ){
57077   Table *pTab = pParse->pNewTable;
57078   char *zType = 0;
57079   int iCol = -1, i;
57080   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
57081   if( pTab->hasPrimKey ){
57082     sqlite3ErrorMsg(pParse, 
57083       "table \"%s\" has more than one primary key", pTab->zName);
57084     goto primary_key_exit;
57085   }
57086   pTab->hasPrimKey = 1;
57087   if( pList==0 ){
57088     iCol = pTab->nCol - 1;
57089     pTab->aCol[iCol].isPrimKey = 1;
57090   }else{
57091     for(i=0; i<pList->nExpr; i++){
57092       for(iCol=0; iCol<pTab->nCol; iCol++){
57093         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
57094           break;
57095         }
57096       }
57097       if( iCol<pTab->nCol ){
57098         pTab->aCol[iCol].isPrimKey = 1;
57099       }
57100     }
57101     if( pList->nExpr>1 ) iCol = -1;
57102   }
57103   if( iCol>=0 && iCol<pTab->nCol ){
57104     zType = pTab->aCol[iCol].zType;
57105   }
57106   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
57107         && sortOrder==SQLITE_SO_ASC ){
57108     pTab->iPKey = iCol;
57109     pTab->keyConf = onError;
57110     pTab->autoInc = autoInc;
57111   }else if( autoInc ){
57112 #ifndef SQLITE_OMIT_AUTOINCREMENT
57113     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
57114        "INTEGER PRIMARY KEY");
57115 #endif
57116   }else{
57117     sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
57118     pList = 0;
57119   }
57120
57121 primary_key_exit:
57122   sqlite3ExprListDelete(pParse->db, pList);
57123   return;
57124 }
57125
57126 /*
57127 ** Add a new CHECK constraint to the table currently under construction.
57128 */
57129 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
57130   Parse *pParse,    /* Parsing context */
57131   Expr *pCheckExpr  /* The check expression */
57132 ){
57133   sqlite3 *db = pParse->db;
57134 #ifndef SQLITE_OMIT_CHECK
57135   Table *pTab = pParse->pNewTable;
57136   if( pTab && !IN_DECLARE_VTAB ){
57137     /* The CHECK expression must be duplicated so that tokens refer
57138     ** to malloced space and not the (ephemeral) text of the CREATE TABLE
57139     ** statement */
57140     pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, 
57141                                   sqlite3ExprDup(db, pCheckExpr));
57142   }
57143 #endif
57144   sqlite3ExprDelete(db, pCheckExpr);
57145 }
57146
57147 /*
57148 ** Set the collation function of the most recently parsed table column
57149 ** to the CollSeq given.
57150 */
57151 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
57152   Table *p;
57153   int i;
57154   char *zColl;              /* Dequoted name of collation sequence */
57155   sqlite3 *db;
57156
57157   if( (p = pParse->pNewTable)==0 ) return;
57158   i = p->nCol-1;
57159   db = pParse->db;
57160   zColl = sqlite3NameFromToken(db, pToken);
57161   if( !zColl ) return;
57162
57163   if( sqlite3LocateCollSeq(pParse, zColl, -1) ){
57164     Index *pIdx;
57165     p->aCol[i].zColl = zColl;
57166   
57167     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
57168     ** then an index may have been created on this column before the
57169     ** collation type was added. Correct this if it is the case.
57170     */
57171     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
57172       assert( pIdx->nColumn==1 );
57173       if( pIdx->aiColumn[0]==i ){
57174         pIdx->azColl[0] = p->aCol[i].zColl;
57175       }
57176     }
57177   }else{
57178     sqlite3DbFree(db, zColl);
57179   }
57180 }
57181
57182 /*
57183 ** This function returns the collation sequence for database native text
57184 ** encoding identified by the string zName, length nName.
57185 **
57186 ** If the requested collation sequence is not available, or not available
57187 ** in the database native encoding, the collation factory is invoked to
57188 ** request it. If the collation factory does not supply such a sequence,
57189 ** and the sequence is available in another text encoding, then that is
57190 ** returned instead.
57191 **
57192 ** If no versions of the requested collations sequence are available, or
57193 ** another error occurs, NULL is returned and an error message written into
57194 ** pParse.
57195 **
57196 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
57197 ** invokes the collation factory if the named collation cannot be found
57198 ** and generates an error message.
57199 */
57200 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
57201   sqlite3 *db = pParse->db;
57202   u8 enc = ENC(db);
57203   u8 initbusy = db->init.busy;
57204   CollSeq *pColl;
57205
57206   pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
57207   if( !initbusy && (!pColl || !pColl->xCmp) ){
57208     pColl = sqlite3GetCollSeq(db, pColl, zName, nName);
57209     if( !pColl ){
57210       if( nName<0 ){
57211         nName = sqlite3Strlen(db, zName);
57212       }
57213       sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName);
57214       pColl = 0;
57215     }
57216   }
57217
57218   return pColl;
57219 }
57220
57221
57222 /*
57223 ** Generate code that will increment the schema cookie.
57224 **
57225 ** The schema cookie is used to determine when the schema for the
57226 ** database changes.  After each schema change, the cookie value
57227 ** changes.  When a process first reads the schema it records the
57228 ** cookie.  Thereafter, whenever it goes to access the database,
57229 ** it checks the cookie to make sure the schema has not changed
57230 ** since it was last read.
57231 **
57232 ** This plan is not completely bullet-proof.  It is possible for
57233 ** the schema to change multiple times and for the cookie to be
57234 ** set back to prior value.  But schema changes are infrequent
57235 ** and the probability of hitting the same cookie value is only
57236 ** 1 chance in 2^32.  So we're safe enough.
57237 */
57238 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
57239   int r1 = sqlite3GetTempReg(pParse);
57240   sqlite3 *db = pParse->db;
57241   Vdbe *v = pParse->pVdbe;
57242   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
57243   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 0, r1);
57244   sqlite3ReleaseTempReg(pParse, r1);
57245 }
57246
57247 /*
57248 ** Measure the number of characters needed to output the given
57249 ** identifier.  The number returned includes any quotes used
57250 ** but does not include the null terminator.
57251 **
57252 ** The estimate is conservative.  It might be larger that what is
57253 ** really needed.
57254 */
57255 static int identLength(const char *z){
57256   int n;
57257   for(n=0; *z; n++, z++){
57258     if( *z=='"' ){ n++; }
57259   }
57260   return n + 2;
57261 }
57262
57263 /*
57264 ** Write an identifier onto the end of the given string.  Add
57265 ** quote characters as needed.
57266 */
57267 static void identPut(char *z, int *pIdx, char *zSignedIdent){
57268   unsigned char *zIdent = (unsigned char*)zSignedIdent;
57269   int i, j, needQuote;
57270   i = *pIdx;
57271   for(j=0; zIdent[j]; j++){
57272     if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
57273   }
57274   needQuote =  zIdent[j]!=0 || isdigit(zIdent[0])
57275                   || sqlite3KeywordCode(zIdent, j)!=TK_ID;
57276   if( needQuote ) z[i++] = '"';
57277   for(j=0; zIdent[j]; j++){
57278     z[i++] = zIdent[j];
57279     if( zIdent[j]=='"' ) z[i++] = '"';
57280   }
57281   if( needQuote ) z[i++] = '"';
57282   z[i] = 0;
57283   *pIdx = i;
57284 }
57285
57286 /*
57287 ** Generate a CREATE TABLE statement appropriate for the given
57288 ** table.  Memory to hold the text of the statement is obtained
57289 ** from sqliteMalloc() and must be freed by the calling function.
57290 */
57291 static char *createTableStmt(sqlite3 *db, Table *p, int isTemp){
57292   int i, k, n;
57293   char *zStmt;
57294   char *zSep, *zSep2, *zEnd, *z;
57295   Column *pCol;
57296   n = 0;
57297   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
57298     n += identLength(pCol->zName);
57299     z = pCol->zType;
57300     if( z ){
57301       n += (strlen(z) + 1);
57302     }
57303   }
57304   n += identLength(p->zName);
57305   if( n<50 ){
57306     zSep = "";
57307     zSep2 = ",";
57308     zEnd = ")";
57309   }else{
57310     zSep = "\n  ";
57311     zSep2 = ",\n  ";
57312     zEnd = "\n)";
57313   }
57314   n += 35 + 6*p->nCol;
57315   zStmt = sqlite3Malloc( n );
57316   if( zStmt==0 ){
57317     db->mallocFailed = 1;
57318     return 0;
57319   }
57320   sqlite3_snprintf(n, zStmt,
57321                   !OMIT_TEMPDB&&isTemp ? "CREATE TEMP TABLE ":"CREATE TABLE ");
57322   k = strlen(zStmt);
57323   identPut(zStmt, &k, p->zName);
57324   zStmt[k++] = '(';
57325   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
57326     sqlite3_snprintf(n-k, &zStmt[k], zSep);
57327     k += strlen(&zStmt[k]);
57328     zSep = zSep2;
57329     identPut(zStmt, &k, pCol->zName);
57330     if( (z = pCol->zType)!=0 ){
57331       zStmt[k++] = ' ';
57332       assert( strlen(z)+k+1<=n );
57333       sqlite3_snprintf(n-k, &zStmt[k], "%s", z);
57334       k += strlen(z);
57335     }
57336   }
57337   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
57338   return zStmt;
57339 }
57340
57341 /*
57342 ** This routine is called to report the final ")" that terminates
57343 ** a CREATE TABLE statement.
57344 **
57345 ** The table structure that other action routines have been building
57346 ** is added to the internal hash tables, assuming no errors have
57347 ** occurred.
57348 **
57349 ** An entry for the table is made in the master table on disk, unless
57350 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
57351 ** it means we are reading the sqlite_master table because we just
57352 ** connected to the database or because the sqlite_master table has
57353 ** recently changed, so the entry for this table already exists in
57354 ** the sqlite_master table.  We do not want to create it again.
57355 **
57356 ** If the pSelect argument is not NULL, it means that this routine
57357 ** was called to create a table generated from a 
57358 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
57359 ** the new table will match the result set of the SELECT.
57360 */
57361 SQLITE_PRIVATE void sqlite3EndTable(
57362   Parse *pParse,          /* Parse context */
57363   Token *pCons,           /* The ',' token after the last column defn. */
57364   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
57365   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
57366 ){
57367   Table *p;
57368   sqlite3 *db = pParse->db;
57369   int iDb;
57370
57371   if( (pEnd==0 && pSelect==0) || pParse->nErr || db->mallocFailed ) {
57372     return;
57373   }
57374   p = pParse->pNewTable;
57375   if( p==0 ) return;
57376
57377   assert( !db->init.busy || !pSelect );
57378
57379   iDb = sqlite3SchemaToIndex(db, p->pSchema);
57380
57381 #ifndef SQLITE_OMIT_CHECK
57382   /* Resolve names in all CHECK constraint expressions.
57383   */
57384   if( p->pCheck ){
57385     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
57386     NameContext sNC;                /* Name context for pParse->pNewTable */
57387
57388     memset(&sNC, 0, sizeof(sNC));
57389     memset(&sSrc, 0, sizeof(sSrc));
57390     sSrc.nSrc = 1;
57391     sSrc.a[0].zName = p->zName;
57392     sSrc.a[0].pTab = p;
57393     sSrc.a[0].iCursor = -1;
57394     sNC.pParse = pParse;
57395     sNC.pSrcList = &sSrc;
57396     sNC.isCheck = 1;
57397     if( sqlite3ExprResolveNames(&sNC, p->pCheck) ){
57398       return;
57399     }
57400   }
57401 #endif /* !defined(SQLITE_OMIT_CHECK) */
57402
57403   /* If the db->init.busy is 1 it means we are reading the SQL off the
57404   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
57405   ** So do not write to the disk again.  Extract the root page number
57406   ** for the table from the db->init.newTnum field.  (The page number
57407   ** should have been put there by the sqliteOpenCb routine.)
57408   */
57409   if( db->init.busy ){
57410     p->tnum = db->init.newTnum;
57411   }
57412
57413   /* If not initializing, then create a record for the new table
57414   ** in the SQLITE_MASTER table of the database.  The record number
57415   ** for the new table entry should already be on the stack.
57416   **
57417   ** If this is a TEMPORARY table, write the entry into the auxiliary
57418   ** file instead of into the main database file.
57419   */
57420   if( !db->init.busy ){
57421     int n;
57422     Vdbe *v;
57423     char *zType;    /* "view" or "table" */
57424     char *zType2;   /* "VIEW" or "TABLE" */
57425     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
57426
57427     v = sqlite3GetVdbe(pParse);
57428     if( v==0 ) return;
57429
57430     sqlite3VdbeAddOp1(v, OP_Close, 0);
57431
57432     /* Create the rootpage for the new table and push it onto the stack.
57433     ** A view has no rootpage, so just push a zero onto the stack for
57434     ** views.  Initialize zType at the same time.
57435     */
57436     if( p->pSelect==0 ){
57437       /* A regular table */
57438       zType = "table";
57439       zType2 = "TABLE";
57440 #ifndef SQLITE_OMIT_VIEW
57441     }else{
57442       /* A view */
57443       zType = "view";
57444       zType2 = "VIEW";
57445 #endif
57446     }
57447
57448     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
57449     ** statement to populate the new table. The root-page number for the
57450     ** new table is on the top of the vdbe stack.
57451     **
57452     ** Once the SELECT has been coded by sqlite3Select(), it is in a
57453     ** suitable state to query for the column names and types to be used
57454     ** by the new table.
57455     **
57456     ** A shared-cache write-lock is not required to write to the new table,
57457     ** as a schema-lock must have already been obtained to create it. Since
57458     ** a schema-lock excludes all other database users, the write-lock would
57459     ** be redundant.
57460     */
57461     if( pSelect ){
57462       SelectDest dest;
57463       Table *pSelTab;
57464
57465       assert(pParse->nTab==0);
57466       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
57467       sqlite3VdbeChangeP5(v, 1);
57468       pParse->nTab = 2;
57469       sqlite3SelectDestInit(&dest, SRT_Table, 1);
57470       sqlite3Select(pParse, pSelect, &dest, 0, 0, 0);
57471       sqlite3VdbeAddOp1(v, OP_Close, 1);
57472       if( pParse->nErr==0 ){
57473         pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSelect);
57474         if( pSelTab==0 ) return;
57475         assert( p->aCol==0 );
57476         p->nCol = pSelTab->nCol;
57477         p->aCol = pSelTab->aCol;
57478         pSelTab->nCol = 0;
57479         pSelTab->aCol = 0;
57480         sqlite3DeleteTable(pSelTab);
57481       }
57482     }
57483
57484     /* Compute the complete text of the CREATE statement */
57485     if( pSelect ){
57486       zStmt = createTableStmt(db, p, p->pSchema==db->aDb[1].pSchema);
57487     }else{
57488       n = pEnd->z - pParse->sNameToken.z + 1;
57489       zStmt = sqlite3MPrintf(db, 
57490           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
57491       );
57492     }
57493
57494     /* A slot for the record has already been allocated in the 
57495     ** SQLITE_MASTER table.  We just need to update that slot with all
57496     ** the information we've collected.  The rowid for the preallocated
57497     ** slot is the 2nd item on the stack.  The top of the stack is the
57498     ** root page for the new table (or a 0 if this is a view).
57499     */
57500     sqlite3NestedParse(pParse,
57501       "UPDATE %Q.%s "
57502          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
57503        "WHERE rowid=#%d",
57504       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
57505       zType,
57506       p->zName,
57507       p->zName,
57508       pParse->regRoot,
57509       zStmt,
57510       pParse->regRowid
57511     );
57512     sqlite3DbFree(db, zStmt);
57513     sqlite3ChangeCookie(pParse, iDb);
57514
57515 #ifndef SQLITE_OMIT_AUTOINCREMENT
57516     /* Check to see if we need to create an sqlite_sequence table for
57517     ** keeping track of autoincrement keys.
57518     */
57519     if( p->autoInc ){
57520       Db *pDb = &db->aDb[iDb];
57521       if( pDb->pSchema->pSeqTab==0 ){
57522         sqlite3NestedParse(pParse,
57523           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
57524           pDb->zName
57525         );
57526       }
57527     }
57528 #endif
57529
57530     /* Reparse everything to update our internal data structures */
57531     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
57532         sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
57533   }
57534
57535
57536   /* Add the table to the in-memory representation of the database.
57537   */
57538   if( db->init.busy && pParse->nErr==0 ){
57539     Table *pOld;
57540     FKey *pFKey; 
57541     Schema *pSchema = p->pSchema;
57542     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, strlen(p->zName)+1,p);
57543     if( pOld ){
57544       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
57545       db->mallocFailed = 1;
57546       return;
57547     }
57548 #ifndef SQLITE_OMIT_FOREIGN_KEY
57549     for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
57550       void *data;
57551       int nTo = strlen(pFKey->zTo) + 1;
57552       pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo);
57553       data = sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey);
57554       if( data==(void *)pFKey ){
57555         db->mallocFailed = 1;
57556       }
57557     }
57558 #endif
57559     pParse->pNewTable = 0;
57560     db->nTable++;
57561     db->flags |= SQLITE_InternChanges;
57562
57563 #ifndef SQLITE_OMIT_ALTERTABLE
57564     if( !p->pSelect ){
57565       const char *zName = (const char *)pParse->sNameToken.z;
57566       int nName;
57567       assert( !pSelect && pCons && pEnd );
57568       if( pCons->z==0 ){
57569         pCons = pEnd;
57570       }
57571       nName = (const char *)pCons->z - zName;
57572       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
57573     }
57574 #endif
57575   }
57576 }
57577
57578 #ifndef SQLITE_OMIT_VIEW
57579 /*
57580 ** The parser calls this routine in order to create a new VIEW
57581 */
57582 SQLITE_PRIVATE void sqlite3CreateView(
57583   Parse *pParse,     /* The parsing context */
57584   Token *pBegin,     /* The CREATE token that begins the statement */
57585   Token *pName1,     /* The token that holds the name of the view */
57586   Token *pName2,     /* The token that holds the name of the view */
57587   Select *pSelect,   /* A SELECT statement that will become the new view */
57588   int isTemp,        /* TRUE for a TEMPORARY view */
57589   int noErr          /* Suppress error messages if VIEW already exists */
57590 ){
57591   Table *p;
57592   int n;
57593   const unsigned char *z;
57594   Token sEnd;
57595   DbFixer sFix;
57596   Token *pName;
57597   int iDb;
57598   sqlite3 *db = pParse->db;
57599
57600   if( pParse->nVar>0 ){
57601     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
57602     sqlite3SelectDelete(db, pSelect);
57603     return;
57604   }
57605   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
57606   p = pParse->pNewTable;
57607   if( p==0 || pParse->nErr ){
57608     sqlite3SelectDelete(db, pSelect);
57609     return;
57610   }
57611   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
57612   iDb = sqlite3SchemaToIndex(db, p->pSchema);
57613   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
57614     && sqlite3FixSelect(&sFix, pSelect)
57615   ){
57616     sqlite3SelectDelete(db, pSelect);
57617     return;
57618   }
57619
57620   /* Make a copy of the entire SELECT statement that defines the view.
57621   ** This will force all the Expr.token.z values to be dynamically
57622   ** allocated rather than point to the input string - which means that
57623   ** they will persist after the current sqlite3_exec() call returns.
57624   */
57625   p->pSelect = sqlite3SelectDup(db, pSelect);
57626   sqlite3SelectDelete(db, pSelect);
57627   if( db->mallocFailed ){
57628     return;
57629   }
57630   if( !db->init.busy ){
57631     sqlite3ViewGetColumnNames(pParse, p);
57632   }
57633
57634   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
57635   ** the end.
57636   */
57637   sEnd = pParse->sLastToken;
57638   if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
57639     sEnd.z += sEnd.n;
57640   }
57641   sEnd.n = 0;
57642   n = sEnd.z - pBegin->z;
57643   z = (const unsigned char*)pBegin->z;
57644   while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
57645   sEnd.z = &z[n-1];
57646   sEnd.n = 1;
57647
57648   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
57649   sqlite3EndTable(pParse, 0, &sEnd, 0);
57650   return;
57651 }
57652 #endif /* SQLITE_OMIT_VIEW */
57653
57654 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
57655 /*
57656 ** The Table structure pTable is really a VIEW.  Fill in the names of
57657 ** the columns of the view in the pTable structure.  Return the number
57658 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
57659 */
57660 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
57661   Table *pSelTab;   /* A fake table from which we get the result set */
57662   Select *pSel;     /* Copy of the SELECT that implements the view */
57663   int nErr = 0;     /* Number of errors encountered */
57664   int n;            /* Temporarily holds the number of cursors assigned */
57665   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
57666   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
57667
57668   assert( pTable );
57669
57670 #ifndef SQLITE_OMIT_VIRTUALTABLE
57671   if( sqlite3VtabCallConnect(pParse, pTable) ){
57672     return SQLITE_ERROR;
57673   }
57674   if( IsVirtual(pTable) ) return 0;
57675 #endif
57676
57677 #ifndef SQLITE_OMIT_VIEW
57678   /* A positive nCol means the columns names for this view are
57679   ** already known.
57680   */
57681   if( pTable->nCol>0 ) return 0;
57682
57683   /* A negative nCol is a special marker meaning that we are currently
57684   ** trying to compute the column names.  If we enter this routine with
57685   ** a negative nCol, it means two or more views form a loop, like this:
57686   **
57687   **     CREATE VIEW one AS SELECT * FROM two;
57688   **     CREATE VIEW two AS SELECT * FROM one;
57689   **
57690   ** Actually, this error is caught previously and so the following test
57691   ** should always fail.  But we will leave it in place just to be safe.
57692   */
57693   if( pTable->nCol<0 ){
57694     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
57695     return 1;
57696   }
57697   assert( pTable->nCol>=0 );
57698
57699   /* If we get this far, it means we need to compute the table names.
57700   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
57701   ** "*" elements in the results set of the view and will assign cursors
57702   ** to the elements of the FROM clause.  But we do not want these changes
57703   ** to be permanent.  So the computation is done on a copy of the SELECT
57704   ** statement that defines the view.
57705   */
57706   assert( pTable->pSelect );
57707   pSel = sqlite3SelectDup(db, pTable->pSelect);
57708   if( pSel ){
57709     n = pParse->nTab;
57710     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
57711     pTable->nCol = -1;
57712 #ifndef SQLITE_OMIT_AUTHORIZATION
57713     xAuth = db->xAuth;
57714     db->xAuth = 0;
57715     pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel);
57716     db->xAuth = xAuth;
57717 #else
57718     pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel);
57719 #endif
57720     pParse->nTab = n;
57721     if( pSelTab ){
57722       assert( pTable->aCol==0 );
57723       pTable->nCol = pSelTab->nCol;
57724       pTable->aCol = pSelTab->aCol;
57725       pSelTab->nCol = 0;
57726       pSelTab->aCol = 0;
57727       sqlite3DeleteTable(pSelTab);
57728       pTable->pSchema->flags |= DB_UnresetViews;
57729     }else{
57730       pTable->nCol = 0;
57731       nErr++;
57732     }
57733     sqlite3SelectDelete(db, pSel);
57734   } else {
57735     nErr++;
57736   }
57737 #endif /* SQLITE_OMIT_VIEW */
57738   return nErr;  
57739 }
57740 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
57741
57742 #ifndef SQLITE_OMIT_VIEW
57743 /*
57744 ** Clear the column names from every VIEW in database idx.
57745 */
57746 static void sqliteViewResetAll(sqlite3 *db, int idx){
57747   HashElem *i;
57748   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
57749   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
57750     Table *pTab = sqliteHashData(i);
57751     if( pTab->pSelect ){
57752       sqliteResetColumnNames(pTab);
57753     }
57754   }
57755   DbClearProperty(db, idx, DB_UnresetViews);
57756 }
57757 #else
57758 # define sqliteViewResetAll(A,B)
57759 #endif /* SQLITE_OMIT_VIEW */
57760
57761 /*
57762 ** This function is called by the VDBE to adjust the internal schema
57763 ** used by SQLite when the btree layer moves a table root page. The
57764 ** root-page of a table or index in database iDb has changed from iFrom
57765 ** to iTo.
57766 **
57767 ** Ticket #1728:  The symbol table might still contain information
57768 ** on tables and/or indices that are the process of being deleted.
57769 ** If you are unlucky, one of those deleted indices or tables might
57770 ** have the same rootpage number as the real table or index that is
57771 ** being moved.  So we cannot stop searching after the first match 
57772 ** because the first match might be for one of the deleted indices
57773 ** or tables and not the table/index that is actually being moved.
57774 ** We must continue looping until all tables and indices with
57775 ** rootpage==iFrom have been converted to have a rootpage of iTo
57776 ** in order to be certain that we got the right one.
57777 */
57778 #ifndef SQLITE_OMIT_AUTOVACUUM
57779 SQLITE_PRIVATE void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
57780   HashElem *pElem;
57781   Hash *pHash;
57782
57783   pHash = &pDb->pSchema->tblHash;
57784   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
57785     Table *pTab = sqliteHashData(pElem);
57786     if( pTab->tnum==iFrom ){
57787       pTab->tnum = iTo;
57788     }
57789   }
57790   pHash = &pDb->pSchema->idxHash;
57791   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
57792     Index *pIdx = sqliteHashData(pElem);
57793     if( pIdx->tnum==iFrom ){
57794       pIdx->tnum = iTo;
57795     }
57796   }
57797 }
57798 #endif
57799
57800 /*
57801 ** Write code to erase the table with root-page iTable from database iDb.
57802 ** Also write code to modify the sqlite_master table and internal schema
57803 ** if a root-page of another table is moved by the btree-layer whilst
57804 ** erasing iTable (this can happen with an auto-vacuum database).
57805 */ 
57806 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
57807   Vdbe *v = sqlite3GetVdbe(pParse);
57808   int r1 = sqlite3GetTempReg(pParse);
57809   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
57810 #ifndef SQLITE_OMIT_AUTOVACUUM
57811   /* OP_Destroy stores an in integer r1. If this integer
57812   ** is non-zero, then it is the root page number of a table moved to
57813   ** location iTable. The following code modifies the sqlite_master table to
57814   ** reflect this.
57815   **
57816   ** The "#%d" in the SQL is a special constant that means whatever value
57817   ** is on the top of the stack.  See sqlite3RegisterExpr().
57818   */
57819   sqlite3NestedParse(pParse, 
57820      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
57821      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
57822 #endif
57823   sqlite3ReleaseTempReg(pParse, r1);
57824 }
57825
57826 /*
57827 ** Write VDBE code to erase table pTab and all associated indices on disk.
57828 ** Code to update the sqlite_master tables and internal schema definitions
57829 ** in case a root-page belonging to another table is moved by the btree layer
57830 ** is also added (this can happen with an auto-vacuum database).
57831 */
57832 static void destroyTable(Parse *pParse, Table *pTab){
57833 #ifdef SQLITE_OMIT_AUTOVACUUM
57834   Index *pIdx;
57835   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
57836   destroyRootPage(pParse, pTab->tnum, iDb);
57837   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
57838     destroyRootPage(pParse, pIdx->tnum, iDb);
57839   }
57840 #else
57841   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
57842   ** is not defined), then it is important to call OP_Destroy on the
57843   ** table and index root-pages in order, starting with the numerically 
57844   ** largest root-page number. This guarantees that none of the root-pages
57845   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
57846   ** following were coded:
57847   **
57848   ** OP_Destroy 4 0
57849   ** ...
57850   ** OP_Destroy 5 0
57851   **
57852   ** and root page 5 happened to be the largest root-page number in the
57853   ** database, then root page 5 would be moved to page 4 by the 
57854   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
57855   ** a free-list page.
57856   */
57857   int iTab = pTab->tnum;
57858   int iDestroyed = 0;
57859
57860   while( 1 ){
57861     Index *pIdx;
57862     int iLargest = 0;
57863
57864     if( iDestroyed==0 || iTab<iDestroyed ){
57865       iLargest = iTab;
57866     }
57867     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
57868       int iIdx = pIdx->tnum;
57869       assert( pIdx->pSchema==pTab->pSchema );
57870       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
57871         iLargest = iIdx;
57872       }
57873     }
57874     if( iLargest==0 ){
57875       return;
57876     }else{
57877       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
57878       destroyRootPage(pParse, iLargest, iDb);
57879       iDestroyed = iLargest;
57880     }
57881   }
57882 #endif
57883 }
57884
57885 /*
57886 ** This routine is called to do the work of a DROP TABLE statement.
57887 ** pName is the name of the table to be dropped.
57888 */
57889 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
57890   Table *pTab;
57891   Vdbe *v;
57892   sqlite3 *db = pParse->db;
57893   int iDb;
57894
57895   if( pParse->nErr || db->mallocFailed ){
57896     goto exit_drop_table;
57897   }
57898   assert( pName->nSrc==1 );
57899   pTab = sqlite3LocateTable(pParse, isView, 
57900                             pName->a[0].zName, pName->a[0].zDatabase);
57901
57902   if( pTab==0 ){
57903     if( noErr ){
57904       sqlite3ErrorClear(pParse);
57905     }
57906     goto exit_drop_table;
57907   }
57908   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
57909   assert( iDb>=0 && iDb<db->nDb );
57910
57911   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
57912   ** it is initialized.
57913   */
57914   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
57915     goto exit_drop_table;
57916   }
57917 #ifndef SQLITE_OMIT_AUTHORIZATION
57918   {
57919     int code;
57920     const char *zTab = SCHEMA_TABLE(iDb);
57921     const char *zDb = db->aDb[iDb].zName;
57922     const char *zArg2 = 0;
57923     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
57924       goto exit_drop_table;
57925     }
57926     if( isView ){
57927       if( !OMIT_TEMPDB && iDb==1 ){
57928         code = SQLITE_DROP_TEMP_VIEW;
57929       }else{
57930         code = SQLITE_DROP_VIEW;
57931       }
57932 #ifndef SQLITE_OMIT_VIRTUALTABLE
57933     }else if( IsVirtual(pTab) ){
57934       code = SQLITE_DROP_VTABLE;
57935       zArg2 = pTab->pMod->zName;
57936 #endif
57937     }else{
57938       if( !OMIT_TEMPDB && iDb==1 ){
57939         code = SQLITE_DROP_TEMP_TABLE;
57940       }else{
57941         code = SQLITE_DROP_TABLE;
57942       }
57943     }
57944     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
57945       goto exit_drop_table;
57946     }
57947     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
57948       goto exit_drop_table;
57949     }
57950   }
57951 #endif
57952   if( pTab->readOnly || pTab==db->aDb[iDb].pSchema->pSeqTab ){
57953     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
57954     goto exit_drop_table;
57955   }
57956
57957 #ifndef SQLITE_OMIT_VIEW
57958   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
57959   ** on a table.
57960   */
57961   if( isView && pTab->pSelect==0 ){
57962     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
57963     goto exit_drop_table;
57964   }
57965   if( !isView && pTab->pSelect ){
57966     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
57967     goto exit_drop_table;
57968   }
57969 #endif
57970
57971   /* Generate code to remove the table from the master table
57972   ** on disk.
57973   */
57974   v = sqlite3GetVdbe(pParse);
57975   if( v ){
57976     Trigger *pTrigger;
57977     Db *pDb = &db->aDb[iDb];
57978     sqlite3BeginWriteOperation(pParse, 1, iDb);
57979
57980 #ifndef SQLITE_OMIT_VIRTUALTABLE
57981     if( IsVirtual(pTab) ){
57982       Vdbe *v = sqlite3GetVdbe(pParse);
57983       if( v ){
57984         sqlite3VdbeAddOp0(v, OP_VBegin);
57985       }
57986     }
57987 #endif
57988
57989     /* Drop all triggers associated with the table being dropped. Code
57990     ** is generated to remove entries from sqlite_master and/or
57991     ** sqlite_temp_master if required.
57992     */
57993     pTrigger = pTab->pTrigger;
57994     while( pTrigger ){
57995       assert( pTrigger->pSchema==pTab->pSchema || 
57996           pTrigger->pSchema==db->aDb[1].pSchema );
57997       sqlite3DropTriggerPtr(pParse, pTrigger);
57998       pTrigger = pTrigger->pNext;
57999     }
58000
58001 #ifndef SQLITE_OMIT_AUTOINCREMENT
58002     /* Remove any entries of the sqlite_sequence table associated with
58003     ** the table being dropped. This is done before the table is dropped
58004     ** at the btree level, in case the sqlite_sequence table needs to
58005     ** move as a result of the drop (can happen in auto-vacuum mode).
58006     */
58007     if( pTab->autoInc ){
58008       sqlite3NestedParse(pParse,
58009         "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
58010         pDb->zName, pTab->zName
58011       );
58012     }
58013 #endif
58014
58015     /* Drop all SQLITE_MASTER table and index entries that refer to the
58016     ** table. The program name loops through the master table and deletes
58017     ** every row that refers to a table of the same name as the one being
58018     ** dropped. Triggers are handled seperately because a trigger can be
58019     ** created in the temp database that refers to a table in another
58020     ** database.
58021     */
58022     sqlite3NestedParse(pParse, 
58023         "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
58024         pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
58025
58026     /* Drop any statistics from the sqlite_stat1 table, if it exists */
58027     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
58028       sqlite3NestedParse(pParse,
58029         "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
58030       );
58031     }
58032
58033     if( !isView && !IsVirtual(pTab) ){
58034       destroyTable(pParse, pTab);
58035     }
58036
58037     /* Remove the table entry from SQLite's internal schema and modify
58038     ** the schema cookie.
58039     */
58040     if( IsVirtual(pTab) ){
58041       sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
58042     }
58043     sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
58044     sqlite3ChangeCookie(pParse, iDb);
58045   }
58046   sqliteViewResetAll(db, iDb);
58047
58048 exit_drop_table:
58049   sqlite3SrcListDelete(db, pName);
58050 }
58051
58052 /*
58053 ** This routine is called to create a new foreign key on the table
58054 ** currently under construction.  pFromCol determines which columns
58055 ** in the current table point to the foreign key.  If pFromCol==0 then
58056 ** connect the key to the last column inserted.  pTo is the name of
58057 ** the table referred to.  pToCol is a list of tables in the other
58058 ** pTo table that the foreign key points to.  flags contains all
58059 ** information about the conflict resolution algorithms specified
58060 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
58061 **
58062 ** An FKey structure is created and added to the table currently
58063 ** under construction in the pParse->pNewTable field.  The new FKey
58064 ** is not linked into db->aFKey at this point - that does not happen
58065 ** until sqlite3EndTable().
58066 **
58067 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
58068 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
58069 */
58070 SQLITE_PRIVATE void sqlite3CreateForeignKey(
58071   Parse *pParse,       /* Parsing context */
58072   ExprList *pFromCol,  /* Columns in this table that point to other table */
58073   Token *pTo,          /* Name of the other table */
58074   ExprList *pToCol,    /* Columns in the other table */
58075   int flags            /* Conflict resolution algorithms. */
58076 ){
58077 #ifndef SQLITE_OMIT_FOREIGN_KEY
58078   FKey *pFKey = 0;
58079   Table *p = pParse->pNewTable;
58080   int nByte;
58081   int i;
58082   int nCol;
58083   char *z;
58084   sqlite3 *db;
58085
58086   assert( pTo!=0 );
58087   db = pParse->db;
58088   if( p==0 || pParse->nErr || IN_DECLARE_VTAB ) goto fk_end;
58089   if( pFromCol==0 ){
58090     int iCol = p->nCol-1;
58091     if( iCol<0 ) goto fk_end;
58092     if( pToCol && pToCol->nExpr!=1 ){
58093       sqlite3ErrorMsg(pParse, "foreign key on %s"
58094          " should reference only one column of table %T",
58095          p->aCol[iCol].zName, pTo);
58096       goto fk_end;
58097     }
58098     nCol = 1;
58099   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
58100     sqlite3ErrorMsg(pParse,
58101         "number of columns in foreign key does not match the number of "
58102         "columns in the referenced table");
58103     goto fk_end;
58104   }else{
58105     nCol = pFromCol->nExpr;
58106   }
58107   nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
58108   if( pToCol ){
58109     for(i=0; i<pToCol->nExpr; i++){
58110       nByte += strlen(pToCol->a[i].zName) + 1;
58111     }
58112   }
58113   pFKey = sqlite3DbMallocZero(db, nByte );
58114   if( pFKey==0 ){
58115     goto fk_end;
58116   }
58117   pFKey->pFrom = p;
58118   pFKey->pNextFrom = p->pFKey;
58119   z = (char*)&pFKey[1];
58120   pFKey->aCol = (struct sColMap*)z;
58121   z += sizeof(struct sColMap)*nCol;
58122   pFKey->zTo = z;
58123   memcpy(z, pTo->z, pTo->n);
58124   z[pTo->n] = 0;
58125   z += pTo->n+1;
58126   pFKey->pNextTo = 0;
58127   pFKey->nCol = nCol;
58128   if( pFromCol==0 ){
58129     pFKey->aCol[0].iFrom = p->nCol-1;
58130   }else{
58131     for(i=0; i<nCol; i++){
58132       int j;
58133       for(j=0; j<p->nCol; j++){
58134         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
58135           pFKey->aCol[i].iFrom = j;
58136           break;
58137         }
58138       }
58139       if( j>=p->nCol ){
58140         sqlite3ErrorMsg(pParse, 
58141           "unknown column \"%s\" in foreign key definition", 
58142           pFromCol->a[i].zName);
58143         goto fk_end;
58144       }
58145     }
58146   }
58147   if( pToCol ){
58148     for(i=0; i<nCol; i++){
58149       int n = strlen(pToCol->a[i].zName);
58150       pFKey->aCol[i].zCol = z;
58151       memcpy(z, pToCol->a[i].zName, n);
58152       z[n] = 0;
58153       z += n+1;
58154     }
58155   }
58156   pFKey->isDeferred = 0;
58157   pFKey->deleteConf = flags & 0xff;
58158   pFKey->updateConf = (flags >> 8 ) & 0xff;
58159   pFKey->insertConf = (flags >> 16 ) & 0xff;
58160
58161   /* Link the foreign key to the table as the last step.
58162   */
58163   p->pFKey = pFKey;
58164   pFKey = 0;
58165
58166 fk_end:
58167   sqlite3DbFree(db, pFKey);
58168 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
58169   sqlite3ExprListDelete(db, pFromCol);
58170   sqlite3ExprListDelete(db, pToCol);
58171 }
58172
58173 /*
58174 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
58175 ** clause is seen as part of a foreign key definition.  The isDeferred
58176 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
58177 ** The behavior of the most recently created foreign key is adjusted
58178 ** accordingly.
58179 */
58180 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
58181 #ifndef SQLITE_OMIT_FOREIGN_KEY
58182   Table *pTab;
58183   FKey *pFKey;
58184   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
58185   pFKey->isDeferred = isDeferred;
58186 #endif
58187 }
58188
58189 /*
58190 ** Generate code that will erase and refill index *pIdx.  This is
58191 ** used to initialize a newly created index or to recompute the
58192 ** content of an index in response to a REINDEX command.
58193 **
58194 ** if memRootPage is not negative, it means that the index is newly
58195 ** created.  The register specified by memRootPage contains the
58196 ** root page number of the index.  If memRootPage is negative, then
58197 ** the index already exists and must be cleared before being refilled and
58198 ** the root page number of the index is taken from pIndex->tnum.
58199 */
58200 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
58201   Table *pTab = pIndex->pTable;  /* The table that is indexed */
58202   int iTab = pParse->nTab;       /* Btree cursor used for pTab */
58203   int iIdx = pParse->nTab+1;     /* Btree cursor used for pIndex */
58204   int addr1;                     /* Address of top of loop */
58205   int tnum;                      /* Root page of index */
58206   Vdbe *v;                       /* Generate code into this virtual machine */
58207   KeyInfo *pKey;                 /* KeyInfo for index */
58208   int regIdxKey;                 /* Registers containing the index key */
58209   int regRecord;                 /* Register holding assemblied index record */
58210   sqlite3 *db = pParse->db;      /* The database connection */
58211   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
58212
58213 #ifndef SQLITE_OMIT_AUTHORIZATION
58214   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
58215       db->aDb[iDb].zName ) ){
58216     return;
58217   }
58218 #endif
58219
58220   /* Require a write-lock on the table to perform this operation */
58221   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
58222
58223   v = sqlite3GetVdbe(pParse);
58224   if( v==0 ) return;
58225   if( memRootPage>=0 ){
58226     tnum = memRootPage;
58227   }else{
58228     tnum = pIndex->tnum;
58229     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
58230   }
58231   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
58232   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
58233                     (char *)pKey, P4_KEYINFO_HANDOFF);
58234   if( memRootPage>=0 ){
58235     sqlite3VdbeChangeP5(v, 1);
58236   }
58237   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
58238   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
58239   regRecord = sqlite3GetTempReg(pParse);
58240   regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
58241   if( pIndex->onError!=OE_None ){
58242     int j1, j2;
58243     int regRowid;
58244
58245     regRowid = regIdxKey + pIndex->nColumn;
58246     j1 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdxKey, 0, pIndex->nColumn);
58247     j2 = sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx,
58248                            0, regRowid, SQLITE_INT_TO_PTR(regRecord), P4_INT32);
58249     sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort, 0,
58250                     "indexed columns are not unique", P4_STATIC);
58251     sqlite3VdbeJumpHere(v, j1);
58252     sqlite3VdbeJumpHere(v, j2);
58253   }
58254   sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
58255   sqlite3ReleaseTempReg(pParse, regRecord);
58256   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
58257   sqlite3VdbeJumpHere(v, addr1);
58258   sqlite3VdbeAddOp1(v, OP_Close, iTab);
58259   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
58260 }
58261
58262 /*
58263 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
58264 ** and pTblList is the name of the table that is to be indexed.  Both will 
58265 ** be NULL for a primary key or an index that is created to satisfy a
58266 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
58267 ** as the table to be indexed.  pParse->pNewTable is a table that is
58268 ** currently being constructed by a CREATE TABLE statement.
58269 **
58270 ** pList is a list of columns to be indexed.  pList will be NULL if this
58271 ** is a primary key or unique-constraint on the most recent column added
58272 ** to the table currently under construction.  
58273 */
58274 SQLITE_PRIVATE void sqlite3CreateIndex(
58275   Parse *pParse,     /* All information about this parse */
58276   Token *pName1,     /* First part of index name. May be NULL */
58277   Token *pName2,     /* Second part of index name. May be NULL */
58278   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
58279   ExprList *pList,   /* A list of columns to be indexed */
58280   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
58281   Token *pStart,     /* The CREATE token that begins this statement */
58282   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
58283   int sortOrder,     /* Sort order of primary key when pList==NULL */
58284   int ifNotExist     /* Omit error if index already exists */
58285 ){
58286   Table *pTab = 0;     /* Table to be indexed */
58287   Index *pIndex = 0;   /* The index to be created */
58288   char *zName = 0;     /* Name of the index */
58289   int nName;           /* Number of characters in zName */
58290   int i, j;
58291   Token nullId;        /* Fake token for an empty ID list */
58292   DbFixer sFix;        /* For assigning database names to pTable */
58293   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
58294   sqlite3 *db = pParse->db;
58295   Db *pDb;             /* The specific table containing the indexed database */
58296   int iDb;             /* Index of the database that is being written */
58297   Token *pName = 0;    /* Unqualified name of the index to create */
58298   struct ExprList_item *pListItem; /* For looping over pList */
58299   int nCol;
58300   int nExtra = 0;
58301   char *zExtra;
58302
58303   if( pParse->nErr || db->mallocFailed || IN_DECLARE_VTAB ){
58304     goto exit_create_index;
58305   }
58306
58307   /*
58308   ** Find the table that is to be indexed.  Return early if not found.
58309   */
58310   if( pTblName!=0 ){
58311
58312     /* Use the two-part index name to determine the database 
58313     ** to search for the table. 'Fix' the table name to this db
58314     ** before looking up the table.
58315     */
58316     assert( pName1 && pName2 );
58317     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
58318     if( iDb<0 ) goto exit_create_index;
58319
58320 #ifndef SQLITE_OMIT_TEMPDB
58321     /* If the index name was unqualified, check if the the table
58322     ** is a temp table. If so, set the database to 1. Do not do this
58323     ** if initialising a database schema.
58324     */
58325     if( !db->init.busy ){
58326       pTab = sqlite3SrcListLookup(pParse, pTblName);
58327       if( pName2 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
58328         iDb = 1;
58329       }
58330     }
58331 #endif
58332
58333     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
58334         sqlite3FixSrcList(&sFix, pTblName)
58335     ){
58336       /* Because the parser constructs pTblName from a single identifier,
58337       ** sqlite3FixSrcList can never fail. */
58338       assert(0);
58339     }
58340     pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName, 
58341         pTblName->a[0].zDatabase);
58342     if( !pTab ) goto exit_create_index;
58343     assert( db->aDb[iDb].pSchema==pTab->pSchema );
58344   }else{
58345     assert( pName==0 );
58346     pTab = pParse->pNewTable;
58347     if( !pTab ) goto exit_create_index;
58348     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
58349   }
58350   pDb = &db->aDb[iDb];
58351
58352   if( pTab==0 || pParse->nErr ) goto exit_create_index;
58353   if( pTab->readOnly ){
58354     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
58355     goto exit_create_index;
58356   }
58357 #ifndef SQLITE_OMIT_VIEW
58358   if( pTab->pSelect ){
58359     sqlite3ErrorMsg(pParse, "views may not be indexed");
58360     goto exit_create_index;
58361   }
58362 #endif
58363 #ifndef SQLITE_OMIT_VIRTUALTABLE
58364   if( IsVirtual(pTab) ){
58365     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
58366     goto exit_create_index;
58367   }
58368 #endif
58369
58370   /*
58371   ** Find the name of the index.  Make sure there is not already another
58372   ** index or table with the same name.  
58373   **
58374   ** Exception:  If we are reading the names of permanent indices from the
58375   ** sqlite_master table (because some other process changed the schema) and
58376   ** one of the index names collides with the name of a temporary table or
58377   ** index, then we will continue to process this index.
58378   **
58379   ** If pName==0 it means that we are
58380   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
58381   ** own name.
58382   */
58383   if( pName ){
58384     zName = sqlite3NameFromToken(db, pName);
58385     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
58386     if( zName==0 ) goto exit_create_index;
58387     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
58388       goto exit_create_index;
58389     }
58390     if( !db->init.busy ){
58391       if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
58392       if( sqlite3FindTable(db, zName, 0)!=0 ){
58393         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
58394         goto exit_create_index;
58395       }
58396     }
58397     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
58398       if( !ifNotExist ){
58399         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
58400       }
58401       goto exit_create_index;
58402     }
58403   }else{
58404     int n;
58405     Index *pLoop;
58406     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
58407     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
58408     if( zName==0 ){
58409       goto exit_create_index;
58410     }
58411   }
58412
58413   /* Check for authorization to create an index.
58414   */
58415 #ifndef SQLITE_OMIT_AUTHORIZATION
58416   {
58417     const char *zDb = pDb->zName;
58418     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
58419       goto exit_create_index;
58420     }
58421     i = SQLITE_CREATE_INDEX;
58422     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
58423     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
58424       goto exit_create_index;
58425     }
58426   }
58427 #endif
58428
58429   /* If pList==0, it means this routine was called to make a primary
58430   ** key out of the last column added to the table under construction.
58431   ** So create a fake list to simulate this.
58432   */
58433   if( pList==0 ){
58434     nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName;
58435     nullId.n = strlen((char*)nullId.z);
58436     pList = sqlite3ExprListAppend(pParse, 0, 0, &nullId);
58437     if( pList==0 ) goto exit_create_index;
58438     pList->a[0].sortOrder = sortOrder;
58439   }
58440
58441   /* Figure out how many bytes of space are required to store explicitly
58442   ** specified collation sequence names.
58443   */
58444   for(i=0; i<pList->nExpr; i++){
58445     Expr *pExpr = pList->a[i].pExpr;
58446     if( pExpr ){
58447       nExtra += (1 + strlen(pExpr->pColl->zName));
58448     }
58449   }
58450
58451   /* 
58452   ** Allocate the index structure. 
58453   */
58454   nName = strlen(zName);
58455   nCol = pList->nExpr;
58456   pIndex = sqlite3DbMallocZero(db, 
58457       sizeof(Index) +              /* Index structure  */
58458       sizeof(int)*nCol +           /* Index.aiColumn   */
58459       sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
58460       sizeof(char *)*nCol +        /* Index.azColl     */
58461       sizeof(u8)*nCol +            /* Index.aSortOrder */
58462       nName + 1 +                  /* Index.zName      */
58463       nExtra                       /* Collation sequence names */
58464   );
58465   if( db->mallocFailed ){
58466     goto exit_create_index;
58467   }
58468   pIndex->azColl = (char**)(&pIndex[1]);
58469   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
58470   pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
58471   pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
58472   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
58473   zExtra = (char *)(&pIndex->zName[nName+1]);
58474   memcpy(pIndex->zName, zName, nName+1);
58475   pIndex->pTable = pTab;
58476   pIndex->nColumn = pList->nExpr;
58477   pIndex->onError = onError;
58478   pIndex->autoIndex = pName==0;
58479   pIndex->pSchema = db->aDb[iDb].pSchema;
58480
58481   /* Check to see if we should honor DESC requests on index columns
58482   */
58483   if( pDb->pSchema->file_format>=4 ){
58484     sortOrderMask = -1;   /* Honor DESC */
58485   }else{
58486     sortOrderMask = 0;    /* Ignore DESC */
58487   }
58488
58489   /* Scan the names of the columns of the table to be indexed and
58490   ** load the column indices into the Index structure.  Report an error
58491   ** if any column is not found.
58492   */
58493   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
58494     const char *zColName = pListItem->zName;
58495     Column *pTabCol;
58496     int requestedSortOrder;
58497     char *zColl;                   /* Collation sequence name */
58498
58499     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
58500       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
58501     }
58502     if( j>=pTab->nCol ){
58503       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
58504         pTab->zName, zColName);
58505       goto exit_create_index;
58506     }
58507     /* TODO:  Add a test to make sure that the same column is not named
58508     ** more than once within the same index.  Only the first instance of
58509     ** the column will ever be used by the optimizer.  Note that using the
58510     ** same column more than once cannot be an error because that would 
58511     ** break backwards compatibility - it needs to be a warning.
58512     */
58513     pIndex->aiColumn[i] = j;
58514     if( pListItem->pExpr ){
58515       assert( pListItem->pExpr->pColl );
58516       zColl = zExtra;
58517       sqlite3_snprintf(nExtra, zExtra, "%s", pListItem->pExpr->pColl->zName);
58518       zExtra += (strlen(zColl) + 1);
58519     }else{
58520       zColl = pTab->aCol[j].zColl;
58521       if( !zColl ){
58522         zColl = db->pDfltColl->zName;
58523       }
58524     }
58525     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl, -1) ){
58526       goto exit_create_index;
58527     }
58528     pIndex->azColl[i] = zColl;
58529     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
58530     pIndex->aSortOrder[i] = requestedSortOrder;
58531   }
58532   sqlite3DefaultRowEst(pIndex);
58533
58534   if( pTab==pParse->pNewTable ){
58535     /* This routine has been called to create an automatic index as a
58536     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
58537     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
58538     ** i.e. one of:
58539     **
58540     ** CREATE TABLE t(x PRIMARY KEY, y);
58541     ** CREATE TABLE t(x, y, UNIQUE(x, y));
58542     **
58543     ** Either way, check to see if the table already has such an index. If
58544     ** so, don't bother creating this one. This only applies to
58545     ** automatically created indices. Users can do as they wish with
58546     ** explicit indices.
58547     */
58548     Index *pIdx;
58549     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
58550       int k;
58551       assert( pIdx->onError!=OE_None );
58552       assert( pIdx->autoIndex );
58553       assert( pIndex->onError!=OE_None );
58554
58555       if( pIdx->nColumn!=pIndex->nColumn ) continue;
58556       for(k=0; k<pIdx->nColumn; k++){
58557         const char *z1 = pIdx->azColl[k];
58558         const char *z2 = pIndex->azColl[k];
58559         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
58560         if( pIdx->aSortOrder[k]!=pIndex->aSortOrder[k] ) break;
58561         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
58562       }
58563       if( k==pIdx->nColumn ){
58564         if( pIdx->onError!=pIndex->onError ){
58565           /* This constraint creates the same index as a previous
58566           ** constraint specified somewhere in the CREATE TABLE statement.
58567           ** However the ON CONFLICT clauses are different. If both this 
58568           ** constraint and the previous equivalent constraint have explicit
58569           ** ON CONFLICT clauses this is an error. Otherwise, use the
58570           ** explicitly specified behaviour for the index.
58571           */
58572           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
58573             sqlite3ErrorMsg(pParse, 
58574                 "conflicting ON CONFLICT clauses specified", 0);
58575           }
58576           if( pIdx->onError==OE_Default ){
58577             pIdx->onError = pIndex->onError;
58578           }
58579         }
58580         goto exit_create_index;
58581       }
58582     }
58583   }
58584
58585   /* Link the new Index structure to its table and to the other
58586   ** in-memory database structures. 
58587   */
58588   if( db->init.busy ){
58589     Index *p;
58590     p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
58591                          pIndex->zName, strlen(pIndex->zName)+1, pIndex);
58592     if( p ){
58593       assert( p==pIndex );  /* Malloc must have failed */
58594       db->mallocFailed = 1;
58595       goto exit_create_index;
58596     }
58597     db->flags |= SQLITE_InternChanges;
58598     if( pTblName!=0 ){
58599       pIndex->tnum = db->init.newTnum;
58600     }
58601   }
58602
58603   /* If the db->init.busy is 0 then create the index on disk.  This
58604   ** involves writing the index into the master table and filling in the
58605   ** index with the current table contents.
58606   **
58607   ** The db->init.busy is 0 when the user first enters a CREATE INDEX 
58608   ** command.  db->init.busy is 1 when a database is opened and 
58609   ** CREATE INDEX statements are read out of the master table.  In
58610   ** the latter case the index already exists on disk, which is why
58611   ** we don't want to recreate it.
58612   **
58613   ** If pTblName==0 it means this index is generated as a primary key
58614   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
58615   ** has just been created, it contains no data and the index initialization
58616   ** step can be skipped.
58617   */
58618   else if( db->init.busy==0 ){
58619     Vdbe *v;
58620     char *zStmt;
58621     int iMem = ++pParse->nMem;
58622
58623     v = sqlite3GetVdbe(pParse);
58624     if( v==0 ) goto exit_create_index;
58625
58626
58627     /* Create the rootpage for the index
58628     */
58629     sqlite3BeginWriteOperation(pParse, 1, iDb);
58630     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
58631
58632     /* Gather the complete text of the CREATE INDEX statement into
58633     ** the zStmt variable
58634     */
58635     if( pStart && pEnd ){
58636       /* A named index with an explicit CREATE INDEX statement */
58637       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
58638         onError==OE_None ? "" : " UNIQUE",
58639         pEnd->z - pName->z + 1,
58640         pName->z);
58641     }else{
58642       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
58643       /* zStmt = sqlite3MPrintf(""); */
58644       zStmt = 0;
58645     }
58646
58647     /* Add an entry in sqlite_master for this index
58648     */
58649     sqlite3NestedParse(pParse, 
58650         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
58651         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
58652         pIndex->zName,
58653         pTab->zName,
58654         iMem,
58655         zStmt
58656     );
58657     sqlite3DbFree(db, zStmt);
58658
58659     /* Fill the index with data and reparse the schema. Code an OP_Expire
58660     ** to invalidate all pre-compiled statements.
58661     */
58662     if( pTblName ){
58663       sqlite3RefillIndex(pParse, pIndex, iMem);
58664       sqlite3ChangeCookie(pParse, iDb);
58665       sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
58666          sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
58667       sqlite3VdbeAddOp1(v, OP_Expire, 0);
58668     }
58669   }
58670
58671   /* When adding an index to the list of indices for a table, make
58672   ** sure all indices labeled OE_Replace come after all those labeled
58673   ** OE_Ignore.  This is necessary for the correct operation of UPDATE
58674   ** and INSERT.
58675   */
58676   if( db->init.busy || pTblName==0 ){
58677     if( onError!=OE_Replace || pTab->pIndex==0
58678          || pTab->pIndex->onError==OE_Replace){
58679       pIndex->pNext = pTab->pIndex;
58680       pTab->pIndex = pIndex;
58681     }else{
58682       Index *pOther = pTab->pIndex;
58683       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
58684         pOther = pOther->pNext;
58685       }
58686       pIndex->pNext = pOther->pNext;
58687       pOther->pNext = pIndex;
58688     }
58689     pIndex = 0;
58690   }
58691
58692   /* Clean up before exiting */
58693 exit_create_index:
58694   if( pIndex ){
58695     freeIndex(pIndex);
58696   }
58697   sqlite3ExprListDelete(db, pList);
58698   sqlite3SrcListDelete(db, pTblName);
58699   sqlite3DbFree(db, zName);
58700   return;
58701 }
58702
58703 /*
58704 ** Generate code to make sure the file format number is at least minFormat.
58705 ** The generated code will increase the file format number if necessary.
58706 */
58707 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
58708   Vdbe *v;
58709   v = sqlite3GetVdbe(pParse);
58710   if( v ){
58711     int r1 = sqlite3GetTempReg(pParse);
58712     int r2 = sqlite3GetTempReg(pParse);
58713     int j1;
58714     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, 1);
58715     sqlite3VdbeUsesBtree(v, iDb);
58716     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
58717     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
58718     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, r2);
58719     sqlite3VdbeJumpHere(v, j1);
58720     sqlite3ReleaseTempReg(pParse, r1);
58721     sqlite3ReleaseTempReg(pParse, r2);
58722   }
58723 }
58724
58725 /*
58726 ** Fill the Index.aiRowEst[] array with default information - information
58727 ** to be used when we have not run the ANALYZE command.
58728 **
58729 ** aiRowEst[0] is suppose to contain the number of elements in the index.
58730 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
58731 ** number of rows in the table that match any particular value of the
58732 ** first column of the index.  aiRowEst[2] is an estimate of the number
58733 ** of rows that match any particular combiniation of the first 2 columns
58734 ** of the index.  And so forth.  It must always be the case that
58735 *
58736 **           aiRowEst[N]<=aiRowEst[N-1]
58737 **           aiRowEst[N]>=1
58738 **
58739 ** Apart from that, we have little to go on besides intuition as to
58740 ** how aiRowEst[] should be initialized.  The numbers generated here
58741 ** are based on typical values found in actual indices.
58742 */
58743 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
58744   unsigned *a = pIdx->aiRowEst;
58745   int i;
58746   assert( a!=0 );
58747   a[0] = 1000000;
58748   for(i=pIdx->nColumn; i>=5; i--){
58749     a[i] = 5;
58750   }
58751   while( i>=1 ){
58752     a[i] = 11 - i;
58753     i--;
58754   }
58755   if( pIdx->onError!=OE_None ){
58756     a[pIdx->nColumn] = 1;
58757   }
58758 }
58759
58760 /*
58761 ** This routine will drop an existing named index.  This routine
58762 ** implements the DROP INDEX statement.
58763 */
58764 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
58765   Index *pIndex;
58766   Vdbe *v;
58767   sqlite3 *db = pParse->db;
58768   int iDb;
58769
58770   if( pParse->nErr || db->mallocFailed ){
58771     goto exit_drop_index;
58772   }
58773   assert( pName->nSrc==1 );
58774   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
58775     goto exit_drop_index;
58776   }
58777   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
58778   if( pIndex==0 ){
58779     if( !ifExists ){
58780       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
58781     }
58782     pParse->checkSchema = 1;
58783     goto exit_drop_index;
58784   }
58785   if( pIndex->autoIndex ){
58786     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
58787       "or PRIMARY KEY constraint cannot be dropped", 0);
58788     goto exit_drop_index;
58789   }
58790   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
58791 #ifndef SQLITE_OMIT_AUTHORIZATION
58792   {
58793     int code = SQLITE_DROP_INDEX;
58794     Table *pTab = pIndex->pTable;
58795     const char *zDb = db->aDb[iDb].zName;
58796     const char *zTab = SCHEMA_TABLE(iDb);
58797     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
58798       goto exit_drop_index;
58799     }
58800     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
58801     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
58802       goto exit_drop_index;
58803     }
58804   }
58805 #endif
58806
58807   /* Generate code to remove the index and from the master table */
58808   v = sqlite3GetVdbe(pParse);
58809   if( v ){
58810     sqlite3BeginWriteOperation(pParse, 1, iDb);
58811     sqlite3NestedParse(pParse,
58812        "DELETE FROM %Q.%s WHERE name=%Q",
58813        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
58814        pIndex->zName
58815     );
58816     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
58817       sqlite3NestedParse(pParse,
58818         "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
58819         db->aDb[iDb].zName, pIndex->zName
58820       );
58821     }
58822     sqlite3ChangeCookie(pParse, iDb);
58823     destroyRootPage(pParse, pIndex->tnum, iDb);
58824     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
58825   }
58826
58827 exit_drop_index:
58828   sqlite3SrcListDelete(db, pName);
58829 }
58830
58831 /*
58832 ** pArray is a pointer to an array of objects.  Each object in the
58833 ** array is szEntry bytes in size.  This routine allocates a new
58834 ** object on the end of the array.
58835 **
58836 ** *pnEntry is the number of entries already in use.  *pnAlloc is
58837 ** the previously allocated size of the array.  initSize is the
58838 ** suggested initial array size allocation.
58839 **
58840 ** The index of the new entry is returned in *pIdx.
58841 **
58842 ** This routine returns a pointer to the array of objects.  This
58843 ** might be the same as the pArray parameter or it might be a different
58844 ** pointer if the array was resized.
58845 */
58846 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
58847   sqlite3 *db,      /* Connection to notify of malloc failures */
58848   void *pArray,     /* Array of objects.  Might be reallocated */
58849   int szEntry,      /* Size of each object in the array */
58850   int initSize,     /* Suggested initial allocation, in elements */
58851   int *pnEntry,     /* Number of objects currently in use */
58852   int *pnAlloc,     /* Current size of the allocation, in elements */
58853   int *pIdx         /* Write the index of a new slot here */
58854 ){
58855   char *z;
58856   if( *pnEntry >= *pnAlloc ){
58857     void *pNew;
58858     int newSize;
58859     newSize = (*pnAlloc)*2 + initSize;
58860     pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
58861     if( pNew==0 ){
58862       *pIdx = -1;
58863       return pArray;
58864     }
58865     *pnAlloc = newSize;
58866     pArray = pNew;
58867   }
58868   z = (char*)pArray;
58869   memset(&z[*pnEntry * szEntry], 0, szEntry);
58870   *pIdx = *pnEntry;
58871   ++*pnEntry;
58872   return pArray;
58873 }
58874
58875 /*
58876 ** Append a new element to the given IdList.  Create a new IdList if
58877 ** need be.
58878 **
58879 ** A new IdList is returned, or NULL if malloc() fails.
58880 */
58881 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
58882   int i;
58883   if( pList==0 ){
58884     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
58885     if( pList==0 ) return 0;
58886     pList->nAlloc = 0;
58887   }
58888   pList->a = sqlite3ArrayAllocate(
58889       db,
58890       pList->a,
58891       sizeof(pList->a[0]),
58892       5,
58893       &pList->nId,
58894       &pList->nAlloc,
58895       &i
58896   );
58897   if( i<0 ){
58898     sqlite3IdListDelete(db, pList);
58899     return 0;
58900   }
58901   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
58902   return pList;
58903 }
58904
58905 /*
58906 ** Delete an IdList.
58907 */
58908 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
58909   int i;
58910   if( pList==0 ) return;
58911   for(i=0; i<pList->nId; i++){
58912     sqlite3DbFree(db, pList->a[i].zName);
58913   }
58914   sqlite3DbFree(db, pList->a);
58915   sqlite3DbFree(db, pList);
58916 }
58917
58918 /*
58919 ** Return the index in pList of the identifier named zId.  Return -1
58920 ** if not found.
58921 */
58922 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
58923   int i;
58924   if( pList==0 ) return -1;
58925   for(i=0; i<pList->nId; i++){
58926     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
58927   }
58928   return -1;
58929 }
58930
58931 /*
58932 ** Append a new table name to the given SrcList.  Create a new SrcList if
58933 ** need be.  A new entry is created in the SrcList even if pToken is NULL.
58934 **
58935 ** A new SrcList is returned, or NULL if malloc() fails.
58936 **
58937 ** If pDatabase is not null, it means that the table has an optional
58938 ** database name prefix.  Like this:  "database.table".  The pDatabase
58939 ** points to the table name and the pTable points to the database name.
58940 ** The SrcList.a[].zName field is filled with the table name which might
58941 ** come from pTable (if pDatabase is NULL) or from pDatabase.  
58942 ** SrcList.a[].zDatabase is filled with the database name from pTable,
58943 ** or with NULL if no database is specified.
58944 **
58945 ** In other words, if call like this:
58946 **
58947 **         sqlite3SrcListAppend(D,A,B,0);
58948 **
58949 ** Then B is a table name and the database name is unspecified.  If called
58950 ** like this:
58951 **
58952 **         sqlite3SrcListAppend(D,A,B,C);
58953 **
58954 ** Then C is the table name and B is the database name.
58955 */
58956 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
58957   sqlite3 *db,        /* Connection to notify of malloc failures */
58958   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
58959   Token *pTable,      /* Table to append */
58960   Token *pDatabase    /* Database of the table */
58961 ){
58962   struct SrcList_item *pItem;
58963   if( pList==0 ){
58964     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
58965     if( pList==0 ) return 0;
58966     pList->nAlloc = 1;
58967   }
58968   if( pList->nSrc>=pList->nAlloc ){
58969     SrcList *pNew;
58970     pList->nAlloc *= 2;
58971     pNew = sqlite3DbRealloc(db, pList,
58972                sizeof(*pList) + (pList->nAlloc-1)*sizeof(pList->a[0]) );
58973     if( pNew==0 ){
58974       sqlite3SrcListDelete(db, pList);
58975       return 0;
58976     }
58977     pList = pNew;
58978   }
58979   pItem = &pList->a[pList->nSrc];
58980   memset(pItem, 0, sizeof(pList->a[0]));
58981   if( pDatabase && pDatabase->z==0 ){
58982     pDatabase = 0;
58983   }
58984   if( pDatabase && pTable ){
58985     Token *pTemp = pDatabase;
58986     pDatabase = pTable;
58987     pTable = pTemp;
58988   }
58989   pItem->zName = sqlite3NameFromToken(db, pTable);
58990   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
58991   pItem->iCursor = -1;
58992   pItem->isPopulated = 0;
58993   pList->nSrc++;
58994   return pList;
58995 }
58996
58997 /*
58998 ** Assign cursors to all tables in a SrcList
58999 */
59000 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
59001   int i;
59002   struct SrcList_item *pItem;
59003   assert(pList || pParse->db->mallocFailed );
59004   if( pList ){
59005     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
59006       if( pItem->iCursor>=0 ) break;
59007       pItem->iCursor = pParse->nTab++;
59008       if( pItem->pSelect ){
59009         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
59010       }
59011     }
59012   }
59013 }
59014
59015 /*
59016 ** Delete an entire SrcList including all its substructure.
59017 */
59018 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
59019   int i;
59020   struct SrcList_item *pItem;
59021   if( pList==0 ) return;
59022   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
59023     sqlite3DbFree(db, pItem->zDatabase);
59024     sqlite3DbFree(db, pItem->zName);
59025     sqlite3DbFree(db, pItem->zAlias);
59026     sqlite3DeleteTable(pItem->pTab);
59027     sqlite3SelectDelete(db, pItem->pSelect);
59028     sqlite3ExprDelete(db, pItem->pOn);
59029     sqlite3IdListDelete(db, pItem->pUsing);
59030   }
59031   sqlite3DbFree(db, pList);
59032 }
59033
59034 /*
59035 ** This routine is called by the parser to add a new term to the
59036 ** end of a growing FROM clause.  The "p" parameter is the part of
59037 ** the FROM clause that has already been constructed.  "p" is NULL
59038 ** if this is the first term of the FROM clause.  pTable and pDatabase
59039 ** are the name of the table and database named in the FROM clause term.
59040 ** pDatabase is NULL if the database name qualifier is missing - the
59041 ** usual case.  If the term has a alias, then pAlias points to the
59042 ** alias token.  If the term is a subquery, then pSubquery is the
59043 ** SELECT statement that the subquery encodes.  The pTable and
59044 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
59045 ** parameters are the content of the ON and USING clauses.
59046 **
59047 ** Return a new SrcList which encodes is the FROM with the new
59048 ** term added.
59049 */
59050 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
59051   Parse *pParse,          /* Parsing context */
59052   SrcList *p,             /* The left part of the FROM clause already seen */
59053   Token *pTable,          /* Name of the table to add to the FROM clause */
59054   Token *pDatabase,       /* Name of the database containing pTable */
59055   Token *pAlias,          /* The right-hand side of the AS subexpression */
59056   Select *pSubquery,      /* A subquery used in place of a table name */
59057   Expr *pOn,              /* The ON clause of a join */
59058   IdList *pUsing          /* The USING clause of a join */
59059 ){
59060   struct SrcList_item *pItem;
59061   sqlite3 *db = pParse->db;
59062   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
59063   if( p==0 || p->nSrc==0 ){
59064     sqlite3ExprDelete(db, pOn);
59065     sqlite3IdListDelete(db, pUsing);
59066     sqlite3SelectDelete(db, pSubquery);
59067     return p;
59068   }
59069   pItem = &p->a[p->nSrc-1];
59070   if( pAlias && pAlias->n ){
59071     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
59072   }
59073   pItem->pSelect = pSubquery;
59074   pItem->pOn = pOn;
59075   pItem->pUsing = pUsing;
59076   return p;
59077 }
59078
59079 /*
59080 ** When building up a FROM clause in the parser, the join operator
59081 ** is initially attached to the left operand.  But the code generator
59082 ** expects the join operator to be on the right operand.  This routine
59083 ** Shifts all join operators from left to right for an entire FROM
59084 ** clause.
59085 **
59086 ** Example: Suppose the join is like this:
59087 **
59088 **           A natural cross join B
59089 **
59090 ** The operator is "natural cross join".  The A and B operands are stored
59091 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
59092 ** operator with A.  This routine shifts that operator over to B.
59093 */
59094 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
59095   if( p && p->a ){
59096     int i;
59097     for(i=p->nSrc-1; i>0; i--){
59098       p->a[i].jointype = p->a[i-1].jointype;
59099     }
59100     p->a[0].jointype = 0;
59101   }
59102 }
59103
59104 /*
59105 ** Begin a transaction
59106 */
59107 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
59108   sqlite3 *db;
59109   Vdbe *v;
59110   int i;
59111
59112   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
59113   if( pParse->nErr || db->mallocFailed ) return;
59114   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
59115
59116   v = sqlite3GetVdbe(pParse);
59117   if( !v ) return;
59118   if( type!=TK_DEFERRED ){
59119     for(i=0; i<db->nDb; i++){
59120       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
59121       sqlite3VdbeUsesBtree(v, i);
59122     }
59123   }
59124   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
59125 }
59126
59127 /*
59128 ** Commit a transaction
59129 */
59130 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
59131   sqlite3 *db;
59132   Vdbe *v;
59133
59134   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
59135   if( pParse->nErr || db->mallocFailed ) return;
59136   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
59137
59138   v = sqlite3GetVdbe(pParse);
59139   if( v ){
59140     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
59141   }
59142 }
59143
59144 /*
59145 ** Rollback a transaction
59146 */
59147 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
59148   sqlite3 *db;
59149   Vdbe *v;
59150
59151   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
59152   if( pParse->nErr || db->mallocFailed ) return;
59153   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
59154
59155   v = sqlite3GetVdbe(pParse);
59156   if( v ){
59157     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
59158   }
59159 }
59160
59161 /*
59162 ** Make sure the TEMP database is open and available for use.  Return
59163 ** the number of errors.  Leave any error messages in the pParse structure.
59164 */
59165 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
59166   sqlite3 *db = pParse->db;
59167   if( db->aDb[1].pBt==0 && !pParse->explain ){
59168     int rc;
59169     static const int flags = 
59170           SQLITE_OPEN_READWRITE |
59171           SQLITE_OPEN_CREATE |
59172           SQLITE_OPEN_EXCLUSIVE |
59173           SQLITE_OPEN_DELETEONCLOSE |
59174           SQLITE_OPEN_TEMP_DB;
59175
59176     rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags,
59177                                  &db->aDb[1].pBt);
59178     if( rc!=SQLITE_OK ){
59179       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
59180         "file for storing temporary tables");
59181       pParse->rc = rc;
59182       return 1;
59183     }
59184     assert( (db->flags & SQLITE_InTrans)==0 || db->autoCommit );
59185     assert( db->aDb[1].pSchema );
59186     sqlite3PagerJournalMode(sqlite3BtreePager(db->aDb[1].pBt),
59187                             db->dfltJournalMode);
59188   }
59189   return 0;
59190 }
59191
59192 /*
59193 ** Generate VDBE code that will verify the schema cookie and start
59194 ** a read-transaction for all named database files.
59195 **
59196 ** It is important that all schema cookies be verified and all
59197 ** read transactions be started before anything else happens in
59198 ** the VDBE program.  But this routine can be called after much other
59199 ** code has been generated.  So here is what we do:
59200 **
59201 ** The first time this routine is called, we code an OP_Goto that
59202 ** will jump to a subroutine at the end of the program.  Then we
59203 ** record every database that needs its schema verified in the
59204 ** pParse->cookieMask field.  Later, after all other code has been
59205 ** generated, the subroutine that does the cookie verifications and
59206 ** starts the transactions will be coded and the OP_Goto P2 value
59207 ** will be made to point to that subroutine.  The generation of the
59208 ** cookie verification subroutine code happens in sqlite3FinishCoding().
59209 **
59210 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
59211 ** schema on any databases.  This can be used to position the OP_Goto
59212 ** early in the code, before we know if any database tables will be used.
59213 */
59214 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
59215   sqlite3 *db;
59216   Vdbe *v;
59217   int mask;
59218
59219   v = sqlite3GetVdbe(pParse);
59220   if( v==0 ) return;  /* This only happens if there was a prior error */
59221   db = pParse->db;
59222   if( pParse->cookieGoto==0 ){
59223     pParse->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
59224   }
59225   if( iDb>=0 ){
59226     assert( iDb<db->nDb );
59227     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
59228     assert( iDb<SQLITE_MAX_ATTACHED+2 );
59229     mask = 1<<iDb;
59230     if( (pParse->cookieMask & mask)==0 ){
59231       pParse->cookieMask |= mask;
59232       pParse->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
59233       if( !OMIT_TEMPDB && iDb==1 ){
59234         sqlite3OpenTempDatabase(pParse);
59235       }
59236     }
59237   }
59238 }
59239
59240 /*
59241 ** Generate VDBE code that prepares for doing an operation that
59242 ** might change the database.
59243 **
59244 ** This routine starts a new transaction if we are not already within
59245 ** a transaction.  If we are already within a transaction, then a checkpoint
59246 ** is set if the setStatement parameter is true.  A checkpoint should
59247 ** be set for operations that might fail (due to a constraint) part of
59248 ** the way through and which will need to undo some writes without having to
59249 ** rollback the whole transaction.  For operations where all constraints
59250 ** can be checked before any changes are made to the database, it is never
59251 ** necessary to undo a write and the checkpoint should not be set.
59252 **
59253 ** Only database iDb and the temp database are made writable by this call.
59254 ** If iDb==0, then the main and temp databases are made writable.   If
59255 ** iDb==1 then only the temp database is made writable.  If iDb>1 then the
59256 ** specified auxiliary database and the temp database are made writable.
59257 */
59258 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
59259   Vdbe *v = sqlite3GetVdbe(pParse);
59260   if( v==0 ) return;
59261   sqlite3CodeVerifySchema(pParse, iDb);
59262   pParse->writeMask |= 1<<iDb;
59263   if( setStatement && pParse->nested==0 ){
59264     sqlite3VdbeAddOp1(v, OP_Statement, iDb);
59265   }
59266   if( (OMIT_TEMPDB || iDb!=1) && pParse->db->aDb[1].pBt!=0 ){
59267     sqlite3BeginWriteOperation(pParse, setStatement, 1);
59268   }
59269 }
59270
59271 /*
59272 ** Check to see if pIndex uses the collating sequence pColl.  Return
59273 ** true if it does and false if it does not.
59274 */
59275 #ifndef SQLITE_OMIT_REINDEX
59276 static int collationMatch(const char *zColl, Index *pIndex){
59277   int i;
59278   for(i=0; i<pIndex->nColumn; i++){
59279     const char *z = pIndex->azColl[i];
59280     if( z==zColl || (z && zColl && 0==sqlite3StrICmp(z, zColl)) ){
59281       return 1;
59282     }
59283   }
59284   return 0;
59285 }
59286 #endif
59287
59288 /*
59289 ** Recompute all indices of pTab that use the collating sequence pColl.
59290 ** If pColl==0 then recompute all indices of pTab.
59291 */
59292 #ifndef SQLITE_OMIT_REINDEX
59293 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
59294   Index *pIndex;              /* An index associated with pTab */
59295
59296   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
59297     if( zColl==0 || collationMatch(zColl, pIndex) ){
59298       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
59299       sqlite3BeginWriteOperation(pParse, 0, iDb);
59300       sqlite3RefillIndex(pParse, pIndex, -1);
59301     }
59302   }
59303 }
59304 #endif
59305
59306 /*
59307 ** Recompute all indices of all tables in all databases where the
59308 ** indices use the collating sequence pColl.  If pColl==0 then recompute
59309 ** all indices everywhere.
59310 */
59311 #ifndef SQLITE_OMIT_REINDEX
59312 static void reindexDatabases(Parse *pParse, char const *zColl){
59313   Db *pDb;                    /* A single database */
59314   int iDb;                    /* The database index number */
59315   sqlite3 *db = pParse->db;   /* The database connection */
59316   HashElem *k;                /* For looping over tables in pDb */
59317   Table *pTab;                /* A table in the database */
59318
59319   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
59320     assert( pDb!=0 );
59321     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
59322       pTab = (Table*)sqliteHashData(k);
59323       reindexTable(pParse, pTab, zColl);
59324     }
59325   }
59326 }
59327 #endif
59328
59329 /*
59330 ** Generate code for the REINDEX command.
59331 **
59332 **        REINDEX                            -- 1
59333 **        REINDEX  <collation>               -- 2
59334 **        REINDEX  ?<database>.?<tablename>  -- 3
59335 **        REINDEX  ?<database>.?<indexname>  -- 4
59336 **
59337 ** Form 1 causes all indices in all attached databases to be rebuilt.
59338 ** Form 2 rebuilds all indices in all databases that use the named
59339 ** collating function.  Forms 3 and 4 rebuild the named index or all
59340 ** indices associated with the named table.
59341 */
59342 #ifndef SQLITE_OMIT_REINDEX
59343 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
59344   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
59345   char *z;                    /* Name of a table or index */
59346   const char *zDb;            /* Name of the database */
59347   Table *pTab;                /* A table in the database */
59348   Index *pIndex;              /* An index associated with pTab */
59349   int iDb;                    /* The database index number */
59350   sqlite3 *db = pParse->db;   /* The database connection */
59351   Token *pObjName;            /* Name of the table or index to be reindexed */
59352
59353   /* Read the database schema. If an error occurs, leave an error message
59354   ** and code in pParse and return NULL. */
59355   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
59356     return;
59357   }
59358
59359   if( pName1==0 || pName1->z==0 ){
59360     reindexDatabases(pParse, 0);
59361     return;
59362   }else if( pName2==0 || pName2->z==0 ){
59363     char *zColl;
59364     assert( pName1->z );
59365     zColl = sqlite3NameFromToken(pParse->db, pName1);
59366     if( !zColl ) return;
59367     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, -1, 0);
59368     if( pColl ){
59369       if( zColl ){
59370         reindexDatabases(pParse, zColl);
59371         sqlite3DbFree(db, zColl);
59372       }
59373       return;
59374     }
59375     sqlite3DbFree(db, zColl);
59376   }
59377   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
59378   if( iDb<0 ) return;
59379   z = sqlite3NameFromToken(db, pObjName);
59380   if( z==0 ) return;
59381   zDb = db->aDb[iDb].zName;
59382   pTab = sqlite3FindTable(db, z, zDb);
59383   if( pTab ){
59384     reindexTable(pParse, pTab, 0);
59385     sqlite3DbFree(db, z);
59386     return;
59387   }
59388   pIndex = sqlite3FindIndex(db, z, zDb);
59389   sqlite3DbFree(db, z);
59390   if( pIndex ){
59391     sqlite3BeginWriteOperation(pParse, 0, iDb);
59392     sqlite3RefillIndex(pParse, pIndex, -1);
59393     return;
59394   }
59395   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
59396 }
59397 #endif
59398
59399 /*
59400 ** Return a dynamicly allocated KeyInfo structure that can be used
59401 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
59402 **
59403 ** If successful, a pointer to the new structure is returned. In this case
59404 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned 
59405 ** pointer. If an error occurs (out of memory or missing collation 
59406 ** sequence), NULL is returned and the state of pParse updated to reflect
59407 ** the error.
59408 */
59409 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
59410   int i;
59411   int nCol = pIdx->nColumn;
59412   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
59413   sqlite3 *db = pParse->db;
59414   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
59415
59416   if( pKey ){
59417     pKey->db = pParse->db;
59418     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
59419     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
59420     for(i=0; i<nCol; i++){
59421       char *zColl = pIdx->azColl[i];
59422       assert( zColl );
59423       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl, -1);
59424       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
59425     }
59426     pKey->nField = nCol;
59427   }
59428
59429   if( pParse->nErr ){
59430     sqlite3DbFree(db, pKey);
59431     pKey = 0;
59432   }
59433   return pKey;
59434 }
59435
59436 /************** End of build.c ***********************************************/
59437 /************** Begin file callback.c ****************************************/
59438 /*
59439 ** 2005 May 23 
59440 **
59441 ** The author disclaims copyright to this source code.  In place of
59442 ** a legal notice, here is a blessing:
59443 **
59444 **    May you do good and not evil.
59445 **    May you find forgiveness for yourself and forgive others.
59446 **    May you share freely, never taking more than you give.
59447 **
59448 *************************************************************************
59449 **
59450 ** This file contains functions used to access the internal hash tables
59451 ** of user defined functions and collation sequences.
59452 **
59453 ** $Id: callback.c,v 1.26 2008/07/28 19:34:53 drh Exp $
59454 */
59455
59456
59457 /*
59458 ** Invoke the 'collation needed' callback to request a collation sequence
59459 ** in the database text encoding of name zName, length nName.
59460 ** If the collation sequence
59461 */
59462 static void callCollNeeded(sqlite3 *db, const char *zName, int nName){
59463   assert( !db->xCollNeeded || !db->xCollNeeded16 );
59464   if( nName<0 ) nName = sqlite3Strlen(db, zName);
59465   if( db->xCollNeeded ){
59466     char *zExternal = sqlite3DbStrNDup(db, zName, nName);
59467     if( !zExternal ) return;
59468     db->xCollNeeded(db->pCollNeededArg, db, (int)ENC(db), zExternal);
59469     sqlite3DbFree(db, zExternal);
59470   }
59471 #ifndef SQLITE_OMIT_UTF16
59472   if( db->xCollNeeded16 ){
59473     char const *zExternal;
59474     sqlite3_value *pTmp = sqlite3ValueNew(db);
59475     sqlite3ValueSetStr(pTmp, nName, zName, SQLITE_UTF8, SQLITE_STATIC);
59476     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
59477     if( zExternal ){
59478       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
59479     }
59480     sqlite3ValueFree(pTmp);
59481   }
59482 #endif
59483 }
59484
59485 /*
59486 ** This routine is called if the collation factory fails to deliver a
59487 ** collation function in the best encoding but there may be other versions
59488 ** of this collation function (for other text encodings) available. Use one
59489 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
59490 ** possible.
59491 */
59492 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
59493   CollSeq *pColl2;
59494   char *z = pColl->zName;
59495   int n = strlen(z);
59496   int i;
59497   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
59498   for(i=0; i<3; i++){
59499     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, n, 0);
59500     if( pColl2->xCmp!=0 ){
59501       memcpy(pColl, pColl2, sizeof(CollSeq));
59502       pColl->xDel = 0;         /* Do not copy the destructor */
59503       return SQLITE_OK;
59504     }
59505   }
59506   return SQLITE_ERROR;
59507 }
59508
59509 /*
59510 ** This function is responsible for invoking the collation factory callback
59511 ** or substituting a collation sequence of a different encoding when the
59512 ** requested collation sequence is not available in the database native
59513 ** encoding.
59514 ** 
59515 ** If it is not NULL, then pColl must point to the database native encoding 
59516 ** collation sequence with name zName, length nName.
59517 **
59518 ** The return value is either the collation sequence to be used in database
59519 ** db for collation type name zName, length nName, or NULL, if no collation
59520 ** sequence can be found.
59521 */
59522 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
59523   sqlite3* db, 
59524   CollSeq *pColl, 
59525   const char *zName, 
59526   int nName
59527 ){
59528   CollSeq *p;
59529
59530   p = pColl;
59531   if( !p ){
59532     p = sqlite3FindCollSeq(db, ENC(db), zName, nName, 0);
59533   }
59534   if( !p || !p->xCmp ){
59535     /* No collation sequence of this type for this encoding is registered.
59536     ** Call the collation factory to see if it can supply us with one.
59537     */
59538     callCollNeeded(db, zName, nName);
59539     p = sqlite3FindCollSeq(db, ENC(db), zName, nName, 0);
59540   }
59541   if( p && !p->xCmp && synthCollSeq(db, p) ){
59542     p = 0;
59543   }
59544   assert( !p || p->xCmp );
59545   return p;
59546 }
59547
59548 /*
59549 ** This routine is called on a collation sequence before it is used to
59550 ** check that it is defined. An undefined collation sequence exists when
59551 ** a database is loaded that contains references to collation sequences
59552 ** that have not been defined by sqlite3_create_collation() etc.
59553 **
59554 ** If required, this routine calls the 'collation needed' callback to
59555 ** request a definition of the collating sequence. If this doesn't work, 
59556 ** an equivalent collating sequence that uses a text encoding different
59557 ** from the main database is substituted, if one is available.
59558 */
59559 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
59560   if( pColl ){
59561     const char *zName = pColl->zName;
59562     CollSeq *p = sqlite3GetCollSeq(pParse->db, pColl, zName, -1);
59563     if( !p ){
59564       if( pParse->nErr==0 ){
59565         sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
59566       }
59567       pParse->nErr++;
59568       return SQLITE_ERROR;
59569     }
59570     assert( p==pColl );
59571   }
59572   return SQLITE_OK;
59573 }
59574
59575
59576
59577 /*
59578 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
59579 ** specified by zName and nName is not found and parameter 'create' is
59580 ** true, then create a new entry. Otherwise return NULL.
59581 **
59582 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
59583 ** array of three CollSeq structures. The first is the collation sequence
59584 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
59585 **
59586 ** Stored immediately after the three collation sequences is a copy of
59587 ** the collation sequence name. A pointer to this string is stored in
59588 ** each collation sequence structure.
59589 */
59590 static CollSeq *findCollSeqEntry(
59591   sqlite3 *db,
59592   const char *zName,
59593   int nName,
59594   int create
59595 ){
59596   CollSeq *pColl;
59597   if( nName<0 ) nName = sqlite3Strlen(db, zName);
59598   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
59599
59600   if( 0==pColl && create ){
59601     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
59602     if( pColl ){
59603       CollSeq *pDel = 0;
59604       pColl[0].zName = (char*)&pColl[3];
59605       pColl[0].enc = SQLITE_UTF8;
59606       pColl[1].zName = (char*)&pColl[3];
59607       pColl[1].enc = SQLITE_UTF16LE;
59608       pColl[2].zName = (char*)&pColl[3];
59609       pColl[2].enc = SQLITE_UTF16BE;
59610       memcpy(pColl[0].zName, zName, nName);
59611       pColl[0].zName[nName] = 0;
59612       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
59613
59614       /* If a malloc() failure occured in sqlite3HashInsert(), it will 
59615       ** return the pColl pointer to be deleted (because it wasn't added
59616       ** to the hash table).
59617       */
59618       assert( pDel==0 || pDel==pColl );
59619       if( pDel!=0 ){
59620         db->mallocFailed = 1;
59621         sqlite3DbFree(db, pDel);
59622         pColl = 0;
59623       }
59624     }
59625   }
59626   return pColl;
59627 }
59628
59629 /*
59630 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
59631 ** Return the CollSeq* pointer for the collation sequence named zName
59632 ** for the encoding 'enc' from the database 'db'.
59633 **
59634 ** If the entry specified is not found and 'create' is true, then create a
59635 ** new entry.  Otherwise return NULL.
59636 **
59637 ** A separate function sqlite3LocateCollSeq() is a wrapper around
59638 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
59639 ** if necessary and generates an error message if the collating sequence
59640 ** cannot be found.
59641 */
59642 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
59643   sqlite3 *db,
59644   u8 enc,
59645   const char *zName,
59646   int nName,
59647   int create
59648 ){
59649   CollSeq *pColl;
59650   if( zName ){
59651     pColl = findCollSeqEntry(db, zName, nName, create);
59652   }else{
59653     pColl = db->pDfltColl;
59654   }
59655   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
59656   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
59657   if( pColl ) pColl += enc-1;
59658   return pColl;
59659 }
59660
59661 /*
59662 ** Locate a user function given a name, a number of arguments and a flag
59663 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
59664 ** pointer to the FuncDef structure that defines that function, or return
59665 ** NULL if the function does not exist.
59666 **
59667 ** If the createFlag argument is true, then a new (blank) FuncDef
59668 ** structure is created and liked into the "db" structure if a
59669 ** no matching function previously existed.  When createFlag is true
59670 ** and the nArg parameter is -1, then only a function that accepts
59671 ** any number of arguments will be returned.
59672 **
59673 ** If createFlag is false and nArg is -1, then the first valid
59674 ** function found is returned.  A function is valid if either xFunc
59675 ** or xStep is non-zero.
59676 **
59677 ** If createFlag is false, then a function with the required name and
59678 ** number of arguments may be returned even if the eTextRep flag does not
59679 ** match that requested.
59680 */
59681 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
59682   sqlite3 *db,       /* An open database */
59683   const char *zName, /* Name of the function.  Not null-terminated */
59684   int nName,         /* Number of characters in the name */
59685   int nArg,          /* Number of arguments.  -1 means any number */
59686   u8 enc,            /* Preferred text encoding */
59687   int createFlag     /* Create new entry if true and does not otherwise exist */
59688 ){
59689   FuncDef *p;         /* Iterator variable */
59690   FuncDef *pFirst;    /* First function with this name */
59691   FuncDef *pBest = 0; /* Best match found so far */
59692   int bestmatch = 0;  
59693
59694
59695   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
59696   if( nArg<-1 ) nArg = -1;
59697
59698   pFirst = (FuncDef*)sqlite3HashFind(&db->aFunc, zName, nName);
59699   for(p=pFirst; p; p=p->pNext){
59700     /* During the search for the best function definition, bestmatch is set
59701     ** as follows to indicate the quality of the match with the definition
59702     ** pointed to by pBest:
59703     **
59704     ** 0: pBest is NULL. No match has been found.
59705     ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
59706     **    encoding is requested, or vice versa.
59707     ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
59708     **    requested, or vice versa.
59709     ** 3: A variable arguments function using the same text encoding.
59710     ** 4: A function with the exact number of arguments requested that
59711     **    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
59712     ** 5: A function with the exact number of arguments requested that
59713     **    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
59714     ** 6: An exact match.
59715     **
59716     ** A larger value of 'matchqual' indicates a more desirable match.
59717     */
59718     if( p->nArg==-1 || p->nArg==nArg || nArg==-1 ){
59719       int match = 1;          /* Quality of this match */
59720       if( p->nArg==nArg || nArg==-1 ){
59721         match = 4;
59722       }
59723       if( enc==p->iPrefEnc ){
59724         match += 2;
59725       }
59726       else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
59727                (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
59728         match += 1;
59729       }
59730
59731       if( match>bestmatch ){
59732         pBest = p;
59733         bestmatch = match;
59734       }
59735     }
59736   }
59737
59738   /* If the createFlag parameter is true, and the seach did not reveal an
59739   ** exact match for the name, number of arguments and encoding, then add a
59740   ** new entry to the hash table and return it.
59741   */
59742   if( createFlag && bestmatch<6 && 
59743       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName))!=0 ){
59744     pBest->nArg = nArg;
59745     pBest->pNext = pFirst;
59746     pBest->iPrefEnc = enc;
59747     memcpy(pBest->zName, zName, nName);
59748     pBest->zName[nName] = 0;
59749     if( pBest==sqlite3HashInsert(&db->aFunc,pBest->zName,nName,(void*)pBest) ){
59750       db->mallocFailed = 1;
59751       sqlite3DbFree(db, pBest);
59752       return 0;
59753     }
59754   }
59755
59756   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
59757     return pBest;
59758   }
59759   return 0;
59760 }
59761
59762 /*
59763 ** Free all resources held by the schema structure. The void* argument points
59764 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the 
59765 ** pointer itself, it just cleans up subsiduary resources (i.e. the contents
59766 ** of the schema hash tables).
59767 **
59768 ** The Schema.cache_size variable is not cleared.
59769 */
59770 SQLITE_PRIVATE void sqlite3SchemaFree(void *p){
59771   Hash temp1;
59772   Hash temp2;
59773   HashElem *pElem;
59774   Schema *pSchema = (Schema *)p;
59775
59776   temp1 = pSchema->tblHash;
59777   temp2 = pSchema->trigHash;
59778   sqlite3HashInit(&pSchema->trigHash, SQLITE_HASH_STRING, 0);
59779   sqlite3HashClear(&pSchema->aFKey);
59780   sqlite3HashClear(&pSchema->idxHash);
59781   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
59782     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
59783   }
59784   sqlite3HashClear(&temp2);
59785   sqlite3HashInit(&pSchema->tblHash, SQLITE_HASH_STRING, 0);
59786   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
59787     Table *pTab = sqliteHashData(pElem);
59788     sqlite3DeleteTable(pTab);
59789   }
59790   sqlite3HashClear(&temp1);
59791   pSchema->pSeqTab = 0;
59792   pSchema->flags &= ~DB_SchemaLoaded;
59793 }
59794
59795 /*
59796 ** Find and return the schema associated with a BTree.  Create
59797 ** a new one if necessary.
59798 */
59799 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
59800   Schema * p;
59801   if( pBt ){
59802     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaFree);
59803   }else{
59804     p = (Schema *)sqlite3MallocZero(sizeof(Schema));
59805   }
59806   if( !p ){
59807     db->mallocFailed = 1;
59808   }else if ( 0==p->file_format ){
59809     sqlite3HashInit(&p->tblHash, SQLITE_HASH_STRING, 0);
59810     sqlite3HashInit(&p->idxHash, SQLITE_HASH_STRING, 0);
59811     sqlite3HashInit(&p->trigHash, SQLITE_HASH_STRING, 0);
59812     sqlite3HashInit(&p->aFKey, SQLITE_HASH_STRING, 1);
59813     p->enc = SQLITE_UTF8;
59814   }
59815   return p;
59816 }
59817
59818 /************** End of callback.c ********************************************/
59819 /************** Begin file delete.c ******************************************/
59820 /*
59821 ** 2001 September 15
59822 **
59823 ** The author disclaims copyright to this source code.  In place of
59824 ** a legal notice, here is a blessing:
59825 **
59826 **    May you do good and not evil.
59827 **    May you find forgiveness for yourself and forgive others.
59828 **    May you share freely, never taking more than you give.
59829 **
59830 *************************************************************************
59831 ** This file contains C code routines that are called by the parser
59832 ** in order to generate code for DELETE FROM statements.
59833 **
59834 ** $Id: delete.c,v 1.171 2008/07/28 19:34:53 drh Exp $
59835 */
59836
59837 /*
59838 ** Look up every table that is named in pSrc.  If any table is not found,
59839 ** add an error message to pParse->zErrMsg and return NULL.  If all tables
59840 ** are found, return a pointer to the last table.
59841 */
59842 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
59843   Table *pTab = 0;
59844   int i;
59845   struct SrcList_item *pItem;
59846   for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){
59847     pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
59848     sqlite3DeleteTable(pItem->pTab);
59849     pItem->pTab = pTab;
59850     if( pTab ){
59851       pTab->nRef++;
59852     }
59853   }
59854   return pTab;
59855 }
59856
59857 /*
59858 ** Check to make sure the given table is writable.  If it is not
59859 ** writable, generate an error message and return 1.  If it is
59860 ** writable return 0;
59861 */
59862 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
59863   if( (pTab->readOnly && (pParse->db->flags & SQLITE_WriteSchema)==0
59864         && pParse->nested==0) 
59865 #ifndef SQLITE_OMIT_VIRTUALTABLE
59866       || (pTab->pMod && pTab->pMod->pModule->xUpdate==0)
59867 #endif
59868   ){
59869     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
59870     return 1;
59871   }
59872 #ifndef SQLITE_OMIT_VIEW
59873   if( !viewOk && pTab->pSelect ){
59874     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
59875     return 1;
59876   }
59877 #endif
59878   return 0;
59879 }
59880
59881 /*
59882 ** Generate code that will open a table for reading.
59883 */
59884 SQLITE_PRIVATE void sqlite3OpenTable(
59885   Parse *p,       /* Generate code into this VDBE */
59886   int iCur,       /* The cursor number of the table */
59887   int iDb,        /* The database index in sqlite3.aDb[] */
59888   Table *pTab,    /* The table to be opened */
59889   int opcode      /* OP_OpenRead or OP_OpenWrite */
59890 ){
59891   Vdbe *v;
59892   if( IsVirtual(pTab) ) return;
59893   v = sqlite3GetVdbe(p);
59894   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
59895   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite), pTab->zName);
59896   sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
59897   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
59898   VdbeComment((v, "%s", pTab->zName));
59899 }
59900
59901
59902 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
59903 /*
59904 ** Evaluate a view and store its result in an ephemeral table.  The
59905 ** pWhere argument is an optional WHERE clause that restricts the
59906 ** set of rows in the view that are to be added to the ephemeral table.
59907 */
59908 SQLITE_PRIVATE void sqlite3MaterializeView(
59909   Parse *pParse,       /* Parsing context */
59910   Select *pView,       /* View definition */
59911   Expr *pWhere,        /* Optional WHERE clause to be added */
59912   int iCur             /* Cursor number for ephemerial table */
59913 ){
59914   SelectDest dest;
59915   Select *pDup;
59916   sqlite3 *db = pParse->db;
59917
59918   pDup = sqlite3SelectDup(db, pView);
59919   if( pWhere ){
59920     SrcList *pFrom;
59921     
59922     pWhere = sqlite3ExprDup(db, pWhere);
59923     pFrom = sqlite3SrcListAppendFromTerm(pParse, 0, 0, 0, 0, pDup, 0, 0);
59924     pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
59925   }
59926   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
59927   sqlite3Select(pParse, pDup, &dest, 0, 0, 0);
59928   sqlite3SelectDelete(db, pDup);
59929 }
59930 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
59931
59932
59933 /*
59934 ** Generate code for a DELETE FROM statement.
59935 **
59936 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
59937 **                 \________/       \________________/
59938 **                  pTabList              pWhere
59939 */
59940 SQLITE_PRIVATE void sqlite3DeleteFrom(
59941   Parse *pParse,         /* The parser context */
59942   SrcList *pTabList,     /* The table from which we should delete things */
59943   Expr *pWhere           /* The WHERE clause.  May be null */
59944 ){
59945   Vdbe *v;               /* The virtual database engine */
59946   Table *pTab;           /* The table from which records will be deleted */
59947   const char *zDb;       /* Name of database holding pTab */
59948   int end, addr = 0;     /* A couple addresses of generated code */
59949   int i;                 /* Loop counter */
59950   WhereInfo *pWInfo;     /* Information about the WHERE clause */
59951   Index *pIdx;           /* For looping over indices of the table */
59952   int iCur;              /* VDBE Cursor number for pTab */
59953   sqlite3 *db;           /* Main database structure */
59954   AuthContext sContext;  /* Authorization context */
59955   int oldIdx = -1;       /* Cursor for the OLD table of AFTER triggers */
59956   NameContext sNC;       /* Name context to resolve expressions in */
59957   int iDb;               /* Database number */
59958   int memCnt = 0;        /* Memory cell used for change counting */
59959
59960 #ifndef SQLITE_OMIT_TRIGGER
59961   int isView;                  /* True if attempting to delete from a view */
59962   int triggers_exist = 0;      /* True if any triggers exist */
59963 #endif
59964   int iBeginAfterTrigger;      /* Address of after trigger program */
59965   int iEndAfterTrigger;        /* Exit of after trigger program */
59966   int iBeginBeforeTrigger;     /* Address of before trigger program */
59967   int iEndBeforeTrigger;       /* Exit of before trigger program */
59968   u32 old_col_mask = 0;        /* Mask of OLD.* columns in use */
59969
59970   sContext.pParse = 0;
59971   db = pParse->db;
59972   if( pParse->nErr || db->mallocFailed ){
59973     goto delete_from_cleanup;
59974   }
59975   assert( pTabList->nSrc==1 );
59976
59977   /* Locate the table which we want to delete.  This table has to be
59978   ** put in an SrcList structure because some of the subroutines we
59979   ** will be calling are designed to work with multiple tables and expect
59980   ** an SrcList* parameter instead of just a Table* parameter.
59981   */
59982   pTab = sqlite3SrcListLookup(pParse, pTabList);
59983   if( pTab==0 )  goto delete_from_cleanup;
59984
59985   /* Figure out if we have any triggers and if the table being
59986   ** deleted from is a view
59987   */
59988 #ifndef SQLITE_OMIT_TRIGGER
59989   triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0);
59990   isView = pTab->pSelect!=0;
59991 #else
59992 # define triggers_exist 0
59993 # define isView 0
59994 #endif
59995 #ifdef SQLITE_OMIT_VIEW
59996 # undef isView
59997 # define isView 0
59998 #endif
59999
60000   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
60001     goto delete_from_cleanup;
60002   }
60003   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
60004   assert( iDb<db->nDb );
60005   zDb = db->aDb[iDb].zName;
60006   if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
60007     goto delete_from_cleanup;
60008   }
60009
60010   /* If pTab is really a view, make sure it has been initialized.
60011   */
60012   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
60013     goto delete_from_cleanup;
60014   }
60015
60016   /* Allocate a cursor used to store the old.* data for a trigger.
60017   */
60018   if( triggers_exist ){ 
60019     oldIdx = pParse->nTab++;
60020   }
60021
60022   /* Assign  cursor number to the table and all its indices.
60023   */
60024   assert( pTabList->nSrc==1 );
60025   iCur = pTabList->a[0].iCursor = pParse->nTab++;
60026   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
60027     pParse->nTab++;
60028   }
60029
60030   /* Start the view context
60031   */
60032   if( isView ){
60033     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
60034   }
60035
60036   /* Begin generating code.
60037   */
60038   v = sqlite3GetVdbe(pParse);
60039   if( v==0 ){
60040     goto delete_from_cleanup;
60041   }
60042   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
60043   sqlite3BeginWriteOperation(pParse, triggers_exist, iDb);
60044
60045   if( triggers_exist ){
60046     int orconf = ((pParse->trigStack)?pParse->trigStack->orconf:OE_Default);
60047     int iGoto = sqlite3VdbeAddOp0(v, OP_Goto);
60048     addr = sqlite3VdbeMakeLabel(v);
60049
60050     iBeginBeforeTrigger = sqlite3VdbeCurrentAddr(v);
60051     (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_BEFORE, pTab,
60052         -1, oldIdx, orconf, addr, &old_col_mask, 0);
60053     iEndBeforeTrigger = sqlite3VdbeAddOp0(v, OP_Goto);
60054
60055     iBeginAfterTrigger = sqlite3VdbeCurrentAddr(v);
60056     (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_AFTER, pTab, -1,
60057         oldIdx, orconf, addr, &old_col_mask, 0);
60058     iEndAfterTrigger = sqlite3VdbeAddOp0(v, OP_Goto);
60059
60060     sqlite3VdbeJumpHere(v, iGoto);
60061   }
60062
60063   /* If we are trying to delete from a view, realize that view into
60064   ** a ephemeral table.
60065   */
60066   if( isView ){
60067     sqlite3MaterializeView(pParse, pTab->pSelect, pWhere, iCur);
60068   }
60069
60070   /* Resolve the column names in the WHERE clause.
60071   */
60072   memset(&sNC, 0, sizeof(sNC));
60073   sNC.pParse = pParse;
60074   sNC.pSrcList = pTabList;
60075   if( sqlite3ExprResolveNames(&sNC, pWhere) ){
60076     goto delete_from_cleanup;
60077   }
60078
60079   /* Initialize the counter of the number of rows deleted, if
60080   ** we are counting rows.
60081   */
60082   if( db->flags & SQLITE_CountRows ){
60083     memCnt = ++pParse->nMem;
60084     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
60085   }
60086
60087   /* Special case: A DELETE without a WHERE clause deletes everything.
60088   ** It is easier just to erase the whole table.  Note, however, that
60089   ** this means that the row change count will be incorrect.
60090   */
60091   if( pWhere==0 && !triggers_exist && !IsVirtual(pTab) ){
60092     if( db->flags & SQLITE_CountRows ){
60093       /* If counting rows deleted, just count the total number of
60094       ** entries in the table. */
60095       int addr2;
60096       if( !isView ){
60097         sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
60098       }
60099       sqlite3VdbeAddOp2(v, OP_Rewind, iCur, sqlite3VdbeCurrentAddr(v)+2);
60100       addr2 = sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
60101       sqlite3VdbeAddOp2(v, OP_Next, iCur, addr2);
60102       sqlite3VdbeAddOp1(v, OP_Close, iCur);
60103     }
60104     if( !isView ){
60105       sqlite3VdbeAddOp2(v, OP_Clear, pTab->tnum, iDb);
60106       if( !pParse->nested ){
60107         sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
60108       }
60109       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
60110         assert( pIdx->pSchema==pTab->pSchema );
60111         sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
60112       }
60113     }
60114   } 
60115   /* The usual case: There is a WHERE clause so we have to scan through
60116   ** the table and pick which records to delete.
60117   */
60118   else{
60119     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
60120
60121     /* Begin the database scan
60122     */
60123     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0);
60124     if( pWInfo==0 ) goto delete_from_cleanup;
60125
60126     /* Remember the rowid of every item to be deleted.
60127     */
60128     sqlite3VdbeAddOp2(v, IsVirtual(pTab) ? OP_VRowid : OP_Rowid, iCur, iRowid);
60129     sqlite3VdbeAddOp1(v, OP_FifoWrite, iRowid);
60130     if( db->flags & SQLITE_CountRows ){
60131       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
60132     }
60133
60134     /* End the database scan loop.
60135     */
60136     sqlite3WhereEnd(pWInfo);
60137
60138     /* Open the pseudo-table used to store OLD if there are triggers.
60139     */
60140     if( triggers_exist ){
60141       sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
60142       sqlite3VdbeAddOp1(v, OP_OpenPseudo, oldIdx);
60143     }
60144
60145     /* Delete every item whose key was written to the list during the
60146     ** database scan.  We have to delete items after the scan is complete
60147     ** because deleting an item can change the scan order.
60148     */
60149     end = sqlite3VdbeMakeLabel(v);
60150
60151     if( !isView ){
60152       /* Open cursors for the table we are deleting from and 
60153       ** all its indices.
60154       */
60155       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
60156     }
60157
60158     /* This is the beginning of the delete loop. If a trigger encounters
60159     ** an IGNORE constraint, it jumps back to here.
60160     */
60161     if( triggers_exist ){
60162       sqlite3VdbeResolveLabel(v, addr);
60163     }
60164     addr = sqlite3VdbeAddOp2(v, OP_FifoRead, iRowid, end);
60165
60166     if( triggers_exist ){
60167       int iData = ++pParse->nMem;   /* For storing row data of OLD table */
60168
60169       /* If the record is no longer present in the table, jump to the
60170       ** next iteration of the loop through the contents of the fifo.
60171       */
60172       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, iRowid);
60173
60174       /* Populate the OLD.* pseudo-table */
60175       if( old_col_mask ){
60176         sqlite3VdbeAddOp2(v, OP_RowData, iCur, iData);
60177       }else{
60178         sqlite3VdbeAddOp2(v, OP_Null, 0, iData);
60179       }
60180       sqlite3VdbeAddOp3(v, OP_Insert, oldIdx, iData, iRowid);
60181
60182       /* Jump back and run the BEFORE triggers */
60183       sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginBeforeTrigger);
60184       sqlite3VdbeJumpHere(v, iEndBeforeTrigger);
60185     }
60186
60187     if( !isView ){
60188       /* Delete the row */
60189 #ifndef SQLITE_OMIT_VIRTUALTABLE
60190       if( IsVirtual(pTab) ){
60191         const char *pVtab = (const char *)pTab->pVtab;
60192         sqlite3VtabMakeWritable(pParse, pTab);
60193         sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVtab, P4_VTAB);
60194       }else
60195 #endif
60196       {
60197         sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, pParse->nested==0);
60198       }
60199     }
60200
60201     /* If there are row triggers, close all cursors then invoke
60202     ** the AFTER triggers
60203     */
60204     if( triggers_exist ){
60205       /* Jump back and run the AFTER triggers */
60206       sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginAfterTrigger);
60207       sqlite3VdbeJumpHere(v, iEndAfterTrigger);
60208     }
60209
60210     /* End of the delete loop */
60211     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
60212     sqlite3VdbeResolveLabel(v, end);
60213
60214     /* Close the cursors after the loop if there are no row triggers */
60215     if( !isView  && !IsVirtual(pTab) ){
60216       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
60217         sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
60218       }
60219       sqlite3VdbeAddOp1(v, OP_Close, iCur);
60220     }
60221   }
60222
60223   /*
60224   ** Return the number of rows that were deleted. If this routine is 
60225   ** generating code because of a call to sqlite3NestedParse(), do not
60226   ** invoke the callback function.
60227   */
60228   if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
60229     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
60230     sqlite3VdbeSetNumCols(v, 1);
60231     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", P4_STATIC);
60232   }
60233
60234 delete_from_cleanup:
60235   sqlite3AuthContextPop(&sContext);
60236   sqlite3SrcListDelete(db, pTabList);
60237   sqlite3ExprDelete(db, pWhere);
60238   return;
60239 }
60240
60241 /*
60242 ** This routine generates VDBE code that causes a single row of a
60243 ** single table to be deleted.
60244 **
60245 ** The VDBE must be in a particular state when this routine is called.
60246 ** These are the requirements:
60247 **
60248 **   1.  A read/write cursor pointing to pTab, the table containing the row
60249 **       to be deleted, must be opened as cursor number "base".
60250 **
60251 **   2.  Read/write cursors for all indices of pTab must be open as
60252 **       cursor number base+i for the i-th index.
60253 **
60254 **   3.  The record number of the row to be deleted must be stored in
60255 **       memory cell iRowid.
60256 **
60257 ** This routine pops the top of the stack to remove the record number
60258 ** and then generates code to remove both the table record and all index
60259 ** entries that point to that record.
60260 */
60261 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
60262   Parse *pParse,     /* Parsing context */
60263   Table *pTab,       /* Table containing the row to be deleted */
60264   int iCur,          /* Cursor number for the table */
60265   int iRowid,        /* Memory cell that contains the rowid to delete */
60266   int count          /* Increment the row change counter */
60267 ){
60268   int addr;
60269   Vdbe *v;
60270
60271   v = pParse->pVdbe;
60272   addr = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowid);
60273   sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
60274   sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
60275   if( count ){
60276     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
60277   }
60278   sqlite3VdbeJumpHere(v, addr);
60279 }
60280
60281 /*
60282 ** This routine generates VDBE code that causes the deletion of all
60283 ** index entries associated with a single row of a single table.
60284 **
60285 ** The VDBE must be in a particular state when this routine is called.
60286 ** These are the requirements:
60287 **
60288 **   1.  A read/write cursor pointing to pTab, the table containing the row
60289 **       to be deleted, must be opened as cursor number "iCur".
60290 **
60291 **   2.  Read/write cursors for all indices of pTab must be open as
60292 **       cursor number iCur+i for the i-th index.
60293 **
60294 **   3.  The "iCur" cursor must be pointing to the row that is to be
60295 **       deleted.
60296 */
60297 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
60298   Parse *pParse,     /* Parsing and code generating context */
60299   Table *pTab,       /* Table containing the row to be deleted */
60300   int iCur,          /* Cursor number for the table */
60301   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
60302 ){
60303   int i;
60304   Index *pIdx;
60305   int r1;
60306
60307   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
60308     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
60309     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
60310     sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
60311   }
60312 }
60313
60314 /*
60315 ** Generate code that will assemble an index key and put it in register
60316 ** regOut.  The key with be for index pIdx which is an index on pTab.
60317 ** iCur is the index of a cursor open on the pTab table and pointing to
60318 ** the entry that needs indexing.
60319 **
60320 ** Return a register number which is the first in a block of
60321 ** registers that holds the elements of the index key.  The
60322 ** block of registers has already been deallocated by the time
60323 ** this routine returns.
60324 */
60325 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
60326   Parse *pParse,     /* Parsing context */
60327   Index *pIdx,       /* The index for which to generate a key */
60328   int iCur,          /* Cursor number for the pIdx->pTable table */
60329   int regOut,        /* Write the new index key to this register */
60330   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
60331 ){
60332   Vdbe *v = pParse->pVdbe;
60333   int j;
60334   Table *pTab = pIdx->pTable;
60335   int regBase;
60336   int nCol;
60337
60338   nCol = pIdx->nColumn;
60339   regBase = sqlite3GetTempRange(pParse, nCol+1);
60340   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
60341   for(j=0; j<nCol; j++){
60342     int idx = pIdx->aiColumn[j];
60343     if( idx==pTab->iPKey ){
60344       sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
60345     }else{
60346       sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
60347       sqlite3ColumnDefault(v, pTab, idx);
60348     }
60349   }
60350   if( doMakeRec ){
60351     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
60352     sqlite3IndexAffinityStr(v, pIdx);
60353     sqlite3ExprCacheAffinityChange(pParse, regBase, nCol+1);
60354   }
60355   sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
60356   return regBase;
60357 }
60358
60359 /* Make sure "isView" gets undefined in case this file becomes part of
60360 ** the amalgamation - so that subsequent files do not see isView as a
60361 ** macro. */
60362 #undef isView
60363
60364 /************** End of delete.c **********************************************/
60365 /************** Begin file func.c ********************************************/
60366 /*
60367 ** 2002 February 23
60368 **
60369 ** The author disclaims copyright to this source code.  In place of
60370 ** a legal notice, here is a blessing:
60371 **
60372 **    May you do good and not evil.
60373 **    May you find forgiveness for yourself and forgive others.
60374 **    May you share freely, never taking more than you give.
60375 **
60376 *************************************************************************
60377 ** This file contains the C functions that implement various SQL
60378 ** functions of SQLite.  
60379 **
60380 ** There is only one exported symbol in this file - the function
60381 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
60382 ** All other code has file scope.
60383 **
60384 ** $Id: func.c,v 1.196 2008/07/28 19:34:53 drh Exp $
60385 */
60386
60387
60388 /*
60389 ** Return the collating function associated with a function.
60390 */
60391 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
60392   return context->pColl;
60393 }
60394
60395 /*
60396 ** Implementation of the non-aggregate min() and max() functions
60397 */
60398 static void minmaxFunc(
60399   sqlite3_context *context,
60400   int argc,
60401   sqlite3_value **argv
60402 ){
60403   int i;
60404   int mask;    /* 0 for min() or 0xffffffff for max() */
60405   int iBest;
60406   CollSeq *pColl;
60407
60408   if( argc==0 ) return;
60409   mask = sqlite3_user_data(context)==0 ? 0 : -1;
60410   pColl = sqlite3GetFuncCollSeq(context);
60411   assert( pColl );
60412   assert( mask==-1 || mask==0 );
60413   iBest = 0;
60414   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
60415   for(i=1; i<argc; i++){
60416     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
60417     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
60418       iBest = i;
60419     }
60420   }
60421   sqlite3_result_value(context, argv[iBest]);
60422 }
60423
60424 /*
60425 ** Return the type of the argument.
60426 */
60427 static void typeofFunc(
60428   sqlite3_context *context,
60429   int argc,
60430   sqlite3_value **argv
60431 ){
60432   const char *z = 0;
60433   switch( sqlite3_value_type(argv[0]) ){
60434     case SQLITE_NULL:    z = "null";    break;
60435     case SQLITE_INTEGER: z = "integer"; break;
60436     case SQLITE_TEXT:    z = "text";    break;
60437     case SQLITE_FLOAT:   z = "real";    break;
60438     case SQLITE_BLOB:    z = "blob";    break;
60439   }
60440   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
60441 }
60442
60443
60444 /*
60445 ** Implementation of the length() function
60446 */
60447 static void lengthFunc(
60448   sqlite3_context *context,
60449   int argc,
60450   sqlite3_value **argv
60451 ){
60452   int len;
60453
60454   assert( argc==1 );
60455   switch( sqlite3_value_type(argv[0]) ){
60456     case SQLITE_BLOB:
60457     case SQLITE_INTEGER:
60458     case SQLITE_FLOAT: {
60459       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
60460       break;
60461     }
60462     case SQLITE_TEXT: {
60463       const unsigned char *z = sqlite3_value_text(argv[0]);
60464       if( z==0 ) return;
60465       len = 0;
60466       while( *z ){
60467         len++;
60468         SQLITE_SKIP_UTF8(z);
60469       }
60470       sqlite3_result_int(context, len);
60471       break;
60472     }
60473     default: {
60474       sqlite3_result_null(context);
60475       break;
60476     }
60477   }
60478 }
60479
60480 /*
60481 ** Implementation of the abs() function
60482 */
60483 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
60484   assert( argc==1 );
60485   switch( sqlite3_value_type(argv[0]) ){
60486     case SQLITE_INTEGER: {
60487       i64 iVal = sqlite3_value_int64(argv[0]);
60488       if( iVal<0 ){
60489         if( (iVal<<1)==0 ){
60490           sqlite3_result_error(context, "integer overflow", -1);
60491           return;
60492         }
60493         iVal = -iVal;
60494       } 
60495       sqlite3_result_int64(context, iVal);
60496       break;
60497     }
60498     case SQLITE_NULL: {
60499       sqlite3_result_null(context);
60500       break;
60501     }
60502     default: {
60503       double rVal = sqlite3_value_double(argv[0]);
60504       if( rVal<0 ) rVal = -rVal;
60505       sqlite3_result_double(context, rVal);
60506       break;
60507     }
60508   }
60509 }
60510
60511 /*
60512 ** Implementation of the substr() function.
60513 **
60514 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
60515 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
60516 ** of x.  If x is text, then we actually count UTF-8 characters.
60517 ** If x is a blob, then we count bytes.
60518 **
60519 ** If p1 is negative, then we begin abs(p1) from the end of x[].
60520 */
60521 static void substrFunc(
60522   sqlite3_context *context,
60523   int argc,
60524   sqlite3_value **argv
60525 ){
60526   const unsigned char *z;
60527   const unsigned char *z2;
60528   int len;
60529   int p0type;
60530   i64 p1, p2;
60531
60532   assert( argc==3 || argc==2 );
60533   p0type = sqlite3_value_type(argv[0]);
60534   if( p0type==SQLITE_BLOB ){
60535     len = sqlite3_value_bytes(argv[0]);
60536     z = sqlite3_value_blob(argv[0]);
60537     if( z==0 ) return;
60538     assert( len==sqlite3_value_bytes(argv[0]) );
60539   }else{
60540     z = sqlite3_value_text(argv[0]);
60541     if( z==0 ) return;
60542     len = 0;
60543     for(z2=z; *z2; len++){
60544       SQLITE_SKIP_UTF8(z2);
60545     }
60546   }
60547   p1 = sqlite3_value_int(argv[1]);
60548   if( argc==3 ){
60549     p2 = sqlite3_value_int(argv[2]);
60550   }else{
60551     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
60552   }
60553   if( p1<0 ){
60554     p1 += len;
60555     if( p1<0 ){
60556       p2 += p1;
60557       p1 = 0;
60558     }
60559   }else if( p1>0 ){
60560     p1--;
60561   }
60562   if( p1+p2>len ){
60563     p2 = len-p1;
60564   }
60565   if( p0type!=SQLITE_BLOB ){
60566     while( *z && p1 ){
60567       SQLITE_SKIP_UTF8(z);
60568       p1--;
60569     }
60570     for(z2=z; *z2 && p2; p2--){
60571       SQLITE_SKIP_UTF8(z2);
60572     }
60573     sqlite3_result_text(context, (char*)z, z2-z, SQLITE_TRANSIENT);
60574   }else{
60575     if( p2<0 ) p2 = 0;
60576     sqlite3_result_blob(context, (char*)&z[p1], p2, SQLITE_TRANSIENT);
60577   }
60578 }
60579
60580 /*
60581 ** Implementation of the round() function
60582 */
60583 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
60584   int n = 0;
60585   double r;
60586   char zBuf[500];  /* larger than the %f representation of the largest double */
60587   assert( argc==1 || argc==2 );
60588   if( argc==2 ){
60589     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
60590     n = sqlite3_value_int(argv[1]);
60591     if( n>30 ) n = 30;
60592     if( n<0 ) n = 0;
60593   }
60594   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
60595   r = sqlite3_value_double(argv[0]);
60596   sqlite3_snprintf(sizeof(zBuf),zBuf,"%.*f",n,r);
60597   sqlite3AtoF(zBuf, &r);
60598   sqlite3_result_double(context, r);
60599 }
60600
60601 /*
60602 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
60603 ** allocation fails, call sqlite3_result_error_nomem() to notify
60604 ** the database handle that malloc() has failed.
60605 */
60606 static void *contextMalloc(sqlite3_context *context, i64 nByte){
60607   char *z;
60608   if( nByte>sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH] ){
60609     sqlite3_result_error_toobig(context);
60610     z = 0;
60611   }else{
60612     z = sqlite3Malloc(nByte);
60613     if( !z && nByte>0 ){
60614       sqlite3_result_error_nomem(context);
60615     }
60616   }
60617   return z;
60618 }
60619
60620 /*
60621 ** Implementation of the upper() and lower() SQL functions.
60622 */
60623 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
60624   char *z1;
60625   const char *z2;
60626   int i, n;
60627   if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
60628   z2 = (char*)sqlite3_value_text(argv[0]);
60629   n = sqlite3_value_bytes(argv[0]);
60630   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
60631   assert( z2==(char*)sqlite3_value_text(argv[0]) );
60632   if( z2 ){
60633     z1 = contextMalloc(context, ((i64)n)+1);
60634     if( z1 ){
60635       memcpy(z1, z2, n+1);
60636       for(i=0; z1[i]; i++){
60637         z1[i] = toupper(z1[i]);
60638       }
60639       sqlite3_result_text(context, z1, -1, sqlite3_free);
60640     }
60641   }
60642 }
60643 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
60644   char *z1;
60645   const char *z2;
60646   int i, n;
60647   if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
60648   z2 = (char*)sqlite3_value_text(argv[0]);
60649   n = sqlite3_value_bytes(argv[0]);
60650   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
60651   assert( z2==(char*)sqlite3_value_text(argv[0]) );
60652   if( z2 ){
60653     z1 = contextMalloc(context, ((i64)n)+1);
60654     if( z1 ){
60655       memcpy(z1, z2, n+1);
60656       for(i=0; z1[i]; i++){
60657         z1[i] = tolower(z1[i]);
60658       }
60659       sqlite3_result_text(context, z1, -1, sqlite3_free);
60660     }
60661   }
60662 }
60663
60664 /*
60665 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  
60666 ** All three do the same thing.  They return the first non-NULL
60667 ** argument.
60668 */
60669 static void ifnullFunc(
60670   sqlite3_context *context,
60671   int argc,
60672   sqlite3_value **argv
60673 ){
60674   int i;
60675   for(i=0; i<argc; i++){
60676     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
60677       sqlite3_result_value(context, argv[i]);
60678       break;
60679     }
60680   }
60681 }
60682
60683 /*
60684 ** Implementation of random().  Return a random integer.  
60685 */
60686 static void randomFunc(
60687   sqlite3_context *context,
60688   int argc,
60689   sqlite3_value **argv
60690 ){
60691   sqlite_int64 r;
60692   sqlite3_randomness(sizeof(r), &r);
60693   if( (r<<1)==0 ) r = 0;  /* Prevent 0x8000.... as the result so that we */
60694                           /* can always do abs() of the result */
60695   sqlite3_result_int64(context, r);
60696 }
60697
60698 /*
60699 ** Implementation of randomblob(N).  Return a random blob
60700 ** that is N bytes long.
60701 */
60702 static void randomBlob(
60703   sqlite3_context *context,
60704   int argc,
60705   sqlite3_value **argv
60706 ){
60707   int n;
60708   unsigned char *p;
60709   assert( argc==1 );
60710   n = sqlite3_value_int(argv[0]);
60711   if( n<1 ){
60712     n = 1;
60713   }
60714   p = contextMalloc(context, n);
60715   if( p ){
60716     sqlite3_randomness(n, p);
60717     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
60718   }
60719 }
60720
60721 /*
60722 ** Implementation of the last_insert_rowid() SQL function.  The return
60723 ** value is the same as the sqlite3_last_insert_rowid() API function.
60724 */
60725 static void last_insert_rowid(
60726   sqlite3_context *context, 
60727   int arg, 
60728   sqlite3_value **argv
60729 ){
60730   sqlite3 *db = sqlite3_context_db_handle(context);
60731   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
60732 }
60733
60734 /*
60735 ** Implementation of the changes() SQL function.  The return value is the
60736 ** same as the sqlite3_changes() API function.
60737 */
60738 static void changes(
60739   sqlite3_context *context,
60740   int arg,
60741   sqlite3_value **argv
60742 ){
60743   sqlite3 *db = sqlite3_context_db_handle(context);
60744   sqlite3_result_int(context, sqlite3_changes(db));
60745 }
60746
60747 /*
60748 ** Implementation of the total_changes() SQL function.  The return value is
60749 ** the same as the sqlite3_total_changes() API function.
60750 */
60751 static void total_changes(
60752   sqlite3_context *context,
60753   int arg,
60754   sqlite3_value **argv
60755 ){
60756   sqlite3 *db = sqlite3_context_db_handle(context);
60757   sqlite3_result_int(context, sqlite3_total_changes(db));
60758 }
60759
60760 /*
60761 ** A structure defining how to do GLOB-style comparisons.
60762 */
60763 struct compareInfo {
60764   u8 matchAll;
60765   u8 matchOne;
60766   u8 matchSet;
60767   u8 noCase;
60768 };
60769
60770 /*
60771 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
60772 ** character is exactly one byte in size.  Also, all characters are
60773 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
60774 ** whereas only characters less than 0x80 do in ASCII.
60775 */
60776 #if defined(SQLITE_EBCDIC)
60777 # define sqlite3Utf8Read(A,B,C)  (*(A++))
60778 # define GlogUpperToLower(A)     A = sqlite3UpperToLower[A]
60779 #else
60780 # define GlogUpperToLower(A)     if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
60781 #endif
60782
60783 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
60784 /* The correct SQL-92 behavior is for the LIKE operator to ignore
60785 ** case.  Thus  'a' LIKE 'A' would be true. */
60786 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
60787 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
60788 ** is case sensitive causing 'a' LIKE 'A' to be false */
60789 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
60790
60791 /*
60792 ** Compare two UTF-8 strings for equality where the first string can
60793 ** potentially be a "glob" expression.  Return true (1) if they
60794 ** are the same and false (0) if they are different.
60795 **
60796 ** Globbing rules:
60797 **
60798 **      '*'       Matches any sequence of zero or more characters.
60799 **
60800 **      '?'       Matches exactly one character.
60801 **
60802 **     [...]      Matches one character from the enclosed list of
60803 **                characters.
60804 **
60805 **     [^...]     Matches one character not in the enclosed list.
60806 **
60807 ** With the [...] and [^...] matching, a ']' character can be included
60808 ** in the list by making it the first character after '[' or '^'.  A
60809 ** range of characters can be specified using '-'.  Example:
60810 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
60811 ** it the last character in the list.
60812 **
60813 ** This routine is usually quick, but can be N**2 in the worst case.
60814 **
60815 ** Hints: to match '*' or '?', put them in "[]".  Like this:
60816 **
60817 **         abc[*]xyz        Matches "abc*xyz" only
60818 */
60819 static int patternCompare(
60820   const u8 *zPattern,              /* The glob pattern */
60821   const u8 *zString,               /* The string to compare against the glob */
60822   const struct compareInfo *pInfo, /* Information about how to do the compare */
60823   const int esc                    /* The escape character */
60824 ){
60825   int c, c2;
60826   int invert;
60827   int seen;
60828   u8 matchOne = pInfo->matchOne;
60829   u8 matchAll = pInfo->matchAll;
60830   u8 matchSet = pInfo->matchSet;
60831   u8 noCase = pInfo->noCase; 
60832   int prevEscape = 0;     /* True if the previous character was 'escape' */
60833
60834   while( (c = sqlite3Utf8Read(zPattern,0,&zPattern))!=0 ){
60835     if( !prevEscape && c==matchAll ){
60836       while( (c=sqlite3Utf8Read(zPattern,0,&zPattern)) == matchAll
60837                || c == matchOne ){
60838         if( c==matchOne && sqlite3Utf8Read(zString, 0, &zString)==0 ){
60839           return 0;
60840         }
60841       }
60842       if( c==0 ){
60843         return 1;
60844       }else if( c==esc ){
60845         c = sqlite3Utf8Read(zPattern, 0, &zPattern);
60846         if( c==0 ){
60847           return 0;
60848         }
60849       }else if( c==matchSet ){
60850         assert( esc==0 );         /* This is GLOB, not LIKE */
60851         assert( matchSet<0x80 );  /* '[' is a single-byte character */
60852         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
60853           SQLITE_SKIP_UTF8(zString);
60854         }
60855         return *zString!=0;
60856       }
60857       while( (c2 = sqlite3Utf8Read(zString,0,&zString))!=0 ){
60858         if( noCase ){
60859           GlogUpperToLower(c2);
60860           GlogUpperToLower(c);
60861           while( c2 != 0 && c2 != c ){
60862             c2 = sqlite3Utf8Read(zString, 0, &zString);
60863             GlogUpperToLower(c2);
60864           }
60865         }else{
60866           while( c2 != 0 && c2 != c ){
60867             c2 = sqlite3Utf8Read(zString, 0, &zString);
60868           }
60869         }
60870         if( c2==0 ) return 0;
60871         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
60872       }
60873       return 0;
60874     }else if( !prevEscape && c==matchOne ){
60875       if( sqlite3Utf8Read(zString, 0, &zString)==0 ){
60876         return 0;
60877       }
60878     }else if( c==matchSet ){
60879       int prior_c = 0;
60880       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
60881       seen = 0;
60882       invert = 0;
60883       c = sqlite3Utf8Read(zString, 0, &zString);
60884       if( c==0 ) return 0;
60885       c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
60886       if( c2=='^' ){
60887         invert = 1;
60888         c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
60889       }
60890       if( c2==']' ){
60891         if( c==']' ) seen = 1;
60892         c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
60893       }
60894       while( c2 && c2!=']' ){
60895         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
60896           c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
60897           if( c>=prior_c && c<=c2 ) seen = 1;
60898           prior_c = 0;
60899         }else{
60900           if( c==c2 ){
60901             seen = 1;
60902           }
60903           prior_c = c2;
60904         }
60905         c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
60906       }
60907       if( c2==0 || (seen ^ invert)==0 ){
60908         return 0;
60909       }
60910     }else if( esc==c && !prevEscape ){
60911       prevEscape = 1;
60912     }else{
60913       c2 = sqlite3Utf8Read(zString, 0, &zString);
60914       if( noCase ){
60915         GlogUpperToLower(c);
60916         GlogUpperToLower(c2);
60917       }
60918       if( c!=c2 ){
60919         return 0;
60920       }
60921       prevEscape = 0;
60922     }
60923   }
60924   return *zString==0;
60925 }
60926
60927 /*
60928 ** Count the number of times that the LIKE operator (or GLOB which is
60929 ** just a variation of LIKE) gets called.  This is used for testing
60930 ** only.
60931 */
60932 #ifdef SQLITE_TEST
60933 SQLITE_API int sqlite3_like_count = 0;
60934 #endif
60935
60936
60937 /*
60938 ** Implementation of the like() SQL function.  This function implements
60939 ** the build-in LIKE operator.  The first argument to the function is the
60940 ** pattern and the second argument is the string.  So, the SQL statements:
60941 **
60942 **       A LIKE B
60943 **
60944 ** is implemented as like(B,A).
60945 **
60946 ** This same function (with a different compareInfo structure) computes
60947 ** the GLOB operator.
60948 */
60949 static void likeFunc(
60950   sqlite3_context *context, 
60951   int argc, 
60952   sqlite3_value **argv
60953 ){
60954   const unsigned char *zA, *zB;
60955   int escape = 0;
60956   sqlite3 *db = sqlite3_context_db_handle(context);
60957
60958   zB = sqlite3_value_text(argv[0]);
60959   zA = sqlite3_value_text(argv[1]);
60960
60961   /* Limit the length of the LIKE or GLOB pattern to avoid problems
60962   ** of deep recursion and N*N behavior in patternCompare().
60963   */
60964   if( sqlite3_value_bytes(argv[0]) >
60965         db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
60966     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
60967     return;
60968   }
60969   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
60970
60971   if( argc==3 ){
60972     /* The escape character string must consist of a single UTF-8 character.
60973     ** Otherwise, return an error.
60974     */
60975     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
60976     if( zEsc==0 ) return;
60977     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
60978       sqlite3_result_error(context, 
60979           "ESCAPE expression must be a single character", -1);
60980       return;
60981     }
60982     escape = sqlite3Utf8Read(zEsc, 0, &zEsc);
60983   }
60984   if( zA && zB ){
60985     struct compareInfo *pInfo = sqlite3_user_data(context);
60986 #ifdef SQLITE_TEST
60987     sqlite3_like_count++;
60988 #endif
60989     
60990     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
60991   }
60992 }
60993
60994 /*
60995 ** Implementation of the NULLIF(x,y) function.  The result is the first
60996 ** argument if the arguments are different.  The result is NULL if the
60997 ** arguments are equal to each other.
60998 */
60999 static void nullifFunc(
61000   sqlite3_context *context,
61001   int argc,
61002   sqlite3_value **argv
61003 ){
61004   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
61005   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
61006     sqlite3_result_value(context, argv[0]);
61007   }
61008 }
61009
61010 /*
61011 ** Implementation of the VERSION(*) function.  The result is the version
61012 ** of the SQLite library that is running.
61013 */
61014 static void versionFunc(
61015   sqlite3_context *context,
61016   int argc,
61017   sqlite3_value **argv
61018 ){
61019   sqlite3_result_text(context, sqlite3_version, -1, SQLITE_STATIC);
61020 }
61021
61022 /* Array for converting from half-bytes (nybbles) into ASCII hex
61023 ** digits. */
61024 static const char hexdigits[] = {
61025   '0', '1', '2', '3', '4', '5', '6', '7',
61026   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
61027 };
61028
61029 /*
61030 ** EXPERIMENTAL - This is not an official function.  The interface may
61031 ** change.  This function may disappear.  Do not write code that depends
61032 ** on this function.
61033 **
61034 ** Implementation of the QUOTE() function.  This function takes a single
61035 ** argument.  If the argument is numeric, the return value is the same as
61036 ** the argument.  If the argument is NULL, the return value is the string
61037 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
61038 ** single-quote escapes.
61039 */
61040 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
61041   if( argc<1 ) return;
61042   switch( sqlite3_value_type(argv[0]) ){
61043     case SQLITE_NULL: {
61044       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
61045       break;
61046     }
61047     case SQLITE_INTEGER:
61048     case SQLITE_FLOAT: {
61049       sqlite3_result_value(context, argv[0]);
61050       break;
61051     }
61052     case SQLITE_BLOB: {
61053       char *zText = 0;
61054       char const *zBlob = sqlite3_value_blob(argv[0]);
61055       int nBlob = sqlite3_value_bytes(argv[0]);
61056       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
61057       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 
61058       if( zText ){
61059         int i;
61060         for(i=0; i<nBlob; i++){
61061           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
61062           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
61063         }
61064         zText[(nBlob*2)+2] = '\'';
61065         zText[(nBlob*2)+3] = '\0';
61066         zText[0] = 'X';
61067         zText[1] = '\'';
61068         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
61069         sqlite3_free(zText);
61070       }
61071       break;
61072     }
61073     case SQLITE_TEXT: {
61074       int i,j;
61075       u64 n;
61076       const unsigned char *zArg = sqlite3_value_text(argv[0]);
61077       char *z;
61078
61079       if( zArg==0 ) return;
61080       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
61081       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
61082       if( z ){
61083         z[0] = '\'';
61084         for(i=0, j=1; zArg[i]; i++){
61085           z[j++] = zArg[i];
61086           if( zArg[i]=='\'' ){
61087             z[j++] = '\'';
61088           }
61089         }
61090         z[j++] = '\'';
61091         z[j] = 0;
61092         sqlite3_result_text(context, z, j, sqlite3_free);
61093       }
61094     }
61095   }
61096 }
61097
61098 /*
61099 ** The hex() function.  Interpret the argument as a blob.  Return
61100 ** a hexadecimal rendering as text.
61101 */
61102 static void hexFunc(
61103   sqlite3_context *context,
61104   int argc,
61105   sqlite3_value **argv
61106 ){
61107   int i, n;
61108   const unsigned char *pBlob;
61109   char *zHex, *z;
61110   assert( argc==1 );
61111   pBlob = sqlite3_value_blob(argv[0]);
61112   n = sqlite3_value_bytes(argv[0]);
61113   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
61114   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
61115   if( zHex ){
61116     for(i=0; i<n; i++, pBlob++){
61117       unsigned char c = *pBlob;
61118       *(z++) = hexdigits[(c>>4)&0xf];
61119       *(z++) = hexdigits[c&0xf];
61120     }
61121     *z = 0;
61122     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
61123   }
61124 }
61125
61126 /*
61127 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
61128 */
61129 static void zeroblobFunc(
61130   sqlite3_context *context,
61131   int argc,
61132   sqlite3_value **argv
61133 ){
61134   i64 n;
61135   assert( argc==1 );
61136   n = sqlite3_value_int64(argv[0]);
61137   if( n>SQLITE_MAX_LENGTH ){
61138     sqlite3_result_error_toobig(context);
61139   }else{
61140     sqlite3_result_zeroblob(context, n);
61141   }
61142 }
61143
61144 /*
61145 ** The replace() function.  Three arguments are all strings: call
61146 ** them A, B, and C. The result is also a string which is derived
61147 ** from A by replacing every occurance of B with C.  The match
61148 ** must be exact.  Collating sequences are not used.
61149 */
61150 static void replaceFunc(
61151   sqlite3_context *context,
61152   int argc,
61153   sqlite3_value **argv
61154 ){
61155   const unsigned char *zStr;        /* The input string A */
61156   const unsigned char *zPattern;    /* The pattern string B */
61157   const unsigned char *zRep;        /* The replacement string C */
61158   unsigned char *zOut;              /* The output */
61159   int nStr;                /* Size of zStr */
61160   int nPattern;            /* Size of zPattern */
61161   int nRep;                /* Size of zRep */
61162   i64 nOut;                /* Maximum size of zOut */
61163   int loopLimit;           /* Last zStr[] that might match zPattern[] */
61164   int i, j;                /* Loop counters */
61165
61166   assert( argc==3 );
61167   zStr = sqlite3_value_text(argv[0]);
61168   if( zStr==0 ) return;
61169   nStr = sqlite3_value_bytes(argv[0]);
61170   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
61171   zPattern = sqlite3_value_text(argv[1]);
61172   if( zPattern==0 || zPattern[0]==0 ) return;
61173   nPattern = sqlite3_value_bytes(argv[1]);
61174   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
61175   zRep = sqlite3_value_text(argv[2]);
61176   if( zRep==0 ) return;
61177   nRep = sqlite3_value_bytes(argv[2]);
61178   assert( zRep==sqlite3_value_text(argv[2]) );
61179   nOut = nStr + 1;
61180   assert( nOut<SQLITE_MAX_LENGTH );
61181   zOut = contextMalloc(context, (i64)nOut);
61182   if( zOut==0 ){
61183     return;
61184   }
61185   loopLimit = nStr - nPattern;  
61186   for(i=j=0; i<=loopLimit; i++){
61187     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
61188       zOut[j++] = zStr[i];
61189     }else{
61190       u8 *zOld;
61191       sqlite3 *db = sqlite3_context_db_handle(context);
61192       nOut += nRep - nPattern;
61193       if( nOut>=db->aLimit[SQLITE_LIMIT_LENGTH] ){
61194         sqlite3_result_error_toobig(context);
61195         sqlite3DbFree(db, zOut);
61196         return;
61197       }
61198       zOld = zOut;
61199       zOut = sqlite3_realloc(zOut, (int)nOut);
61200       if( zOut==0 ){
61201         sqlite3_result_error_nomem(context);
61202         sqlite3DbFree(db, zOld);
61203         return;
61204       }
61205       memcpy(&zOut[j], zRep, nRep);
61206       j += nRep;
61207       i += nPattern-1;
61208     }
61209   }
61210   assert( j+nStr-i+1==nOut );
61211   memcpy(&zOut[j], &zStr[i], nStr-i);
61212   j += nStr - i;
61213   assert( j<=nOut );
61214   zOut[j] = 0;
61215   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
61216 }
61217
61218 /*
61219 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
61220 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
61221 */
61222 static void trimFunc(
61223   sqlite3_context *context,
61224   int argc,
61225   sqlite3_value **argv
61226 ){
61227   const unsigned char *zIn;         /* Input string */
61228   const unsigned char *zCharSet;    /* Set of characters to trim */
61229   int nIn;                          /* Number of bytes in input */
61230   int flags;                        /* 1: trimleft  2: trimright  3: trim */
61231   int i;                            /* Loop counter */
61232   unsigned char *aLen;              /* Length of each character in zCharSet */
61233   unsigned char **azChar;           /* Individual characters in zCharSet */
61234   int nChar;                        /* Number of characters in zCharSet */
61235
61236   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
61237     return;
61238   }
61239   zIn = sqlite3_value_text(argv[0]);
61240   if( zIn==0 ) return;
61241   nIn = sqlite3_value_bytes(argv[0]);
61242   assert( zIn==sqlite3_value_text(argv[0]) );
61243   if( argc==1 ){
61244     static const unsigned char lenOne[] = { 1 };
61245     static const unsigned char *azOne[] = { (u8*)" " };
61246     nChar = 1;
61247     aLen = (u8*)lenOne;
61248     azChar = (unsigned char **)azOne;
61249     zCharSet = 0;
61250   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
61251     return;
61252   }else{
61253     const unsigned char *z;
61254     for(z=zCharSet, nChar=0; *z; nChar++){
61255       SQLITE_SKIP_UTF8(z);
61256     }
61257     if( nChar>0 ){
61258       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
61259       if( azChar==0 ){
61260         return;
61261       }
61262       aLen = (unsigned char*)&azChar[nChar];
61263       for(z=zCharSet, nChar=0; *z; nChar++){
61264         azChar[nChar] = (unsigned char *)z;
61265         SQLITE_SKIP_UTF8(z);
61266         aLen[nChar] = z - azChar[nChar];
61267       }
61268     }
61269   }
61270   if( nChar>0 ){
61271     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
61272     if( flags & 1 ){
61273       while( nIn>0 ){
61274         int len;
61275         for(i=0; i<nChar; i++){
61276           len = aLen[i];
61277           if( memcmp(zIn, azChar[i], len)==0 ) break;
61278         }
61279         if( i>=nChar ) break;
61280         zIn += len;
61281         nIn -= len;
61282       }
61283     }
61284     if( flags & 2 ){
61285       while( nIn>0 ){
61286         int len;
61287         for(i=0; i<nChar; i++){
61288           len = aLen[i];
61289           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
61290         }
61291         if( i>=nChar ) break;
61292         nIn -= len;
61293       }
61294     }
61295     if( zCharSet ){
61296       sqlite3_free(azChar);
61297     }
61298   }
61299   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
61300 }
61301
61302 #ifdef SQLITE_SOUNDEX
61303 /*
61304 ** Compute the soundex encoding of a word.
61305 */
61306 static void soundexFunc(
61307   sqlite3_context *context,
61308   int argc,
61309   sqlite3_value **argv
61310 ){
61311   char zResult[8];
61312   const u8 *zIn;
61313   int i, j;
61314   static const unsigned char iCode[] = {
61315     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
61316     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
61317     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
61318     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
61319     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
61320     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
61321     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
61322     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
61323   };
61324   assert( argc==1 );
61325   zIn = (u8*)sqlite3_value_text(argv[0]);
61326   if( zIn==0 ) zIn = (u8*)"";
61327   for(i=0; zIn[i] && !isalpha(zIn[i]); i++){}
61328   if( zIn[i] ){
61329     u8 prevcode = iCode[zIn[i]&0x7f];
61330     zResult[0] = toupper(zIn[i]);
61331     for(j=1; j<4 && zIn[i]; i++){
61332       int code = iCode[zIn[i]&0x7f];
61333       if( code>0 ){
61334         if( code!=prevcode ){
61335           prevcode = code;
61336           zResult[j++] = code + '0';
61337         }
61338       }else{
61339         prevcode = 0;
61340       }
61341     }
61342     while( j<4 ){
61343       zResult[j++] = '0';
61344     }
61345     zResult[j] = 0;
61346     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
61347   }else{
61348     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
61349   }
61350 }
61351 #endif
61352
61353 #ifndef SQLITE_OMIT_LOAD_EXTENSION
61354 /*
61355 ** A function that loads a shared-library extension then returns NULL.
61356 */
61357 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
61358   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
61359   const char *zProc;
61360   sqlite3 *db = sqlite3_context_db_handle(context);
61361   char *zErrMsg = 0;
61362
61363   if( argc==2 ){
61364     zProc = (const char *)sqlite3_value_text(argv[1]);
61365   }else{
61366     zProc = 0;
61367   }
61368   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
61369     sqlite3_result_error(context, zErrMsg, -1);
61370     sqlite3_free(zErrMsg);
61371   }
61372 }
61373 #endif
61374
61375
61376 /*
61377 ** An instance of the following structure holds the context of a
61378 ** sum() or avg() aggregate computation.
61379 */
61380 typedef struct SumCtx SumCtx;
61381 struct SumCtx {
61382   double rSum;      /* Floating point sum */
61383   i64 iSum;         /* Integer sum */   
61384   i64 cnt;          /* Number of elements summed */
61385   u8 overflow;      /* True if integer overflow seen */
61386   u8 approx;        /* True if non-integer value was input to the sum */
61387 };
61388
61389 /*
61390 ** Routines used to compute the sum, average, and total.
61391 **
61392 ** The SUM() function follows the (broken) SQL standard which means
61393 ** that it returns NULL if it sums over no inputs.  TOTAL returns
61394 ** 0.0 in that case.  In addition, TOTAL always returns a float where
61395 ** SUM might return an integer if it never encounters a floating point
61396 ** value.  TOTAL never fails, but SUM might through an exception if
61397 ** it overflows an integer.
61398 */
61399 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
61400   SumCtx *p;
61401   int type;
61402   assert( argc==1 );
61403   p = sqlite3_aggregate_context(context, sizeof(*p));
61404   type = sqlite3_value_numeric_type(argv[0]);
61405   if( p && type!=SQLITE_NULL ){
61406     p->cnt++;
61407     if( type==SQLITE_INTEGER ){
61408       i64 v = sqlite3_value_int64(argv[0]);
61409       p->rSum += v;
61410       if( (p->approx|p->overflow)==0 ){
61411         i64 iNewSum = p->iSum + v;
61412         int s1 = p->iSum >> (sizeof(i64)*8-1);
61413         int s2 = v       >> (sizeof(i64)*8-1);
61414         int s3 = iNewSum >> (sizeof(i64)*8-1);
61415         p->overflow = (s1&s2&~s3) | (~s1&~s2&s3);
61416         p->iSum = iNewSum;
61417       }
61418     }else{
61419       p->rSum += sqlite3_value_double(argv[0]);
61420       p->approx = 1;
61421     }
61422   }
61423 }
61424 static void sumFinalize(sqlite3_context *context){
61425   SumCtx *p;
61426   p = sqlite3_aggregate_context(context, 0);
61427   if( p && p->cnt>0 ){
61428     if( p->overflow ){
61429       sqlite3_result_error(context,"integer overflow",-1);
61430     }else if( p->approx ){
61431       sqlite3_result_double(context, p->rSum);
61432     }else{
61433       sqlite3_result_int64(context, p->iSum);
61434     }
61435   }
61436 }
61437 static void avgFinalize(sqlite3_context *context){
61438   SumCtx *p;
61439   p = sqlite3_aggregate_context(context, 0);
61440   if( p && p->cnt>0 ){
61441     sqlite3_result_double(context, p->rSum/(double)p->cnt);
61442   }
61443 }
61444 static void totalFinalize(sqlite3_context *context){
61445   SumCtx *p;
61446   p = sqlite3_aggregate_context(context, 0);
61447   sqlite3_result_double(context, p ? p->rSum : 0.0);
61448 }
61449
61450 /*
61451 ** The following structure keeps track of state information for the
61452 ** count() aggregate function.
61453 */
61454 typedef struct CountCtx CountCtx;
61455 struct CountCtx {
61456   i64 n;
61457 };
61458
61459 /*
61460 ** Routines to implement the count() aggregate function.
61461 */
61462 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
61463   CountCtx *p;
61464   p = sqlite3_aggregate_context(context, sizeof(*p));
61465   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
61466     p->n++;
61467   }
61468 }   
61469 static void countFinalize(sqlite3_context *context){
61470   CountCtx *p;
61471   p = sqlite3_aggregate_context(context, 0);
61472   sqlite3_result_int64(context, p ? p->n : 0);
61473 }
61474
61475 /*
61476 ** Routines to implement min() and max() aggregate functions.
61477 */
61478 static void minmaxStep(sqlite3_context *context, int argc, sqlite3_value **argv){
61479   Mem *pArg  = (Mem *)argv[0];
61480   Mem *pBest;
61481
61482   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
61483   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
61484   if( !pBest ) return;
61485
61486   if( pBest->flags ){
61487     int max;
61488     int cmp;
61489     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
61490     /* This step function is used for both the min() and max() aggregates,
61491     ** the only difference between the two being that the sense of the
61492     ** comparison is inverted. For the max() aggregate, the
61493     ** sqlite3_user_data() function returns (void *)-1. For min() it
61494     ** returns (void *)db, where db is the sqlite3* database pointer.
61495     ** Therefore the next statement sets variable 'max' to 1 for the max()
61496     ** aggregate, or 0 for min().
61497     */
61498     max = sqlite3_user_data(context)!=0;
61499     cmp = sqlite3MemCompare(pBest, pArg, pColl);
61500     if( (max && cmp<0) || (!max && cmp>0) ){
61501       sqlite3VdbeMemCopy(pBest, pArg);
61502     }
61503   }else{
61504     sqlite3VdbeMemCopy(pBest, pArg);
61505   }
61506 }
61507 static void minMaxFinalize(sqlite3_context *context){
61508   sqlite3_value *pRes;
61509   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
61510   if( pRes ){
61511     if( pRes->flags ){
61512       sqlite3_result_value(context, pRes);
61513     }
61514     sqlite3VdbeMemRelease(pRes);
61515   }
61516 }
61517
61518 /*
61519 ** group_concat(EXPR, ?SEPARATOR?)
61520 */
61521 static void groupConcatStep(
61522   sqlite3_context *context,
61523   int argc,
61524   sqlite3_value **argv
61525 ){
61526   const char *zVal;
61527   StrAccum *pAccum;
61528   const char *zSep;
61529   int nVal, nSep, i;
61530   if( argc==0 || sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
61531   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
61532
61533   if( pAccum ){
61534     sqlite3 *db = sqlite3_context_db_handle(context);
61535     pAccum->useMalloc = 1;
61536     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
61537     if( pAccum->nChar ){
61538       if( argc>1 ){
61539         zSep = (char*)sqlite3_value_text(argv[argc-1]);
61540         nSep = sqlite3_value_bytes(argv[argc-1]);
61541       }else{
61542         zSep = ",";
61543         nSep = 1;
61544       }
61545       sqlite3StrAccumAppend(pAccum, zSep, nSep);
61546     }
61547     i = 0;
61548     do{
61549       zVal = (char*)sqlite3_value_text(argv[i]);
61550       nVal = sqlite3_value_bytes(argv[i]);
61551       sqlite3StrAccumAppend(pAccum, zVal, nVal);
61552       i++;
61553     }while( i<argc-1 );
61554   }
61555 }
61556 static void groupConcatFinalize(sqlite3_context *context){
61557   StrAccum *pAccum;
61558   pAccum = sqlite3_aggregate_context(context, 0);
61559   if( pAccum ){
61560     if( pAccum->tooBig ){
61561       sqlite3_result_error_toobig(context);
61562     }else if( pAccum->mallocFailed ){
61563       sqlite3_result_error_nomem(context);
61564     }else{    
61565       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
61566                           sqlite3_free);
61567     }
61568   }
61569 }
61570
61571 /*
61572 ** This function registered all of the above C functions as SQL
61573 ** functions.  This should be the only routine in this file with
61574 ** external linkage.
61575 */
61576 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
61577   static const struct {
61578      char *zName;
61579      signed char nArg;
61580      u8 argType;           /* 1: 0, 2: 1, 3: 2,...  N:  N-1. */
61581      u8 eTextRep;          /* 1: UTF-16.  0: UTF-8 */
61582      u8 needCollSeq;
61583      void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
61584   } aFuncs[] = {
61585     { "min",               -1, 0, SQLITE_UTF8,    1, minmaxFunc },
61586     { "min",                0, 0, SQLITE_UTF8,    1, 0          },
61587     { "max",               -1, 1, SQLITE_UTF8,    1, minmaxFunc },
61588     { "max",                0, 1, SQLITE_UTF8,    1, 0          },
61589     { "typeof",             1, 0, SQLITE_UTF8,    0, typeofFunc },
61590     { "length",             1, 0, SQLITE_UTF8,    0, lengthFunc },
61591     { "substr",             2, 0, SQLITE_UTF8,    0, substrFunc },
61592     { "substr",             3, 0, SQLITE_UTF8,    0, substrFunc },
61593     { "abs",                1, 0, SQLITE_UTF8,    0, absFunc    },
61594     { "round",              1, 0, SQLITE_UTF8,    0, roundFunc  },
61595     { "round",              2, 0, SQLITE_UTF8,    0, roundFunc  },
61596     { "upper",              1, 0, SQLITE_UTF8,    0, upperFunc  },
61597     { "lower",              1, 0, SQLITE_UTF8,    0, lowerFunc  },
61598     { "coalesce",          -1, 0, SQLITE_UTF8,    0, ifnullFunc },
61599     { "coalesce",           0, 0, SQLITE_UTF8,    0, 0          },
61600     { "coalesce",           1, 0, SQLITE_UTF8,    0, 0          },
61601     { "hex",                1, 0, SQLITE_UTF8,    0, hexFunc    },
61602     { "ifnull",             2, 0, SQLITE_UTF8,    1, ifnullFunc },
61603     { "random",            -1, 0, SQLITE_UTF8,    0, randomFunc },
61604     { "randomblob",         1, 0, SQLITE_UTF8,    0, randomBlob },
61605     { "nullif",             2, 0, SQLITE_UTF8,    1, nullifFunc },
61606     { "sqlite_version",     0, 0, SQLITE_UTF8,    0, versionFunc},
61607     { "quote",              1, 0, SQLITE_UTF8,    0, quoteFunc  },
61608     { "last_insert_rowid",  0, 0, SQLITE_UTF8, 0, last_insert_rowid },
61609     { "changes",            0, 0, SQLITE_UTF8, 0, changes           },
61610     { "total_changes",      0, 0, SQLITE_UTF8, 0, total_changes     },
61611     { "replace",            3, 0, SQLITE_UTF8,    0, replaceFunc       },
61612     { "ltrim",              1, 1, SQLITE_UTF8,    0, trimFunc          },
61613     { "ltrim",              2, 1, SQLITE_UTF8,    0, trimFunc          },
61614     { "rtrim",              1, 2, SQLITE_UTF8,    0, trimFunc          },
61615     { "rtrim",              2, 2, SQLITE_UTF8,    0, trimFunc          },
61616     { "trim",               1, 3, SQLITE_UTF8,    0, trimFunc          },
61617     { "trim",               2, 3, SQLITE_UTF8,    0, trimFunc          },
61618     { "zeroblob",           1, 0, SQLITE_UTF8,    0, zeroblobFunc      },
61619 #ifdef SQLITE_SOUNDEX
61620     { "soundex",            1, 0, SQLITE_UTF8,    0, soundexFunc},
61621 #endif
61622 #ifndef SQLITE_OMIT_LOAD_EXTENSION
61623     { "load_extension",     1, 0, SQLITE_UTF8, 0, loadExt },
61624     { "load_extension",     2, 0, SQLITE_UTF8, 0, loadExt },
61625 #endif
61626   };
61627   static const struct {
61628     char *zName;
61629     signed char nArg;
61630     u8 argType;
61631     u8 needCollSeq;
61632     void (*xStep)(sqlite3_context*,int,sqlite3_value**);
61633     void (*xFinalize)(sqlite3_context*);
61634   } aAggs[] = {
61635     { "min",    1, 0, 1, minmaxStep,   minMaxFinalize },
61636     { "max",    1, 1, 1, minmaxStep,   minMaxFinalize },
61637     { "sum",    1, 0, 0, sumStep,      sumFinalize    },
61638     { "total",  1, 0, 0, sumStep,      totalFinalize    },
61639     { "avg",    1, 0, 0, sumStep,      avgFinalize    },
61640     { "count",  0, 0, 0, countStep,    countFinalize  },
61641     { "count",  1, 0, 0, countStep,    countFinalize  },
61642     { "group_concat", -1, 0, 0, groupConcatStep, groupConcatFinalize },
61643   };
61644   int i;
61645
61646   for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
61647     void *pArg;
61648     u8 argType = aFuncs[i].argType;
61649     pArg = SQLITE_INT_TO_PTR(argType);
61650     sqlite3CreateFunc(db, aFuncs[i].zName, aFuncs[i].nArg,
61651         aFuncs[i].eTextRep, pArg, aFuncs[i].xFunc, 0, 0);
61652     if( aFuncs[i].needCollSeq ){
61653       FuncDef *pFunc = sqlite3FindFunction(db, aFuncs[i].zName, 
61654           strlen(aFuncs[i].zName), aFuncs[i].nArg, aFuncs[i].eTextRep, 0);
61655       if( pFunc && aFuncs[i].needCollSeq ){
61656         pFunc->needCollSeq = 1;
61657       }
61658     }
61659   }
61660 #ifndef SQLITE_OMIT_ALTERTABLE
61661   sqlite3AlterFunctions(db);
61662 #endif
61663 #ifndef SQLITE_OMIT_PARSER
61664   sqlite3AttachFunctions(db);
61665 #endif
61666   for(i=0; i<sizeof(aAggs)/sizeof(aAggs[0]); i++){
61667     void *pArg = SQLITE_INT_TO_PTR(aAggs[i].argType);
61668     sqlite3CreateFunc(db, aAggs[i].zName, aAggs[i].nArg, SQLITE_UTF8, 
61669         pArg, 0, aAggs[i].xStep, aAggs[i].xFinalize);
61670     if( aAggs[i].needCollSeq ){
61671       FuncDef *pFunc = sqlite3FindFunction( db, aAggs[i].zName,
61672           strlen(aAggs[i].zName), aAggs[i].nArg, SQLITE_UTF8, 0);
61673       if( pFunc && aAggs[i].needCollSeq ){
61674         pFunc->needCollSeq = 1;
61675       }
61676     }
61677   }
61678   sqlite3RegisterDateTimeFunctions(db);
61679   if( !db->mallocFailed ){
61680     int rc = sqlite3_overload_function(db, "MATCH", 2);
61681     assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
61682     if( rc==SQLITE_NOMEM ){
61683       db->mallocFailed = 1;
61684     }
61685   }
61686 #ifdef SQLITE_SSE
61687   (void)sqlite3SseFunctions(db);
61688 #endif
61689 #ifdef SQLITE_CASE_SENSITIVE_LIKE
61690   sqlite3RegisterLikeFunctions(db, 1);
61691 #else
61692   sqlite3RegisterLikeFunctions(db, 0);
61693 #endif
61694 }
61695
61696 /*
61697 ** Set the LIKEOPT flag on the 2-argument function with the given name.
61698 */
61699 static void setLikeOptFlag(sqlite3 *db, const char *zName, int flagVal){
61700   FuncDef *pDef;
61701   pDef = sqlite3FindFunction(db, zName, strlen(zName), 2, SQLITE_UTF8, 0);
61702   if( pDef ){
61703     pDef->flags = flagVal;
61704   }
61705 }
61706
61707 /*
61708 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
61709 ** parameter determines whether or not the LIKE operator is case
61710 ** sensitive.  GLOB is always case sensitive.
61711 */
61712 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
61713   struct compareInfo *pInfo;
61714   if( caseSensitive ){
61715     pInfo = (struct compareInfo*)&likeInfoAlt;
61716   }else{
61717     pInfo = (struct compareInfo*)&likeInfoNorm;
61718   }
61719   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
61720   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
61721   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8, 
61722       (struct compareInfo*)&globInfo, likeFunc, 0,0);
61723   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
61724   setLikeOptFlag(db, "like", 
61725       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
61726 }
61727
61728 /*
61729 ** pExpr points to an expression which implements a function.  If
61730 ** it is appropriate to apply the LIKE optimization to that function
61731 ** then set aWc[0] through aWc[2] to the wildcard characters and
61732 ** return TRUE.  If the function is not a LIKE-style function then
61733 ** return FALSE.
61734 */
61735 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
61736   FuncDef *pDef;
61737   if( pExpr->op!=TK_FUNCTION || !pExpr->pList ){
61738     return 0;
61739   }
61740   if( pExpr->pList->nExpr!=2 ){
61741     return 0;
61742   }
61743   pDef = sqlite3FindFunction(db, (char*)pExpr->token.z, pExpr->token.n, 2,
61744                              SQLITE_UTF8, 0);
61745   if( pDef==0 || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
61746     return 0;
61747   }
61748
61749   /* The memcpy() statement assumes that the wildcard characters are
61750   ** the first three statements in the compareInfo structure.  The
61751   ** asserts() that follow verify that assumption
61752   */
61753   memcpy(aWc, pDef->pUserData, 3);
61754   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
61755   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
61756   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
61757   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
61758   return 1;
61759 }
61760
61761 /************** End of func.c ************************************************/
61762 /************** Begin file insert.c ******************************************/
61763 /*
61764 ** 2001 September 15
61765 **
61766 ** The author disclaims copyright to this source code.  In place of
61767 ** a legal notice, here is a blessing:
61768 **
61769 **    May you do good and not evil.
61770 **    May you find forgiveness for yourself and forgive others.
61771 **    May you share freely, never taking more than you give.
61772 **
61773 *************************************************************************
61774 ** This file contains C code routines that are called by the parser
61775 ** to handle INSERT statements in SQLite.
61776 **
61777 ** $Id: insert.c,v 1.248 2008/07/28 19:34:53 drh Exp $
61778 */
61779
61780 /*
61781 ** Set P4 of the most recently inserted opcode to a column affinity
61782 ** string for index pIdx. A column affinity string has one character
61783 ** for each column in the table, according to the affinity of the column:
61784 **
61785 **  Character      Column affinity
61786 **  ------------------------------
61787 **  'a'            TEXT
61788 **  'b'            NONE
61789 **  'c'            NUMERIC
61790 **  'd'            INTEGER
61791 **  'e'            REAL
61792 **
61793 ** An extra 'b' is appended to the end of the string to cover the
61794 ** rowid that appears as the last column in every index.
61795 */
61796 SQLITE_PRIVATE void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
61797   if( !pIdx->zColAff ){
61798     /* The first time a column affinity string for a particular index is
61799     ** required, it is allocated and populated here. It is then stored as
61800     ** a member of the Index structure for subsequent use.
61801     **
61802     ** The column affinity string will eventually be deleted by
61803     ** sqliteDeleteIndex() when the Index structure itself is cleaned
61804     ** up.
61805     */
61806     int n;
61807     Table *pTab = pIdx->pTable;
61808     sqlite3 *db = sqlite3VdbeDb(v);
61809     pIdx->zColAff = (char *)sqlite3Malloc(pIdx->nColumn+2);
61810     if( !pIdx->zColAff ){
61811       db->mallocFailed = 1;
61812       return;
61813     }
61814     for(n=0; n<pIdx->nColumn; n++){
61815       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
61816     }
61817     pIdx->zColAff[n++] = SQLITE_AFF_NONE;
61818     pIdx->zColAff[n] = 0;
61819   }
61820  
61821   sqlite3VdbeChangeP4(v, -1, pIdx->zColAff, 0);
61822 }
61823
61824 /*
61825 ** Set P4 of the most recently inserted opcode to a column affinity
61826 ** string for table pTab. A column affinity string has one character
61827 ** for each column indexed by the index, according to the affinity of the
61828 ** column:
61829 **
61830 **  Character      Column affinity
61831 **  ------------------------------
61832 **  'a'            TEXT
61833 **  'b'            NONE
61834 **  'c'            NUMERIC
61835 **  'd'            INTEGER
61836 **  'e'            REAL
61837 */
61838 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
61839   /* The first time a column affinity string for a particular table
61840   ** is required, it is allocated and populated here. It is then 
61841   ** stored as a member of the Table structure for subsequent use.
61842   **
61843   ** The column affinity string will eventually be deleted by
61844   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
61845   */
61846   if( !pTab->zColAff ){
61847     char *zColAff;
61848     int i;
61849     sqlite3 *db = sqlite3VdbeDb(v);
61850
61851     zColAff = (char *)sqlite3Malloc(pTab->nCol+1);
61852     if( !zColAff ){
61853       db->mallocFailed = 1;
61854       return;
61855     }
61856
61857     for(i=0; i<pTab->nCol; i++){
61858       zColAff[i] = pTab->aCol[i].affinity;
61859     }
61860     zColAff[pTab->nCol] = '\0';
61861
61862     pTab->zColAff = zColAff;
61863   }
61864
61865   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
61866 }
61867
61868 /*
61869 ** Return non-zero if the table pTab in database iDb or any of its indices
61870 ** have been opened at any point in the VDBE program beginning at location
61871 ** iStartAddr throught the end of the program.  This is used to see if 
61872 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
61873 ** run without using temporary table for the results of the SELECT. 
61874 */
61875 static int readsTable(Vdbe *v, int iStartAddr, int iDb, Table *pTab){
61876   int i;
61877   int iEnd = sqlite3VdbeCurrentAddr(v);
61878   for(i=iStartAddr; i<iEnd; i++){
61879     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
61880     assert( pOp!=0 );
61881     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
61882       Index *pIndex;
61883       int tnum = pOp->p2;
61884       if( tnum==pTab->tnum ){
61885         return 1;
61886       }
61887       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
61888         if( tnum==pIndex->tnum ){
61889           return 1;
61890         }
61891       }
61892     }
61893 #ifndef SQLITE_OMIT_VIRTUALTABLE
61894     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pTab->pVtab ){
61895       assert( pOp->p4.pVtab!=0 );
61896       assert( pOp->p4type==P4_VTAB );
61897       return 1;
61898     }
61899 #endif
61900   }
61901   return 0;
61902 }
61903
61904 #ifndef SQLITE_OMIT_AUTOINCREMENT
61905 /*
61906 ** Write out code to initialize the autoincrement logic.  This code
61907 ** looks up the current autoincrement value in the sqlite_sequence
61908 ** table and stores that value in a register.  Code generated by
61909 ** autoIncStep() will keep that register holding the largest
61910 ** rowid value.  Code generated by autoIncEnd() will write the new
61911 ** largest value of the counter back into the sqlite_sequence table.
61912 **
61913 ** This routine returns the index of the mem[] cell that contains
61914 ** the maximum rowid counter.
61915 **
61916 ** Three consecutive registers are allocated by this routine.  The
61917 ** first two hold the name of the target table and the maximum rowid 
61918 ** inserted into the target table, respectively.
61919 ** The third holds the rowid in sqlite_sequence where we will
61920 ** write back the revised maximum rowid.  This routine returns the
61921 ** index of the second of these three registers.
61922 */
61923 static int autoIncBegin(
61924   Parse *pParse,      /* Parsing context */
61925   int iDb,            /* Index of the database holding pTab */
61926   Table *pTab         /* The table we are writing to */
61927 ){
61928   int memId = 0;      /* Register holding maximum rowid */
61929   if( pTab->autoInc ){
61930     Vdbe *v = pParse->pVdbe;
61931     Db *pDb = &pParse->db->aDb[iDb];
61932     int iCur = pParse->nTab;
61933     int addr;               /* Address of the top of the loop */
61934     assert( v );
61935     pParse->nMem++;         /* Holds name of table */
61936     memId = ++pParse->nMem;
61937     pParse->nMem++;
61938     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
61939     addr = sqlite3VdbeCurrentAddr(v);
61940     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, pTab->zName, 0);
61941     sqlite3VdbeAddOp2(v, OP_Rewind, iCur, addr+9);
61942     sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, memId);
61943     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
61944     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
61945     sqlite3VdbeAddOp2(v, OP_Rowid, iCur, memId+1);
61946     sqlite3VdbeAddOp3(v, OP_Column, iCur, 1, memId);
61947     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
61948     sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+2);
61949     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
61950     sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
61951   }
61952   return memId;
61953 }
61954
61955 /*
61956 ** Update the maximum rowid for an autoincrement calculation.
61957 **
61958 ** This routine should be called when the top of the stack holds a
61959 ** new rowid that is about to be inserted.  If that new rowid is
61960 ** larger than the maximum rowid in the memId memory cell, then the
61961 ** memory cell is updated.  The stack is unchanged.
61962 */
61963 static void autoIncStep(Parse *pParse, int memId, int regRowid){
61964   if( memId>0 ){
61965     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
61966   }
61967 }
61968
61969 /*
61970 ** After doing one or more inserts, the maximum rowid is stored
61971 ** in reg[memId].  Generate code to write this value back into the
61972 ** the sqlite_sequence table.
61973 */
61974 static void autoIncEnd(
61975   Parse *pParse,     /* The parsing context */
61976   int iDb,           /* Index of the database holding pTab */
61977   Table *pTab,       /* Table we are inserting into */
61978   int memId          /* Memory cell holding the maximum rowid */
61979 ){
61980   if( pTab->autoInc ){
61981     int iCur = pParse->nTab;
61982     Vdbe *v = pParse->pVdbe;
61983     Db *pDb = &pParse->db->aDb[iDb];
61984     int j1;
61985     int iRec = ++pParse->nMem;    /* Memory cell used for record */
61986
61987     assert( v );
61988     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
61989     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
61990     sqlite3VdbeAddOp2(v, OP_NewRowid, iCur, memId+1);
61991     sqlite3VdbeJumpHere(v, j1);
61992     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
61993     sqlite3VdbeAddOp3(v, OP_Insert, iCur, iRec, memId+1);
61994     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
61995     sqlite3VdbeAddOp1(v, OP_Close, iCur);
61996   }
61997 }
61998 #else
61999 /*
62000 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
62001 ** above are all no-ops
62002 */
62003 # define autoIncBegin(A,B,C) (0)
62004 # define autoIncStep(A,B,C)
62005 # define autoIncEnd(A,B,C,D)
62006 #endif /* SQLITE_OMIT_AUTOINCREMENT */
62007
62008
62009 /* Forward declaration */
62010 static int xferOptimization(
62011   Parse *pParse,        /* Parser context */
62012   Table *pDest,         /* The table we are inserting into */
62013   Select *pSelect,      /* A SELECT statement to use as the data source */
62014   int onError,          /* How to handle constraint errors */
62015   int iDbDest           /* The database of pDest */
62016 );
62017
62018 /*
62019 ** This routine is call to handle SQL of the following forms:
62020 **
62021 **    insert into TABLE (IDLIST) values(EXPRLIST)
62022 **    insert into TABLE (IDLIST) select
62023 **
62024 ** The IDLIST following the table name is always optional.  If omitted,
62025 ** then a list of all columns for the table is substituted.  The IDLIST
62026 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
62027 **
62028 ** The pList parameter holds EXPRLIST in the first form of the INSERT
62029 ** statement above, and pSelect is NULL.  For the second form, pList is
62030 ** NULL and pSelect is a pointer to the select statement used to generate
62031 ** data for the insert.
62032 **
62033 ** The code generated follows one of four templates.  For a simple
62034 ** select with data coming from a VALUES clause, the code executes
62035 ** once straight down through.  Pseudo-code follows (we call this
62036 ** the "1st template"):
62037 **
62038 **         open write cursor to <table> and its indices
62039 **         puts VALUES clause expressions onto the stack
62040 **         write the resulting record into <table>
62041 **         cleanup
62042 **
62043 ** The three remaining templates assume the statement is of the form
62044 **
62045 **   INSERT INTO <table> SELECT ...
62046 **
62047 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
62048 ** in other words if the SELECT pulls all columns from a single table
62049 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
62050 ** if <table2> and <table1> are distinct tables but have identical
62051 ** schemas, including all the same indices, then a special optimization
62052 ** is invoked that copies raw records from <table2> over to <table1>.
62053 ** See the xferOptimization() function for the implementation of this
62054 ** template.  This is the 2nd template.
62055 **
62056 **         open a write cursor to <table>
62057 **         open read cursor on <table2>
62058 **         transfer all records in <table2> over to <table>
62059 **         close cursors
62060 **         foreach index on <table>
62061 **           open a write cursor on the <table> index
62062 **           open a read cursor on the corresponding <table2> index
62063 **           transfer all records from the read to the write cursors
62064 **           close cursors
62065 **         end foreach
62066 **
62067 ** The 3rd template is for when the second template does not apply
62068 ** and the SELECT clause does not read from <table> at any time.
62069 ** The generated code follows this template:
62070 **
62071 **         EOF <- 0
62072 **         X <- A
62073 **         goto B
62074 **      A: setup for the SELECT
62075 **         loop over the rows in the SELECT
62076 **           load values into registers R..R+n
62077 **           yield X
62078 **         end loop
62079 **         cleanup after the SELECT
62080 **         EOF <- 1
62081 **         yield X
62082 **         goto A
62083 **      B: open write cursor to <table> and its indices
62084 **      C: yield X
62085 **         if EOF goto D
62086 **         insert the select result into <table> from R..R+n
62087 **         goto C
62088 **      D: cleanup
62089 **
62090 ** The 4th template is used if the insert statement takes its
62091 ** values from a SELECT but the data is being inserted into a table
62092 ** that is also read as part of the SELECT.  In the third form,
62093 ** we have to use a intermediate table to store the results of
62094 ** the select.  The template is like this:
62095 **
62096 **         EOF <- 0
62097 **         X <- A
62098 **         goto B
62099 **      A: setup for the SELECT
62100 **         loop over the tables in the SELECT
62101 **           load value into register R..R+n
62102 **           yield X
62103 **         end loop
62104 **         cleanup after the SELECT
62105 **         EOF <- 1
62106 **         yield X
62107 **         halt-error
62108 **      B: open temp table
62109 **      L: yield X
62110 **         if EOF goto M
62111 **         insert row from R..R+n into temp table
62112 **         goto L
62113 **      M: open write cursor to <table> and its indices
62114 **         rewind temp table
62115 **      C: loop over rows of intermediate table
62116 **           transfer values form intermediate table into <table>
62117 **         end loop
62118 **      D: cleanup
62119 */
62120 SQLITE_PRIVATE void sqlite3Insert(
62121   Parse *pParse,        /* Parser context */
62122   SrcList *pTabList,    /* Name of table into which we are inserting */
62123   ExprList *pList,      /* List of values to be inserted */
62124   Select *pSelect,      /* A SELECT statement to use as the data source */
62125   IdList *pColumn,      /* Column names corresponding to IDLIST. */
62126   int onError           /* How to handle constraint errors */
62127 ){
62128   sqlite3 *db;          /* The main database structure */
62129   Table *pTab;          /* The table to insert into.  aka TABLE */
62130   char *zTab;           /* Name of the table into which we are inserting */
62131   const char *zDb;      /* Name of the database holding this table */
62132   int i, j, idx;        /* Loop counters */
62133   Vdbe *v;              /* Generate code into this virtual machine */
62134   Index *pIdx;          /* For looping over indices of the table */
62135   int nColumn;          /* Number of columns in the data */
62136   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
62137   int baseCur = 0;      /* VDBE Cursor number for pTab */
62138   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
62139   int endOfLoop;        /* Label for the end of the insertion loop */
62140   int useTempTable = 0; /* Store SELECT results in intermediate table */
62141   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
62142   int addrInsTop = 0;   /* Jump to label "D" */
62143   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
62144   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
62145   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
62146   int newIdx = -1;      /* Cursor for the NEW pseudo-table */
62147   int iDb;              /* Index of database holding TABLE */
62148   Db *pDb;              /* The database containing table being inserted into */
62149   int appendFlag = 0;   /* True if the insert is likely to be an append */
62150
62151   /* Register allocations */
62152   int regFromSelect;    /* Base register for data coming from SELECT */
62153   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
62154   int regRowCount = 0;  /* Memory cell used for the row counter */
62155   int regIns;           /* Block of regs holding rowid+data being inserted */
62156   int regRowid;         /* registers holding insert rowid */
62157   int regData;          /* register holding first column to insert */
62158   int regRecord;        /* Holds the assemblied row record */
62159   int regEof;           /* Register recording end of SELECT data */
62160   int *aRegIdx = 0;     /* One register allocated to each index */
62161
62162
62163 #ifndef SQLITE_OMIT_TRIGGER
62164   int isView;                 /* True if attempting to insert into a view */
62165   int triggers_exist = 0;     /* True if there are FOR EACH ROW triggers */
62166 #endif
62167
62168   db = pParse->db;
62169   if( pParse->nErr || db->mallocFailed ){
62170     goto insert_cleanup;
62171   }
62172
62173   /* Locate the table into which we will be inserting new information.
62174   */
62175   assert( pTabList->nSrc==1 );
62176   zTab = pTabList->a[0].zName;
62177   if( zTab==0 ) goto insert_cleanup;
62178   pTab = sqlite3SrcListLookup(pParse, pTabList);
62179   if( pTab==0 ){
62180     goto insert_cleanup;
62181   }
62182   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
62183   assert( iDb<db->nDb );
62184   pDb = &db->aDb[iDb];
62185   zDb = pDb->zName;
62186   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
62187     goto insert_cleanup;
62188   }
62189
62190   /* Figure out if we have any triggers and if the table being
62191   ** inserted into is a view
62192   */
62193 #ifndef SQLITE_OMIT_TRIGGER
62194   triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
62195   isView = pTab->pSelect!=0;
62196 #else
62197 # define triggers_exist 0
62198 # define isView 0
62199 #endif
62200 #ifdef SQLITE_OMIT_VIEW
62201 # undef isView
62202 # define isView 0
62203 #endif
62204
62205   /* Ensure that:
62206   *  (a) the table is not read-only, 
62207   *  (b) that if it is a view then ON INSERT triggers exist
62208   */
62209   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
62210     goto insert_cleanup;
62211   }
62212   assert( pTab!=0 );
62213
62214   /* If pTab is really a view, make sure it has been initialized.
62215   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 
62216   ** module table).
62217   */
62218   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
62219     goto insert_cleanup;
62220   }
62221
62222   /* Allocate a VDBE
62223   */
62224   v = sqlite3GetVdbe(pParse);
62225   if( v==0 ) goto insert_cleanup;
62226   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
62227   sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
62228
62229   /* if there are row triggers, allocate a temp table for new.* references. */
62230   if( triggers_exist ){
62231     newIdx = pParse->nTab++;
62232   }
62233
62234 #ifndef SQLITE_OMIT_XFER_OPT
62235   /* If the statement is of the form
62236   **
62237   **       INSERT INTO <table1> SELECT * FROM <table2>;
62238   **
62239   ** Then special optimizations can be applied that make the transfer
62240   ** very fast and which reduce fragmentation of indices.
62241   **
62242   ** This is the 2nd template.
62243   */
62244   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
62245     assert( !triggers_exist );
62246     assert( pList==0 );
62247     goto insert_cleanup;
62248   }
62249 #endif /* SQLITE_OMIT_XFER_OPT */
62250
62251   /* If this is an AUTOINCREMENT table, look up the sequence number in the
62252   ** sqlite_sequence table and store it in memory cell regAutoinc.
62253   */
62254   regAutoinc = autoIncBegin(pParse, iDb, pTab);
62255
62256   /* Figure out how many columns of data are supplied.  If the data
62257   ** is coming from a SELECT statement, then generate a co-routine that
62258   ** produces a single row of the SELECT on each invocation.  The
62259   ** co-routine is the common header to the 3rd and 4th templates.
62260   */
62261   if( pSelect ){
62262     /* Data is coming from a SELECT.  Generate code to implement that SELECT
62263     ** as a co-routine.  The code is common to both the 3rd and 4th
62264     ** templates:
62265     **
62266     **         EOF <- 0
62267     **         X <- A
62268     **         goto B
62269     **      A: setup for the SELECT
62270     **         loop over the tables in the SELECT
62271     **           load value into register R..R+n
62272     **           yield X
62273     **         end loop
62274     **         cleanup after the SELECT
62275     **         EOF <- 1
62276     **         yield X
62277     **         halt-error
62278     **
62279     ** On each invocation of the co-routine, it puts a single row of the
62280     ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
62281     ** (These output registers are allocated by sqlite3Select().)  When
62282     ** the SELECT completes, it sets the EOF flag stored in regEof.
62283     */
62284     int rc, j1;
62285
62286     regEof = ++pParse->nMem;
62287     sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
62288     VdbeComment((v, "SELECT eof flag"));
62289     sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
62290     addrSelect = sqlite3VdbeCurrentAddr(v)+2;
62291     sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
62292     j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
62293     VdbeComment((v, "Jump over SELECT coroutine"));
62294
62295     /* Resolve the expressions in the SELECT statement and execute it. */
62296     rc = sqlite3Select(pParse, pSelect, &dest, 0, 0, 0);
62297     if( rc || pParse->nErr || db->mallocFailed ){
62298       goto insert_cleanup;
62299     }
62300     sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
62301     sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
62302     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
62303     VdbeComment((v, "End of SELECT coroutine"));
62304     sqlite3VdbeJumpHere(v, j1);                          /* label B: */
62305
62306     regFromSelect = dest.iMem;
62307     assert( pSelect->pEList );
62308     nColumn = pSelect->pEList->nExpr;
62309     assert( dest.nMem==nColumn );
62310
62311     /* Set useTempTable to TRUE if the result of the SELECT statement
62312     ** should be written into a temporary table (template 4).  Set to
62313     ** FALSE if each* row of the SELECT can be written directly into
62314     ** the destination table (template 3).
62315     **
62316     ** A temp table must be used if the table being updated is also one
62317     ** of the tables being read by the SELECT statement.  Also use a 
62318     ** temp table in the case of row triggers.
62319     */
62320     if( triggers_exist || readsTable(v, addrSelect, iDb, pTab) ){
62321       useTempTable = 1;
62322     }
62323
62324     if( useTempTable ){
62325       /* Invoke the coroutine to extract information from the SELECT
62326       ** and add it to a transient table srcTab.  The code generated
62327       ** here is from the 4th template:
62328       **
62329       **      B: open temp table
62330       **      L: yield X
62331       **         if EOF goto M
62332       **         insert row from R..R+n into temp table
62333       **         goto L
62334       **      M: ...
62335       */
62336       int regRec;      /* Register to hold packed record */
62337       int regRowid;    /* Register to hold temp table ROWID */
62338       int addrTop;     /* Label "L" */
62339       int addrIf;      /* Address of jump to M */
62340
62341       srcTab = pParse->nTab++;
62342       regRec = sqlite3GetTempReg(pParse);
62343       regRowid = sqlite3GetTempReg(pParse);
62344       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
62345       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
62346       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
62347       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
62348       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regRowid);
62349       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regRowid);
62350       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
62351       sqlite3VdbeJumpHere(v, addrIf);
62352       sqlite3ReleaseTempReg(pParse, regRec);
62353       sqlite3ReleaseTempReg(pParse, regRowid);
62354     }
62355   }else{
62356     /* This is the case if the data for the INSERT is coming from a VALUES
62357     ** clause
62358     */
62359     NameContext sNC;
62360     memset(&sNC, 0, sizeof(sNC));
62361     sNC.pParse = pParse;
62362     srcTab = -1;
62363     assert( useTempTable==0 );
62364     nColumn = pList ? pList->nExpr : 0;
62365     for(i=0; i<nColumn; i++){
62366       if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){
62367         goto insert_cleanup;
62368       }
62369     }
62370   }
62371
62372   /* Make sure the number of columns in the source data matches the number
62373   ** of columns to be inserted into the table.
62374   */
62375   if( IsVirtual(pTab) ){
62376     for(i=0; i<pTab->nCol; i++){
62377       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
62378     }
62379   }
62380   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
62381     sqlite3ErrorMsg(pParse, 
62382        "table %S has %d columns but %d values were supplied",
62383        pTabList, 0, pTab->nCol, nColumn);
62384     goto insert_cleanup;
62385   }
62386   if( pColumn!=0 && nColumn!=pColumn->nId ){
62387     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
62388     goto insert_cleanup;
62389   }
62390
62391   /* If the INSERT statement included an IDLIST term, then make sure
62392   ** all elements of the IDLIST really are columns of the table and 
62393   ** remember the column indices.
62394   **
62395   ** If the table has an INTEGER PRIMARY KEY column and that column
62396   ** is named in the IDLIST, then record in the keyColumn variable
62397   ** the index into IDLIST of the primary key column.  keyColumn is
62398   ** the index of the primary key as it appears in IDLIST, not as
62399   ** is appears in the original table.  (The index of the primary
62400   ** key in the original table is pTab->iPKey.)
62401   */
62402   if( pColumn ){
62403     for(i=0; i<pColumn->nId; i++){
62404       pColumn->a[i].idx = -1;
62405     }
62406     for(i=0; i<pColumn->nId; i++){
62407       for(j=0; j<pTab->nCol; j++){
62408         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
62409           pColumn->a[i].idx = j;
62410           if( j==pTab->iPKey ){
62411             keyColumn = i;
62412           }
62413           break;
62414         }
62415       }
62416       if( j>=pTab->nCol ){
62417         if( sqlite3IsRowid(pColumn->a[i].zName) ){
62418           keyColumn = i;
62419         }else{
62420           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
62421               pTabList, 0, pColumn->a[i].zName);
62422           pParse->nErr++;
62423           goto insert_cleanup;
62424         }
62425       }
62426     }
62427   }
62428
62429   /* If there is no IDLIST term but the table has an integer primary
62430   ** key, the set the keyColumn variable to the primary key column index
62431   ** in the original table definition.
62432   */
62433   if( pColumn==0 && nColumn>0 ){
62434     keyColumn = pTab->iPKey;
62435   }
62436
62437   /* Open the temp table for FOR EACH ROW triggers
62438   */
62439   if( triggers_exist ){
62440     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
62441     sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0);
62442   }
62443     
62444   /* Initialize the count of rows to be inserted
62445   */
62446   if( db->flags & SQLITE_CountRows ){
62447     regRowCount = ++pParse->nMem;
62448     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
62449   }
62450
62451   /* If this is not a view, open the table and and all indices */
62452   if( !isView ){
62453     int nIdx;
62454     int i;
62455
62456     baseCur = pParse->nTab;
62457     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
62458     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
62459     if( aRegIdx==0 ){
62460       goto insert_cleanup;
62461     }
62462     for(i=0; i<nIdx; i++){
62463       aRegIdx[i] = ++pParse->nMem;
62464     }
62465   }
62466
62467   /* This is the top of the main insertion loop */
62468   if( useTempTable ){
62469     /* This block codes the top of loop only.  The complete loop is the
62470     ** following pseudocode (template 4):
62471     **
62472     **         rewind temp table
62473     **      C: loop over rows of intermediate table
62474     **           transfer values form intermediate table into <table>
62475     **         end loop
62476     **      D: ...
62477     */
62478     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
62479     addrCont = sqlite3VdbeCurrentAddr(v);
62480   }else if( pSelect ){
62481     /* This block codes the top of loop only.  The complete loop is the
62482     ** following pseudocode (template 3):
62483     **
62484     **      C: yield X
62485     **         if EOF goto D
62486     **         insert the select result into <table> from R..R+n
62487     **         goto C
62488     **      D: ...
62489     */
62490     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
62491     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
62492   }
62493
62494   /* Allocate registers for holding the rowid of the new row,
62495   ** the content of the new row, and the assemblied row record.
62496   */
62497   regRecord = ++pParse->nMem;
62498   regRowid = regIns = pParse->nMem+1;
62499   pParse->nMem += pTab->nCol + 1;
62500   if( IsVirtual(pTab) ){
62501     regRowid++;
62502     pParse->nMem++;
62503   }
62504   regData = regRowid+1;
62505
62506   /* Run the BEFORE and INSTEAD OF triggers, if there are any
62507   */
62508   endOfLoop = sqlite3VdbeMakeLabel(v);
62509   if( triggers_exist & TRIGGER_BEFORE ){
62510     int regRowid;
62511     int regCols;
62512     int regRec;
62513
62514     /* build the NEW.* reference row.  Note that if there is an INTEGER
62515     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
62516     ** translated into a unique ID for the row.  But on a BEFORE trigger,
62517     ** we do not know what the unique ID will be (because the insert has
62518     ** not happened yet) so we substitute a rowid of -1
62519     */
62520     regRowid = sqlite3GetTempReg(pParse);
62521     if( keyColumn<0 ){
62522       sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
62523     }else if( useTempTable ){
62524       sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
62525     }else{
62526       int j1;
62527       assert( pSelect==0 );  /* Otherwise useTempTable is true */
62528       sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
62529       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
62530       sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
62531       sqlite3VdbeJumpHere(v, j1);
62532       sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
62533     }
62534
62535     /* Cannot have triggers on a virtual table. If it were possible,
62536     ** this block would have to account for hidden column.
62537     */
62538     assert(!IsVirtual(pTab));
62539
62540     /* Create the new column data
62541     */
62542     regCols = sqlite3GetTempRange(pParse, pTab->nCol);
62543     for(i=0; i<pTab->nCol; i++){
62544       if( pColumn==0 ){
62545         j = i;
62546       }else{
62547         for(j=0; j<pColumn->nId; j++){
62548           if( pColumn->a[j].idx==i ) break;
62549         }
62550       }
62551       if( pColumn && j>=pColumn->nId ){
62552         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i);
62553       }else if( useTempTable ){
62554         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i); 
62555       }else{
62556         assert( pSelect==0 ); /* Otherwise useTempTable is true */
62557         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i);
62558       }
62559     }
62560     regRec = sqlite3GetTempReg(pParse);
62561     sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRec);
62562
62563     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
62564     ** do not attempt any conversions before assembling the record.
62565     ** If this is a real table, attempt conversions as required by the
62566     ** table column affinities.
62567     */
62568     if( !isView ){
62569       sqlite3TableAffinityStr(v, pTab);
62570     }
62571     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid);
62572     sqlite3ReleaseTempReg(pParse, regRec);
62573     sqlite3ReleaseTempReg(pParse, regRowid);
62574     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol);
62575
62576     /* Fire BEFORE or INSTEAD OF triggers */
62577     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab, 
62578         newIdx, -1, onError, endOfLoop, 0, 0) ){
62579       goto insert_cleanup;
62580     }
62581   }
62582
62583   /* Push the record number for the new entry onto the stack.  The
62584   ** record number is a randomly generate integer created by NewRowid
62585   ** except when the table has an INTEGER PRIMARY KEY column, in which
62586   ** case the record number is the same as that column. 
62587   */
62588   if( !isView ){
62589     if( IsVirtual(pTab) ){
62590       /* The row that the VUpdate opcode will delete: none */
62591       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
62592     }
62593     if( keyColumn>=0 ){
62594       if( useTempTable ){
62595         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
62596       }else if( pSelect ){
62597         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
62598       }else{
62599         VdbeOp *pOp;
62600         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
62601         pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
62602         if( pOp && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
62603           appendFlag = 1;
62604           pOp->opcode = OP_NewRowid;
62605           pOp->p1 = baseCur;
62606           pOp->p2 = regRowid;
62607           pOp->p3 = regAutoinc;
62608         }
62609       }
62610       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
62611       ** to generate a unique primary key value.
62612       */
62613       if( !appendFlag ){
62614         int j1;
62615         if( !IsVirtual(pTab) ){
62616           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
62617           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
62618           sqlite3VdbeJumpHere(v, j1);
62619         }else{
62620           j1 = sqlite3VdbeCurrentAddr(v);
62621           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
62622         }
62623         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
62624       }
62625     }else if( IsVirtual(pTab) ){
62626       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
62627     }else{
62628       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
62629       appendFlag = 1;
62630     }
62631     autoIncStep(pParse, regAutoinc, regRowid);
62632
62633     /* Push onto the stack, data for all columns of the new entry, beginning
62634     ** with the first column.
62635     */
62636     nHidden = 0;
62637     for(i=0; i<pTab->nCol; i++){
62638       int iRegStore = regRowid+1+i;
62639       if( i==pTab->iPKey ){
62640         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
62641         ** Whenever this column is read, the record number will be substituted
62642         ** in its place.  So will fill this column with a NULL to avoid
62643         ** taking up data space with information that will never be used. */
62644         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
62645         continue;
62646       }
62647       if( pColumn==0 ){
62648         if( IsHiddenColumn(&pTab->aCol[i]) ){
62649           assert( IsVirtual(pTab) );
62650           j = -1;
62651           nHidden++;
62652         }else{
62653           j = i - nHidden;
62654         }
62655       }else{
62656         for(j=0; j<pColumn->nId; j++){
62657           if( pColumn->a[j].idx==i ) break;
62658         }
62659       }
62660       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
62661         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
62662       }else if( useTempTable ){
62663         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
62664       }else if( pSelect ){
62665         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
62666       }else{
62667         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
62668       }
62669     }
62670
62671     /* Generate code to check constraints and generate index keys and
62672     ** do the insertion.
62673     */
62674 #ifndef SQLITE_OMIT_VIRTUALTABLE
62675     if( IsVirtual(pTab) ){
62676       sqlite3VtabMakeWritable(pParse, pTab);
62677       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns,
62678                      (const char*)pTab->pVtab, P4_VTAB);
62679     }else
62680 #endif
62681     {
62682       sqlite3GenerateConstraintChecks(
62683           pParse,
62684           pTab,
62685           baseCur,
62686           regIns,
62687           aRegIdx,
62688           keyColumn>=0,
62689           0,
62690           onError,
62691           endOfLoop
62692       );
62693       sqlite3CompleteInsertion(
62694           pParse,
62695           pTab,
62696           baseCur,
62697           regIns,
62698           aRegIdx,
62699           0,
62700           0,
62701           (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
62702           appendFlag
62703        );
62704     }
62705   }
62706
62707   /* Update the count of rows that are inserted
62708   */
62709   if( (db->flags & SQLITE_CountRows)!=0 ){
62710     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
62711   }
62712
62713   if( triggers_exist ){
62714     /* Code AFTER triggers */
62715     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
62716           newIdx, -1, onError, endOfLoop, 0, 0) ){
62717       goto insert_cleanup;
62718     }
62719   }
62720
62721   /* The bottom of the main insertion loop, if the data source
62722   ** is a SELECT statement.
62723   */
62724   sqlite3VdbeResolveLabel(v, endOfLoop);
62725   if( useTempTable ){
62726     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
62727     sqlite3VdbeJumpHere(v, addrInsTop);
62728     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
62729   }else if( pSelect ){
62730     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
62731     sqlite3VdbeJumpHere(v, addrInsTop);
62732   }
62733
62734   if( !IsVirtual(pTab) && !isView ){
62735     /* Close all tables opened */
62736     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
62737     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
62738       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
62739     }
62740   }
62741
62742   /* Update the sqlite_sequence table by storing the content of the
62743   ** counter value in memory regAutoinc back into the sqlite_sequence
62744   ** table.
62745   */
62746   autoIncEnd(pParse, iDb, pTab, regAutoinc);
62747
62748   /*
62749   ** Return the number of rows inserted. If this routine is 
62750   ** generating code because of a call to sqlite3NestedParse(), do not
62751   ** invoke the callback function.
62752   */
62753   if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
62754     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
62755     sqlite3VdbeSetNumCols(v, 1);
62756     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P4_STATIC);
62757   }
62758
62759 insert_cleanup:
62760   sqlite3SrcListDelete(db, pTabList);
62761   sqlite3ExprListDelete(db, pList);
62762   sqlite3SelectDelete(db, pSelect);
62763   sqlite3IdListDelete(db, pColumn);
62764   sqlite3DbFree(db, aRegIdx);
62765 }
62766
62767 /*
62768 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
62769 **
62770 ** The input is a range of consecutive registers as follows:
62771 **
62772 **    1.  The rowid of the row to be updated before the update.  This
62773 **        value is omitted unless we are doing an UPDATE that involves a
62774 **        change to the record number or writing to a virtual table.
62775 **
62776 **    2.  The rowid of the row after the update.
62777 **
62778 **    3.  The data in the first column of the entry after the update.
62779 **
62780 **    i.  Data from middle columns...
62781 **
62782 **    N.  The data in the last column of the entry after the update.
62783 **
62784 ** The regRowid parameter is the index of the register containing (2).
62785 **
62786 ** The old rowid shown as entry (1) above is omitted unless both isUpdate
62787 ** and rowidChng are 1.  isUpdate is true for UPDATEs and false for
62788 ** INSERTs.  RowidChng means that the new rowid is explicitly specified by
62789 ** the update or insert statement.  If rowidChng is false, it means that
62790 ** the rowid is computed automatically in an insert or that the rowid value
62791 ** is not modified by the update.
62792 **
62793 ** The code generated by this routine store new index entries into
62794 ** registers identified by aRegIdx[].  No index entry is created for
62795 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
62796 ** the same as the order of indices on the linked list of indices
62797 ** attached to the table.
62798 **
62799 ** This routine also generates code to check constraints.  NOT NULL,
62800 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
62801 ** then the appropriate action is performed.  There are five possible
62802 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
62803 **
62804 **  Constraint type  Action       What Happens
62805 **  ---------------  ----------   ----------------------------------------
62806 **  any              ROLLBACK     The current transaction is rolled back and
62807 **                                sqlite3_exec() returns immediately with a
62808 **                                return code of SQLITE_CONSTRAINT.
62809 **
62810 **  any              ABORT        Back out changes from the current command
62811 **                                only (do not do a complete rollback) then
62812 **                                cause sqlite3_exec() to return immediately
62813 **                                with SQLITE_CONSTRAINT.
62814 **
62815 **  any              FAIL         Sqlite_exec() returns immediately with a
62816 **                                return code of SQLITE_CONSTRAINT.  The
62817 **                                transaction is not rolled back and any
62818 **                                prior changes are retained.
62819 **
62820 **  any              IGNORE       The record number and data is popped from
62821 **                                the stack and there is an immediate jump
62822 **                                to label ignoreDest.
62823 **
62824 **  NOT NULL         REPLACE      The NULL value is replace by the default
62825 **                                value for that column.  If the default value
62826 **                                is NULL, the action is the same as ABORT.
62827 **
62828 **  UNIQUE           REPLACE      The other row that conflicts with the row
62829 **                                being inserted is removed.
62830 **
62831 **  CHECK            REPLACE      Illegal.  The results in an exception.
62832 **
62833 ** Which action to take is determined by the overrideError parameter.
62834 ** Or if overrideError==OE_Default, then the pParse->onError parameter
62835 ** is used.  Or if pParse->onError==OE_Default then the onError value
62836 ** for the constraint is used.
62837 **
62838 ** The calling routine must open a read/write cursor for pTab with
62839 ** cursor number "baseCur".  All indices of pTab must also have open
62840 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
62841 ** Except, if there is no possibility of a REPLACE action then
62842 ** cursors do not need to be open for indices where aRegIdx[i]==0.
62843 */
62844 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
62845   Parse *pParse,      /* The parser context */
62846   Table *pTab,        /* the table into which we are inserting */
62847   int baseCur,        /* Index of a read/write cursor pointing at pTab */
62848   int regRowid,       /* Index of the range of input registers */
62849   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
62850   int rowidChng,      /* True if the rowid might collide with existing entry */
62851   int isUpdate,       /* True for UPDATE, False for INSERT */
62852   int overrideError,  /* Override onError to this if not OE_Default */
62853   int ignoreDest      /* Jump to this label on an OE_Ignore resolution */
62854 ){
62855   int i;
62856   Vdbe *v;
62857   int nCol;
62858   int onError;
62859   int j1, j2, j3;     /* Addresses of jump instructions */
62860   int regData;        /* Register containing first data column */
62861   int iCur;
62862   Index *pIdx;
62863   int seenReplace = 0;
62864   int hasTwoRowids = (isUpdate && rowidChng);
62865
62866   v = sqlite3GetVdbe(pParse);
62867   assert( v!=0 );
62868   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
62869   nCol = pTab->nCol;
62870   regData = regRowid + 1;
62871
62872
62873   /* Test all NOT NULL constraints.
62874   */
62875   for(i=0; i<nCol; i++){
62876     if( i==pTab->iPKey ){
62877       continue;
62878     }
62879     onError = pTab->aCol[i].notNull;
62880     if( onError==OE_None ) continue;
62881     if( overrideError!=OE_Default ){
62882       onError = overrideError;
62883     }else if( onError==OE_Default ){
62884       onError = OE_Abort;
62885     }
62886     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
62887       onError = OE_Abort;
62888     }
62889     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
62890     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
62891         || onError==OE_Ignore || onError==OE_Replace );
62892     switch( onError ){
62893       case OE_Rollback:
62894       case OE_Abort:
62895       case OE_Fail: {
62896         char *zMsg;
62897         sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
62898         zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
62899                               pTab->zName, pTab->aCol[i].zName);
62900         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
62901         break;
62902       }
62903       case OE_Ignore: {
62904         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
62905         break;
62906       }
62907       case OE_Replace: {
62908         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
62909         break;
62910       }
62911     }
62912     sqlite3VdbeJumpHere(v, j1);
62913   }
62914
62915   /* Test all CHECK constraints
62916   */
62917 #ifndef SQLITE_OMIT_CHECK
62918   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
62919     int allOk = sqlite3VdbeMakeLabel(v);
62920     pParse->ckBase = regData;
62921     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
62922     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
62923     if( onError==OE_Ignore ){
62924       sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
62925     }else{
62926       sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
62927     }
62928     sqlite3VdbeResolveLabel(v, allOk);
62929   }
62930 #endif /* !defined(SQLITE_OMIT_CHECK) */
62931
62932   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
62933   ** of the new record does not previously exist.  Except, if this
62934   ** is an UPDATE and the primary key is not changing, that is OK.
62935   */
62936   if( rowidChng ){
62937     onError = pTab->keyConf;
62938     if( overrideError!=OE_Default ){
62939       onError = overrideError;
62940     }else if( onError==OE_Default ){
62941       onError = OE_Abort;
62942     }
62943     
62944     if( onError!=OE_Replace || pTab->pIndex ){
62945       if( isUpdate ){
62946         j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, regRowid-1);
62947       }
62948       j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
62949       switch( onError ){
62950         default: {
62951           onError = OE_Abort;
62952           /* Fall thru into the next case */
62953         }
62954         case OE_Rollback:
62955         case OE_Abort:
62956         case OE_Fail: {
62957           sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
62958                            "PRIMARY KEY must be unique", P4_STATIC);
62959           break;
62960         }
62961         case OE_Replace: {
62962           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
62963           seenReplace = 1;
62964           break;
62965         }
62966         case OE_Ignore: {
62967           assert( seenReplace==0 );
62968           sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
62969           break;
62970         }
62971       }
62972       sqlite3VdbeJumpHere(v, j3);
62973       if( isUpdate ){
62974         sqlite3VdbeJumpHere(v, j2);
62975       }
62976     }
62977   }
62978
62979   /* Test all UNIQUE constraints by creating entries for each UNIQUE
62980   ** index and making sure that duplicate entries do not already exist.
62981   ** Add the new records to the indices as we go.
62982   */
62983   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
62984     int regIdx;
62985     int regR;
62986
62987     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
62988
62989     /* Create a key for accessing the index entry */
62990     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
62991     for(i=0; i<pIdx->nColumn; i++){
62992       int idx = pIdx->aiColumn[i];
62993       if( idx==pTab->iPKey ){
62994         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
62995       }else{
62996         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
62997       }
62998     }
62999     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
63000     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
63001     sqlite3IndexAffinityStr(v, pIdx);
63002     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
63003     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
63004
63005     /* Find out what action to take in case there is an indexing conflict */
63006     onError = pIdx->onError;
63007     if( onError==OE_None ) continue;  /* pIdx is not a UNIQUE index */
63008     if( overrideError!=OE_Default ){
63009       onError = overrideError;
63010     }else if( onError==OE_Default ){
63011       onError = OE_Abort;
63012     }
63013     if( seenReplace ){
63014       if( onError==OE_Ignore ) onError = OE_Replace;
63015       else if( onError==OE_Fail ) onError = OE_Abort;
63016     }
63017     
63018
63019     /* Check to see if the new index entry will be unique */
63020     j2 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdx, 0, pIdx->nColumn);
63021     regR = sqlite3GetTempReg(pParse);
63022     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid-hasTwoRowids, regR);
63023     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
63024                            regR, SQLITE_INT_TO_PTR(aRegIdx[iCur]),
63025                            P4_INT32);
63026
63027     /* Generate code that executes if the new index entry is not unique */
63028     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
63029         || onError==OE_Ignore || onError==OE_Replace );
63030     switch( onError ){
63031       case OE_Rollback:
63032       case OE_Abort:
63033       case OE_Fail: {
63034         int j, n1, n2;
63035         char zErrMsg[200];
63036         sqlite3_snprintf(sizeof(zErrMsg), zErrMsg,
63037                          pIdx->nColumn>1 ? "columns " : "column ");
63038         n1 = strlen(zErrMsg);
63039         for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
63040           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
63041           n2 = strlen(zCol);
63042           if( j>0 ){
63043             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", ");
63044             n1 += 2;
63045           }
63046           if( n1+n2>sizeof(zErrMsg)-30 ){
63047             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "...");
63048             n1 += 3;
63049             break;
63050           }else{
63051             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
63052             n1 += n2;
63053           }
63054         }
63055         sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], 
63056             pIdx->nColumn>1 ? " are not unique" : " is not unique");
63057         sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErrMsg,0);
63058         break;
63059       }
63060       case OE_Ignore: {
63061         assert( seenReplace==0 );
63062         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
63063         break;
63064       }
63065       case OE_Replace: {
63066         sqlite3GenerateRowDelete(pParse, pTab, baseCur, regR, 0);
63067         seenReplace = 1;
63068         break;
63069       }
63070     }
63071     sqlite3VdbeJumpHere(v, j2);
63072     sqlite3VdbeJumpHere(v, j3);
63073     sqlite3ReleaseTempReg(pParse, regR);
63074   }
63075 }
63076
63077 /*
63078 ** This routine generates code to finish the INSERT or UPDATE operation
63079 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
63080 ** A consecutive range of registers starting at regRowid contains the
63081 ** rowid and the content to be inserted.
63082 **
63083 ** The arguments to this routine should be the same as the first six
63084 ** arguments to sqlite3GenerateConstraintChecks.
63085 */
63086 SQLITE_PRIVATE void sqlite3CompleteInsertion(
63087   Parse *pParse,      /* The parser context */
63088   Table *pTab,        /* the table into which we are inserting */
63089   int baseCur,        /* Index of a read/write cursor pointing at pTab */
63090   int regRowid,       /* Range of content */
63091   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
63092   int rowidChng,      /* True if the record number will change */
63093   int isUpdate,       /* True for UPDATE, False for INSERT */
63094   int newIdx,         /* Index of NEW table for triggers.  -1 if none */
63095   int appendBias      /* True if this is likely to be an append */
63096 ){
63097   int i;
63098   Vdbe *v;
63099   int nIdx;
63100   Index *pIdx;
63101   int pik_flags;
63102   int regData;
63103   int regRec;
63104
63105   v = sqlite3GetVdbe(pParse);
63106   assert( v!=0 );
63107   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
63108   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
63109   for(i=nIdx-1; i>=0; i--){
63110     if( aRegIdx[i]==0 ) continue;
63111     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
63112   }
63113   regData = regRowid + 1;
63114   regRec = sqlite3GetTempReg(pParse);
63115   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
63116   sqlite3TableAffinityStr(v, pTab);
63117   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
63118 #ifndef SQLITE_OMIT_TRIGGER
63119   if( newIdx>=0 ){
63120     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid);
63121   }
63122 #endif
63123   if( pParse->nested ){
63124     pik_flags = 0;
63125   }else{
63126     pik_flags = OPFLAG_NCHANGE;
63127     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
63128   }
63129   if( appendBias ){
63130     pik_flags |= OPFLAG_APPEND;
63131   }
63132   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
63133   if( !pParse->nested ){
63134     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
63135   }
63136   sqlite3VdbeChangeP5(v, pik_flags);
63137 }
63138
63139 /*
63140 ** Generate code that will open cursors for a table and for all
63141 ** indices of that table.  The "baseCur" parameter is the cursor number used
63142 ** for the table.  Indices are opened on subsequent cursors.
63143 **
63144 ** Return the number of indices on the table.
63145 */
63146 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
63147   Parse *pParse,   /* Parsing context */
63148   Table *pTab,     /* Table to be opened */
63149   int baseCur,        /* Cursor number assigned to the table */
63150   int op           /* OP_OpenRead or OP_OpenWrite */
63151 ){
63152   int i;
63153   int iDb;
63154   Index *pIdx;
63155   Vdbe *v;
63156
63157   if( IsVirtual(pTab) ) return 0;
63158   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
63159   v = sqlite3GetVdbe(pParse);
63160   assert( v!=0 );
63161   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
63162   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
63163     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
63164     assert( pIdx->pSchema==pTab->pSchema );
63165     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
63166                       (char*)pKey, P4_KEYINFO_HANDOFF);
63167     VdbeComment((v, "%s", pIdx->zName));
63168   }
63169   if( pParse->nTab<=baseCur+i ){
63170     pParse->nTab = baseCur+i;
63171   }
63172   return i-1;
63173 }
63174
63175
63176 #ifdef SQLITE_TEST
63177 /*
63178 ** The following global variable is incremented whenever the
63179 ** transfer optimization is used.  This is used for testing
63180 ** purposes only - to make sure the transfer optimization really
63181 ** is happening when it is suppose to.
63182 */
63183 SQLITE_API int sqlite3_xferopt_count;
63184 #endif /* SQLITE_TEST */
63185
63186
63187 #ifndef SQLITE_OMIT_XFER_OPT
63188 /*
63189 ** Check to collation names to see if they are compatible.
63190 */
63191 static int xferCompatibleCollation(const char *z1, const char *z2){
63192   if( z1==0 ){
63193     return z2==0;
63194   }
63195   if( z2==0 ){
63196     return 0;
63197   }
63198   return sqlite3StrICmp(z1, z2)==0;
63199 }
63200
63201
63202 /*
63203 ** Check to see if index pSrc is compatible as a source of data
63204 ** for index pDest in an insert transfer optimization.  The rules
63205 ** for a compatible index:
63206 **
63207 **    *   The index is over the same set of columns
63208 **    *   The same DESC and ASC markings occurs on all columns
63209 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
63210 **    *   The same collating sequence on each column
63211 */
63212 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
63213   int i;
63214   assert( pDest && pSrc );
63215   assert( pDest->pTable!=pSrc->pTable );
63216   if( pDest->nColumn!=pSrc->nColumn ){
63217     return 0;   /* Different number of columns */
63218   }
63219   if( pDest->onError!=pSrc->onError ){
63220     return 0;   /* Different conflict resolution strategies */
63221   }
63222   for(i=0; i<pSrc->nColumn; i++){
63223     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
63224       return 0;   /* Different columns indexed */
63225     }
63226     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
63227       return 0;   /* Different sort orders */
63228     }
63229     if( pSrc->azColl[i]!=pDest->azColl[i] ){
63230       return 0;   /* Different collating sequences */
63231     }
63232   }
63233
63234   /* If no test above fails then the indices must be compatible */
63235   return 1;
63236 }
63237
63238 /*
63239 ** Attempt the transfer optimization on INSERTs of the form
63240 **
63241 **     INSERT INTO tab1 SELECT * FROM tab2;
63242 **
63243 ** This optimization is only attempted if
63244 **
63245 **    (1)  tab1 and tab2 have identical schemas including all the
63246 **         same indices and constraints
63247 **
63248 **    (2)  tab1 and tab2 are different tables
63249 **
63250 **    (3)  There must be no triggers on tab1
63251 **
63252 **    (4)  The result set of the SELECT statement is "*"
63253 **
63254 **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
63255 **         or LIMIT clause.
63256 **
63257 **    (6)  The SELECT statement is a simple (not a compound) select that
63258 **         contains only tab2 in its FROM clause
63259 **
63260 ** This method for implementing the INSERT transfers raw records from
63261 ** tab2 over to tab1.  The columns are not decoded.  Raw records from
63262 ** the indices of tab2 are transfered to tab1 as well.  In so doing,
63263 ** the resulting tab1 has much less fragmentation.
63264 **
63265 ** This routine returns TRUE if the optimization is attempted.  If any
63266 ** of the conditions above fail so that the optimization should not
63267 ** be attempted, then this routine returns FALSE.
63268 */
63269 static int xferOptimization(
63270   Parse *pParse,        /* Parser context */
63271   Table *pDest,         /* The table we are inserting into */
63272   Select *pSelect,      /* A SELECT statement to use as the data source */
63273   int onError,          /* How to handle constraint errors */
63274   int iDbDest           /* The database of pDest */
63275 ){
63276   ExprList *pEList;                /* The result set of the SELECT */
63277   Table *pSrc;                     /* The table in the FROM clause of SELECT */
63278   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
63279   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
63280   int i;                           /* Loop counter */
63281   int iDbSrc;                      /* The database of pSrc */
63282   int iSrc, iDest;                 /* Cursors from source and destination */
63283   int addr1, addr2;                /* Loop addresses */
63284   int emptyDestTest;               /* Address of test for empty pDest */
63285   int emptySrcTest;                /* Address of test for empty pSrc */
63286   Vdbe *v;                         /* The VDBE we are building */
63287   KeyInfo *pKey;                   /* Key information for an index */
63288   int regAutoinc;                  /* Memory register used by AUTOINC */
63289   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
63290   int regData, regRowid;           /* Registers holding data and rowid */
63291
63292   if( pSelect==0 ){
63293     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
63294   }
63295   if( pDest->pTrigger ){
63296     return 0;   /* tab1 must not have triggers */
63297   }
63298 #ifndef SQLITE_OMIT_VIRTUALTABLE
63299   if( pDest->isVirtual ){
63300     return 0;   /* tab1 must not be a virtual table */
63301   }
63302 #endif
63303   if( onError==OE_Default ){
63304     onError = OE_Abort;
63305   }
63306   if( onError!=OE_Abort && onError!=OE_Rollback ){
63307     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
63308   }
63309   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
63310   if( pSelect->pSrc->nSrc!=1 ){
63311     return 0;   /* FROM clause must have exactly one term */
63312   }
63313   if( pSelect->pSrc->a[0].pSelect ){
63314     return 0;   /* FROM clause cannot contain a subquery */
63315   }
63316   if( pSelect->pWhere ){
63317     return 0;   /* SELECT may not have a WHERE clause */
63318   }
63319   if( pSelect->pOrderBy ){
63320     return 0;   /* SELECT may not have an ORDER BY clause */
63321   }
63322   /* Do not need to test for a HAVING clause.  If HAVING is present but
63323   ** there is no ORDER BY, we will get an error. */
63324   if( pSelect->pGroupBy ){
63325     return 0;   /* SELECT may not have a GROUP BY clause */
63326   }
63327   if( pSelect->pLimit ){
63328     return 0;   /* SELECT may not have a LIMIT clause */
63329   }
63330   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
63331   if( pSelect->pPrior ){
63332     return 0;   /* SELECT may not be a compound query */
63333   }
63334   if( pSelect->isDistinct ){
63335     return 0;   /* SELECT may not be DISTINCT */
63336   }
63337   pEList = pSelect->pEList;
63338   assert( pEList!=0 );
63339   if( pEList->nExpr!=1 ){
63340     return 0;   /* The result set must have exactly one column */
63341   }
63342   assert( pEList->a[0].pExpr );
63343   if( pEList->a[0].pExpr->op!=TK_ALL ){
63344     return 0;   /* The result set must be the special operator "*" */
63345   }
63346
63347   /* At this point we have established that the statement is of the
63348   ** correct syntactic form to participate in this optimization.  Now
63349   ** we have to check the semantics.
63350   */
63351   pItem = pSelect->pSrc->a;
63352   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
63353   if( pSrc==0 ){
63354     return 0;   /* FROM clause does not contain a real table */
63355   }
63356   if( pSrc==pDest ){
63357     return 0;   /* tab1 and tab2 may not be the same table */
63358   }
63359 #ifndef SQLITE_OMIT_VIRTUALTABLE
63360   if( pSrc->isVirtual ){
63361     return 0;   /* tab2 must not be a virtual table */
63362   }
63363 #endif
63364   if( pSrc->pSelect ){
63365     return 0;   /* tab2 may not be a view */
63366   }
63367   if( pDest->nCol!=pSrc->nCol ){
63368     return 0;   /* Number of columns must be the same in tab1 and tab2 */
63369   }
63370   if( pDest->iPKey!=pSrc->iPKey ){
63371     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
63372   }
63373   for(i=0; i<pDest->nCol; i++){
63374     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
63375       return 0;    /* Affinity must be the same on all columns */
63376     }
63377     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
63378       return 0;    /* Collating sequence must be the same on all columns */
63379     }
63380     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
63381       return 0;    /* tab2 must be NOT NULL if tab1 is */
63382     }
63383   }
63384   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
63385     if( pDestIdx->onError!=OE_None ){
63386       destHasUniqueIdx = 1;
63387     }
63388     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
63389       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
63390     }
63391     if( pSrcIdx==0 ){
63392       return 0;    /* pDestIdx has no corresponding index in pSrc */
63393     }
63394   }
63395 #ifndef SQLITE_OMIT_CHECK
63396   if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
63397     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
63398   }
63399 #endif
63400
63401   /* If we get this far, it means either:
63402   **
63403   **    *   We can always do the transfer if the table contains an
63404   **        an integer primary key
63405   **
63406   **    *   We can conditionally do the transfer if the destination
63407   **        table is empty.
63408   */
63409 #ifdef SQLITE_TEST
63410   sqlite3_xferopt_count++;
63411 #endif
63412   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
63413   v = sqlite3GetVdbe(pParse);
63414   sqlite3CodeVerifySchema(pParse, iDbSrc);
63415   iSrc = pParse->nTab++;
63416   iDest = pParse->nTab++;
63417   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
63418   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
63419   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
63420     /* If tables do not have an INTEGER PRIMARY KEY and there
63421     ** are indices to be copied and the destination is not empty,
63422     ** we have to disallow the transfer optimization because the
63423     ** the rowids might change which will mess up indexing.
63424     **
63425     ** Or if the destination has a UNIQUE index and is not empty,
63426     ** we also disallow the transfer optimization because we cannot
63427     ** insure that all entries in the union of DEST and SRC will be
63428     ** unique.
63429     */
63430     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
63431     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
63432     sqlite3VdbeJumpHere(v, addr1);
63433   }else{
63434     emptyDestTest = 0;
63435   }
63436   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
63437   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
63438   regData = sqlite3GetTempReg(pParse);
63439   regRowid = sqlite3GetTempReg(pParse);
63440   if( pDest->iPKey>=0 ){
63441     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
63442     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
63443     sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
63444                       "PRIMARY KEY must be unique", P4_STATIC);
63445     sqlite3VdbeJumpHere(v, addr2);
63446     autoIncStep(pParse, regAutoinc, regRowid);
63447   }else if( pDest->pIndex==0 ){
63448     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
63449   }else{
63450     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
63451     assert( pDest->autoInc==0 );
63452   }
63453   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
63454   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
63455   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
63456   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
63457   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
63458   autoIncEnd(pParse, iDbDest, pDest, regAutoinc);
63459   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
63460     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
63461       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
63462     }
63463     assert( pSrcIdx );
63464     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
63465     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
63466     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
63467     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
63468                       (char*)pKey, P4_KEYINFO_HANDOFF);
63469     VdbeComment((v, "%s", pSrcIdx->zName));
63470     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
63471     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
63472                       (char*)pKey, P4_KEYINFO_HANDOFF);
63473     VdbeComment((v, "%s", pDestIdx->zName));
63474     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
63475     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
63476     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
63477     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
63478     sqlite3VdbeJumpHere(v, addr1);
63479   }
63480   sqlite3VdbeJumpHere(v, emptySrcTest);
63481   sqlite3ReleaseTempReg(pParse, regRowid);
63482   sqlite3ReleaseTempReg(pParse, regData);
63483   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
63484   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
63485   if( emptyDestTest ){
63486     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
63487     sqlite3VdbeJumpHere(v, emptyDestTest);
63488     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
63489     return 0;
63490   }else{
63491     return 1;
63492   }
63493 }
63494 #endif /* SQLITE_OMIT_XFER_OPT */
63495
63496 /* Make sure "isView" gets undefined in case this file becomes part of
63497 ** the amalgamation - so that subsequent files do not see isView as a
63498 ** macro. */
63499 #undef isView
63500
63501 /************** End of insert.c **********************************************/
63502 /************** Begin file legacy.c ******************************************/
63503 /*
63504 ** 2001 September 15
63505 **
63506 ** The author disclaims copyright to this source code.  In place of
63507 ** a legal notice, here is a blessing:
63508 **
63509 **    May you do good and not evil.
63510 **    May you find forgiveness for yourself and forgive others.
63511 **    May you share freely, never taking more than you give.
63512 **
63513 *************************************************************************
63514 ** Main file for the SQLite library.  The routines in this file
63515 ** implement the programmer interface to the library.  Routines in
63516 ** other files are for internal use by SQLite and should not be
63517 ** accessed by users of the library.
63518 **
63519 ** $Id: legacy.c,v 1.29 2008/08/02 03:50:39 drh Exp $
63520 */
63521
63522
63523 /*
63524 ** Execute SQL code.  Return one of the SQLITE_ success/failure
63525 ** codes.  Also write an error message into memory obtained from
63526 ** malloc() and make *pzErrMsg point to that message.
63527 **
63528 ** If the SQL is a query, then for each row in the query result
63529 ** the xCallback() function is called.  pArg becomes the first
63530 ** argument to xCallback().  If xCallback=NULL then no callback
63531 ** is invoked, even for queries.
63532 */
63533 SQLITE_API int sqlite3_exec(
63534   sqlite3 *db,                /* The database on which the SQL executes */
63535   const char *zSql,           /* The SQL to be executed */
63536   sqlite3_callback xCallback, /* Invoke this callback routine */
63537   void *pArg,                 /* First argument to xCallback() */
63538   char **pzErrMsg             /* Write error messages here */
63539 ){
63540   int rc = SQLITE_OK;
63541   const char *zLeftover;
63542   sqlite3_stmt *pStmt = 0;
63543   char **azCols = 0;
63544
63545   int nRetry = 0;
63546   int nCallback;
63547
63548   if( zSql==0 ) zSql = "";
63549
63550   sqlite3_mutex_enter(db->mutex);
63551   sqlite3Error(db, SQLITE_OK, 0);
63552   while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
63553     int nCol;
63554     char **azVals = 0;
63555
63556     pStmt = 0;
63557     rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
63558     assert( rc==SQLITE_OK || pStmt==0 );
63559     if( rc!=SQLITE_OK ){
63560       continue;
63561     }
63562     if( !pStmt ){
63563       /* this happens for a comment or white-space */
63564       zSql = zLeftover;
63565       continue;
63566     }
63567
63568     nCallback = 0;
63569     nCol = sqlite3_column_count(pStmt);
63570
63571     while( 1 ){
63572       int i;
63573       rc = sqlite3_step(pStmt);
63574
63575       /* Invoke the callback function if required */
63576       if( xCallback && (SQLITE_ROW==rc || 
63577           (SQLITE_DONE==rc && !nCallback && db->flags&SQLITE_NullCallback)) ){
63578         if( 0==nCallback ){
63579           if( azCols==0 ){
63580             azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
63581             if( azCols==0 ){
63582               goto exec_out;
63583             }
63584           }
63585           for(i=0; i<nCol; i++){
63586             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
63587             /* sqlite3VdbeSetColName() installs column names as UTF8
63588             ** strings so there is no way for sqlite3_column_name() to fail. */
63589             assert( azCols[i]!=0 );
63590           }
63591           nCallback++;
63592         }
63593         if( rc==SQLITE_ROW ){
63594           azVals = &azCols[nCol];
63595           for(i=0; i<nCol; i++){
63596             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
63597             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
63598               db->mallocFailed = 1;
63599               goto exec_out;
63600             }
63601           }
63602         }
63603         if( xCallback(pArg, nCol, azVals, azCols) ){
63604           rc = SQLITE_ABORT;
63605           sqlite3_finalize(pStmt);
63606           pStmt = 0;
63607           sqlite3Error(db, SQLITE_ABORT, 0);
63608           goto exec_out;
63609         }
63610       }
63611
63612       if( rc!=SQLITE_ROW ){
63613         rc = sqlite3_finalize(pStmt);
63614         pStmt = 0;
63615         if( rc!=SQLITE_SCHEMA ){
63616           nRetry = 0;
63617           zSql = zLeftover;
63618           while( isspace((unsigned char)zSql[0]) ) zSql++;
63619         }
63620         break;
63621       }
63622     }
63623
63624     sqlite3DbFree(db, azCols);
63625     azCols = 0;
63626   }
63627
63628 exec_out:
63629   if( pStmt ) sqlite3_finalize(pStmt);
63630   sqlite3DbFree(db, azCols);
63631
63632   rc = sqlite3ApiExit(db, rc);
63633   if( rc!=SQLITE_OK && rc==sqlite3_errcode(db) && pzErrMsg ){
63634     int nErrMsg = 1 + strlen(sqlite3_errmsg(db));
63635     *pzErrMsg = sqlite3Malloc(nErrMsg);
63636     if( *pzErrMsg ){
63637       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
63638     }
63639   }else if( pzErrMsg ){
63640     *pzErrMsg = 0;
63641   }
63642
63643   assert( (rc&db->errMask)==rc );
63644   sqlite3_mutex_leave(db->mutex);
63645   return rc;
63646 }
63647
63648 /************** End of legacy.c **********************************************/
63649 /************** Begin file loadext.c *****************************************/
63650 /*
63651 ** 2006 June 7
63652 **
63653 ** The author disclaims copyright to this source code.  In place of
63654 ** a legal notice, here is a blessing:
63655 **
63656 **    May you do good and not evil.
63657 **    May you find forgiveness for yourself and forgive others.
63658 **    May you share freely, never taking more than you give.
63659 **
63660 *************************************************************************
63661 ** This file contains code used to dynamically load extensions into
63662 ** the SQLite library.
63663 **
63664 ** $Id: loadext.c,v 1.53 2008/08/02 03:50:39 drh Exp $
63665 */
63666
63667 #ifndef SQLITE_CORE
63668   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
63669 #endif
63670 /************** Include sqlite3ext.h in the middle of loadext.c **************/
63671 /************** Begin file sqlite3ext.h **************************************/
63672 /*
63673 ** 2006 June 7
63674 **
63675 ** The author disclaims copyright to this source code.  In place of
63676 ** a legal notice, here is a blessing:
63677 **
63678 **    May you do good and not evil.
63679 **    May you find forgiveness for yourself and forgive others.
63680 **    May you share freely, never taking more than you give.
63681 **
63682 *************************************************************************
63683 ** This header file defines the SQLite interface for use by
63684 ** shared libraries that want to be imported as extensions into
63685 ** an SQLite instance.  Shared libraries that intend to be loaded
63686 ** as extensions by SQLite should #include this file instead of 
63687 ** sqlite3.h.
63688 **
63689 ** @(#) $Id: sqlite3ext.h,v 1.24 2008/06/30 15:09:29 danielk1977 Exp $
63690 */
63691 #ifndef _SQLITE3EXT_H_
63692 #define _SQLITE3EXT_H_
63693
63694 typedef struct sqlite3_api_routines sqlite3_api_routines;
63695
63696 /*
63697 ** The following structure holds pointers to all of the SQLite API
63698 ** routines.
63699 **
63700 ** WARNING:  In order to maintain backwards compatibility, add new
63701 ** interfaces to the end of this structure only.  If you insert new
63702 ** interfaces in the middle of this structure, then older different
63703 ** versions of SQLite will not be able to load each others' shared
63704 ** libraries!
63705 */
63706 struct sqlite3_api_routines {
63707   void * (*aggregate_context)(sqlite3_context*,int nBytes);
63708   int  (*aggregate_count)(sqlite3_context*);
63709   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
63710   int  (*bind_double)(sqlite3_stmt*,int,double);
63711   int  (*bind_int)(sqlite3_stmt*,int,int);
63712   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
63713   int  (*bind_null)(sqlite3_stmt*,int);
63714   int  (*bind_parameter_count)(sqlite3_stmt*);
63715   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
63716   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
63717   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
63718   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
63719   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
63720   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
63721   int  (*busy_timeout)(sqlite3*,int ms);
63722   int  (*changes)(sqlite3*);
63723   int  (*close)(sqlite3*);
63724   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
63725   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
63726   const void * (*column_blob)(sqlite3_stmt*,int iCol);
63727   int  (*column_bytes)(sqlite3_stmt*,int iCol);
63728   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
63729   int  (*column_count)(sqlite3_stmt*pStmt);
63730   const char * (*column_database_name)(sqlite3_stmt*,int);
63731   const void * (*column_database_name16)(sqlite3_stmt*,int);
63732   const char * (*column_decltype)(sqlite3_stmt*,int i);
63733   const void * (*column_decltype16)(sqlite3_stmt*,int);
63734   double  (*column_double)(sqlite3_stmt*,int iCol);
63735   int  (*column_int)(sqlite3_stmt*,int iCol);
63736   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
63737   const char * (*column_name)(sqlite3_stmt*,int);
63738   const void * (*column_name16)(sqlite3_stmt*,int);
63739   const char * (*column_origin_name)(sqlite3_stmt*,int);
63740   const void * (*column_origin_name16)(sqlite3_stmt*,int);
63741   const char * (*column_table_name)(sqlite3_stmt*,int);
63742   const void * (*column_table_name16)(sqlite3_stmt*,int);
63743   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
63744   const void * (*column_text16)(sqlite3_stmt*,int iCol);
63745   int  (*column_type)(sqlite3_stmt*,int iCol);
63746   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
63747   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
63748   int  (*complete)(const char*sql);
63749   int  (*complete16)(const void*sql);
63750   int  (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
63751   int  (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*));
63752   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*));
63753   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*));
63754   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
63755   int  (*data_count)(sqlite3_stmt*pStmt);
63756   sqlite3 * (*db_handle)(sqlite3_stmt*);
63757   int (*declare_vtab)(sqlite3*,const char*);
63758   int  (*enable_shared_cache)(int);
63759   int  (*errcode)(sqlite3*db);
63760   const char * (*errmsg)(sqlite3*);
63761   const void * (*errmsg16)(sqlite3*);
63762   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
63763   int  (*expired)(sqlite3_stmt*);
63764   int  (*finalize)(sqlite3_stmt*pStmt);
63765   void  (*free)(void*);
63766   void  (*free_table)(char**result);
63767   int  (*get_autocommit)(sqlite3*);
63768   void * (*get_auxdata)(sqlite3_context*,int);
63769   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
63770   int  (*global_recover)(void);
63771   void  (*interruptx)(sqlite3*);
63772   sqlite_int64  (*last_insert_rowid)(sqlite3*);
63773   const char * (*libversion)(void);
63774   int  (*libversion_number)(void);
63775   void *(*malloc)(int);
63776   char * (*mprintf)(const char*,...);
63777   int  (*open)(const char*,sqlite3**);
63778   int  (*open16)(const void*,sqlite3**);
63779   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
63780   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
63781   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
63782   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
63783   void *(*realloc)(void*,int);
63784   int  (*reset)(sqlite3_stmt*pStmt);
63785   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
63786   void  (*result_double)(sqlite3_context*,double);
63787   void  (*result_error)(sqlite3_context*,const char*,int);
63788   void  (*result_error16)(sqlite3_context*,const void*,int);
63789   void  (*result_int)(sqlite3_context*,int);
63790   void  (*result_int64)(sqlite3_context*,sqlite_int64);
63791   void  (*result_null)(sqlite3_context*);
63792   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
63793   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
63794   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
63795   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
63796   void  (*result_value)(sqlite3_context*,sqlite3_value*);
63797   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
63798   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
63799   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
63800   char * (*snprintf)(int,char*,const char*,...);
63801   int  (*step)(sqlite3_stmt*);
63802   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
63803   void  (*thread_cleanup)(void);
63804   int  (*total_changes)(sqlite3*);
63805   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
63806   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
63807   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
63808   void * (*user_data)(sqlite3_context*);
63809   const void * (*value_blob)(sqlite3_value*);
63810   int  (*value_bytes)(sqlite3_value*);
63811   int  (*value_bytes16)(sqlite3_value*);
63812   double  (*value_double)(sqlite3_value*);
63813   int  (*value_int)(sqlite3_value*);
63814   sqlite_int64  (*value_int64)(sqlite3_value*);
63815   int  (*value_numeric_type)(sqlite3_value*);
63816   const unsigned char * (*value_text)(sqlite3_value*);
63817   const void * (*value_text16)(sqlite3_value*);
63818   const void * (*value_text16be)(sqlite3_value*);
63819   const void * (*value_text16le)(sqlite3_value*);
63820   int  (*value_type)(sqlite3_value*);
63821   char *(*vmprintf)(const char*,va_list);
63822   /* Added ??? */
63823   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
63824   /* Added by 3.3.13 */
63825   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
63826   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
63827   int (*clear_bindings)(sqlite3_stmt*);
63828   /* Added by 3.4.1 */
63829   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
63830   /* Added by 3.5.0 */
63831   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
63832   int (*blob_bytes)(sqlite3_blob*);
63833   int (*blob_close)(sqlite3_blob*);
63834   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
63835   int (*blob_read)(sqlite3_blob*,void*,int,int);
63836   int (*blob_write)(sqlite3_blob*,const void*,int,int);
63837   int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
63838   int (*file_control)(sqlite3*,const char*,int,void*);
63839   sqlite3_int64 (*memory_highwater)(int);
63840   sqlite3_int64 (*memory_used)(void);
63841   sqlite3_mutex *(*mutex_alloc)(int);
63842   void (*mutex_enter)(sqlite3_mutex*);
63843   void (*mutex_free)(sqlite3_mutex*);
63844   void (*mutex_leave)(sqlite3_mutex*);
63845   int (*mutex_try)(sqlite3_mutex*);
63846   int (*open_v2)(const char*,sqlite3**,int,const char*);
63847   int (*release_memory)(int);
63848   void (*result_error_nomem)(sqlite3_context*);
63849   void (*result_error_toobig)(sqlite3_context*);
63850   int (*sleep)(int);
63851   void (*soft_heap_limit)(int);
63852   sqlite3_vfs *(*vfs_find)(const char*);
63853   int (*vfs_register)(sqlite3_vfs*,int);
63854   int (*vfs_unregister)(sqlite3_vfs*);
63855   int (*xthreadsafe)(void);
63856   void (*result_zeroblob)(sqlite3_context*,int);
63857   void (*result_error_code)(sqlite3_context*,int);
63858   int (*test_control)(int, ...);
63859   void (*randomness)(int,void*);
63860   sqlite3 *(*context_db_handle)(sqlite3_context*);
63861   int (*extended_result_codes)(sqlite3*,int);
63862   int (*limit)(sqlite3*,int,int);
63863   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
63864   const char *(*sql)(sqlite3_stmt*);
63865   int (*status)(int,int*,int*,int);
63866 };
63867
63868 /*
63869 ** The following macros redefine the API routines so that they are
63870 ** redirected throught the global sqlite3_api structure.
63871 **
63872 ** This header file is also used by the loadext.c source file
63873 ** (part of the main SQLite library - not an extension) so that
63874 ** it can get access to the sqlite3_api_routines structure
63875 ** definition.  But the main library does not want to redefine
63876 ** the API.  So the redefinition macros are only valid if the
63877 ** SQLITE_CORE macros is undefined.
63878 */
63879 #ifndef SQLITE_CORE
63880 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
63881 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
63882 #define sqlite3_bind_blob              sqlite3_api->bind_blob
63883 #define sqlite3_bind_double            sqlite3_api->bind_double
63884 #define sqlite3_bind_int               sqlite3_api->bind_int
63885 #define sqlite3_bind_int64             sqlite3_api->bind_int64
63886 #define sqlite3_bind_null              sqlite3_api->bind_null
63887 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
63888 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
63889 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
63890 #define sqlite3_bind_text              sqlite3_api->bind_text
63891 #define sqlite3_bind_text16            sqlite3_api->bind_text16
63892 #define sqlite3_bind_value             sqlite3_api->bind_value
63893 #define sqlite3_busy_handler           sqlite3_api->busy_handler
63894 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
63895 #define sqlite3_changes                sqlite3_api->changes
63896 #define sqlite3_close                  sqlite3_api->close
63897 #define sqlite3_collation_needed       sqlite3_api->collation_needed
63898 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
63899 #define sqlite3_column_blob            sqlite3_api->column_blob
63900 #define sqlite3_column_bytes           sqlite3_api->column_bytes
63901 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
63902 #define sqlite3_column_count           sqlite3_api->column_count
63903 #define sqlite3_column_database_name   sqlite3_api->column_database_name
63904 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
63905 #define sqlite3_column_decltype        sqlite3_api->column_decltype
63906 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
63907 #define sqlite3_column_double          sqlite3_api->column_double
63908 #define sqlite3_column_int             sqlite3_api->column_int
63909 #define sqlite3_column_int64           sqlite3_api->column_int64
63910 #define sqlite3_column_name            sqlite3_api->column_name
63911 #define sqlite3_column_name16          sqlite3_api->column_name16
63912 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
63913 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
63914 #define sqlite3_column_table_name      sqlite3_api->column_table_name
63915 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
63916 #define sqlite3_column_text            sqlite3_api->column_text
63917 #define sqlite3_column_text16          sqlite3_api->column_text16
63918 #define sqlite3_column_type            sqlite3_api->column_type
63919 #define sqlite3_column_value           sqlite3_api->column_value
63920 #define sqlite3_commit_hook            sqlite3_api->commit_hook
63921 #define sqlite3_complete               sqlite3_api->complete
63922 #define sqlite3_complete16             sqlite3_api->complete16
63923 #define sqlite3_create_collation       sqlite3_api->create_collation
63924 #define sqlite3_create_collation16     sqlite3_api->create_collation16
63925 #define sqlite3_create_function        sqlite3_api->create_function
63926 #define sqlite3_create_function16      sqlite3_api->create_function16
63927 #define sqlite3_create_module          sqlite3_api->create_module
63928 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
63929 #define sqlite3_data_count             sqlite3_api->data_count
63930 #define sqlite3_db_handle              sqlite3_api->db_handle
63931 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
63932 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
63933 #define sqlite3_errcode                sqlite3_api->errcode
63934 #define sqlite3_errmsg                 sqlite3_api->errmsg
63935 #define sqlite3_errmsg16               sqlite3_api->errmsg16
63936 #define sqlite3_exec                   sqlite3_api->exec
63937 #define sqlite3_expired                sqlite3_api->expired
63938 #define sqlite3_finalize               sqlite3_api->finalize
63939 #define sqlite3_free                   sqlite3_api->free
63940 #define sqlite3_free_table             sqlite3_api->free_table
63941 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
63942 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
63943 #define sqlite3_get_table              sqlite3_api->get_table
63944 #define sqlite3_global_recover         sqlite3_api->global_recover
63945 #define sqlite3_interrupt              sqlite3_api->interruptx
63946 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
63947 #define sqlite3_libversion             sqlite3_api->libversion
63948 #define sqlite3_libversion_number      sqlite3_api->libversion_number
63949 #define sqlite3_malloc                 sqlite3_api->malloc
63950 #define sqlite3_mprintf                sqlite3_api->mprintf
63951 #define sqlite3_open                   sqlite3_api->open
63952 #define sqlite3_open16                 sqlite3_api->open16
63953 #define sqlite3_prepare                sqlite3_api->prepare
63954 #define sqlite3_prepare16              sqlite3_api->prepare16
63955 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
63956 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
63957 #define sqlite3_profile                sqlite3_api->profile
63958 #define sqlite3_progress_handler       sqlite3_api->progress_handler
63959 #define sqlite3_realloc                sqlite3_api->realloc
63960 #define sqlite3_reset                  sqlite3_api->reset
63961 #define sqlite3_result_blob            sqlite3_api->result_blob
63962 #define sqlite3_result_double          sqlite3_api->result_double
63963 #define sqlite3_result_error           sqlite3_api->result_error
63964 #define sqlite3_result_error16         sqlite3_api->result_error16
63965 #define sqlite3_result_int             sqlite3_api->result_int
63966 #define sqlite3_result_int64           sqlite3_api->result_int64
63967 #define sqlite3_result_null            sqlite3_api->result_null
63968 #define sqlite3_result_text            sqlite3_api->result_text
63969 #define sqlite3_result_text16          sqlite3_api->result_text16
63970 #define sqlite3_result_text16be        sqlite3_api->result_text16be
63971 #define sqlite3_result_text16le        sqlite3_api->result_text16le
63972 #define sqlite3_result_value           sqlite3_api->result_value
63973 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
63974 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
63975 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
63976 #define sqlite3_snprintf               sqlite3_api->snprintf
63977 #define sqlite3_step                   sqlite3_api->step
63978 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
63979 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
63980 #define sqlite3_total_changes          sqlite3_api->total_changes
63981 #define sqlite3_trace                  sqlite3_api->trace
63982 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
63983 #define sqlite3_update_hook            sqlite3_api->update_hook
63984 #define sqlite3_user_data              sqlite3_api->user_data
63985 #define sqlite3_value_blob             sqlite3_api->value_blob
63986 #define sqlite3_value_bytes            sqlite3_api->value_bytes
63987 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
63988 #define sqlite3_value_double           sqlite3_api->value_double
63989 #define sqlite3_value_int              sqlite3_api->value_int
63990 #define sqlite3_value_int64            sqlite3_api->value_int64
63991 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
63992 #define sqlite3_value_text             sqlite3_api->value_text
63993 #define sqlite3_value_text16           sqlite3_api->value_text16
63994 #define sqlite3_value_text16be         sqlite3_api->value_text16be
63995 #define sqlite3_value_text16le         sqlite3_api->value_text16le
63996 #define sqlite3_value_type             sqlite3_api->value_type
63997 #define sqlite3_vmprintf               sqlite3_api->vmprintf
63998 #define sqlite3_overload_function      sqlite3_api->overload_function
63999 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
64000 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
64001 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
64002 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
64003 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
64004 #define sqlite3_blob_close             sqlite3_api->blob_close
64005 #define sqlite3_blob_open              sqlite3_api->blob_open
64006 #define sqlite3_blob_read              sqlite3_api->blob_read
64007 #define sqlite3_blob_write             sqlite3_api->blob_write
64008 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
64009 #define sqlite3_file_control           sqlite3_api->file_control
64010 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
64011 #define sqlite3_memory_used            sqlite3_api->memory_used
64012 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
64013 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
64014 #define sqlite3_mutex_free             sqlite3_api->mutex_free
64015 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
64016 #define sqlite3_mutex_try              sqlite3_api->mutex_try
64017 #define sqlite3_open_v2                sqlite3_api->open_v2
64018 #define sqlite3_release_memory         sqlite3_api->release_memory
64019 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
64020 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
64021 #define sqlite3_sleep                  sqlite3_api->sleep
64022 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
64023 #define sqlite3_vfs_find               sqlite3_api->vfs_find
64024 #define sqlite3_vfs_register           sqlite3_api->vfs_register
64025 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
64026 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
64027 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
64028 #define sqlite3_result_error_code      sqlite3_api->result_error_code
64029 #define sqlite3_test_control           sqlite3_api->test_control
64030 #define sqlite3_randomness             sqlite3_api->randomness
64031 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
64032 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
64033 #define sqlite3_limit                  sqlite3_api->limit
64034 #define sqlite3_next_stmt              sqlite3_api->next_stmt
64035 #define sqlite3_sql                    sqlite3_api->sql
64036 #define sqlite3_status                 sqlite3_api->status
64037 #endif /* SQLITE_CORE */
64038
64039 #define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
64040 #define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
64041
64042 #endif /* _SQLITE3EXT_H_ */
64043
64044 /************** End of sqlite3ext.h ******************************************/
64045 /************** Continuing where we left off in loadext.c ********************/
64046
64047 #ifndef SQLITE_OMIT_LOAD_EXTENSION
64048
64049 /*
64050 ** Some API routines are omitted when various features are
64051 ** excluded from a build of SQLite.  Substitute a NULL pointer
64052 ** for any missing APIs.
64053 */
64054 #ifndef SQLITE_ENABLE_COLUMN_METADATA
64055 # define sqlite3_column_database_name   0
64056 # define sqlite3_column_database_name16 0
64057 # define sqlite3_column_table_name      0
64058 # define sqlite3_column_table_name16    0
64059 # define sqlite3_column_origin_name     0
64060 # define sqlite3_column_origin_name16   0
64061 # define sqlite3_table_column_metadata  0
64062 #endif
64063
64064 #ifdef SQLITE_OMIT_AUTHORIZATION
64065 # define sqlite3_set_authorizer         0
64066 #endif
64067
64068 #ifdef SQLITE_OMIT_UTF16
64069 # define sqlite3_bind_text16            0
64070 # define sqlite3_collation_needed16     0
64071 # define sqlite3_column_decltype16      0
64072 # define sqlite3_column_name16          0
64073 # define sqlite3_column_text16          0
64074 # define sqlite3_complete16             0
64075 # define sqlite3_create_collation16     0
64076 # define sqlite3_create_function16      0
64077 # define sqlite3_errmsg16               0
64078 # define sqlite3_open16                 0
64079 # define sqlite3_prepare16              0
64080 # define sqlite3_prepare16_v2           0
64081 # define sqlite3_result_error16         0
64082 # define sqlite3_result_text16          0
64083 # define sqlite3_result_text16be        0
64084 # define sqlite3_result_text16le        0
64085 # define sqlite3_value_text16           0
64086 # define sqlite3_value_text16be         0
64087 # define sqlite3_value_text16le         0
64088 # define sqlite3_column_database_name16 0
64089 # define sqlite3_column_table_name16    0
64090 # define sqlite3_column_origin_name16   0
64091 #endif
64092
64093 #ifdef SQLITE_OMIT_COMPLETE
64094 # define sqlite3_complete 0
64095 # define sqlite3_complete16 0
64096 #endif
64097
64098 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
64099 # define sqlite3_progress_handler 0
64100 #endif
64101
64102 #ifdef SQLITE_OMIT_VIRTUALTABLE
64103 # define sqlite3_create_module 0
64104 # define sqlite3_create_module_v2 0
64105 # define sqlite3_declare_vtab 0
64106 #endif
64107
64108 #ifdef SQLITE_OMIT_SHARED_CACHE
64109 # define sqlite3_enable_shared_cache 0
64110 #endif
64111
64112 #ifdef SQLITE_OMIT_TRACE
64113 # define sqlite3_profile       0
64114 # define sqlite3_trace         0
64115 #endif
64116
64117 #ifdef SQLITE_OMIT_GET_TABLE
64118 # define sqlite3_free_table    0
64119 # define sqlite3_get_table     0
64120 #endif
64121
64122 #ifdef SQLITE_OMIT_INCRBLOB
64123 #define sqlite3_bind_zeroblob  0
64124 #define sqlite3_blob_bytes     0
64125 #define sqlite3_blob_close     0
64126 #define sqlite3_blob_open      0
64127 #define sqlite3_blob_read      0
64128 #define sqlite3_blob_write     0
64129 #endif
64130
64131 /*
64132 ** The following structure contains pointers to all SQLite API routines.
64133 ** A pointer to this structure is passed into extensions when they are
64134 ** loaded so that the extension can make calls back into the SQLite
64135 ** library.
64136 **
64137 ** When adding new APIs, add them to the bottom of this structure
64138 ** in order to preserve backwards compatibility.
64139 **
64140 ** Extensions that use newer APIs should first call the
64141 ** sqlite3_libversion_number() to make sure that the API they
64142 ** intend to use is supported by the library.  Extensions should
64143 ** also check to make sure that the pointer to the function is
64144 ** not NULL before calling it.
64145 */
64146 static const sqlite3_api_routines sqlite3Apis = {
64147   sqlite3_aggregate_context,
64148   sqlite3_aggregate_count,
64149   sqlite3_bind_blob,
64150   sqlite3_bind_double,
64151   sqlite3_bind_int,
64152   sqlite3_bind_int64,
64153   sqlite3_bind_null,
64154   sqlite3_bind_parameter_count,
64155   sqlite3_bind_parameter_index,
64156   sqlite3_bind_parameter_name,
64157   sqlite3_bind_text,
64158   sqlite3_bind_text16,
64159   sqlite3_bind_value,
64160   sqlite3_busy_handler,
64161   sqlite3_busy_timeout,
64162   sqlite3_changes,
64163   sqlite3_close,
64164   sqlite3_collation_needed,
64165   sqlite3_collation_needed16,
64166   sqlite3_column_blob,
64167   sqlite3_column_bytes,
64168   sqlite3_column_bytes16,
64169   sqlite3_column_count,
64170   sqlite3_column_database_name,
64171   sqlite3_column_database_name16,
64172   sqlite3_column_decltype,
64173   sqlite3_column_decltype16,
64174   sqlite3_column_double,
64175   sqlite3_column_int,
64176   sqlite3_column_int64,
64177   sqlite3_column_name,
64178   sqlite3_column_name16,
64179   sqlite3_column_origin_name,
64180   sqlite3_column_origin_name16,
64181   sqlite3_column_table_name,
64182   sqlite3_column_table_name16,
64183   sqlite3_column_text,
64184   sqlite3_column_text16,
64185   sqlite3_column_type,
64186   sqlite3_column_value,
64187   sqlite3_commit_hook,
64188   sqlite3_complete,
64189   sqlite3_complete16,
64190   sqlite3_create_collation,
64191   sqlite3_create_collation16,
64192   sqlite3_create_function,
64193   sqlite3_create_function16,
64194   sqlite3_create_module,
64195   sqlite3_data_count,
64196   sqlite3_db_handle,
64197   sqlite3_declare_vtab,
64198   sqlite3_enable_shared_cache,
64199   sqlite3_errcode,
64200   sqlite3_errmsg,
64201   sqlite3_errmsg16,
64202   sqlite3_exec,
64203   sqlite3_expired,
64204   sqlite3_finalize,
64205   sqlite3_free,
64206   sqlite3_free_table,
64207   sqlite3_get_autocommit,
64208   sqlite3_get_auxdata,
64209   sqlite3_get_table,
64210   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
64211   sqlite3_interrupt,
64212   sqlite3_last_insert_rowid,
64213   sqlite3_libversion,
64214   sqlite3_libversion_number,
64215   sqlite3_malloc,
64216   sqlite3_mprintf,
64217   sqlite3_open,
64218   sqlite3_open16,
64219   sqlite3_prepare,
64220   sqlite3_prepare16,
64221   sqlite3_profile,
64222   sqlite3_progress_handler,
64223   sqlite3_realloc,
64224   sqlite3_reset,
64225   sqlite3_result_blob,
64226   sqlite3_result_double,
64227   sqlite3_result_error,
64228   sqlite3_result_error16,
64229   sqlite3_result_int,
64230   sqlite3_result_int64,
64231   sqlite3_result_null,
64232   sqlite3_result_text,
64233   sqlite3_result_text16,
64234   sqlite3_result_text16be,
64235   sqlite3_result_text16le,
64236   sqlite3_result_value,
64237   sqlite3_rollback_hook,
64238   sqlite3_set_authorizer,
64239   sqlite3_set_auxdata,
64240   sqlite3_snprintf,
64241   sqlite3_step,
64242   sqlite3_table_column_metadata,
64243   sqlite3_thread_cleanup,
64244   sqlite3_total_changes,
64245   sqlite3_trace,
64246   sqlite3_transfer_bindings,
64247   sqlite3_update_hook,
64248   sqlite3_user_data,
64249   sqlite3_value_blob,
64250   sqlite3_value_bytes,
64251   sqlite3_value_bytes16,
64252   sqlite3_value_double,
64253   sqlite3_value_int,
64254   sqlite3_value_int64,
64255   sqlite3_value_numeric_type,
64256   sqlite3_value_text,
64257   sqlite3_value_text16,
64258   sqlite3_value_text16be,
64259   sqlite3_value_text16le,
64260   sqlite3_value_type,
64261   sqlite3_vmprintf,
64262   /*
64263   ** The original API set ends here.  All extensions can call any
64264   ** of the APIs above provided that the pointer is not NULL.  But
64265   ** before calling APIs that follow, extension should check the
64266   ** sqlite3_libversion_number() to make sure they are dealing with
64267   ** a library that is new enough to support that API.
64268   *************************************************************************
64269   */
64270   sqlite3_overload_function,
64271
64272   /*
64273   ** Added after 3.3.13
64274   */
64275   sqlite3_prepare_v2,
64276   sqlite3_prepare16_v2,
64277   sqlite3_clear_bindings,
64278
64279   /*
64280   ** Added for 3.4.1
64281   */
64282   sqlite3_create_module_v2,
64283
64284   /*
64285   ** Added for 3.5.0
64286   */
64287   sqlite3_bind_zeroblob,
64288   sqlite3_blob_bytes,
64289   sqlite3_blob_close,
64290   sqlite3_blob_open,
64291   sqlite3_blob_read,
64292   sqlite3_blob_write,
64293   sqlite3_create_collation_v2,
64294   sqlite3_file_control,
64295   sqlite3_memory_highwater,
64296   sqlite3_memory_used,
64297 #ifdef SQLITE_MUTEX_NOOP
64298   0, 
64299   0, 
64300   0,
64301   0,
64302   0,
64303 #else
64304   sqlite3_mutex_alloc,
64305   sqlite3_mutex_enter,
64306   sqlite3_mutex_free,
64307   sqlite3_mutex_leave,
64308   sqlite3_mutex_try,
64309 #endif
64310   sqlite3_open_v2,
64311   sqlite3_release_memory,
64312   sqlite3_result_error_nomem,
64313   sqlite3_result_error_toobig,
64314   sqlite3_sleep,
64315   sqlite3_soft_heap_limit,
64316   sqlite3_vfs_find,
64317   sqlite3_vfs_register,
64318   sqlite3_vfs_unregister,
64319
64320   /*
64321   ** Added for 3.5.8
64322   */
64323   sqlite3_threadsafe,
64324   sqlite3_result_zeroblob,
64325   sqlite3_result_error_code,
64326   sqlite3_test_control,
64327   sqlite3_randomness,
64328   sqlite3_context_db_handle,
64329
64330   /*
64331   ** Added for 3.6.0
64332   */
64333   sqlite3_extended_result_codes,
64334   sqlite3_limit,
64335   sqlite3_next_stmt,
64336   sqlite3_sql,
64337   sqlite3_status,
64338 };
64339
64340 /*
64341 ** Attempt to load an SQLite extension library contained in the file
64342 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
64343 ** default entry point name (sqlite3_extension_init) is used.  Use
64344 ** of the default name is recommended.
64345 **
64346 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
64347 **
64348 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
64349 ** error message text.  The calling function should free this memory
64350 ** by calling sqlite3DbFree(db, ).
64351 */
64352 static int sqlite3LoadExtension(
64353   sqlite3 *db,          /* Load the extension into this database connection */
64354   const char *zFile,    /* Name of the shared library containing extension */
64355   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
64356   char **pzErrMsg       /* Put error message here if not 0 */
64357 ){
64358   sqlite3_vfs *pVfs = db->pVfs;
64359   void *handle;
64360   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
64361   char *zErrmsg = 0;
64362   void **aHandle;
64363
64364   /* Ticket #1863.  To avoid a creating security problems for older
64365   ** applications that relink against newer versions of SQLite, the
64366   ** ability to run load_extension is turned off by default.  One
64367   ** must call sqlite3_enable_load_extension() to turn on extension
64368   ** loading.  Otherwise you get the following error.
64369   */
64370   if( (db->flags & SQLITE_LoadExtension)==0 ){
64371     if( pzErrMsg ){
64372       *pzErrMsg = sqlite3_mprintf("not authorized");
64373     }
64374     return SQLITE_ERROR;
64375   }
64376
64377   if( zProc==0 ){
64378     zProc = "sqlite3_extension_init";
64379   }
64380
64381   handle = sqlite3OsDlOpen(pVfs, zFile);
64382   if( handle==0 ){
64383     if( pzErrMsg ){
64384       char zErr[256];
64385       zErr[sizeof(zErr)-1] = '\0';
64386       sqlite3_snprintf(sizeof(zErr)-1, zErr, 
64387           "unable to open shared library [%s]", zFile);
64388       sqlite3OsDlError(pVfs, sizeof(zErr)-1, zErr);
64389       *pzErrMsg = sqlite3DbStrDup(0, zErr);
64390     }
64391     return SQLITE_ERROR;
64392   }
64393   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
64394                    sqlite3OsDlSym(pVfs, handle, zProc);
64395   if( xInit==0 ){
64396     if( pzErrMsg ){
64397       char zErr[256];
64398       zErr[sizeof(zErr)-1] = '\0';
64399       sqlite3_snprintf(sizeof(zErr)-1, zErr,
64400           "no entry point [%s] in shared library [%s]", zProc,zFile);
64401       sqlite3OsDlError(pVfs, sizeof(zErr)-1, zErr);
64402       *pzErrMsg = sqlite3DbStrDup(0, zErr);
64403       sqlite3OsDlClose(pVfs, handle);
64404     }
64405     return SQLITE_ERROR;
64406   }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
64407     if( pzErrMsg ){
64408       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
64409     }
64410     sqlite3_free(zErrmsg);
64411     sqlite3OsDlClose(pVfs, handle);
64412     return SQLITE_ERROR;
64413   }
64414
64415   /* Append the new shared library handle to the db->aExtension array. */
64416   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
64417   if( aHandle==0 ){
64418     return SQLITE_NOMEM;
64419   }
64420   if( db->nExtension>0 ){
64421     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
64422   }
64423   sqlite3DbFree(db, db->aExtension);
64424   db->aExtension = aHandle;
64425
64426   db->aExtension[db->nExtension++] = handle;
64427   return SQLITE_OK;
64428 }
64429 SQLITE_API int sqlite3_load_extension(
64430   sqlite3 *db,          /* Load the extension into this database connection */
64431   const char *zFile,    /* Name of the shared library containing extension */
64432   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
64433   char **pzErrMsg       /* Put error message here if not 0 */
64434 ){
64435   int rc;
64436   sqlite3_mutex_enter(db->mutex);
64437   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
64438   sqlite3_mutex_leave(db->mutex);
64439   return rc;
64440 }
64441
64442 /*
64443 ** Call this routine when the database connection is closing in order
64444 ** to clean up loaded extensions
64445 */
64446 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
64447   int i;
64448   assert( sqlite3_mutex_held(db->mutex) );
64449   for(i=0; i<db->nExtension; i++){
64450     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
64451   }
64452   sqlite3DbFree(db, db->aExtension);
64453 }
64454
64455 /*
64456 ** Enable or disable extension loading.  Extension loading is disabled by
64457 ** default so as not to open security holes in older applications.
64458 */
64459 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
64460   sqlite3_mutex_enter(db->mutex);
64461   if( onoff ){
64462     db->flags |= SQLITE_LoadExtension;
64463   }else{
64464     db->flags &= ~SQLITE_LoadExtension;
64465   }
64466   sqlite3_mutex_leave(db->mutex);
64467   return SQLITE_OK;
64468 }
64469
64470 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
64471
64472 /*
64473 ** The auto-extension code added regardless of whether or not extension
64474 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
64475 ** code if regular extension loading is not available.  This is that
64476 ** dummy pointer.
64477 */
64478 #ifdef SQLITE_OMIT_LOAD_EXTENSION
64479 static const sqlite3_api_routines sqlite3Apis = { 0 };
64480 #endif
64481
64482
64483 /*
64484 ** The following object holds the list of automatically loaded
64485 ** extensions.
64486 **
64487 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
64488 ** mutex must be held while accessing this list.
64489 */
64490 static struct {
64491   int nExt;        /* Number of entries in aExt[] */          
64492   void **aExt;     /* Pointers to the extension init functions */
64493 } autoext = { 0, 0 };
64494
64495
64496 /*
64497 ** Register a statically linked extension that is automatically
64498 ** loaded by every new database connection.
64499 */
64500 SQLITE_API int sqlite3_auto_extension(void *xInit){
64501   int rc = SQLITE_OK;
64502 #ifndef SQLITE_OMIT_AUTOINIT
64503   rc = sqlite3_initialize();
64504   if( rc ){
64505     return rc;
64506   }else
64507 #endif
64508   {
64509     int i;
64510 #ifndef SQLITE_MUTEX_NOOP
64511     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
64512 #endif
64513     sqlite3_mutex_enter(mutex);
64514     for(i=0; i<autoext.nExt; i++){
64515       if( autoext.aExt[i]==xInit ) break;
64516     }
64517     if( i==autoext.nExt ){
64518       int nByte = (autoext.nExt+1)*sizeof(autoext.aExt[0]);
64519       void **aNew;
64520       aNew = sqlite3_realloc(autoext.aExt, nByte);
64521       if( aNew==0 ){
64522         rc = SQLITE_NOMEM;
64523       }else{
64524         autoext.aExt = aNew;
64525         autoext.aExt[autoext.nExt] = xInit;
64526         autoext.nExt++;
64527       }
64528     }
64529     sqlite3_mutex_leave(mutex);
64530     assert( (rc&0xff)==rc );
64531     return rc;
64532   }
64533 }
64534
64535 /*
64536 ** Reset the automatic extension loading mechanism.
64537 */
64538 SQLITE_API void sqlite3_reset_auto_extension(void){
64539 #ifndef SQLITE_OMIT_AUTOINIT
64540   if( sqlite3_initialize()==SQLITE_OK )
64541 #endif
64542   {
64543 #ifndef SQLITE_MUTEX_NOOP
64544     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
64545 #endif
64546     sqlite3_mutex_enter(mutex);
64547     sqlite3_free(autoext.aExt);
64548     autoext.aExt = 0;
64549     autoext.nExt = 0;
64550     sqlite3_mutex_leave(mutex);
64551   }
64552 }
64553
64554 /*
64555 ** Load all automatic extensions.
64556 */
64557 SQLITE_PRIVATE int sqlite3AutoLoadExtensions(sqlite3 *db){
64558   int i;
64559   int go = 1;
64560   int rc = SQLITE_OK;
64561   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
64562
64563   if( autoext.nExt==0 ){
64564     /* Common case: early out without every having to acquire a mutex */
64565     return SQLITE_OK;
64566   }
64567   for(i=0; go; i++){
64568     char *zErrmsg = 0;
64569 #ifndef SQLITE_MUTEX_NOOP
64570     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
64571 #endif
64572     sqlite3_mutex_enter(mutex);
64573     if( i>=autoext.nExt ){
64574       xInit = 0;
64575       go = 0;
64576     }else{
64577       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
64578               autoext.aExt[i];
64579     }
64580     sqlite3_mutex_leave(mutex);
64581     if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
64582       sqlite3Error(db, SQLITE_ERROR,
64583             "automatic extension loading failed: %s", zErrmsg);
64584       go = 0;
64585       rc = SQLITE_ERROR;
64586       sqlite3_free(zErrmsg);
64587     }
64588   }
64589   return rc;
64590 }
64591
64592 /************** End of loadext.c *********************************************/
64593 /************** Begin file pragma.c ******************************************/
64594 /*
64595 ** 2003 April 6
64596 **
64597 ** The author disclaims copyright to this source code.  In place of
64598 ** a legal notice, here is a blessing:
64599 **
64600 **    May you do good and not evil.
64601 **    May you find forgiveness for yourself and forgive others.
64602 **    May you share freely, never taking more than you give.
64603 **
64604 *************************************************************************
64605 ** This file contains code used to implement the PRAGMA command.
64606 **
64607 ** $Id: pragma.c,v 1.183 2008/07/28 19:34:53 drh Exp $
64608 */
64609
64610 /* Ignore this whole file if pragmas are disabled
64611 */
64612 #if !defined(SQLITE_OMIT_PRAGMA) && !defined(SQLITE_OMIT_PARSER)
64613
64614 /*
64615 ** Interpret the given string as a safety level.  Return 0 for OFF,
64616 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or 
64617 ** unrecognized string argument.
64618 **
64619 ** Note that the values returned are one less that the values that
64620 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
64621 ** to support legacy SQL code.  The safety level used to be boolean
64622 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
64623 */
64624 static int getSafetyLevel(const char *z){
64625                              /* 123456789 123456789 */
64626   static const char zText[] = "onoffalseyestruefull";
64627   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
64628   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
64629   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
64630   int i, n;
64631   if( isdigit(*z) ){
64632     return atoi(z);
64633   }
64634   n = strlen(z);
64635   for(i=0; i<sizeof(iLength); i++){
64636     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
64637       return iValue[i];
64638     }
64639   }
64640   return 1;
64641 }
64642
64643 /*
64644 ** Interpret the given string as a boolean value.
64645 */
64646 static int getBoolean(const char *z){
64647   return getSafetyLevel(z)&1;
64648 }
64649
64650 /*
64651 ** Interpret the given string as a locking mode value.
64652 */
64653 static int getLockingMode(const char *z){
64654   if( z ){
64655     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
64656     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
64657   }
64658   return PAGER_LOCKINGMODE_QUERY;
64659 }
64660
64661 #ifndef SQLITE_OMIT_AUTOVACUUM
64662 /*
64663 ** Interpret the given string as an auto-vacuum mode value.
64664 **
64665 ** The following strings, "none", "full" and "incremental" are 
64666 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
64667 */
64668 static int getAutoVacuum(const char *z){
64669   int i;
64670   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
64671   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
64672   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
64673   i = atoi(z);
64674   return ((i>=0&&i<=2)?i:0);
64675 }
64676 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
64677
64678 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
64679 /*
64680 ** Interpret the given string as a temp db location. Return 1 for file
64681 ** backed temporary databases, 2 for the Red-Black tree in memory database
64682 ** and 0 to use the compile-time default.
64683 */
64684 static int getTempStore(const char *z){
64685   if( z[0]>='0' && z[0]<='2' ){
64686     return z[0] - '0';
64687   }else if( sqlite3StrICmp(z, "file")==0 ){
64688     return 1;
64689   }else if( sqlite3StrICmp(z, "memory")==0 ){
64690     return 2;
64691   }else{
64692     return 0;
64693   }
64694 }
64695 #endif /* SQLITE_PAGER_PRAGMAS */
64696
64697 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
64698 /*
64699 ** Invalidate temp storage, either when the temp storage is changed
64700 ** from default, or when 'file' and the temp_store_directory has changed
64701 */
64702 static int invalidateTempStorage(Parse *pParse){
64703   sqlite3 *db = pParse->db;
64704   if( db->aDb[1].pBt!=0 ){
64705     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
64706       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
64707         "from within a transaction");
64708       return SQLITE_ERROR;
64709     }
64710     sqlite3BtreeClose(db->aDb[1].pBt);
64711     db->aDb[1].pBt = 0;
64712     sqlite3ResetInternalSchema(db, 0);
64713   }
64714   return SQLITE_OK;
64715 }
64716 #endif /* SQLITE_PAGER_PRAGMAS */
64717
64718 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
64719 /*
64720 ** If the TEMP database is open, close it and mark the database schema
64721 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
64722 ** or DEFAULT_TEMP_STORE pragmas.
64723 */
64724 static int changeTempStorage(Parse *pParse, const char *zStorageType){
64725   int ts = getTempStore(zStorageType);
64726   sqlite3 *db = pParse->db;
64727   if( db->temp_store==ts ) return SQLITE_OK;
64728   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
64729     return SQLITE_ERROR;
64730   }
64731   db->temp_store = ts;
64732   return SQLITE_OK;
64733 }
64734 #endif /* SQLITE_PAGER_PRAGMAS */
64735
64736 /*
64737 ** Generate code to return a single integer value.
64738 */
64739 static void returnSingleInt(Parse *pParse, const char *zLabel, int value){
64740   Vdbe *v = sqlite3GetVdbe(pParse);
64741   int mem = ++pParse->nMem;
64742   sqlite3VdbeAddOp2(v, OP_Integer, value, mem);
64743   if( pParse->explain==0 ){
64744     sqlite3VdbeSetNumCols(v, 1);
64745     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, P4_STATIC);
64746   }
64747   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
64748 }
64749
64750 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
64751 /*
64752 ** Check to see if zRight and zLeft refer to a pragma that queries
64753 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
64754 ** Also, implement the pragma.
64755 */
64756 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
64757   static const struct sPragmaType {
64758     const char *zName;  /* Name of the pragma */
64759     int mask;           /* Mask for the db->flags value */
64760   } aPragma[] = {
64761     { "full_column_names",        SQLITE_FullColNames  },
64762     { "short_column_names",       SQLITE_ShortColNames },
64763     { "count_changes",            SQLITE_CountRows     },
64764     { "empty_result_callbacks",   SQLITE_NullCallback  },
64765     { "legacy_file_format",       SQLITE_LegacyFileFmt },
64766     { "fullfsync",                SQLITE_FullFSync     },
64767 #ifdef SQLITE_DEBUG
64768     { "sql_trace",                SQLITE_SqlTrace      },
64769     { "vdbe_listing",             SQLITE_VdbeListing   },
64770     { "vdbe_trace",               SQLITE_VdbeTrace     },
64771 #endif
64772 #ifndef SQLITE_OMIT_CHECK
64773     { "ignore_check_constraints", SQLITE_IgnoreChecks  },
64774 #endif
64775     /* The following is VERY experimental */
64776     { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
64777     { "omit_readlock",            SQLITE_NoReadlock    },
64778
64779     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
64780     ** flag if there are any active statements. */
64781     { "read_uncommitted",         SQLITE_ReadUncommitted },
64782   };
64783   int i;
64784   const struct sPragmaType *p;
64785   for(i=0, p=aPragma; i<sizeof(aPragma)/sizeof(aPragma[0]); i++, p++){
64786     if( sqlite3StrICmp(zLeft, p->zName)==0 ){
64787       sqlite3 *db = pParse->db;
64788       Vdbe *v;
64789       v = sqlite3GetVdbe(pParse);
64790       if( v ){
64791         if( zRight==0 ){
64792           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
64793         }else{
64794           if( getBoolean(zRight) ){
64795             db->flags |= p->mask;
64796           }else{
64797             db->flags &= ~p->mask;
64798           }
64799
64800           /* Many of the flag-pragmas modify the code generated by the SQL 
64801           ** compiler (eg. count_changes). So add an opcode to expire all
64802           ** compiled SQL statements after modifying a pragma value.
64803           */
64804           sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
64805         }
64806       }
64807
64808       return 1;
64809     }
64810   }
64811   return 0;
64812 }
64813 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
64814
64815 /*
64816 ** Process a pragma statement.  
64817 **
64818 ** Pragmas are of this form:
64819 **
64820 **      PRAGMA [database.]id [= value]
64821 **
64822 ** The identifier might also be a string.  The value is a string, and
64823 ** identifier, or a number.  If minusFlag is true, then the value is
64824 ** a number that was preceded by a minus sign.
64825 **
64826 ** If the left side is "database.id" then pId1 is the database name
64827 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
64828 ** id and pId2 is any empty string.
64829 */
64830 SQLITE_PRIVATE void sqlite3Pragma(
64831   Parse *pParse, 
64832   Token *pId1,        /* First part of [database.]id field */
64833   Token *pId2,        /* Second part of [database.]id field, or NULL */
64834   Token *pValue,      /* Token for <value>, or NULL */
64835   int minusFlag       /* True if a '-' sign preceded <value> */
64836 ){
64837   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
64838   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
64839   const char *zDb = 0;   /* The database name */
64840   Token *pId;            /* Pointer to <id> token */
64841   int iDb;               /* Database index for <database> */
64842   sqlite3 *db = pParse->db;
64843   Db *pDb;
64844   Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
64845   if( v==0 ) return;
64846   pParse->nMem = 2;
64847
64848   /* Interpret the [database.] part of the pragma statement. iDb is the
64849   ** index of the database this pragma is being applied to in db.aDb[]. */
64850   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
64851   if( iDb<0 ) return;
64852   pDb = &db->aDb[iDb];
64853
64854   /* If the temp database has been explicitly named as part of the 
64855   ** pragma, make sure it is open. 
64856   */
64857   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
64858     return;
64859   }
64860
64861   zLeft = sqlite3NameFromToken(db, pId);
64862   if( !zLeft ) return;
64863   if( minusFlag ){
64864     zRight = sqlite3MPrintf(db, "-%T", pValue);
64865   }else{
64866     zRight = sqlite3NameFromToken(db, pValue);
64867   }
64868
64869   zDb = ((iDb>0)?pDb->zName:0);
64870   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
64871     goto pragma_out;
64872   }
64873  
64874 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
64875   /*
64876   **  PRAGMA [database.]default_cache_size
64877   **  PRAGMA [database.]default_cache_size=N
64878   **
64879   ** The first form reports the current persistent setting for the
64880   ** page cache size.  The value returned is the maximum number of
64881   ** pages in the page cache.  The second form sets both the current
64882   ** page cache size value and the persistent page cache size value
64883   ** stored in the database file.
64884   **
64885   ** The default cache size is stored in meta-value 2 of page 1 of the
64886   ** database file.  The cache size is actually the absolute value of
64887   ** this memory location.  The sign of meta-value 2 determines the
64888   ** synchronous setting.  A negative value means synchronous is off
64889   ** and a positive value means synchronous is on.
64890   */
64891   if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
64892     static const VdbeOpList getCacheSize[] = {
64893       { OP_ReadCookie,  0, 1,        2},  /* 0 */
64894       { OP_IfPos,       1, 6,        0},
64895       { OP_Integer,     0, 2,        0},
64896       { OP_Subtract,    1, 2,        1},
64897       { OP_IfPos,       1, 6,        0},
64898       { OP_Integer,     0, 1,        0},  /* 5 */
64899       { OP_ResultRow,   1, 1,        0},
64900     };
64901     int addr;
64902     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
64903     sqlite3VdbeUsesBtree(v, iDb);
64904     if( !zRight ){
64905       sqlite3VdbeSetNumCols(v, 1);
64906       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", P4_STATIC);
64907       pParse->nMem += 2;
64908       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
64909       sqlite3VdbeChangeP1(v, addr, iDb);
64910       sqlite3VdbeChangeP1(v, addr+5, SQLITE_DEFAULT_CACHE_SIZE);
64911     }else{
64912       int size = atoi(zRight);
64913       if( size<0 ) size = -size;
64914       sqlite3BeginWriteOperation(pParse, 0, iDb);
64915       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
64916       sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, 2, 2);
64917       addr = sqlite3VdbeAddOp2(v, OP_IfPos, 2, 0);
64918       sqlite3VdbeAddOp2(v, OP_Integer, -size, 1);
64919       sqlite3VdbeJumpHere(v, addr);
64920       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 2, 1);
64921       pDb->pSchema->cache_size = size;
64922       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
64923     }
64924   }else
64925
64926   /*
64927   **  PRAGMA [database.]page_size
64928   **  PRAGMA [database.]page_size=N
64929   **
64930   ** The first form reports the current setting for the
64931   ** database page size in bytes.  The second form sets the
64932   ** database page size value.  The value can only be set if
64933   ** the database has not yet been created.
64934   */
64935   if( sqlite3StrICmp(zLeft,"page_size")==0 ){
64936     Btree *pBt = pDb->pBt;
64937     if( !zRight ){
64938       int size = pBt ? sqlite3BtreeGetPageSize(pBt) : 0;
64939       returnSingleInt(pParse, "page_size", size);
64940     }else{
64941       /* Malloc may fail when setting the page-size, as there is an internal
64942       ** buffer that the pager module resizes using sqlite3_realloc().
64943       */
64944       db->nextPagesize = atoi(zRight);
64945       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1) ){
64946         db->mallocFailed = 1;
64947       }
64948     }
64949   }else
64950
64951   /*
64952   **  PRAGMA [database.]max_page_count
64953   **  PRAGMA [database.]max_page_count=N
64954   **
64955   ** The first form reports the current setting for the
64956   ** maximum number of pages in the database file.  The 
64957   ** second form attempts to change this setting.  Both
64958   ** forms return the current setting.
64959   */
64960   if( sqlite3StrICmp(zLeft,"max_page_count")==0 ){
64961     Btree *pBt = pDb->pBt;
64962     int newMax = 0;
64963     if( zRight ){
64964       newMax = atoi(zRight);
64965     }
64966     if( pBt ){
64967       newMax = sqlite3BtreeMaxPageCount(pBt, newMax);
64968     }
64969     returnSingleInt(pParse, "max_page_count", newMax);
64970   }else
64971
64972   /*
64973   **  PRAGMA [database.]page_count
64974   **
64975   ** Return the number of pages in the specified database.
64976   */
64977   if( sqlite3StrICmp(zLeft,"page_count")==0 ){
64978     Vdbe *v;
64979     int iReg;
64980     v = sqlite3GetVdbe(pParse);
64981     if( !v || sqlite3ReadSchema(pParse) ) goto pragma_out;
64982     sqlite3CodeVerifySchema(pParse, iDb);
64983     iReg = ++pParse->nMem;
64984     sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
64985     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
64986     sqlite3VdbeSetNumCols(v, 1);
64987     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "page_count", P4_STATIC);
64988   }else
64989
64990   /*
64991   **  PRAGMA [database.]locking_mode
64992   **  PRAGMA [database.]locking_mode = (normal|exclusive)
64993   */
64994   if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
64995     const char *zRet = "normal";
64996     int eMode = getLockingMode(zRight);
64997
64998     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
64999       /* Simple "PRAGMA locking_mode;" statement. This is a query for
65000       ** the current default locking mode (which may be different to
65001       ** the locking-mode of the main database).
65002       */
65003       eMode = db->dfltLockMode;
65004     }else{
65005       Pager *pPager;
65006       if( pId2->n==0 ){
65007         /* This indicates that no database name was specified as part
65008         ** of the PRAGMA command. In this case the locking-mode must be
65009         ** set on all attached databases, as well as the main db file.
65010         **
65011         ** Also, the sqlite3.dfltLockMode variable is set so that
65012         ** any subsequently attached databases also use the specified
65013         ** locking mode.
65014         */
65015         int ii;
65016         assert(pDb==&db->aDb[0]);
65017         for(ii=2; ii<db->nDb; ii++){
65018           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
65019           sqlite3PagerLockingMode(pPager, eMode);
65020         }
65021         db->dfltLockMode = eMode;
65022       }
65023       pPager = sqlite3BtreePager(pDb->pBt);
65024       eMode = sqlite3PagerLockingMode(pPager, eMode);
65025     }
65026
65027     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
65028     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
65029       zRet = "exclusive";
65030     }
65031     sqlite3VdbeSetNumCols(v, 1);
65032     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", P4_STATIC);
65033     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
65034     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
65035   }else
65036
65037   /*
65038   **  PRAGMA [database.]journal_mode
65039   **  PRAGMA [database.]journal_mode = (delete|persist|off)
65040   */
65041   if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
65042     int eMode;
65043     static const char *azModeName[] = {"delete", "persist", "off"};
65044
65045     if( zRight==0 ){
65046       eMode = PAGER_JOURNALMODE_QUERY;
65047     }else{
65048       int n = strlen(zRight);
65049       eMode = 2;
65050       while( eMode>=0 && sqlite3StrNICmp(zRight, azModeName[eMode], n)!=0 ){
65051         eMode--;
65052       }
65053     }
65054     if( pId2->n==0 && eMode==PAGER_JOURNALMODE_QUERY ){
65055       /* Simple "PRAGMA journal_mode;" statement. This is a query for
65056       ** the current default journal mode (which may be different to
65057       ** the journal-mode of the main database).
65058       */
65059       eMode = db->dfltJournalMode;
65060     }else{
65061       Pager *pPager;
65062       if( pId2->n==0 ){
65063         /* This indicates that no database name was specified as part
65064         ** of the PRAGMA command. In this case the journal-mode must be
65065         ** set on all attached databases, as well as the main db file.
65066         **
65067         ** Also, the sqlite3.dfltJournalMode variable is set so that
65068         ** any subsequently attached databases also use the specified
65069         ** journal mode.
65070         */
65071         int ii;
65072         assert(pDb==&db->aDb[0]);
65073         for(ii=1; ii<db->nDb; ii++){
65074           if( db->aDb[ii].pBt ){
65075             pPager = sqlite3BtreePager(db->aDb[ii].pBt);
65076             sqlite3PagerJournalMode(pPager, eMode);
65077           }
65078         }
65079         db->dfltJournalMode = eMode;
65080       }
65081       pPager = sqlite3BtreePager(pDb->pBt);
65082       eMode = sqlite3PagerJournalMode(pPager, eMode);
65083     }
65084     assert( eMode==PAGER_JOURNALMODE_DELETE
65085               || eMode==PAGER_JOURNALMODE_PERSIST
65086               || eMode==PAGER_JOURNALMODE_OFF );
65087     sqlite3VdbeSetNumCols(v, 1);
65088     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", P4_STATIC);
65089     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, 
65090            azModeName[eMode], P4_STATIC);
65091     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
65092   }else
65093
65094   /*
65095   **  PRAGMA [database.]journal_size_limit
65096   **  PRAGMA [database.]journal_size_limit=N
65097   **
65098   ** Get or set the (boolean) value of the database 'auto-vacuum' parameter.
65099   */
65100   if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
65101     Pager *pPager = sqlite3BtreePager(pDb->pBt);
65102     i64 iLimit = -2;
65103     if( zRight ){
65104       int iLimit32 = atoi(zRight);
65105       if( iLimit32<-1 ){
65106         iLimit32 = -1;
65107       }
65108       iLimit = iLimit32;
65109     }
65110     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
65111     returnSingleInt(pParse, "journal_size_limit", (int)iLimit);
65112   }else
65113
65114 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
65115
65116   /*
65117   **  PRAGMA [database.]auto_vacuum
65118   **  PRAGMA [database.]auto_vacuum=N
65119   **
65120   ** Get or set the (boolean) value of the database 'auto-vacuum' parameter.
65121   */
65122 #ifndef SQLITE_OMIT_AUTOVACUUM
65123   if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
65124     Btree *pBt = pDb->pBt;
65125     if( sqlite3ReadSchema(pParse) ){
65126       goto pragma_out;
65127     }
65128     if( !zRight ){
65129       int auto_vacuum = 
65130           pBt ? sqlite3BtreeGetAutoVacuum(pBt) : SQLITE_DEFAULT_AUTOVACUUM;
65131       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
65132     }else{
65133       int eAuto = getAutoVacuum(zRight);
65134       db->nextAutovac = eAuto;
65135       if( eAuto>=0 ){
65136         /* Call SetAutoVacuum() to set initialize the internal auto and
65137         ** incr-vacuum flags. This is required in case this connection
65138         ** creates the database file. It is important that it is created
65139         ** as an auto-vacuum capable db.
65140         */
65141         int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
65142         if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
65143           /* When setting the auto_vacuum mode to either "full" or 
65144           ** "incremental", write the value of meta[6] in the database
65145           ** file. Before writing to meta[6], check that meta[3] indicates
65146           ** that this really is an auto-vacuum capable database.
65147           */
65148           static const VdbeOpList setMeta6[] = {
65149             { OP_Transaction,    0,               1,        0},    /* 0 */
65150             { OP_ReadCookie,     0,               1,        3},    /* 1 */
65151             { OP_If,             1,               0,        0},    /* 2 */
65152             { OP_Halt,           SQLITE_OK,       OE_Abort, 0},    /* 3 */
65153             { OP_Integer,        0,               1,        0},    /* 4 */
65154             { OP_SetCookie,      0,               6,        1},    /* 5 */
65155           };
65156           int iAddr;
65157           iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
65158           sqlite3VdbeChangeP1(v, iAddr, iDb);
65159           sqlite3VdbeChangeP1(v, iAddr+1, iDb);
65160           sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
65161           sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
65162           sqlite3VdbeChangeP1(v, iAddr+5, iDb);
65163           sqlite3VdbeUsesBtree(v, iDb);
65164         }
65165       }
65166     }
65167   }else
65168 #endif
65169
65170   /*
65171   **  PRAGMA [database.]incremental_vacuum(N)
65172   **
65173   ** Do N steps of incremental vacuuming on a database.
65174   */
65175 #ifndef SQLITE_OMIT_AUTOVACUUM
65176   if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
65177     int iLimit, addr;
65178     if( sqlite3ReadSchema(pParse) ){
65179       goto pragma_out;
65180     }
65181     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
65182       iLimit = 0x7fffffff;
65183     }
65184     sqlite3BeginWriteOperation(pParse, 0, iDb);
65185     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
65186     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
65187     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
65188     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
65189     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
65190     sqlite3VdbeJumpHere(v, addr);
65191   }else
65192 #endif
65193
65194 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
65195   /*
65196   **  PRAGMA [database.]cache_size
65197   **  PRAGMA [database.]cache_size=N
65198   **
65199   ** The first form reports the current local setting for the
65200   ** page cache size.  The local setting can be different from
65201   ** the persistent cache size value that is stored in the database
65202   ** file itself.  The value returned is the maximum number of
65203   ** pages in the page cache.  The second form sets the local
65204   ** page cache size value.  It does not change the persistent
65205   ** cache size stored on the disk so the cache size will revert
65206   ** to its default value when the database is closed and reopened.
65207   ** N should be a positive integer.
65208   */
65209   if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
65210     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
65211     if( !zRight ){
65212       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
65213     }else{
65214       int size = atoi(zRight);
65215       if( size<0 ) size = -size;
65216       pDb->pSchema->cache_size = size;
65217       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
65218     }
65219   }else
65220
65221   /*
65222   **   PRAGMA temp_store
65223   **   PRAGMA temp_store = "default"|"memory"|"file"
65224   **
65225   ** Return or set the local value of the temp_store flag.  Changing
65226   ** the local value does not make changes to the disk file and the default
65227   ** value will be restored the next time the database is opened.
65228   **
65229   ** Note that it is possible for the library compile-time options to
65230   ** override this setting
65231   */
65232   if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
65233     if( !zRight ){
65234       returnSingleInt(pParse, "temp_store", db->temp_store);
65235     }else{
65236       changeTempStorage(pParse, zRight);
65237     }
65238   }else
65239
65240   /*
65241   **   PRAGMA temp_store_directory
65242   **   PRAGMA temp_store_directory = ""|"directory_name"
65243   **
65244   ** Return or set the local value of the temp_store_directory flag.  Changing
65245   ** the value sets a specific directory to be used for temporary files.
65246   ** Setting to a null string reverts to the default temporary directory search.
65247   ** If temporary directory is changed, then invalidateTempStorage.
65248   **
65249   */
65250   if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
65251     if( !zRight ){
65252       if( sqlite3_temp_directory ){
65253         sqlite3VdbeSetNumCols(v, 1);
65254         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
65255             "temp_store_directory", P4_STATIC);
65256         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
65257         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
65258       }
65259     }else{
65260       if( zRight[0] ){
65261         int res;
65262         sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
65263         if( res==0 ){
65264           sqlite3ErrorMsg(pParse, "not a writable directory");
65265           goto pragma_out;
65266         }
65267       }
65268       if( SQLITE_TEMP_STORE==0
65269        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
65270        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
65271       ){
65272         invalidateTempStorage(pParse);
65273       }
65274       sqlite3_free(sqlite3_temp_directory);
65275       if( zRight[0] ){
65276         sqlite3_temp_directory = sqlite3DbStrDup(0, zRight);
65277       }else{
65278         sqlite3_temp_directory = 0;
65279       }
65280     }
65281   }else
65282
65283   /*
65284   **   PRAGMA [database.]synchronous
65285   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
65286   **
65287   ** Return or set the local value of the synchronous flag.  Changing
65288   ** the local value does not make changes to the disk file and the
65289   ** default value will be restored the next time the database is
65290   ** opened.
65291   */
65292   if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
65293     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
65294     if( !zRight ){
65295       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
65296     }else{
65297       if( !db->autoCommit ){
65298         sqlite3ErrorMsg(pParse, 
65299             "Safety level may not be changed inside a transaction");
65300       }else{
65301         pDb->safety_level = getSafetyLevel(zRight)+1;
65302       }
65303     }
65304   }else
65305 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
65306
65307 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
65308   if( flagPragma(pParse, zLeft, zRight) ){
65309     /* The flagPragma() subroutine also generates any necessary code
65310     ** there is nothing more to do here */
65311   }else
65312 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
65313
65314 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
65315   /*
65316   **   PRAGMA table_info(<table>)
65317   **
65318   ** Return a single row for each column of the named table. The columns of
65319   ** the returned data set are:
65320   **
65321   ** cid:        Column id (numbered from left to right, starting at 0)
65322   ** name:       Column name
65323   ** type:       Column declaration type.
65324   ** notnull:    True if 'NOT NULL' is part of column declaration
65325   ** dflt_value: The default value for the column, if any.
65326   */
65327   if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
65328     Table *pTab;
65329     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
65330     pTab = sqlite3FindTable(db, zRight, zDb);
65331     if( pTab ){
65332       int i;
65333       int nHidden = 0;
65334       Column *pCol;
65335       sqlite3VdbeSetNumCols(v, 6);
65336       pParse->nMem = 6;
65337       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", P4_STATIC);
65338       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P4_STATIC);
65339       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", P4_STATIC);
65340       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", P4_STATIC);
65341       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", P4_STATIC);
65342       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", P4_STATIC);
65343       sqlite3ViewGetColumnNames(pParse, pTab);
65344       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
65345         const Token *pDflt;
65346         if( IsHiddenColumn(pCol) ){
65347           nHidden++;
65348           continue;
65349         }
65350         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
65351         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
65352         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
65353            pCol->zType ? pCol->zType : "", 0);
65354         sqlite3VdbeAddOp2(v, OP_Integer, pCol->notNull, 4);
65355         if( pCol->pDflt && (pDflt = &pCol->pDflt->span)->z ){
65356           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pDflt->z, pDflt->n);
65357         }else{
65358           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
65359         }
65360         sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
65361         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
65362       }
65363     }
65364   }else
65365
65366   if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
65367     Index *pIdx;
65368     Table *pTab;
65369     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
65370     pIdx = sqlite3FindIndex(db, zRight, zDb);
65371     if( pIdx ){
65372       int i;
65373       pTab = pIdx->pTable;
65374       sqlite3VdbeSetNumCols(v, 3);
65375       pParse->nMem = 3;
65376       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", P4_STATIC);
65377       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", P4_STATIC);
65378       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", P4_STATIC);
65379       for(i=0; i<pIdx->nColumn; i++){
65380         int cnum = pIdx->aiColumn[i];
65381         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
65382         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
65383         assert( pTab->nCol>cnum );
65384         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
65385         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
65386       }
65387     }
65388   }else
65389
65390   if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
65391     Index *pIdx;
65392     Table *pTab;
65393     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
65394     pTab = sqlite3FindTable(db, zRight, zDb);
65395     if( pTab ){
65396       v = sqlite3GetVdbe(pParse);
65397       pIdx = pTab->pIndex;
65398       if( pIdx ){
65399         int i = 0; 
65400         sqlite3VdbeSetNumCols(v, 3);
65401         pParse->nMem = 3;
65402         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P4_STATIC);
65403         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P4_STATIC);
65404         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", P4_STATIC);
65405         while(pIdx){
65406           sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
65407           sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
65408           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
65409           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
65410           ++i;
65411           pIdx = pIdx->pNext;
65412         }
65413       }
65414     }
65415   }else
65416
65417   if( sqlite3StrICmp(zLeft, "database_list")==0 ){
65418     int i;
65419     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
65420     sqlite3VdbeSetNumCols(v, 3);
65421     pParse->nMem = 3;
65422     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P4_STATIC);
65423     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P4_STATIC);
65424     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", P4_STATIC);
65425     for(i=0; i<db->nDb; i++){
65426       if( db->aDb[i].pBt==0 ) continue;
65427       assert( db->aDb[i].zName!=0 );
65428       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
65429       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
65430       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
65431            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
65432       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
65433     }
65434   }else
65435
65436   if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
65437     int i = 0;
65438     HashElem *p;
65439     sqlite3VdbeSetNumCols(v, 2);
65440     pParse->nMem = 2;
65441     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P4_STATIC);
65442     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P4_STATIC);
65443     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
65444       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
65445       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
65446       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
65447       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
65448     }
65449   }else
65450 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
65451
65452 #ifndef SQLITE_OMIT_FOREIGN_KEY
65453   if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
65454     FKey *pFK;
65455     Table *pTab;
65456     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
65457     pTab = sqlite3FindTable(db, zRight, zDb);
65458     if( pTab ){
65459       v = sqlite3GetVdbe(pParse);
65460       pFK = pTab->pFKey;
65461       if( pFK ){
65462         int i = 0; 
65463         sqlite3VdbeSetNumCols(v, 5);
65464         pParse->nMem = 5;
65465         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", P4_STATIC);
65466         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", P4_STATIC);
65467         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", P4_STATIC);
65468         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", P4_STATIC);
65469         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", P4_STATIC);
65470         while(pFK){
65471           int j;
65472           for(j=0; j<pFK->nCol; j++){
65473             char *zCol = pFK->aCol[j].zCol;
65474             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
65475             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
65476             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
65477             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
65478                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
65479             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
65480             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
65481           }
65482           ++i;
65483           pFK = pFK->pNextFrom;
65484         }
65485       }
65486     }
65487   }else
65488 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
65489
65490 #ifndef NDEBUG
65491   if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
65492     if( zRight ){
65493       if( getBoolean(zRight) ){
65494         sqlite3ParserTrace(stderr, "parser: ");
65495       }else{
65496         sqlite3ParserTrace(0, 0);
65497       }
65498     }
65499   }else
65500 #endif
65501
65502   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
65503   ** used will be case sensitive or not depending on the RHS.
65504   */
65505   if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
65506     if( zRight ){
65507       sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
65508     }
65509   }else
65510
65511 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
65512 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
65513 #endif
65514
65515 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
65516   /* Pragma "quick_check" is an experimental reduced version of 
65517   ** integrity_check designed to detect most database corruption
65518   ** without most of the overhead of a full integrity-check.
65519   */
65520   if( sqlite3StrICmp(zLeft, "integrity_check")==0
65521    || sqlite3StrICmp(zLeft, "quick_check")==0 
65522   ){
65523     int i, j, addr, mxErr;
65524
65525     /* Code that appears at the end of the integrity check.  If no error
65526     ** messages have been generated, output OK.  Otherwise output the
65527     ** error message
65528     */
65529     static const VdbeOpList endCode[] = {
65530       { OP_AddImm,      1, 0,        0},    /* 0 */
65531       { OP_IfNeg,       1, 0,        0},    /* 1 */
65532       { OP_String8,     0, 3,        0},    /* 2 */
65533       { OP_ResultRow,   3, 1,        0},
65534     };
65535
65536     int isQuick = (zLeft[0]=='q');
65537
65538     /* Initialize the VDBE program */
65539     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
65540     pParse->nMem = 6;
65541     sqlite3VdbeSetNumCols(v, 1);
65542     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", P4_STATIC);
65543
65544     /* Set the maximum error count */
65545     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
65546     if( zRight ){
65547       mxErr = atoi(zRight);
65548       if( mxErr<=0 ){
65549         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
65550       }
65551     }
65552     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
65553
65554     /* Do an integrity check on each database file */
65555     for(i=0; i<db->nDb; i++){
65556       HashElem *x;
65557       Hash *pTbls;
65558       int cnt = 0;
65559
65560       if( OMIT_TEMPDB && i==1 ) continue;
65561
65562       sqlite3CodeVerifySchema(pParse, i);
65563       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
65564       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
65565       sqlite3VdbeJumpHere(v, addr);
65566
65567       /* Do an integrity check of the B-Tree
65568       **
65569       ** Begin by filling registers 2, 3, ... with the root pages numbers
65570       ** for all tables and indices in the database.
65571       */
65572       pTbls = &db->aDb[i].pSchema->tblHash;
65573       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
65574         Table *pTab = sqliteHashData(x);
65575         Index *pIdx;
65576         sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
65577         cnt++;
65578         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
65579           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
65580           cnt++;
65581         }
65582       }
65583       if( cnt==0 ) continue;
65584
65585       /* Make sure sufficient number of registers have been allocated */
65586       if( pParse->nMem < cnt+4 ){
65587         pParse->nMem = cnt+4;
65588       }
65589
65590       /* Do the b-tree integrity checks */
65591       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
65592       sqlite3VdbeChangeP5(v, i);
65593       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
65594       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
65595          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
65596          P4_DYNAMIC);
65597       sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
65598       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
65599       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
65600       sqlite3VdbeJumpHere(v, addr);
65601
65602       /* Make sure all the indices are constructed correctly.
65603       */
65604       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
65605         Table *pTab = sqliteHashData(x);
65606         Index *pIdx;
65607         int loopTop;
65608
65609         if( pTab->pIndex==0 ) continue;
65610         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
65611         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
65612         sqlite3VdbeJumpHere(v, addr);
65613         sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
65614         sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
65615         loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
65616         sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
65617         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
65618           int jmp2;
65619           static const VdbeOpList idxErr[] = {
65620             { OP_AddImm,      1, -1,  0},
65621             { OP_String8,     0,  3,  0},    /* 1 */
65622             { OP_Rowid,       1,  4,  0},
65623             { OP_String8,     0,  5,  0},    /* 3 */
65624             { OP_String8,     0,  6,  0},    /* 4 */
65625             { OP_Concat,      4,  3,  3},
65626             { OP_Concat,      5,  3,  3},
65627             { OP_Concat,      6,  3,  3},
65628             { OP_ResultRow,   3,  1,  0},
65629             { OP_IfPos,       1,  0,  0},    /* 9 */
65630             { OP_Halt,        0,  0,  0},
65631           };
65632           sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 1);
65633           jmp2 = sqlite3VdbeAddOp3(v, OP_Found, j+2, 0, 3);
65634           addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
65635           sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
65636           sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
65637           sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_STATIC);
65638           sqlite3VdbeJumpHere(v, addr+9);
65639           sqlite3VdbeJumpHere(v, jmp2);
65640         }
65641         sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
65642         sqlite3VdbeJumpHere(v, loopTop);
65643         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
65644           static const VdbeOpList cntIdx[] = {
65645              { OP_Integer,      0,  3,  0},
65646              { OP_Rewind,       0,  0,  0},  /* 1 */
65647              { OP_AddImm,       3,  1,  0},
65648              { OP_Next,         0,  0,  0},  /* 3 */
65649              { OP_Eq,           2,  0,  3},  /* 4 */
65650              { OP_AddImm,       1, -1,  0},
65651              { OP_String8,      0,  2,  0},  /* 6 */
65652              { OP_String8,      0,  3,  0},  /* 7 */
65653              { OP_Concat,       3,  2,  2},
65654              { OP_ResultRow,    2,  1,  0},
65655           };
65656           if( pIdx->tnum==0 ) continue;
65657           addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
65658           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
65659           sqlite3VdbeJumpHere(v, addr);
65660           addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
65661           sqlite3VdbeChangeP1(v, addr+1, j+2);
65662           sqlite3VdbeChangeP2(v, addr+1, addr+4);
65663           sqlite3VdbeChangeP1(v, addr+3, j+2);
65664           sqlite3VdbeChangeP2(v, addr+3, addr+2);
65665           sqlite3VdbeJumpHere(v, addr+4);
65666           sqlite3VdbeChangeP4(v, addr+6, 
65667                      "wrong # of entries in index ", P4_STATIC);
65668           sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_STATIC);
65669         }
65670       } 
65671     }
65672     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
65673     sqlite3VdbeChangeP2(v, addr, -mxErr);
65674     sqlite3VdbeJumpHere(v, addr+1);
65675     sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
65676   }else
65677 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
65678
65679 #ifndef SQLITE_OMIT_UTF16
65680   /*
65681   **   PRAGMA encoding
65682   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
65683   **
65684   ** In its first form, this pragma returns the encoding of the main
65685   ** database. If the database is not initialized, it is initialized now.
65686   **
65687   ** The second form of this pragma is a no-op if the main database file
65688   ** has not already been initialized. In this case it sets the default
65689   ** encoding that will be used for the main database file if a new file
65690   ** is created. If an existing main database file is opened, then the
65691   ** default text encoding for the existing database is used.
65692   ** 
65693   ** In all cases new databases created using the ATTACH command are
65694   ** created to use the same default text encoding as the main database. If
65695   ** the main database has not been initialized and/or created when ATTACH
65696   ** is executed, this is done before the ATTACH operation.
65697   **
65698   ** In the second form this pragma sets the text encoding to be used in
65699   ** new database files created using this database handle. It is only
65700   ** useful if invoked immediately after the main database i
65701   */
65702   if( sqlite3StrICmp(zLeft, "encoding")==0 ){
65703     static const struct EncName {
65704       char *zName;
65705       u8 enc;
65706     } encnames[] = {
65707       { "UTF-8",    SQLITE_UTF8        },
65708       { "UTF8",     SQLITE_UTF8        },
65709       { "UTF-16le", SQLITE_UTF16LE     },
65710       { "UTF16le",  SQLITE_UTF16LE     },
65711       { "UTF-16be", SQLITE_UTF16BE     },
65712       { "UTF16be",  SQLITE_UTF16BE     },
65713       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
65714       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
65715       { 0, 0 }
65716     };
65717     const struct EncName *pEnc;
65718     if( !zRight ){    /* "PRAGMA encoding" */
65719       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
65720       sqlite3VdbeSetNumCols(v, 1);
65721       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", P4_STATIC);
65722       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
65723       for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
65724         if( pEnc->enc==ENC(pParse->db) ){
65725           sqlite3VdbeChangeP4(v, -1, pEnc->zName, P4_STATIC);
65726           break;
65727         }
65728       }
65729       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
65730     }else{                        /* "PRAGMA encoding = XXX" */
65731       /* Only change the value of sqlite.enc if the database handle is not
65732       ** initialized. If the main database exists, the new sqlite.enc value
65733       ** will be overwritten when the schema is next loaded. If it does not
65734       ** already exists, it will be created to use the new encoding value.
65735       */
65736       if( 
65737         !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
65738         DbHasProperty(db, 0, DB_Empty) 
65739       ){
65740         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
65741           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
65742             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
65743             break;
65744           }
65745         }
65746         if( !pEnc->zName ){
65747           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
65748         }
65749       }
65750     }
65751   }else
65752 #endif /* SQLITE_OMIT_UTF16 */
65753
65754 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
65755   /*
65756   **   PRAGMA [database.]schema_version
65757   **   PRAGMA [database.]schema_version = <integer>
65758   **
65759   **   PRAGMA [database.]user_version
65760   **   PRAGMA [database.]user_version = <integer>
65761   **
65762   ** The pragma's schema_version and user_version are used to set or get
65763   ** the value of the schema-version and user-version, respectively. Both
65764   ** the schema-version and the user-version are 32-bit signed integers
65765   ** stored in the database header.
65766   **
65767   ** The schema-cookie is usually only manipulated internally by SQLite. It
65768   ** is incremented by SQLite whenever the database schema is modified (by
65769   ** creating or dropping a table or index). The schema version is used by
65770   ** SQLite each time a query is executed to ensure that the internal cache
65771   ** of the schema used when compiling the SQL query matches the schema of
65772   ** the database against which the compiled query is actually executed.
65773   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
65774   ** the schema-version is potentially dangerous and may lead to program
65775   ** crashes or database corruption. Use with caution!
65776   **
65777   ** The user-version is not used internally by SQLite. It may be used by
65778   ** applications for any purpose.
65779   */
65780   if( sqlite3StrICmp(zLeft, "schema_version")==0 
65781    || sqlite3StrICmp(zLeft, "user_version")==0 
65782    || sqlite3StrICmp(zLeft, "freelist_count")==0 
65783   ){
65784
65785     int iCookie;   /* Cookie index. 0 for schema-cookie, 6 for user-cookie. */
65786     sqlite3VdbeUsesBtree(v, iDb);
65787     switch( zLeft[0] ){
65788       case 's': case 'S':
65789         iCookie = 0;
65790         break;
65791       case 'f': case 'F':
65792         iCookie = 1;
65793         iDb = (-1*(iDb+1));
65794         assert(iDb<=0);
65795         break;
65796       default:
65797         iCookie = 5;
65798         break;
65799     }
65800
65801     if( zRight && iDb>=0 ){
65802       /* Write the specified cookie value */
65803       static const VdbeOpList setCookie[] = {
65804         { OP_Transaction,    0,  1,  0},    /* 0 */
65805         { OP_Integer,        0,  1,  0},    /* 1 */
65806         { OP_SetCookie,      0,  0,  1},    /* 2 */
65807       };
65808       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
65809       sqlite3VdbeChangeP1(v, addr, iDb);
65810       sqlite3VdbeChangeP1(v, addr+1, atoi(zRight));
65811       sqlite3VdbeChangeP1(v, addr+2, iDb);
65812       sqlite3VdbeChangeP2(v, addr+2, iCookie);
65813     }else{
65814       /* Read the specified cookie value */
65815       static const VdbeOpList readCookie[] = {
65816         { OP_ReadCookie,      0,  1,  0},    /* 0 */
65817         { OP_ResultRow,       1,  1,  0}
65818       };
65819       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
65820       sqlite3VdbeChangeP1(v, addr, iDb);
65821       sqlite3VdbeChangeP3(v, addr, iCookie);
65822       sqlite3VdbeSetNumCols(v, 1);
65823       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, P4_TRANSIENT);
65824     }
65825   }else
65826 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
65827
65828 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
65829   /*
65830   ** Report the current state of file logs for all databases
65831   */
65832   if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
65833     static const char *const azLockName[] = {
65834       "unlocked", "shared", "reserved", "pending", "exclusive"
65835     };
65836     int i;
65837     Vdbe *v = sqlite3GetVdbe(pParse);
65838     sqlite3VdbeSetNumCols(v, 2);
65839     pParse->nMem = 2;
65840     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", P4_STATIC);
65841     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", P4_STATIC);
65842     for(i=0; i<db->nDb; i++){
65843       Btree *pBt;
65844       Pager *pPager;
65845       const char *zState = "unknown";
65846       int j;
65847       if( db->aDb[i].zName==0 ) continue;
65848       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
65849       pBt = db->aDb[i].pBt;
65850       if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
65851         zState = "closed";
65852       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, 
65853                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
65854          zState = azLockName[j];
65855       }
65856       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
65857       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
65858     }
65859   }else
65860 #endif
65861
65862 #ifdef SQLITE_SSE
65863   /*
65864   ** Check to see if the sqlite_statements table exists.  Create it
65865   ** if it does not.
65866   */
65867   if( sqlite3StrICmp(zLeft, "create_sqlite_statement_table")==0 ){
65868     extern int sqlite3CreateStatementsTable(Parse*);
65869     sqlite3CreateStatementsTable(pParse);
65870   }else
65871 #endif
65872
65873 #if SQLITE_HAS_CODEC
65874   if( sqlite3StrICmp(zLeft, "key")==0 ){
65875     sqlite3_key(db, zRight, strlen(zRight));
65876   }else
65877 #endif
65878 #if SQLITE_HAS_CODEC || defined(SQLITE_ENABLE_CEROD)
65879   if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
65880 #if SQLITE_HAS_CODEC
65881     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
65882       extern void sqlite3_activate_see(const char*);
65883       sqlite3_activate_see(&zRight[4]);
65884     }
65885 #endif
65886 #ifdef SQLITE_ENABLE_CEROD
65887     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
65888       extern void sqlite3_activate_cerod(const char*);
65889       sqlite3_activate_cerod(&zRight[6]);
65890     }
65891 #endif
65892   }
65893 #endif
65894
65895   {}
65896
65897   if( v ){
65898     /* Code an OP_Expire at the end of each PRAGMA program to cause
65899     ** the VDBE implementing the pragma to expire. Most (all?) pragmas
65900     ** are only valid for a single execution.
65901     */
65902     sqlite3VdbeAddOp2(v, OP_Expire, 1, 0);
65903
65904     /*
65905     ** Reset the safety level, in case the fullfsync flag or synchronous
65906     ** setting changed.
65907     */
65908 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
65909     if( db->autoCommit ){
65910       sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
65911                  (db->flags&SQLITE_FullFSync)!=0);
65912     }
65913 #endif
65914   }
65915 pragma_out:
65916   sqlite3DbFree(db, zLeft);
65917   sqlite3DbFree(db, zRight);
65918 }
65919
65920 #endif /* SQLITE_OMIT_PRAGMA || SQLITE_OMIT_PARSER */
65921
65922 /************** End of pragma.c **********************************************/
65923 /************** Begin file prepare.c *****************************************/
65924 /*
65925 ** 2005 May 25
65926 **
65927 ** The author disclaims copyright to this source code.  In place of
65928 ** a legal notice, here is a blessing:
65929 **
65930 **    May you do good and not evil.
65931 **    May you find forgiveness for yourself and forgive others.
65932 **    May you share freely, never taking more than you give.
65933 **
65934 *************************************************************************
65935 ** This file contains the implementation of the sqlite3_prepare()
65936 ** interface, and routines that contribute to loading the database schema
65937 ** from disk.
65938 **
65939 ** $Id: prepare.c,v 1.91 2008/08/02 03:50:39 drh Exp $
65940 */
65941
65942 /*
65943 ** Fill the InitData structure with an error message that indicates
65944 ** that the database is corrupt.
65945 */
65946 static void corruptSchema(
65947   InitData *pData,     /* Initialization context */
65948   const char *zObj,    /* Object being parsed at the point of error */
65949   const char *zExtra   /* Error information */
65950 ){
65951   if( !pData->db->mallocFailed ){
65952     if( zObj==0 ) zObj = "?";
65953     sqlite3SetString(pData->pzErrMsg, pData->db,
65954        "malformed database schema (%s)", zObj);
65955     if( zExtra && zExtra[0] ){
65956       *pData->pzErrMsg = sqlite3MAppendf(pData->db, *pData->pzErrMsg, "%s - %s",
65957                                   *pData->pzErrMsg, zExtra);
65958     }
65959   }
65960   pData->rc = SQLITE_CORRUPT;
65961 }
65962
65963 /*
65964 ** This is the callback routine for the code that initializes the
65965 ** database.  See sqlite3Init() below for additional information.
65966 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
65967 **
65968 ** Each callback contains the following information:
65969 **
65970 **     argv[0] = name of thing being created
65971 **     argv[1] = root page number for table or index. 0 for trigger or view.
65972 **     argv[2] = SQL text for the CREATE statement.
65973 **
65974 */
65975 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **azColName){
65976   InitData *pData = (InitData*)pInit;
65977   sqlite3 *db = pData->db;
65978   int iDb = pData->iDb;
65979
65980   assert( sqlite3_mutex_held(db->mutex) );
65981   pData->rc = SQLITE_OK;
65982   DbClearProperty(db, iDb, DB_Empty);
65983   if( db->mallocFailed ){
65984     corruptSchema(pData, argv[0], 0);
65985     return SQLITE_NOMEM;
65986   }
65987
65988   assert( argc==3 );
65989   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
65990   if( argv[1]==0 ){
65991     corruptSchema(pData, argv[0], 0);
65992     return 1;
65993   }
65994   assert( iDb>=0 && iDb<db->nDb );
65995   if( argv[2] && argv[2][0] ){
65996     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
65997     ** But because db->init.busy is set to 1, no VDBE code is generated
65998     ** or executed.  All the parser does is build the internal data
65999     ** structures that describe the table, index, or view.
66000     */
66001     char *zErr;
66002     int rc;
66003     u8 lookasideEnabled;
66004     assert( db->init.busy );
66005     db->init.iDb = iDb;
66006     db->init.newTnum = atoi(argv[1]);
66007     lookasideEnabled = db->lookaside.bEnabled;
66008     db->lookaside.bEnabled = 0;
66009     rc = sqlite3_exec(db, argv[2], 0, 0, &zErr);
66010     db->init.iDb = 0;
66011     db->lookaside.bEnabled = lookasideEnabled;
66012     assert( rc!=SQLITE_OK || zErr==0 );
66013     if( SQLITE_OK!=rc ){
66014       pData->rc = rc;
66015       if( rc==SQLITE_NOMEM ){
66016         db->mallocFailed = 1;
66017       }else if( rc!=SQLITE_INTERRUPT ){
66018         corruptSchema(pData, argv[0], zErr);
66019       }
66020       sqlite3DbFree(db, zErr);
66021       return 1;
66022     }
66023   }else if( argv[0]==0 ){
66024     corruptSchema(pData, 0, 0);
66025   }else{
66026     /* If the SQL column is blank it means this is an index that
66027     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
66028     ** constraint for a CREATE TABLE.  The index should have already
66029     ** been created when we processed the CREATE TABLE.  All we have
66030     ** to do here is record the root page number for that index.
66031     */
66032     Index *pIndex;
66033     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
66034     if( pIndex==0 || pIndex->tnum!=0 ){
66035       /* This can occur if there exists an index on a TEMP table which
66036       ** has the same name as another index on a permanent index.  Since
66037       ** the permanent table is hidden by the TEMP table, we can also
66038       ** safely ignore the index on the permanent table.
66039       */
66040       /* Do Nothing */;
66041     }else{
66042       pIndex->tnum = atoi(argv[1]);
66043     }
66044   }
66045   return 0;
66046 }
66047
66048 /*
66049 ** Attempt to read the database schema and initialize internal
66050 ** data structures for a single database file.  The index of the
66051 ** database file is given by iDb.  iDb==0 is used for the main
66052 ** database.  iDb==1 should never be used.  iDb>=2 is used for
66053 ** auxiliary databases.  Return one of the SQLITE_ error codes to
66054 ** indicate success or failure.
66055 */
66056 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
66057   int rc;
66058   BtCursor *curMain;
66059   int size;
66060   Table *pTab;
66061   Db *pDb;
66062   char const *azArg[4];
66063   int meta[10];
66064   InitData initData;
66065   char const *zMasterSchema;
66066   char const *zMasterName = SCHEMA_TABLE(iDb);
66067
66068   /*
66069   ** The master database table has a structure like this
66070   */
66071   static const char master_schema[] = 
66072      "CREATE TABLE sqlite_master(\n"
66073      "  type text,\n"
66074      "  name text,\n"
66075      "  tbl_name text,\n"
66076      "  rootpage integer,\n"
66077      "  sql text\n"
66078      ")"
66079   ;
66080 #ifndef SQLITE_OMIT_TEMPDB
66081   static const char temp_master_schema[] = 
66082      "CREATE TEMP TABLE sqlite_temp_master(\n"
66083      "  type text,\n"
66084      "  name text,\n"
66085      "  tbl_name text,\n"
66086      "  rootpage integer,\n"
66087      "  sql text\n"
66088      ")"
66089   ;
66090 #else
66091   #define temp_master_schema 0
66092 #endif
66093
66094   assert( iDb>=0 && iDb<db->nDb );
66095   assert( db->aDb[iDb].pSchema );
66096   assert( sqlite3_mutex_held(db->mutex) );
66097   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
66098
66099   /* zMasterSchema and zInitScript are set to point at the master schema
66100   ** and initialisation script appropriate for the database being
66101   ** initialised. zMasterName is the name of the master table.
66102   */
66103   if( !OMIT_TEMPDB && iDb==1 ){
66104     zMasterSchema = temp_master_schema;
66105   }else{
66106     zMasterSchema = master_schema;
66107   }
66108   zMasterName = SCHEMA_TABLE(iDb);
66109
66110   /* Construct the schema tables.  */
66111   azArg[0] = zMasterName;
66112   azArg[1] = "1";
66113   azArg[2] = zMasterSchema;
66114   azArg[3] = 0;
66115   initData.db = db;
66116   initData.iDb = iDb;
66117   initData.pzErrMsg = pzErrMsg;
66118   (void)sqlite3SafetyOff(db);
66119   rc = sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
66120   (void)sqlite3SafetyOn(db);
66121   if( rc ){
66122     rc = initData.rc;
66123     goto error_out;
66124   }
66125   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
66126   if( pTab ){
66127     pTab->readOnly = 1;
66128   }
66129
66130   /* Create a cursor to hold the database open
66131   */
66132   pDb = &db->aDb[iDb];
66133   if( pDb->pBt==0 ){
66134     if( !OMIT_TEMPDB && iDb==1 ){
66135       DbSetProperty(db, 1, DB_SchemaLoaded);
66136     }
66137     return SQLITE_OK;
66138   }
66139   curMain = sqlite3MallocZero(sqlite3BtreeCursorSize());
66140   if( !curMain ){
66141     rc = SQLITE_NOMEM;
66142     goto error_out;
66143   }
66144   sqlite3BtreeEnter(pDb->pBt);
66145   rc = sqlite3BtreeCursor(pDb->pBt, MASTER_ROOT, 0, 0, curMain);
66146   if( rc!=SQLITE_OK && rc!=SQLITE_EMPTY ){
66147     sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
66148     goto initone_error_out;
66149   }
66150
66151   /* Get the database meta information.
66152   **
66153   ** Meta values are as follows:
66154   **    meta[0]   Schema cookie.  Changes with each schema change.
66155   **    meta[1]   File format of schema layer.
66156   **    meta[2]   Size of the page cache.
66157   **    meta[3]   Use freelist if 0.  Autovacuum if greater than zero.
66158   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
66159   **    meta[5]   The user cookie. Used by the application.
66160   **    meta[6]   Incremental-vacuum flag.
66161   **    meta[7]
66162   **    meta[8]
66163   **    meta[9]
66164   **
66165   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
66166   ** the possible values of meta[4].
66167   */
66168   if( rc==SQLITE_OK ){
66169     int i;
66170     for(i=0; i<sizeof(meta)/sizeof(meta[0]); i++){
66171       rc = sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
66172       if( rc ){
66173         sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
66174         goto initone_error_out;
66175       }
66176     }
66177   }else{
66178     memset(meta, 0, sizeof(meta));
66179   }
66180   pDb->pSchema->schema_cookie = meta[0];
66181
66182   /* If opening a non-empty database, check the text encoding. For the
66183   ** main database, set sqlite3.enc to the encoding of the main database.
66184   ** For an attached db, it is an error if the encoding is not the same
66185   ** as sqlite3.enc.
66186   */
66187   if( meta[4] ){  /* text encoding */
66188     if( iDb==0 ){
66189       /* If opening the main database, set ENC(db). */
66190       ENC(db) = (u8)meta[4];
66191       db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0);
66192     }else{
66193       /* If opening an attached database, the encoding much match ENC(db) */
66194       if( meta[4]!=ENC(db) ){
66195         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
66196             " text encoding as main database");
66197         rc = SQLITE_ERROR;
66198         goto initone_error_out;
66199       }
66200     }
66201   }else{
66202     DbSetProperty(db, iDb, DB_Empty);
66203   }
66204   pDb->pSchema->enc = ENC(db);
66205
66206   if( pDb->pSchema->cache_size==0 ){
66207     size = meta[2];
66208     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
66209     if( size<0 ) size = -size;
66210     pDb->pSchema->cache_size = size;
66211     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
66212   }
66213
66214   /*
66215   ** file_format==1    Version 3.0.0.
66216   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
66217   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
66218   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
66219   */
66220   pDb->pSchema->file_format = meta[1];
66221   if( pDb->pSchema->file_format==0 ){
66222     pDb->pSchema->file_format = 1;
66223   }
66224   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
66225     sqlite3SetString(pzErrMsg, db, "unsupported file format");
66226     rc = SQLITE_ERROR;
66227     goto initone_error_out;
66228   }
66229
66230   /* Ticket #2804:  When we open a database in the newer file format,
66231   ** clear the legacy_file_format pragma flag so that a VACUUM will
66232   ** not downgrade the database and thus invalidate any descending
66233   ** indices that the user might have created.
66234   */
66235   if( iDb==0 && meta[1]>=4 ){
66236     db->flags &= ~SQLITE_LegacyFileFmt;
66237   }
66238
66239   /* Read the schema information out of the schema tables
66240   */
66241   assert( db->init.busy );
66242   if( rc==SQLITE_EMPTY ){
66243     /* For an empty database, there is nothing to read */
66244     rc = SQLITE_OK;
66245   }else{
66246     char *zSql;
66247     zSql = sqlite3MPrintf(db, 
66248         "SELECT name, rootpage, sql FROM '%q'.%s",
66249         db->aDb[iDb].zName, zMasterName);
66250     (void)sqlite3SafetyOff(db);
66251 #ifndef SQLITE_OMIT_AUTHORIZATION
66252     {
66253       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
66254       xAuth = db->xAuth;
66255       db->xAuth = 0;
66256 #endif
66257       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
66258 #ifndef SQLITE_OMIT_AUTHORIZATION
66259       db->xAuth = xAuth;
66260     }
66261 #endif
66262     if( rc==SQLITE_ABORT ) rc = initData.rc;
66263     (void)sqlite3SafetyOn(db);
66264     sqlite3DbFree(db, zSql);
66265 #ifndef SQLITE_OMIT_ANALYZE
66266     if( rc==SQLITE_OK ){
66267       sqlite3AnalysisLoad(db, iDb);
66268     }
66269 #endif
66270   }
66271   if( db->mallocFailed ){
66272     rc = SQLITE_NOMEM;
66273     sqlite3ResetInternalSchema(db, 0);
66274   }
66275   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
66276     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
66277     ** the schema loaded, even if errors occured. In this situation the 
66278     ** current sqlite3_prepare() operation will fail, but the following one
66279     ** will attempt to compile the supplied statement against whatever subset
66280     ** of the schema was loaded before the error occured. The primary
66281     ** purpose of this is to allow access to the sqlite_master table
66282     ** even when its contents have been corrupted.
66283     */
66284     DbSetProperty(db, iDb, DB_SchemaLoaded);
66285     rc = SQLITE_OK;
66286   }
66287
66288   /* Jump here for an error that occurs after successfully allocating
66289   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
66290   ** before that point, jump to error_out.
66291   */
66292 initone_error_out:
66293   sqlite3BtreeCloseCursor(curMain);
66294   sqlite3_free(curMain);
66295   sqlite3BtreeLeave(pDb->pBt);
66296
66297 error_out:
66298   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
66299     db->mallocFailed = 1;
66300   }
66301   return rc;
66302 }
66303
66304 /*
66305 ** Initialize all database files - the main database file, the file
66306 ** used to store temporary tables, and any additional database files
66307 ** created using ATTACH statements.  Return a success code.  If an
66308 ** error occurs, write an error message into *pzErrMsg.
66309 **
66310 ** After a database is initialized, the DB_SchemaLoaded bit is set
66311 ** bit is set in the flags field of the Db structure. If the database
66312 ** file was of zero-length, then the DB_Empty flag is also set.
66313 */
66314 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
66315   int i, rc;
66316   int commit_internal = !(db->flags&SQLITE_InternChanges);
66317   
66318   assert( sqlite3_mutex_held(db->mutex) );
66319   if( db->init.busy ) return SQLITE_OK;
66320   rc = SQLITE_OK;
66321   db->init.busy = 1;
66322   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
66323     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
66324     rc = sqlite3InitOne(db, i, pzErrMsg);
66325     if( rc ){
66326       sqlite3ResetInternalSchema(db, i);
66327     }
66328   }
66329
66330   /* Once all the other databases have been initialised, load the schema
66331   ** for the TEMP database. This is loaded last, as the TEMP database
66332   ** schema may contain references to objects in other databases.
66333   */
66334 #ifndef SQLITE_OMIT_TEMPDB
66335   if( rc==SQLITE_OK && db->nDb>1 && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
66336     rc = sqlite3InitOne(db, 1, pzErrMsg);
66337     if( rc ){
66338       sqlite3ResetInternalSchema(db, 1);
66339     }
66340   }
66341 #endif
66342
66343   db->init.busy = 0;
66344   if( rc==SQLITE_OK && commit_internal ){
66345     sqlite3CommitInternalChanges(db);
66346   }
66347
66348   return rc; 
66349 }
66350
66351 /*
66352 ** This routine is a no-op if the database schema is already initialised.
66353 ** Otherwise, the schema is loaded. An error code is returned.
66354 */
66355 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
66356   int rc = SQLITE_OK;
66357   sqlite3 *db = pParse->db;
66358   assert( sqlite3_mutex_held(db->mutex) );
66359   if( !db->init.busy ){
66360     rc = sqlite3Init(db, &pParse->zErrMsg);
66361   }
66362   if( rc!=SQLITE_OK ){
66363     pParse->rc = rc;
66364     pParse->nErr++;
66365   }
66366   return rc;
66367 }
66368
66369
66370 /*
66371 ** Check schema cookies in all databases.  If any cookie is out
66372 ** of date, return 0.  If all schema cookies are current, return 1.
66373 */
66374 static int schemaIsValid(sqlite3 *db){
66375   int iDb;
66376   int rc;
66377   BtCursor *curTemp;
66378   int cookie;
66379   int allOk = 1;
66380
66381   curTemp = (BtCursor *)sqlite3Malloc(sqlite3BtreeCursorSize());
66382   if( curTemp ){
66383     assert( sqlite3_mutex_held(db->mutex) );
66384     for(iDb=0; allOk && iDb<db->nDb; iDb++){
66385       Btree *pBt;
66386       pBt = db->aDb[iDb].pBt;
66387       if( pBt==0 ) continue;
66388       memset(curTemp, 0, sqlite3BtreeCursorSize());
66389       rc = sqlite3BtreeCursor(pBt, MASTER_ROOT, 0, 0, curTemp);
66390       if( rc==SQLITE_OK ){
66391         rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&cookie);
66392         if( rc==SQLITE_OK && cookie!=db->aDb[iDb].pSchema->schema_cookie ){
66393           allOk = 0;
66394         }
66395         sqlite3BtreeCloseCursor(curTemp);
66396       }
66397       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
66398         db->mallocFailed = 1;
66399       }
66400     }
66401     sqlite3_free(curTemp);
66402   }else{
66403     allOk = 0;
66404     db->mallocFailed = 1;
66405   }
66406
66407   return allOk;
66408 }
66409
66410 /*
66411 ** Convert a schema pointer into the iDb index that indicates
66412 ** which database file in db->aDb[] the schema refers to.
66413 **
66414 ** If the same database is attached more than once, the first
66415 ** attached database is returned.
66416 */
66417 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
66418   int i = -1000000;
66419
66420   /* If pSchema is NULL, then return -1000000. This happens when code in 
66421   ** expr.c is trying to resolve a reference to a transient table (i.e. one
66422   ** created by a sub-select). In this case the return value of this 
66423   ** function should never be used.
66424   **
66425   ** We return -1000000 instead of the more usual -1 simply because using
66426   ** -1000000 as incorrectly using -1000000 index into db->aDb[] is much 
66427   ** more likely to cause a segfault than -1 (of course there are assert()
66428   ** statements too, but it never hurts to play the odds).
66429   */
66430   assert( sqlite3_mutex_held(db->mutex) );
66431   if( pSchema ){
66432     for(i=0; i<db->nDb; i++){
66433       if( db->aDb[i].pSchema==pSchema ){
66434         break;
66435       }
66436     }
66437     assert( i>=0 &&i>=0 &&  i<db->nDb );
66438   }
66439   return i;
66440 }
66441
66442 /*
66443 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
66444 */
66445 static int sqlite3Prepare(
66446   sqlite3 *db,              /* Database handle. */
66447   const char *zSql,         /* UTF-8 encoded SQL statement. */
66448   int nBytes,               /* Length of zSql in bytes. */
66449   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
66450   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
66451   const char **pzTail       /* OUT: End of parsed string */
66452 ){
66453   Parse sParse;
66454   char *zErrMsg = 0;
66455   int rc = SQLITE_OK;
66456   int i;
66457
66458   assert( ppStmt );
66459   *ppStmt = 0;
66460   if( sqlite3SafetyOn(db) ){
66461     return SQLITE_MISUSE;
66462   }
66463   assert( !db->mallocFailed );
66464   assert( sqlite3_mutex_held(db->mutex) );
66465
66466   /* If any attached database schemas are locked, do not proceed with
66467   ** compilation. Instead return SQLITE_LOCKED immediately.
66468   */
66469   for(i=0; i<db->nDb; i++) {
66470     Btree *pBt = db->aDb[i].pBt;
66471     if( pBt ){
66472       int rc;
66473       rc = sqlite3BtreeSchemaLocked(pBt);
66474       if( rc ){
66475         const char *zDb = db->aDb[i].zName;
66476         sqlite3Error(db, SQLITE_LOCKED, "database schema is locked: %s", zDb);
66477         (void)sqlite3SafetyOff(db);
66478         return sqlite3ApiExit(db, SQLITE_LOCKED);
66479       }
66480     }
66481   }
66482   
66483   memset(&sParse, 0, sizeof(sParse));
66484   sParse.db = db;
66485   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
66486     char *zSqlCopy;
66487     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
66488     if( nBytes>mxLen ){
66489       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
66490       (void)sqlite3SafetyOff(db);
66491       return sqlite3ApiExit(db, SQLITE_TOOBIG);
66492     }
66493     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
66494     if( zSqlCopy ){
66495       sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
66496       sqlite3DbFree(db, zSqlCopy);
66497       sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
66498     }else{
66499       sParse.zTail = &zSql[nBytes];
66500     }
66501   }else{
66502     sqlite3RunParser(&sParse, zSql, &zErrMsg);
66503   }
66504
66505   if( db->mallocFailed ){
66506     sParse.rc = SQLITE_NOMEM;
66507   }
66508   if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
66509   if( sParse.checkSchema && !schemaIsValid(db) ){
66510     sParse.rc = SQLITE_SCHEMA;
66511   }
66512   if( sParse.rc==SQLITE_SCHEMA ){
66513     sqlite3ResetInternalSchema(db, 0);
66514   }
66515   if( db->mallocFailed ){
66516     sParse.rc = SQLITE_NOMEM;
66517   }
66518   if( pzTail ){
66519     *pzTail = sParse.zTail;
66520   }
66521   rc = sParse.rc;
66522
66523 #ifndef SQLITE_OMIT_EXPLAIN
66524   if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
66525     if( sParse.explain==2 ){
66526       sqlite3VdbeSetNumCols(sParse.pVdbe, 3);
66527       sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "order", P4_STATIC);
66528       sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "from", P4_STATIC);
66529       sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "detail", P4_STATIC);
66530     }else{
66531       sqlite3VdbeSetNumCols(sParse.pVdbe, 8);
66532       sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "addr", P4_STATIC);
66533       sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "opcode", P4_STATIC);
66534       sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "p1", P4_STATIC);
66535       sqlite3VdbeSetColName(sParse.pVdbe, 3, COLNAME_NAME, "p2", P4_STATIC);
66536       sqlite3VdbeSetColName(sParse.pVdbe, 4, COLNAME_NAME, "p3", P4_STATIC);
66537       sqlite3VdbeSetColName(sParse.pVdbe, 5, COLNAME_NAME, "p4", P4_STATIC);
66538       sqlite3VdbeSetColName(sParse.pVdbe, 6, COLNAME_NAME, "p5", P4_STATIC);
66539       sqlite3VdbeSetColName(sParse.pVdbe, 7, COLNAME_NAME, "comment",P4_STATIC);
66540     }
66541   }
66542 #endif
66543
66544   if( sqlite3SafetyOff(db) ){
66545     rc = SQLITE_MISUSE;
66546   }
66547
66548   if( saveSqlFlag ){
66549     sqlite3VdbeSetSql(sParse.pVdbe, zSql, sParse.zTail - zSql);
66550   }
66551   if( rc!=SQLITE_OK || db->mallocFailed ){
66552     sqlite3_finalize((sqlite3_stmt*)sParse.pVdbe);
66553     assert(!(*ppStmt));
66554   }else{
66555     *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
66556   }
66557
66558   if( zErrMsg ){
66559     sqlite3Error(db, rc, "%s", zErrMsg);
66560     sqlite3DbFree(db, zErrMsg);
66561   }else{
66562     sqlite3Error(db, rc, 0);
66563   }
66564
66565   rc = sqlite3ApiExit(db, rc);
66566   assert( (rc&db->errMask)==rc );
66567   return rc;
66568 }
66569 static int sqlite3LockAndPrepare(
66570   sqlite3 *db,              /* Database handle. */
66571   const char *zSql,         /* UTF-8 encoded SQL statement. */
66572   int nBytes,               /* Length of zSql in bytes. */
66573   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
66574   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
66575   const char **pzTail       /* OUT: End of parsed string */
66576 ){
66577   int rc;
66578   if( !sqlite3SafetyCheckOk(db) ){
66579     return SQLITE_MISUSE;
66580   }
66581   sqlite3_mutex_enter(db->mutex);
66582   sqlite3BtreeEnterAll(db);
66583   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, ppStmt, pzTail);
66584   sqlite3BtreeLeaveAll(db);
66585   sqlite3_mutex_leave(db->mutex);
66586   return rc;
66587 }
66588
66589 /*
66590 ** Rerun the compilation of a statement after a schema change.
66591 ** Return true if the statement was recompiled successfully.
66592 ** Return false if there is an error of some kind.
66593 */
66594 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
66595   int rc;
66596   sqlite3_stmt *pNew;
66597   const char *zSql;
66598   sqlite3 *db;
66599
66600   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
66601   zSql = sqlite3_sql((sqlite3_stmt *)p);
66602   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
66603   db = sqlite3VdbeDb(p);
66604   assert( sqlite3_mutex_held(db->mutex) );
66605   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, &pNew, 0);
66606   if( rc ){
66607     if( rc==SQLITE_NOMEM ){
66608       db->mallocFailed = 1;
66609     }
66610     assert( pNew==0 );
66611     return 0;
66612   }else{
66613     assert( pNew!=0 );
66614   }
66615   sqlite3VdbeSwap((Vdbe*)pNew, p);
66616   sqlite3_transfer_bindings(pNew, (sqlite3_stmt*)p);
66617   sqlite3VdbeResetStepResult((Vdbe*)pNew);
66618   sqlite3VdbeFinalize((Vdbe*)pNew);
66619   return 1;
66620 }
66621
66622
66623 /*
66624 ** Two versions of the official API.  Legacy and new use.  In the legacy
66625 ** version, the original SQL text is not saved in the prepared statement
66626 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
66627 ** sqlite3_step().  In the new version, the original SQL text is retained
66628 ** and the statement is automatically recompiled if an schema change
66629 ** occurs.
66630 */
66631 SQLITE_API int sqlite3_prepare(
66632   sqlite3 *db,              /* Database handle. */
66633   const char *zSql,         /* UTF-8 encoded SQL statement. */
66634   int nBytes,               /* Length of zSql in bytes. */
66635   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
66636   const char **pzTail       /* OUT: End of parsed string */
66637 ){
66638   int rc;
66639   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,ppStmt,pzTail);
66640   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
66641   return rc;
66642 }
66643 SQLITE_API int sqlite3_prepare_v2(
66644   sqlite3 *db,              /* Database handle. */
66645   const char *zSql,         /* UTF-8 encoded SQL statement. */
66646   int nBytes,               /* Length of zSql in bytes. */
66647   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
66648   const char **pzTail       /* OUT: End of parsed string */
66649 ){
66650   int rc;
66651   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,ppStmt,pzTail);
66652   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
66653   return rc;
66654 }
66655
66656
66657 #ifndef SQLITE_OMIT_UTF16
66658 /*
66659 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
66660 */
66661 static int sqlite3Prepare16(
66662   sqlite3 *db,              /* Database handle. */ 
66663   const void *zSql,         /* UTF-8 encoded SQL statement. */
66664   int nBytes,               /* Length of zSql in bytes. */
66665   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
66666   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
66667   const void **pzTail       /* OUT: End of parsed string */
66668 ){
66669   /* This function currently works by first transforming the UTF-16
66670   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
66671   ** tricky bit is figuring out the pointer to return in *pzTail.
66672   */
66673   char *zSql8;
66674   const char *zTail8 = 0;
66675   int rc = SQLITE_OK;
66676
66677   if( !sqlite3SafetyCheckOk(db) ){
66678     return SQLITE_MISUSE;
66679   }
66680   sqlite3_mutex_enter(db->mutex);
66681   zSql8 = sqlite3Utf16to8(db, zSql, nBytes);
66682   if( zSql8 ){
66683     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, ppStmt, &zTail8);
66684   }
66685
66686   if( zTail8 && pzTail ){
66687     /* If sqlite3_prepare returns a tail pointer, we calculate the
66688     ** equivalent pointer into the UTF-16 string by counting the unicode
66689     ** characters between zSql8 and zTail8, and then returning a pointer
66690     ** the same number of characters into the UTF-16 string.
66691     */
66692     int chars_parsed = sqlite3Utf8CharLen(zSql8, zTail8-zSql8);
66693     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
66694   }
66695   sqlite3DbFree(db, zSql8); 
66696   rc = sqlite3ApiExit(db, rc);
66697   sqlite3_mutex_leave(db->mutex);
66698   return rc;
66699 }
66700
66701 /*
66702 ** Two versions of the official API.  Legacy and new use.  In the legacy
66703 ** version, the original SQL text is not saved in the prepared statement
66704 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
66705 ** sqlite3_step().  In the new version, the original SQL text is retained
66706 ** and the statement is automatically recompiled if an schema change
66707 ** occurs.
66708 */
66709 SQLITE_API int sqlite3_prepare16(
66710   sqlite3 *db,              /* Database handle. */ 
66711   const void *zSql,         /* UTF-8 encoded SQL statement. */
66712   int nBytes,               /* Length of zSql in bytes. */
66713   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
66714   const void **pzTail       /* OUT: End of parsed string */
66715 ){
66716   int rc;
66717   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
66718   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
66719   return rc;
66720 }
66721 SQLITE_API int sqlite3_prepare16_v2(
66722   sqlite3 *db,              /* Database handle. */ 
66723   const void *zSql,         /* UTF-8 encoded SQL statement. */
66724   int nBytes,               /* Length of zSql in bytes. */
66725   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
66726   const void **pzTail       /* OUT: End of parsed string */
66727 ){
66728   int rc;
66729   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
66730   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
66731   return rc;
66732 }
66733
66734 #endif /* SQLITE_OMIT_UTF16 */
66735
66736 /************** End of prepare.c *********************************************/
66737 /************** Begin file select.c ******************************************/
66738 /*
66739 ** 2001 September 15
66740 **
66741 ** The author disclaims copyright to this source code.  In place of
66742 ** a legal notice, here is a blessing:
66743 **
66744 **    May you do good and not evil.
66745 **    May you find forgiveness for yourself and forgive others.
66746 **    May you share freely, never taking more than you give.
66747 **
66748 *************************************************************************
66749 ** This file contains C code routines that are called by the parser
66750 ** to handle SELECT statements in SQLite.
66751 **
66752 ** $Id: select.c,v 1.463 2008/08/04 03:51:24 danielk1977 Exp $
66753 */
66754
66755
66756 /*
66757 ** Delete all the content of a Select structure but do not deallocate
66758 ** the select structure itself.
66759 */
66760 static void clearSelect(sqlite3 *db, Select *p){
66761   sqlite3ExprListDelete(db, p->pEList);
66762   sqlite3SrcListDelete(db, p->pSrc);
66763   sqlite3ExprDelete(db, p->pWhere);
66764   sqlite3ExprListDelete(db, p->pGroupBy);
66765   sqlite3ExprDelete(db, p->pHaving);
66766   sqlite3ExprListDelete(db, p->pOrderBy);
66767   sqlite3SelectDelete(db, p->pPrior);
66768   sqlite3ExprDelete(db, p->pLimit);
66769   sqlite3ExprDelete(db, p->pOffset);
66770 }
66771
66772 /*
66773 ** Initialize a SelectDest structure.
66774 */
66775 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
66776   pDest->eDest = eDest;
66777   pDest->iParm = iParm;
66778   pDest->affinity = 0;
66779   pDest->iMem = 0;
66780   pDest->nMem = 0;
66781 }
66782
66783
66784 /*
66785 ** Allocate a new Select structure and return a pointer to that
66786 ** structure.
66787 */
66788 SQLITE_PRIVATE Select *sqlite3SelectNew(
66789   Parse *pParse,        /* Parsing context */
66790   ExprList *pEList,     /* which columns to include in the result */
66791   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
66792   Expr *pWhere,         /* the WHERE clause */
66793   ExprList *pGroupBy,   /* the GROUP BY clause */
66794   Expr *pHaving,        /* the HAVING clause */
66795   ExprList *pOrderBy,   /* the ORDER BY clause */
66796   int isDistinct,       /* true if the DISTINCT keyword is present */
66797   Expr *pLimit,         /* LIMIT value.  NULL means not used */
66798   Expr *pOffset         /* OFFSET value.  NULL means no offset */
66799 ){
66800   Select *pNew;
66801   Select standin;
66802   sqlite3 *db = pParse->db;
66803   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
66804   assert( !pOffset || pLimit );   /* Can't have OFFSET without LIMIT. */
66805   if( pNew==0 ){
66806     pNew = &standin;
66807     memset(pNew, 0, sizeof(*pNew));
66808   }
66809   if( pEList==0 ){
66810     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0,0,0), 0);
66811   }
66812   pNew->pEList = pEList;
66813   pNew->pSrc = pSrc;
66814   pNew->pWhere = pWhere;
66815   pNew->pGroupBy = pGroupBy;
66816   pNew->pHaving = pHaving;
66817   pNew->pOrderBy = pOrderBy;
66818   pNew->isDistinct = isDistinct;
66819   pNew->op = TK_SELECT;
66820   assert( pOffset==0 || pLimit!=0 );
66821   pNew->pLimit = pLimit;
66822   pNew->pOffset = pOffset;
66823   pNew->addrOpenEphm[0] = -1;
66824   pNew->addrOpenEphm[1] = -1;
66825   pNew->addrOpenEphm[2] = -1;
66826   if( pNew==&standin) {
66827     clearSelect(db, pNew);
66828     pNew = 0;
66829   }
66830   return pNew;
66831 }
66832
66833 /*
66834 ** Delete the given Select structure and all of its substructures.
66835 */
66836 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
66837   if( p ){
66838     clearSelect(db, p);
66839     sqlite3DbFree(db, p);
66840   }
66841 }
66842
66843 /*
66844 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
66845 ** type of join.  Return an integer constant that expresses that type
66846 ** in terms of the following bit values:
66847 **
66848 **     JT_INNER
66849 **     JT_CROSS
66850 **     JT_OUTER
66851 **     JT_NATURAL
66852 **     JT_LEFT
66853 **     JT_RIGHT
66854 **
66855 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
66856 **
66857 ** If an illegal or unsupported join type is seen, then still return
66858 ** a join type, but put an error in the pParse structure.
66859 */
66860 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
66861   int jointype = 0;
66862   Token *apAll[3];
66863   Token *p;
66864   static const struct {
66865     const char zKeyword[8];
66866     u8 nChar;
66867     u8 code;
66868   } keywords[] = {
66869     { "natural", 7, JT_NATURAL },
66870     { "left",    4, JT_LEFT|JT_OUTER },
66871     { "right",   5, JT_RIGHT|JT_OUTER },
66872     { "full",    4, JT_LEFT|JT_RIGHT|JT_OUTER },
66873     { "outer",   5, JT_OUTER },
66874     { "inner",   5, JT_INNER },
66875     { "cross",   5, JT_INNER|JT_CROSS },
66876   };
66877   int i, j;
66878   apAll[0] = pA;
66879   apAll[1] = pB;
66880   apAll[2] = pC;
66881   for(i=0; i<3 && apAll[i]; i++){
66882     p = apAll[i];
66883     for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
66884       if( p->n==keywords[j].nChar 
66885           && sqlite3StrNICmp((char*)p->z, keywords[j].zKeyword, p->n)==0 ){
66886         jointype |= keywords[j].code;
66887         break;
66888       }
66889     }
66890     if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
66891       jointype |= JT_ERROR;
66892       break;
66893     }
66894   }
66895   if(
66896      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
66897      (jointype & JT_ERROR)!=0
66898   ){
66899     const char *zSp = " ";
66900     assert( pB!=0 );
66901     if( pC==0 ){ zSp++; }
66902     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
66903        "%T %T%s%T", pA, pB, zSp, pC);
66904     jointype = JT_INNER;
66905   }else if( jointype & JT_RIGHT ){
66906     sqlite3ErrorMsg(pParse, 
66907       "RIGHT and FULL OUTER JOINs are not currently supported");
66908     jointype = JT_INNER;
66909   }
66910   return jointype;
66911 }
66912
66913 /*
66914 ** Return the index of a column in a table.  Return -1 if the column
66915 ** is not contained in the table.
66916 */
66917 static int columnIndex(Table *pTab, const char *zCol){
66918   int i;
66919   for(i=0; i<pTab->nCol; i++){
66920     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
66921   }
66922   return -1;
66923 }
66924
66925 /*
66926 ** Set the value of a token to a '\000'-terminated string.
66927 */
66928 static void setToken(Token *p, const char *z){
66929   p->z = (u8*)z;
66930   p->n = z ? strlen(z) : 0;
66931   p->dyn = 0;
66932 }
66933
66934 /*
66935 ** Set the token to the double-quoted and escaped version of the string pointed
66936 ** to by z. For example;
66937 **
66938 **    {a"bc}  ->  {"a""bc"}
66939 */
66940 static void setQuotedToken(Parse *pParse, Token *p, const char *z){
66941
66942   /* Check if the string contains any " characters. If it does, then
66943   ** this function will malloc space to create a quoted version of
66944   ** the string in. Otherwise, save a call to sqlite3MPrintf() by
66945   ** just copying the pointer to the string.
66946   */
66947   const char *z2 = z;
66948   while( *z2 ){
66949     if( *z2=='"' ) break;
66950     z2++;
66951   }
66952
66953   if( *z2 ){
66954     /* String contains " characters - copy and quote the string. */
66955     p->z = (u8 *)sqlite3MPrintf(pParse->db, "\"%w\"", z);
66956     if( p->z ){
66957       p->n = strlen((char *)p->z);
66958       p->dyn = 1;
66959     }
66960   }else{
66961     /* String contains no " characters - copy the pointer. */
66962     p->z = (u8*)z;
66963     p->n = (z2 - z);
66964     p->dyn = 0;
66965   }
66966 }
66967
66968 /*
66969 ** Create an expression node for an identifier with the name of zName
66970 */
66971 SQLITE_PRIVATE Expr *sqlite3CreateIdExpr(Parse *pParse, const char *zName){
66972   Token dummy;
66973   setToken(&dummy, zName);
66974   return sqlite3PExpr(pParse, TK_ID, 0, 0, &dummy);
66975 }
66976
66977 /*
66978 ** Add a term to the WHERE expression in *ppExpr that requires the
66979 ** zCol column to be equal in the two tables pTab1 and pTab2.
66980 */
66981 static void addWhereTerm(
66982   Parse *pParse,           /* Parsing context */
66983   const char *zCol,        /* Name of the column */
66984   const Table *pTab1,      /* First table */
66985   const char *zAlias1,     /* Alias for first table.  May be NULL */
66986   const Table *pTab2,      /* Second table */
66987   const char *zAlias2,     /* Alias for second table.  May be NULL */
66988   int iRightJoinTable,     /* VDBE cursor for the right table */
66989   Expr **ppExpr,           /* Add the equality term to this expression */
66990   int isOuterJoin          /* True if dealing with an OUTER join */
66991 ){
66992   Expr *pE1a, *pE1b, *pE1c;
66993   Expr *pE2a, *pE2b, *pE2c;
66994   Expr *pE;
66995
66996   pE1a = sqlite3CreateIdExpr(pParse, zCol);
66997   pE2a = sqlite3CreateIdExpr(pParse, zCol);
66998   if( zAlias1==0 ){
66999     zAlias1 = pTab1->zName;
67000   }
67001   pE1b = sqlite3CreateIdExpr(pParse, zAlias1);
67002   if( zAlias2==0 ){
67003     zAlias2 = pTab2->zName;
67004   }
67005   pE2b = sqlite3CreateIdExpr(pParse, zAlias2);
67006   pE1c = sqlite3PExpr(pParse, TK_DOT, pE1b, pE1a, 0);
67007   pE2c = sqlite3PExpr(pParse, TK_DOT, pE2b, pE2a, 0);
67008   pE = sqlite3PExpr(pParse, TK_EQ, pE1c, pE2c, 0);
67009   if( pE && isOuterJoin ){
67010     ExprSetProperty(pE, EP_FromJoin);
67011     pE->iRightJoinTable = iRightJoinTable;
67012   }
67013   *ppExpr = sqlite3ExprAnd(pParse->db,*ppExpr, pE);
67014 }
67015
67016 /*
67017 ** Set the EP_FromJoin property on all terms of the given expression.
67018 ** And set the Expr.iRightJoinTable to iTable for every term in the
67019 ** expression.
67020 **
67021 ** The EP_FromJoin property is used on terms of an expression to tell
67022 ** the LEFT OUTER JOIN processing logic that this term is part of the
67023 ** join restriction specified in the ON or USING clause and not a part
67024 ** of the more general WHERE clause.  These terms are moved over to the
67025 ** WHERE clause during join processing but we need to remember that they
67026 ** originated in the ON or USING clause.
67027 **
67028 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
67029 ** expression depends on table iRightJoinTable even if that table is not
67030 ** explicitly mentioned in the expression.  That information is needed
67031 ** for cases like this:
67032 **
67033 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
67034 **
67035 ** The where clause needs to defer the handling of the t1.x=5
67036 ** term until after the t2 loop of the join.  In that way, a
67037 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
67038 ** defer the handling of t1.x=5, it will be processed immediately
67039 ** after the t1 loop and rows with t1.x!=5 will never appear in
67040 ** the output, which is incorrect.
67041 */
67042 static void setJoinExpr(Expr *p, int iTable){
67043   while( p ){
67044     ExprSetProperty(p, EP_FromJoin);
67045     p->iRightJoinTable = iTable;
67046     setJoinExpr(p->pLeft, iTable);
67047     p = p->pRight;
67048   } 
67049 }
67050
67051 /*
67052 ** This routine processes the join information for a SELECT statement.
67053 ** ON and USING clauses are converted into extra terms of the WHERE clause.
67054 ** NATURAL joins also create extra WHERE clause terms.
67055 **
67056 ** The terms of a FROM clause are contained in the Select.pSrc structure.
67057 ** The left most table is the first entry in Select.pSrc.  The right-most
67058 ** table is the last entry.  The join operator is held in the entry to
67059 ** the left.  Thus entry 0 contains the join operator for the join between
67060 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
67061 ** also attached to the left entry.
67062 **
67063 ** This routine returns the number of errors encountered.
67064 */
67065 static int sqliteProcessJoin(Parse *pParse, Select *p){
67066   SrcList *pSrc;                  /* All tables in the FROM clause */
67067   int i, j;                       /* Loop counters */
67068   struct SrcList_item *pLeft;     /* Left table being joined */
67069   struct SrcList_item *pRight;    /* Right table being joined */
67070
67071   pSrc = p->pSrc;
67072   pLeft = &pSrc->a[0];
67073   pRight = &pLeft[1];
67074   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
67075     Table *pLeftTab = pLeft->pTab;
67076     Table *pRightTab = pRight->pTab;
67077     int isOuter;
67078
67079     if( pLeftTab==0 || pRightTab==0 ) continue;
67080     isOuter = (pRight->jointype & JT_OUTER)!=0;
67081
67082     /* When the NATURAL keyword is present, add WHERE clause terms for
67083     ** every column that the two tables have in common.
67084     */
67085     if( pRight->jointype & JT_NATURAL ){
67086       if( pRight->pOn || pRight->pUsing ){
67087         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
67088            "an ON or USING clause", 0);
67089         return 1;
67090       }
67091       for(j=0; j<pLeftTab->nCol; j++){
67092         char *zName = pLeftTab->aCol[j].zName;
67093         if( columnIndex(pRightTab, zName)>=0 ){
67094           addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, 
67095                               pRightTab, pRight->zAlias,
67096                               pRight->iCursor, &p->pWhere, isOuter);
67097           
67098         }
67099       }
67100     }
67101
67102     /* Disallow both ON and USING clauses in the same join
67103     */
67104     if( pRight->pOn && pRight->pUsing ){
67105       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
67106         "clauses in the same join");
67107       return 1;
67108     }
67109
67110     /* Add the ON clause to the end of the WHERE clause, connected by
67111     ** an AND operator.
67112     */
67113     if( pRight->pOn ){
67114       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
67115       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
67116       pRight->pOn = 0;
67117     }
67118
67119     /* Create extra terms on the WHERE clause for each column named
67120     ** in the USING clause.  Example: If the two tables to be joined are 
67121     ** A and B and the USING clause names X, Y, and Z, then add this
67122     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
67123     ** Report an error if any column mentioned in the USING clause is
67124     ** not contained in both tables to be joined.
67125     */
67126     if( pRight->pUsing ){
67127       IdList *pList = pRight->pUsing;
67128       for(j=0; j<pList->nId; j++){
67129         char *zName = pList->a[j].zName;
67130         if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
67131           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
67132             "not present in both tables", zName);
67133           return 1;
67134         }
67135         addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, 
67136                             pRightTab, pRight->zAlias,
67137                             pRight->iCursor, &p->pWhere, isOuter);
67138       }
67139     }
67140   }
67141   return 0;
67142 }
67143
67144 /*
67145 ** Insert code into "v" that will push the record on the top of the
67146 ** stack into the sorter.
67147 */
67148 static void pushOntoSorter(
67149   Parse *pParse,         /* Parser context */
67150   ExprList *pOrderBy,    /* The ORDER BY clause */
67151   Select *pSelect,       /* The whole SELECT statement */
67152   int regData            /* Register holding data to be sorted */
67153 ){
67154   Vdbe *v = pParse->pVdbe;
67155   int nExpr = pOrderBy->nExpr;
67156   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
67157   int regRecord = sqlite3GetTempReg(pParse);
67158   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
67159   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
67160   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
67161   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
67162   sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
67163   sqlite3ReleaseTempReg(pParse, regRecord);
67164   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
67165   if( pSelect->iLimit ){
67166     int addr1, addr2;
67167     int iLimit;
67168     if( pSelect->iOffset ){
67169       iLimit = pSelect->iOffset+1;
67170     }else{
67171       iLimit = pSelect->iLimit;
67172     }
67173     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
67174     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
67175     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
67176     sqlite3VdbeJumpHere(v, addr1);
67177     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
67178     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
67179     sqlite3VdbeJumpHere(v, addr2);
67180     pSelect->iLimit = 0;
67181   }
67182 }
67183
67184 /*
67185 ** Add code to implement the OFFSET
67186 */
67187 static void codeOffset(
67188   Vdbe *v,          /* Generate code into this VM */
67189   Select *p,        /* The SELECT statement being coded */
67190   int iContinue     /* Jump here to skip the current record */
67191 ){
67192   if( p->iOffset && iContinue!=0 ){
67193     int addr;
67194     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
67195     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
67196     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
67197     VdbeComment((v, "skip OFFSET records"));
67198     sqlite3VdbeJumpHere(v, addr);
67199   }
67200 }
67201
67202 /*
67203 ** Add code that will check to make sure the N registers starting at iMem
67204 ** form a distinct entry.  iTab is a sorting index that holds previously
67205 ** seen combinations of the N values.  A new entry is made in iTab
67206 ** if the current N values are new.
67207 **
67208 ** A jump to addrRepeat is made and the N+1 values are popped from the
67209 ** stack if the top N elements are not distinct.
67210 */
67211 static void codeDistinct(
67212   Parse *pParse,     /* Parsing and code generating context */
67213   int iTab,          /* A sorting index used to test for distinctness */
67214   int addrRepeat,    /* Jump to here if not distinct */
67215   int N,             /* Number of elements */
67216   int iMem           /* First element */
67217 ){
67218   Vdbe *v;
67219   int r1;
67220
67221   v = pParse->pVdbe;
67222   r1 = sqlite3GetTempReg(pParse);
67223   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
67224   sqlite3VdbeAddOp3(v, OP_Found, iTab, addrRepeat, r1);
67225   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
67226   sqlite3ReleaseTempReg(pParse, r1);
67227 }
67228
67229 /*
67230 ** Generate an error message when a SELECT is used within a subexpression
67231 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
67232 ** column.  We do this in a subroutine because the error occurs in multiple
67233 ** places.
67234 */
67235 static int checkForMultiColumnSelectError(
67236   Parse *pParse,       /* Parse context. */
67237   SelectDest *pDest,   /* Destination of SELECT results */
67238   int nExpr            /* Number of result columns returned by SELECT */
67239 ){
67240   int eDest = pDest->eDest;
67241   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
67242     sqlite3ErrorMsg(pParse, "only a single result allowed for "
67243        "a SELECT that is part of an expression");
67244     return 1;
67245   }else{
67246     return 0;
67247   }
67248 }
67249
67250 /*
67251 ** This routine generates the code for the inside of the inner loop
67252 ** of a SELECT.
67253 **
67254 ** If srcTab and nColumn are both zero, then the pEList expressions
67255 ** are evaluated in order to get the data for this row.  If nColumn>0
67256 ** then data is pulled from srcTab and pEList is used only to get the
67257 ** datatypes for each column.
67258 */
67259 static void selectInnerLoop(
67260   Parse *pParse,          /* The parser context */
67261   Select *p,              /* The complete select statement being coded */
67262   ExprList *pEList,       /* List of values being extracted */
67263   int srcTab,             /* Pull data from this table */
67264   int nColumn,            /* Number of columns in the source table */
67265   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
67266   int distinct,           /* If >=0, make sure results are distinct */
67267   SelectDest *pDest,      /* How to dispose of the results */
67268   int iContinue,          /* Jump here to continue with next row */
67269   int iBreak              /* Jump here to break out of the inner loop */
67270 ){
67271   Vdbe *v = pParse->pVdbe;
67272   int i;
67273   int hasDistinct;        /* True if the DISTINCT keyword is present */
67274   int regResult;              /* Start of memory holding result set */
67275   int eDest = pDest->eDest;   /* How to dispose of results */
67276   int iParm = pDest->iParm;   /* First argument to disposal method */
67277   int nResultCol;             /* Number of result columns */
67278
67279   if( v==0 ) return;
67280   assert( pEList!=0 );
67281   hasDistinct = distinct>=0;
67282   if( pOrderBy==0 && !hasDistinct ){
67283     codeOffset(v, p, iContinue);
67284   }
67285
67286   /* Pull the requested columns.
67287   */
67288   if( nColumn>0 ){
67289     nResultCol = nColumn;
67290   }else{
67291     nResultCol = pEList->nExpr;
67292   }
67293   if( pDest->iMem==0 ){
67294     pDest->iMem = pParse->nMem+1;
67295     pDest->nMem = nResultCol;
67296     pParse->nMem += nResultCol;
67297   }else if( pDest->nMem!=nResultCol ){
67298     /* This happens when two SELECTs of a compound SELECT have differing
67299     ** numbers of result columns.  The error message will be generated by
67300     ** a higher-level routine. */
67301     return;
67302   }
67303   regResult = pDest->iMem;
67304   if( nColumn>0 ){
67305     for(i=0; i<nColumn; i++){
67306       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
67307     }
67308   }else if( eDest!=SRT_Exists ){
67309     /* If the destination is an EXISTS(...) expression, the actual
67310     ** values returned by the SELECT are not required.
67311     */
67312     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Callback);
67313   }
67314   nColumn = nResultCol;
67315
67316   /* If the DISTINCT keyword was present on the SELECT statement
67317   ** and this row has been seen before, then do not make this row
67318   ** part of the result.
67319   */
67320   if( hasDistinct ){
67321     assert( pEList!=0 );
67322     assert( pEList->nExpr==nColumn );
67323     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
67324     if( pOrderBy==0 ){
67325       codeOffset(v, p, iContinue);
67326     }
67327   }
67328
67329   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
67330     return;
67331   }
67332
67333   switch( eDest ){
67334     /* In this mode, write each query result to the key of the temporary
67335     ** table iParm.
67336     */
67337 #ifndef SQLITE_OMIT_COMPOUND_SELECT
67338     case SRT_Union: {
67339       int r1;
67340       r1 = sqlite3GetTempReg(pParse);
67341       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
67342       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
67343       sqlite3ReleaseTempReg(pParse, r1);
67344       break;
67345     }
67346
67347     /* Construct a record from the query result, but instead of
67348     ** saving that record, use it as a key to delete elements from
67349     ** the temporary table iParm.
67350     */
67351     case SRT_Except: {
67352       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
67353       break;
67354     }
67355 #endif
67356
67357     /* Store the result as data using a unique key.
67358     */
67359     case SRT_Table:
67360     case SRT_EphemTab: {
67361       int r1 = sqlite3GetTempReg(pParse);
67362       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
67363       if( pOrderBy ){
67364         pushOntoSorter(pParse, pOrderBy, p, r1);
67365       }else{
67366         int r2 = sqlite3GetTempReg(pParse);
67367         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
67368         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
67369         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
67370         sqlite3ReleaseTempReg(pParse, r2);
67371       }
67372       sqlite3ReleaseTempReg(pParse, r1);
67373       break;
67374     }
67375
67376 #ifndef SQLITE_OMIT_SUBQUERY
67377     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
67378     ** then there should be a single item on the stack.  Write this
67379     ** item into the set table with bogus data.
67380     */
67381     case SRT_Set: {
67382       assert( nColumn==1 );
67383       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
67384       if( pOrderBy ){
67385         /* At first glance you would think we could optimize out the
67386         ** ORDER BY in this case since the order of entries in the set
67387         ** does not matter.  But there might be a LIMIT clause, in which
67388         ** case the order does matter */
67389         pushOntoSorter(pParse, pOrderBy, p, regResult);
67390       }else{
67391         int r1 = sqlite3GetTempReg(pParse);
67392         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
67393         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
67394         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
67395         sqlite3ReleaseTempReg(pParse, r1);
67396       }
67397       break;
67398     }
67399
67400     /* If any row exist in the result set, record that fact and abort.
67401     */
67402     case SRT_Exists: {
67403       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
67404       /* The LIMIT clause will terminate the loop for us */
67405       break;
67406     }
67407
67408     /* If this is a scalar select that is part of an expression, then
67409     ** store the results in the appropriate memory cell and break out
67410     ** of the scan loop.
67411     */
67412     case SRT_Mem: {
67413       assert( nColumn==1 );
67414       if( pOrderBy ){
67415         pushOntoSorter(pParse, pOrderBy, p, regResult);
67416       }else{
67417         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
67418         /* The LIMIT clause will jump out of the loop for us */
67419       }
67420       break;
67421     }
67422 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
67423
67424     /* Send the data to the callback function or to a subroutine.  In the
67425     ** case of a subroutine, the subroutine itself is responsible for
67426     ** popping the data from the stack.
67427     */
67428     case SRT_Coroutine:
67429     case SRT_Callback: {
67430       if( pOrderBy ){
67431         int r1 = sqlite3GetTempReg(pParse);
67432         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
67433         pushOntoSorter(pParse, pOrderBy, p, r1);
67434         sqlite3ReleaseTempReg(pParse, r1);
67435       }else if( eDest==SRT_Coroutine ){
67436         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
67437       }else{
67438         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
67439         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
67440       }
67441       break;
67442     }
67443
67444 #if !defined(SQLITE_OMIT_TRIGGER)
67445     /* Discard the results.  This is used for SELECT statements inside
67446     ** the body of a TRIGGER.  The purpose of such selects is to call
67447     ** user-defined functions that have side effects.  We do not care
67448     ** about the actual results of the select.
67449     */
67450     default: {
67451       assert( eDest==SRT_Discard );
67452       break;
67453     }
67454 #endif
67455   }
67456
67457   /* Jump to the end of the loop if the LIMIT is reached.
67458   */
67459   if( p->iLimit ){
67460     assert( pOrderBy==0 );  /* If there is an ORDER BY, the call to
67461                             ** pushOntoSorter() would have cleared p->iLimit */
67462     sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
67463     sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak);
67464   }
67465 }
67466
67467 /*
67468 ** Given an expression list, generate a KeyInfo structure that records
67469 ** the collating sequence for each expression in that expression list.
67470 **
67471 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
67472 ** KeyInfo structure is appropriate for initializing a virtual index to
67473 ** implement that clause.  If the ExprList is the result set of a SELECT
67474 ** then the KeyInfo structure is appropriate for initializing a virtual
67475 ** index to implement a DISTINCT test.
67476 **
67477 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
67478 ** function is responsible for seeing that this structure is eventually
67479 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
67480 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
67481 */
67482 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
67483   sqlite3 *db = pParse->db;
67484   int nExpr;
67485   KeyInfo *pInfo;
67486   struct ExprList_item *pItem;
67487   int i;
67488
67489   nExpr = pList->nExpr;
67490   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
67491   if( pInfo ){
67492     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
67493     pInfo->nField = nExpr;
67494     pInfo->enc = ENC(db);
67495     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
67496       CollSeq *pColl;
67497       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
67498       if( !pColl ){
67499         pColl = db->pDfltColl;
67500       }
67501       pInfo->aColl[i] = pColl;
67502       pInfo->aSortOrder[i] = pItem->sortOrder;
67503     }
67504   }
67505   return pInfo;
67506 }
67507
67508
67509 /*
67510 ** If the inner loop was generated using a non-null pOrderBy argument,
67511 ** then the results were placed in a sorter.  After the loop is terminated
67512 ** we need to run the sorter and output the results.  The following
67513 ** routine generates the code needed to do that.
67514 */
67515 static void generateSortTail(
67516   Parse *pParse,    /* Parsing context */
67517   Select *p,        /* The SELECT statement */
67518   Vdbe *v,          /* Generate code into this VDBE */
67519   int nColumn,      /* Number of columns of data */
67520   SelectDest *pDest /* Write the sorted results here */
67521 ){
67522   int brk = sqlite3VdbeMakeLabel(v);
67523   int cont = sqlite3VdbeMakeLabel(v);
67524   int addr;
67525   int iTab;
67526   int pseudoTab = 0;
67527   ExprList *pOrderBy = p->pOrderBy;
67528
67529   int eDest = pDest->eDest;
67530   int iParm = pDest->iParm;
67531
67532   int regRow;
67533   int regRowid;
67534
67535   iTab = pOrderBy->iECursor;
67536   if( eDest==SRT_Callback || eDest==SRT_Coroutine ){
67537     pseudoTab = pParse->nTab++;
67538     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, nColumn);
67539     sqlite3VdbeAddOp2(v, OP_OpenPseudo, pseudoTab, eDest==SRT_Callback);
67540   }
67541   addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, brk);
67542   codeOffset(v, p, cont);
67543   regRow = sqlite3GetTempReg(pParse);
67544   regRowid = sqlite3GetTempReg(pParse);
67545   sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
67546   switch( eDest ){
67547     case SRT_Table:
67548     case SRT_EphemTab: {
67549       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
67550       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
67551       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
67552       break;
67553     }
67554 #ifndef SQLITE_OMIT_SUBQUERY
67555     case SRT_Set: {
67556       assert( nColumn==1 );
67557       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
67558       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
67559       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
67560       break;
67561     }
67562     case SRT_Mem: {
67563       assert( nColumn==1 );
67564       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
67565       /* The LIMIT clause will terminate the loop for us */
67566       break;
67567     }
67568 #endif
67569     case SRT_Callback:
67570     case SRT_Coroutine: {
67571       int i;
67572       sqlite3VdbeAddOp2(v, OP_Integer, 1, regRowid);
67573       sqlite3VdbeAddOp3(v, OP_Insert, pseudoTab, regRow, regRowid);
67574       for(i=0; i<nColumn; i++){
67575         assert( regRow!=pDest->iMem+i );
67576         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
67577       }
67578       if( eDest==SRT_Callback ){
67579         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
67580         sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
67581       }else{
67582         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
67583       }
67584       break;
67585     }
67586     default: {
67587       /* Do nothing */
67588       break;
67589     }
67590   }
67591   sqlite3ReleaseTempReg(pParse, regRow);
67592   sqlite3ReleaseTempReg(pParse, regRowid);
67593
67594   /* LIMIT has been implemented by the pushOntoSorter() routine.
67595   */
67596   assert( p->iLimit==0 );
67597
67598   /* The bottom of the loop
67599   */
67600   sqlite3VdbeResolveLabel(v, cont);
67601   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
67602   sqlite3VdbeResolveLabel(v, brk);
67603   if( eDest==SRT_Callback || eDest==SRT_Coroutine ){
67604     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
67605   }
67606
67607 }
67608
67609 /*
67610 ** Return a pointer to a string containing the 'declaration type' of the
67611 ** expression pExpr. The string may be treated as static by the caller.
67612 **
67613 ** The declaration type is the exact datatype definition extracted from the
67614 ** original CREATE TABLE statement if the expression is a column. The
67615 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
67616 ** is considered a column can be complex in the presence of subqueries. The
67617 ** result-set expression in all of the following SELECT statements is 
67618 ** considered a column by this function.
67619 **
67620 **   SELECT col FROM tbl;
67621 **   SELECT (SELECT col FROM tbl;
67622 **   SELECT (SELECT col FROM tbl);
67623 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
67624 ** 
67625 ** The declaration type for any expression other than a column is NULL.
67626 */
67627 static const char *columnType(
67628   NameContext *pNC, 
67629   Expr *pExpr,
67630   const char **pzOriginDb,
67631   const char **pzOriginTab,
67632   const char **pzOriginCol
67633 ){
67634   char const *zType = 0;
67635   char const *zOriginDb = 0;
67636   char const *zOriginTab = 0;
67637   char const *zOriginCol = 0;
67638   int j;
67639   if( pExpr==0 || pNC->pSrcList==0 ) return 0;
67640
67641   switch( pExpr->op ){
67642     case TK_AGG_COLUMN:
67643     case TK_COLUMN: {
67644       /* The expression is a column. Locate the table the column is being
67645       ** extracted from in NameContext.pSrcList. This table may be real
67646       ** database table or a subquery.
67647       */
67648       Table *pTab = 0;            /* Table structure column is extracted from */
67649       Select *pS = 0;             /* Select the column is extracted from */
67650       int iCol = pExpr->iColumn;  /* Index of column in pTab */
67651       while( pNC && !pTab ){
67652         SrcList *pTabList = pNC->pSrcList;
67653         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
67654         if( j<pTabList->nSrc ){
67655           pTab = pTabList->a[j].pTab;
67656           pS = pTabList->a[j].pSelect;
67657         }else{
67658           pNC = pNC->pNext;
67659         }
67660       }
67661
67662       if( pTab==0 ){
67663         /* FIX ME:
67664         ** This can occurs if you have something like "SELECT new.x;" inside
67665         ** a trigger.  In other words, if you reference the special "new"
67666         ** table in the result set of a select.  We do not have a good way
67667         ** to find the actual table type, so call it "TEXT".  This is really
67668         ** something of a bug, but I do not know how to fix it.
67669         **
67670         ** This code does not produce the correct answer - it just prevents
67671         ** a segfault.  See ticket #1229.
67672         */
67673         zType = "TEXT";
67674         break;
67675       }
67676
67677       assert( pTab );
67678       if( pS ){
67679         /* The "table" is actually a sub-select or a view in the FROM clause
67680         ** of the SELECT statement. Return the declaration type and origin
67681         ** data for the result-set column of the sub-select.
67682         */
67683         if( iCol>=0 && iCol<pS->pEList->nExpr ){
67684           /* If iCol is less than zero, then the expression requests the
67685           ** rowid of the sub-select or view. This expression is legal (see 
67686           ** test case misc2.2.2) - it always evaluates to NULL.
67687           */
67688           NameContext sNC;
67689           Expr *p = pS->pEList->a[iCol].pExpr;
67690           sNC.pSrcList = pS->pSrc;
67691           sNC.pNext = 0;
67692           sNC.pParse = pNC->pParse;
67693           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
67694         }
67695       }else if( pTab->pSchema ){
67696         /* A real table */
67697         assert( !pS );
67698         if( iCol<0 ) iCol = pTab->iPKey;
67699         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
67700         if( iCol<0 ){
67701           zType = "INTEGER";
67702           zOriginCol = "rowid";
67703         }else{
67704           zType = pTab->aCol[iCol].zType;
67705           zOriginCol = pTab->aCol[iCol].zName;
67706         }
67707         zOriginTab = pTab->zName;
67708         if( pNC->pParse ){
67709           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
67710           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
67711         }
67712       }
67713       break;
67714     }
67715 #ifndef SQLITE_OMIT_SUBQUERY
67716     case TK_SELECT: {
67717       /* The expression is a sub-select. Return the declaration type and
67718       ** origin info for the single column in the result set of the SELECT
67719       ** statement.
67720       */
67721       NameContext sNC;
67722       Select *pS = pExpr->pSelect;
67723       Expr *p = pS->pEList->a[0].pExpr;
67724       sNC.pSrcList = pS->pSrc;
67725       sNC.pNext = pNC;
67726       sNC.pParse = pNC->pParse;
67727       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
67728       break;
67729     }
67730 #endif
67731   }
67732   
67733   if( pzOriginDb ){
67734     assert( pzOriginTab && pzOriginCol );
67735     *pzOriginDb = zOriginDb;
67736     *pzOriginTab = zOriginTab;
67737     *pzOriginCol = zOriginCol;
67738   }
67739   return zType;
67740 }
67741
67742 /*
67743 ** Generate code that will tell the VDBE the declaration types of columns
67744 ** in the result set.
67745 */
67746 static void generateColumnTypes(
67747   Parse *pParse,      /* Parser context */
67748   SrcList *pTabList,  /* List of tables */
67749   ExprList *pEList    /* Expressions defining the result set */
67750 ){
67751 #ifndef SQLITE_OMIT_DECLTYPE
67752   Vdbe *v = pParse->pVdbe;
67753   int i;
67754   NameContext sNC;
67755   sNC.pSrcList = pTabList;
67756   sNC.pParse = pParse;
67757   for(i=0; i<pEList->nExpr; i++){
67758     Expr *p = pEList->a[i].pExpr;
67759     const char *zType;
67760 #ifdef SQLITE_ENABLE_COLUMN_METADATA
67761     const char *zOrigDb = 0;
67762     const char *zOrigTab = 0;
67763     const char *zOrigCol = 0;
67764     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
67765
67766     /* The vdbe must make its own copy of the column-type and other 
67767     ** column specific strings, in case the schema is reset before this
67768     ** virtual machine is deleted.
67769     */
67770     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, P4_TRANSIENT);
67771     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, P4_TRANSIENT);
67772     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, P4_TRANSIENT);
67773 #else
67774     zType = columnType(&sNC, p, 0, 0, 0);
67775 #endif
67776     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, P4_TRANSIENT);
67777   }
67778 #endif /* SQLITE_OMIT_DECLTYPE */
67779 }
67780
67781 /*
67782 ** Generate code that will tell the VDBE the names of columns
67783 ** in the result set.  This information is used to provide the
67784 ** azCol[] values in the callback.
67785 */
67786 static void generateColumnNames(
67787   Parse *pParse,      /* Parser context */
67788   SrcList *pTabList,  /* List of tables */
67789   ExprList *pEList    /* Expressions defining the result set */
67790 ){
67791   Vdbe *v = pParse->pVdbe;
67792   int i, j;
67793   sqlite3 *db = pParse->db;
67794   int fullNames, shortNames;
67795
67796 #ifndef SQLITE_OMIT_EXPLAIN
67797   /* If this is an EXPLAIN, skip this step */
67798   if( pParse->explain ){
67799     return;
67800   }
67801 #endif
67802
67803   assert( v!=0 );
67804   if( pParse->colNamesSet || v==0 || db->mallocFailed ) return;
67805   pParse->colNamesSet = 1;
67806   fullNames = (db->flags & SQLITE_FullColNames)!=0;
67807   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
67808   sqlite3VdbeSetNumCols(v, pEList->nExpr);
67809   for(i=0; i<pEList->nExpr; i++){
67810     Expr *p;
67811     p = pEList->a[i].pExpr;
67812     if( p==0 ) continue;
67813     if( pEList->a[i].zName ){
67814       char *zName = pEList->a[i].zName;
67815       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, strlen(zName));
67816     }else if( p->op==TK_COLUMN && pTabList ){
67817       Table *pTab;
67818       char *zCol;
67819       int iCol = p->iColumn;
67820       for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
67821       assert( j<pTabList->nSrc );
67822       pTab = pTabList->a[j].pTab;
67823       if( iCol<0 ) iCol = pTab->iPKey;
67824       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
67825       if( iCol<0 ){
67826         zCol = "rowid";
67827       }else{
67828         zCol = pTab->aCol[iCol].zName;
67829       }
67830       if( !shortNames && !fullNames ){
67831         sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
67832       }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
67833         char *zName = 0;
67834         char *zTab;
67835  
67836         zTab = pTabList->a[j].zAlias;
67837         if( fullNames || zTab==0 ) zTab = pTab->zName;
67838         zName = sqlite3MPrintf(db, "%s.%s", zTab, zCol);
67839         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, P4_DYNAMIC);
67840       }else{
67841         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, strlen(zCol));
67842       }
67843     }else{
67844       sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
67845     }
67846   }
67847   generateColumnTypes(pParse, pTabList, pEList);
67848 }
67849
67850 #ifndef SQLITE_OMIT_COMPOUND_SELECT
67851 /*
67852 ** Name of the connection operator, used for error messages.
67853 */
67854 static const char *selectOpName(int id){
67855   char *z;
67856   switch( id ){
67857     case TK_ALL:       z = "UNION ALL";   break;
67858     case TK_INTERSECT: z = "INTERSECT";   break;
67859     case TK_EXCEPT:    z = "EXCEPT";      break;
67860     default:           z = "UNION";       break;
67861   }
67862   return z;
67863 }
67864 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
67865
67866 /*
67867 ** Forward declaration
67868 */
67869 static int prepSelectStmt(Parse*, Select*);
67870
67871 /*
67872 ** Given a SELECT statement, generate a Table structure that describes
67873 ** the result set of that SELECT.
67874 */
67875 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
67876   Table *pTab;
67877   int i, j, rc;
67878   ExprList *pEList;
67879   Column *aCol, *pCol;
67880   sqlite3 *db = pParse->db;
67881   int savedFlags;
67882
67883   savedFlags = db->flags;
67884   db->flags &= ~SQLITE_FullColNames;
67885   db->flags |= SQLITE_ShortColNames;
67886   rc = sqlite3SelectResolve(pParse, pSelect, 0);
67887   if( rc==SQLITE_OK ){
67888     while( pSelect->pPrior ) pSelect = pSelect->pPrior;
67889     rc = prepSelectStmt(pParse, pSelect);
67890     if( rc==SQLITE_OK ){
67891       rc = sqlite3SelectResolve(pParse, pSelect, 0);
67892     }
67893   }
67894   db->flags = savedFlags;
67895   if( rc ){
67896     return 0;
67897   }
67898   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
67899   if( pTab==0 ){
67900     return 0;
67901   }
67902   pTab->db = db;
67903   pTab->nRef = 1;
67904   pTab->zName = zTabName ? sqlite3DbStrDup(db, zTabName) : 0;
67905   pEList = pSelect->pEList;
67906   pTab->nCol = pEList->nExpr;
67907   assert( pTab->nCol>0 );
67908   pTab->aCol = aCol = sqlite3DbMallocZero(db, sizeof(pTab->aCol[0])*pTab->nCol);
67909   testcase( aCol==0 );
67910   for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){
67911     Expr *p;
67912     char *zType;
67913     char *zName;
67914     int nName;
67915     CollSeq *pColl;
67916     int cnt;
67917     NameContext sNC;
67918     
67919     /* Get an appropriate name for the column
67920     */
67921     p = pEList->a[i].pExpr;
67922     assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
67923     if( (zName = pEList->a[i].zName)!=0 ){
67924       /* If the column contains an "AS <name>" phrase, use <name> as the name */
67925       zName = sqlite3DbStrDup(db, zName);
67926     }else if( p->op==TK_COLUMN && p->pTab ){
67927       /* For columns use the column name name */
67928       int iCol = p->iColumn;
67929       if( iCol<0 ) iCol = p->pTab->iPKey;
67930       zName = sqlite3MPrintf(db, "%s", p->pTab->aCol[iCol].zName);
67931     }else{
67932       /* Use the original text of the column expression as its name */
67933       zName = sqlite3MPrintf(db, "%T", &p->span);
67934     }
67935     if( db->mallocFailed ){
67936       sqlite3DbFree(db, zName);
67937       break;
67938     }
67939     sqlite3Dequote(zName);
67940
67941     /* Make sure the column name is unique.  If the name is not unique,
67942     ** append a integer to the name so that it becomes unique.
67943     */
67944     nName = strlen(zName);
67945     for(j=cnt=0; j<i; j++){
67946       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
67947         char *zNewName;
67948         zName[nName] = 0;
67949         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
67950         sqlite3DbFree(db, zName);
67951         zName = zNewName;
67952         j = -1;
67953         if( zName==0 ) break;
67954       }
67955     }
67956     pCol->zName = zName;
67957
67958     /* Get the typename, type affinity, and collating sequence for the
67959     ** column.
67960     */
67961     memset(&sNC, 0, sizeof(sNC));
67962     sNC.pSrcList = pSelect->pSrc;
67963     zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
67964     pCol->zType = zType;
67965     pCol->affinity = sqlite3ExprAffinity(p);
67966     pColl = sqlite3ExprCollSeq(pParse, p);
67967     if( pColl ){
67968       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
67969     }
67970   }
67971   pTab->iPKey = -1;
67972   if( db->mallocFailed ){
67973     sqlite3DeleteTable(pTab);
67974     return 0;
67975   }
67976   return pTab;
67977 }
67978
67979 /*
67980 ** Prepare a SELECT statement for processing by doing the following
67981 ** things:
67982 **
67983 **    (1)  Make sure VDBE cursor numbers have been assigned to every
67984 **         element of the FROM clause.
67985 **
67986 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
67987 **         defines FROM clause.  When views appear in the FROM clause,
67988 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
67989 **         that implements the view.  A copy is made of the view's SELECT
67990 **         statement so that we can freely modify or delete that statement
67991 **         without worrying about messing up the presistent representation
67992 **         of the view.
67993 **
67994 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
67995 **         on joins and the ON and USING clause of joins.
67996 **
67997 **    (4)  Scan the list of columns in the result set (pEList) looking
67998 **         for instances of the "*" operator or the TABLE.* operator.
67999 **         If found, expand each "*" to be every column in every table
68000 **         and TABLE.* to be every column in TABLE.
68001 **
68002 ** Return 0 on success.  If there are problems, leave an error message
68003 ** in pParse and return non-zero.
68004 */
68005 static int prepSelectStmt(Parse *pParse, Select *p){
68006   int i, j, k, rc;
68007   SrcList *pTabList;
68008   ExprList *pEList;
68009   struct SrcList_item *pFrom;
68010   sqlite3 *db = pParse->db;
68011
68012   if( p==0 || p->pSrc==0 || db->mallocFailed ){
68013     return 1;
68014   }
68015   pTabList = p->pSrc;
68016   pEList = p->pEList;
68017
68018   /* Make sure cursor numbers have been assigned to all entries in
68019   ** the FROM clause of the SELECT statement.
68020   */
68021   sqlite3SrcListAssignCursors(pParse, p->pSrc);
68022
68023   /* Look up every table named in the FROM clause of the select.  If
68024   ** an entry of the FROM clause is a subquery instead of a table or view,
68025   ** then create a transient table structure to describe the subquery.
68026   */
68027   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
68028     Table *pTab;
68029     if( pFrom->pTab!=0 ){
68030       /* This statement has already been prepared.  There is no need
68031       ** to go further. */
68032       assert( i==0 );
68033       return 0;
68034     }
68035     if( pFrom->zName==0 ){
68036 #ifndef SQLITE_OMIT_SUBQUERY
68037       /* A sub-query in the FROM clause of a SELECT */
68038       assert( pFrom->pSelect!=0 );
68039       if( pFrom->zAlias==0 ){
68040         pFrom->zAlias =
68041           sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pFrom->pSelect);
68042       }
68043       assert( pFrom->pTab==0 );
68044       pFrom->pTab = pTab = 
68045         sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect);
68046       if( pTab==0 ){
68047         return 1;
68048       }
68049       /* The isEphem flag indicates that the Table structure has been
68050       ** dynamically allocated and may be freed at any time.  In other words,
68051       ** pTab is not pointing to a persistent table structure that defines
68052       ** part of the schema. */
68053       pTab->isEphem = 1;
68054 #endif
68055     }else{
68056       /* An ordinary table or view name in the FROM clause */
68057       assert( pFrom->pTab==0 );
68058       pFrom->pTab = pTab = 
68059         sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
68060       if( pTab==0 ){
68061         return 1;
68062       }
68063       pTab->nRef++;
68064 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
68065       if( pTab->pSelect || IsVirtual(pTab) ){
68066         /* We reach here if the named table is a really a view */
68067         if( sqlite3ViewGetColumnNames(pParse, pTab) ){
68068           return 1;
68069         }
68070         /* If pFrom->pSelect!=0 it means we are dealing with a
68071         ** view within a view.  The SELECT structure has already been
68072         ** copied by the outer view so we can skip the copy step here
68073         ** in the inner view.
68074         */
68075         if( pFrom->pSelect==0 ){
68076           pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect);
68077         }
68078       }
68079 #endif
68080     }
68081   }
68082
68083   /* Process NATURAL keywords, and ON and USING clauses of joins.
68084   */
68085   if( sqliteProcessJoin(pParse, p) ) return 1;
68086
68087   /* For every "*" that occurs in the column list, insert the names of
68088   ** all columns in all tables.  And for every TABLE.* insert the names
68089   ** of all columns in TABLE.  The parser inserted a special expression
68090   ** with the TK_ALL operator for each "*" that it found in the column list.
68091   ** The following code just has to locate the TK_ALL expressions and expand
68092   ** each one to the list of all columns in all tables.
68093   **
68094   ** The first loop just checks to see if there are any "*" operators
68095   ** that need expanding.
68096   */
68097   for(k=0; k<pEList->nExpr; k++){
68098     Expr *pE = pEList->a[k].pExpr;
68099     if( pE->op==TK_ALL ) break;
68100     if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
68101          && pE->pLeft && pE->pLeft->op==TK_ID ) break;
68102   }
68103   rc = 0;
68104   if( k<pEList->nExpr ){
68105     /*
68106     ** If we get here it means the result set contains one or more "*"
68107     ** operators that need to be expanded.  Loop through each expression
68108     ** in the result set and expand them one by one.
68109     */
68110     struct ExprList_item *a = pEList->a;
68111     ExprList *pNew = 0;
68112     int flags = pParse->db->flags;
68113     int longNames = (flags & SQLITE_FullColNames)!=0
68114                       && (flags & SQLITE_ShortColNames)==0;
68115
68116     for(k=0; k<pEList->nExpr; k++){
68117       Expr *pE = a[k].pExpr;
68118       if( pE->op!=TK_ALL &&
68119            (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
68120         /* This particular expression does not need to be expanded.
68121         */
68122         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr, 0);
68123         if( pNew ){
68124           pNew->a[pNew->nExpr-1].zName = a[k].zName;
68125         }else{
68126           rc = 1;
68127         }
68128         a[k].pExpr = 0;
68129         a[k].zName = 0;
68130       }else{
68131         /* This expression is a "*" or a "TABLE.*" and needs to be
68132         ** expanded. */
68133         int tableSeen = 0;      /* Set to 1 when TABLE matches */
68134         char *zTName;            /* text of name of TABLE */
68135         if( pE->op==TK_DOT && pE->pLeft ){
68136           zTName = sqlite3NameFromToken(db, &pE->pLeft->token);
68137         }else{
68138           zTName = 0;
68139         }
68140         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
68141           Table *pTab = pFrom->pTab;
68142           char *zTabName = pFrom->zAlias;
68143           if( zTabName==0 || zTabName[0]==0 ){ 
68144             zTabName = pTab->zName;
68145           }
68146           assert( zTabName );
68147           if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
68148             continue;
68149           }
68150           tableSeen = 1;
68151           for(j=0; j<pTab->nCol; j++){
68152             Expr *pExpr, *pRight;
68153             char *zName = pTab->aCol[j].zName;
68154
68155             /* If a column is marked as 'hidden' (currently only possible
68156             ** for virtual tables), do not include it in the expanded
68157             ** result-set list.
68158             */
68159             if( IsHiddenColumn(&pTab->aCol[j]) ){
68160               assert(IsVirtual(pTab));
68161               continue;
68162             }
68163
68164             if( i>0 ){
68165               struct SrcList_item *pLeft = &pTabList->a[i-1];
68166               if( (pLeft[1].jointype & JT_NATURAL)!=0 &&
68167                         columnIndex(pLeft->pTab, zName)>=0 ){
68168                 /* In a NATURAL join, omit the join columns from the 
68169                 ** table on the right */
68170                 continue;
68171               }
68172               if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){
68173                 /* In a join with a USING clause, omit columns in the
68174                 ** using clause from the table on the right. */
68175                 continue;
68176               }
68177             }
68178             pRight = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
68179             if( pRight==0 ) break;
68180             setQuotedToken(pParse, &pRight->token, zName);
68181             if( longNames || pTabList->nSrc>1 ){
68182               Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
68183               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
68184               if( pExpr==0 ) break;
68185               setQuotedToken(pParse, &pLeft->token, zTabName);
68186 #if 1
68187               setToken(&pExpr->span, 
68188                   sqlite3MPrintf(db, "%s.%s", zTabName, zName));
68189               pExpr->span.dyn = 1;
68190 #else
68191               pExpr->span = pRight->token;
68192               pExpr->span.dyn = 0;
68193 #endif
68194               pExpr->token.z = 0;
68195               pExpr->token.n = 0;
68196               pExpr->token.dyn = 0;
68197             }else{
68198               pExpr = pRight;
68199               pExpr->span = pExpr->token;
68200               pExpr->span.dyn = 0;
68201             }
68202             if( longNames ){
68203               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pExpr->span);
68204             }else{
68205               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pRight->token);
68206             }
68207           }
68208         }
68209         if( !tableSeen ){
68210           if( zTName ){
68211             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
68212           }else{
68213             sqlite3ErrorMsg(pParse, "no tables specified");
68214           }
68215           rc = 1;
68216         }
68217         sqlite3DbFree(db, zTName);
68218       }
68219     }
68220     sqlite3ExprListDelete(db, pEList);
68221     p->pEList = pNew;
68222   }
68223 #if SQLITE_MAX_COLUMN
68224   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
68225     sqlite3ErrorMsg(pParse, "too many columns in result set");
68226     rc = SQLITE_ERROR;
68227   }
68228 #endif
68229   if( db->mallocFailed ){
68230     rc = SQLITE_NOMEM;
68231   }
68232   return rc;
68233 }
68234
68235 /*
68236 ** pE is a pointer to an expression which is a single term in
68237 ** ORDER BY or GROUP BY clause.
68238 **
68239 ** At the point this routine is called, we already know that the
68240 ** ORDER BY term is not an integer index into the result set.  That
68241 ** casee is handled by the calling routine.
68242 **
68243 ** If pE is a well-formed expression and the SELECT statement
68244 ** is not compound, then return 0.  This indicates to the
68245 ** caller that it should sort by the value of the ORDER BY
68246 ** expression.
68247 **
68248 ** If the SELECT is compound, then attempt to match pE against
68249 ** result set columns in the left-most SELECT statement.  Return
68250 ** the index i of the matching column, as an indication to the 
68251 ** caller that it should sort by the i-th column.  If there is
68252 ** no match, return -1 and leave an error message in pParse.
68253 */
68254 static int matchOrderByTermToExprList(
68255   Parse *pParse,     /* Parsing context for error messages */
68256   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
68257   Expr *pE,          /* The specific ORDER BY term */
68258   int idx,           /* When ORDER BY term is this */
68259   int isCompound,    /* True if this is a compound SELECT */
68260   u8 *pHasAgg        /* True if expression contains aggregate functions */
68261 ){
68262   int i;             /* Loop counter */
68263   ExprList *pEList;  /* The columns of the result set */
68264   NameContext nc;    /* Name context for resolving pE */
68265
68266   assert( sqlite3ExprIsInteger(pE, &i)==0 );
68267   pEList = pSelect->pEList;
68268
68269   /* If the term is a simple identifier that try to match that identifier
68270   ** against a column name in the result set.
68271   */
68272   if( pE->op==TK_ID || (pE->op==TK_STRING && pE->token.z[0]!='\'') ){
68273     sqlite3 *db = pParse->db;
68274     char *zCol = sqlite3NameFromToken(db, &pE->token);
68275     if( zCol==0 ){
68276       return -1;
68277     }
68278     for(i=0; i<pEList->nExpr; i++){
68279       char *zAs = pEList->a[i].zName;
68280       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
68281         sqlite3DbFree(db, zCol);
68282         return i+1;
68283       }
68284     }
68285     sqlite3DbFree(db, zCol);
68286   }
68287
68288   /* Resolve all names in the ORDER BY term expression
68289   */
68290   memset(&nc, 0, sizeof(nc));
68291   nc.pParse = pParse;
68292   nc.pSrcList = pSelect->pSrc;
68293   nc.pEList = pEList;
68294   nc.allowAgg = 1;
68295   nc.nErr = 0;
68296   if( sqlite3ExprResolveNames(&nc, pE) ){
68297     if( isCompound ){
68298       sqlite3ErrorClear(pParse);
68299       return 0;
68300     }else{
68301       return -1;
68302     }
68303   }
68304   if( nc.hasAgg && pHasAgg ){
68305     *pHasAgg = 1;
68306   }
68307
68308   /* For a compound SELECT, we need to try to match the ORDER BY
68309   ** expression against an expression in the result set
68310   */
68311   if( isCompound ){
68312     for(i=0; i<pEList->nExpr; i++){
68313       if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){
68314         return i+1;
68315       }
68316     }
68317   }
68318   return 0;
68319 }
68320
68321
68322 /*
68323 ** Analyze and ORDER BY or GROUP BY clause in a simple SELECT statement.
68324 ** Return the number of errors seen.
68325 **
68326 ** Every term of the ORDER BY or GROUP BY clause needs to be an
68327 ** expression.  If any expression is an integer constant, then
68328 ** that expression is replaced by the corresponding 
68329 ** expression from the result set.
68330 */
68331 static int processOrderGroupBy(
68332   Parse *pParse,        /* Parsing context.  Leave error messages here */
68333   Select *pSelect,      /* The SELECT statement containing the clause */
68334   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
68335   int isOrder,          /* 1 for ORDER BY.  0 for GROUP BY */
68336   u8 *pHasAgg           /* Set to TRUE if any term contains an aggregate */
68337 ){
68338   int i;
68339   sqlite3 *db = pParse->db;
68340   ExprList *pEList;
68341
68342   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
68343 #if SQLITE_MAX_COLUMN
68344   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
68345     const char *zType = isOrder ? "ORDER" : "GROUP";
68346     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
68347     return 1;
68348   }
68349 #endif
68350   pEList = pSelect->pEList;
68351   if( pEList==0 ){
68352     return 0;
68353   }
68354   for(i=0; i<pOrderBy->nExpr; i++){
68355     int iCol;
68356     Expr *pE = pOrderBy->a[i].pExpr;
68357     if( sqlite3ExprIsInteger(pE, &iCol) ){
68358       if( iCol<=0 || iCol>pEList->nExpr ){
68359         const char *zType = isOrder ? "ORDER" : "GROUP";
68360         sqlite3ErrorMsg(pParse, 
68361            "%r %s BY term out of range - should be "
68362            "between 1 and %d", i+1, zType, pEList->nExpr);
68363         return 1;
68364       }
68365     }else{
68366       iCol = matchOrderByTermToExprList(pParse, pSelect, pE, i+1, 0, pHasAgg);
68367       if( iCol<0 ){
68368         return 1;
68369       }
68370     }
68371     if( iCol>0 ){
68372       CollSeq *pColl = pE->pColl;
68373       int flags = pE->flags & EP_ExpCollate;
68374       sqlite3ExprDelete(db, pE);
68375       pE = sqlite3ExprDup(db, pEList->a[iCol-1].pExpr);
68376       pOrderBy->a[i].pExpr = pE;
68377       if( pE && pColl && flags ){
68378         pE->pColl = pColl;
68379         pE->flags |= flags;
68380       }
68381     }
68382   }
68383   return 0;
68384 }
68385
68386 /*
68387 ** Analyze and ORDER BY or GROUP BY clause in a SELECT statement.  Return
68388 ** the number of errors seen.
68389 **
68390 ** If iTable>0 then make the N-th term of the ORDER BY clause refer to
68391 ** the N-th column of table iTable.
68392 **
68393 ** If iTable==0 then transform each term of the ORDER BY clause to refer
68394 ** to a column of the result set by number.
68395 */
68396 static int processCompoundOrderBy(
68397   Parse *pParse,        /* Parsing context.  Leave error messages here */
68398   Select *pSelect       /* The SELECT statement containing the ORDER BY */
68399 ){
68400   int i;
68401   ExprList *pOrderBy;
68402   ExprList *pEList;
68403   sqlite3 *db;
68404   int moreToDo = 1;
68405
68406   pOrderBy = pSelect->pOrderBy;
68407   if( pOrderBy==0 ) return 0;
68408   db = pParse->db;
68409 #if SQLITE_MAX_COLUMN
68410   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
68411     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
68412     return 1;
68413   }
68414 #endif
68415   for(i=0; i<pOrderBy->nExpr; i++){
68416     pOrderBy->a[i].done = 0;
68417   }
68418   while( pSelect->pPrior ){
68419     pSelect = pSelect->pPrior;
68420   }
68421   while( pSelect && moreToDo ){
68422     moreToDo = 0;
68423     pEList = pSelect->pEList;
68424     if( pEList==0 ){
68425       return 1;
68426     }
68427     for(i=0; i<pOrderBy->nExpr; i++){
68428       int iCol = -1;
68429       Expr *pE, *pDup;
68430       if( pOrderBy->a[i].done ) continue;
68431       pE = pOrderBy->a[i].pExpr;
68432       if( sqlite3ExprIsInteger(pE, &iCol) ){
68433         if( iCol<0 || iCol>pEList->nExpr ){
68434           sqlite3ErrorMsg(pParse, 
68435              "%r ORDER BY term out of range - should be "
68436              "between 1 and %d", i+1, pEList->nExpr);
68437           return 1;
68438         }
68439       }else{
68440         pDup = sqlite3ExprDup(db, pE);
68441         if( !db->mallocFailed ){
68442           assert(pDup);
68443           iCol = matchOrderByTermToExprList(pParse, pSelect, pDup, i+1, 1, 0);
68444         }
68445         sqlite3ExprDelete(db, pDup);
68446         if( iCol<0 ){
68447           return 1;
68448         }
68449       }
68450       if( iCol>0 ){
68451         pE->op = TK_INTEGER;
68452         pE->flags |= EP_IntValue;
68453         pE->iTable = iCol;
68454         pOrderBy->a[i].done = 1;
68455       }else{
68456         moreToDo = 1;
68457       }
68458     }
68459     pSelect = pSelect->pNext;
68460   }
68461   for(i=0; i<pOrderBy->nExpr; i++){
68462     if( pOrderBy->a[i].done==0 ){
68463       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
68464             "column in the result set", i+1);
68465       return 1;
68466     }
68467   }
68468   return 0;
68469 }
68470
68471 /*
68472 ** Get a VDBE for the given parser context.  Create a new one if necessary.
68473 ** If an error occurs, return NULL and leave a message in pParse.
68474 */
68475 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
68476   Vdbe *v = pParse->pVdbe;
68477   if( v==0 ){
68478     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
68479 #ifndef SQLITE_OMIT_TRACE
68480     if( v ){
68481       sqlite3VdbeAddOp0(v, OP_Trace);
68482     }
68483 #endif
68484   }
68485   return v;
68486 }
68487
68488
68489 /*
68490 ** Compute the iLimit and iOffset fields of the SELECT based on the
68491 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
68492 ** that appear in the original SQL statement after the LIMIT and OFFSET
68493 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
68494 ** are the integer memory register numbers for counters used to compute 
68495 ** the limit and offset.  If there is no limit and/or offset, then 
68496 ** iLimit and iOffset are negative.
68497 **
68498 ** This routine changes the values of iLimit and iOffset only if
68499 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
68500 ** iOffset should have been preset to appropriate default values
68501 ** (usually but not always -1) prior to calling this routine.
68502 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
68503 ** redefined.  The UNION ALL operator uses this property to force
68504 ** the reuse of the same limit and offset registers across multiple
68505 ** SELECT statements.
68506 */
68507 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
68508   Vdbe *v = 0;
68509   int iLimit = 0;
68510   int iOffset;
68511   int addr1;
68512   if( p->iLimit ) return;
68513
68514   /* 
68515   ** "LIMIT -1" always shows all rows.  There is some
68516   ** contraversy about what the correct behavior should be.
68517   ** The current implementation interprets "LIMIT 0" to mean
68518   ** no rows.
68519   */
68520   if( p->pLimit ){
68521     p->iLimit = iLimit = ++pParse->nMem;
68522     v = sqlite3GetVdbe(pParse);
68523     if( v==0 ) return;
68524     sqlite3ExprCode(pParse, p->pLimit, iLimit);
68525     sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
68526     VdbeComment((v, "LIMIT counter"));
68527     sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
68528   }
68529   if( p->pOffset ){
68530     p->iOffset = iOffset = ++pParse->nMem;
68531     if( p->pLimit ){
68532       pParse->nMem++;   /* Allocate an extra register for limit+offset */
68533     }
68534     v = sqlite3GetVdbe(pParse);
68535     if( v==0 ) return;
68536     sqlite3ExprCode(pParse, p->pOffset, iOffset);
68537     sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
68538     VdbeComment((v, "OFFSET counter"));
68539     addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
68540     sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
68541     sqlite3VdbeJumpHere(v, addr1);
68542     if( p->pLimit ){
68543       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
68544       VdbeComment((v, "LIMIT+OFFSET"));
68545       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
68546       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
68547       sqlite3VdbeJumpHere(v, addr1);
68548     }
68549   }
68550 }
68551
68552 #ifndef SQLITE_OMIT_COMPOUND_SELECT
68553 /*
68554 ** Return the appropriate collating sequence for the iCol-th column of
68555 ** the result set for the compound-select statement "p".  Return NULL if
68556 ** the column has no default collating sequence.
68557 **
68558 ** The collating sequence for the compound select is taken from the
68559 ** left-most term of the select that has a collating sequence.
68560 */
68561 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
68562   CollSeq *pRet;
68563   if( p->pPrior ){
68564     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
68565   }else{
68566     pRet = 0;
68567   }
68568   if( pRet==0 ){
68569     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
68570   }
68571   return pRet;
68572 }
68573 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
68574
68575 /* Forward reference */
68576 static int multiSelectOrderBy(
68577   Parse *pParse,        /* Parsing context */
68578   Select *p,            /* The right-most of SELECTs to be coded */
68579   SelectDest *pDest     /* What to do with query results */
68580 );
68581
68582
68583 #ifndef SQLITE_OMIT_COMPOUND_SELECT
68584 /*
68585 ** This routine is called to process a compound query form from
68586 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
68587 ** INTERSECT
68588 **
68589 ** "p" points to the right-most of the two queries.  the query on the
68590 ** left is p->pPrior.  The left query could also be a compound query
68591 ** in which case this routine will be called recursively. 
68592 **
68593 ** The results of the total query are to be written into a destination
68594 ** of type eDest with parameter iParm.
68595 **
68596 ** Example 1:  Consider a three-way compound SQL statement.
68597 **
68598 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
68599 **
68600 ** This statement is parsed up as follows:
68601 **
68602 **     SELECT c FROM t3
68603 **      |
68604 **      `----->  SELECT b FROM t2
68605 **                |
68606 **                `------>  SELECT a FROM t1
68607 **
68608 ** The arrows in the diagram above represent the Select.pPrior pointer.
68609 ** So if this routine is called with p equal to the t3 query, then
68610 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
68611 **
68612 ** Notice that because of the way SQLite parses compound SELECTs, the
68613 ** individual selects always group from left to right.
68614 */
68615 static int multiSelect(
68616   Parse *pParse,        /* Parsing context */
68617   Select *p,            /* The right-most of SELECTs to be coded */
68618   SelectDest *pDest     /* What to do with query results */
68619 ){
68620   int rc = SQLITE_OK;   /* Success code from a subroutine */
68621   Select *pPrior;       /* Another SELECT immediately to our left */
68622   Vdbe *v;              /* Generate code to this VDBE */
68623   SelectDest dest;      /* Alternative data destination */
68624   Select *pDelete = 0;  /* Chain of simple selects to delete */
68625   sqlite3 *db;          /* Database connection */
68626
68627   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
68628   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
68629   */
68630   assert( p && p->pPrior );  /* Calling function guarantees this much */
68631   db = pParse->db;
68632   pPrior = p->pPrior;
68633   assert( pPrior->pRightmost!=pPrior );
68634   assert( pPrior->pRightmost==p->pRightmost );
68635   if( pPrior->pOrderBy ){
68636     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
68637       selectOpName(p->op));
68638     rc = 1;
68639     goto multi_select_end;
68640   }
68641   if( pPrior->pLimit ){
68642     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
68643       selectOpName(p->op));
68644     rc = 1;
68645     goto multi_select_end;
68646   }
68647
68648   v = sqlite3GetVdbe(pParse);
68649   assert( v!=0 );  /* The VDBE already created by calling function */
68650
68651   /* Create the destination temporary table if necessary
68652   */
68653   dest = *pDest;
68654   if( dest.eDest==SRT_EphemTab ){
68655     assert( p->pEList );
68656     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
68657     dest.eDest = SRT_Table;
68658   }
68659
68660   /* Make sure all SELECTs in the statement have the same number of elements
68661   ** in their result sets.
68662   */
68663   assert( p->pEList && pPrior->pEList );
68664   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
68665     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
68666       " do not have the same number of result columns", selectOpName(p->op));
68667     rc = 1;
68668     goto multi_select_end;
68669   }
68670
68671   /* Compound SELECTs that have an ORDER BY clause are handled separately.
68672   */
68673   if( p->pOrderBy ){
68674     return multiSelectOrderBy(pParse, p, pDest);
68675   }
68676
68677   /* Generate code for the left and right SELECT statements.
68678   */
68679   switch( p->op ){
68680     case TK_ALL: {
68681       int addr = 0;
68682       assert( !pPrior->pLimit );
68683       pPrior->pLimit = p->pLimit;
68684       pPrior->pOffset = p->pOffset;
68685       rc = sqlite3Select(pParse, pPrior, &dest, 0, 0, 0);
68686       p->pLimit = 0;
68687       p->pOffset = 0;
68688       if( rc ){
68689         goto multi_select_end;
68690       }
68691       p->pPrior = 0;
68692       p->iLimit = pPrior->iLimit;
68693       p->iOffset = pPrior->iOffset;
68694       if( p->iLimit ){
68695         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
68696         VdbeComment((v, "Jump ahead if LIMIT reached"));
68697       }
68698       rc = sqlite3Select(pParse, p, &dest, 0, 0, 0);
68699       pDelete = p->pPrior;
68700       p->pPrior = pPrior;
68701       if( rc ){
68702         goto multi_select_end;
68703       }
68704       if( addr ){
68705         sqlite3VdbeJumpHere(v, addr);
68706       }
68707       break;
68708     }
68709     case TK_EXCEPT:
68710     case TK_UNION: {
68711       int unionTab;    /* Cursor number of the temporary table holding result */
68712       int op = 0;      /* One of the SRT_ operations to apply to self */
68713       int priorOp;     /* The SRT_ operation to apply to prior selects */
68714       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
68715       int addr;
68716       SelectDest uniondest;
68717
68718       priorOp = SRT_Union;
68719       if( dest.eDest==priorOp && !p->pLimit && !p->pOffset ){
68720         /* We can reuse a temporary table generated by a SELECT to our
68721         ** right.
68722         */
68723         unionTab = dest.iParm;
68724       }else{
68725         /* We will need to create our own temporary table to hold the
68726         ** intermediate results.
68727         */
68728         unionTab = pParse->nTab++;
68729         assert( p->pOrderBy==0 );
68730         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
68731         assert( p->addrOpenEphm[0] == -1 );
68732         p->addrOpenEphm[0] = addr;
68733         p->pRightmost->usesEphm = 1;
68734         assert( p->pEList );
68735       }
68736
68737       /* Code the SELECT statements to our left
68738       */
68739       assert( !pPrior->pOrderBy );
68740       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
68741       rc = sqlite3Select(pParse, pPrior, &uniondest, 0, 0, 0);
68742       if( rc ){
68743         goto multi_select_end;
68744       }
68745
68746       /* Code the current SELECT statement
68747       */
68748       if( p->op==TK_EXCEPT ){
68749         op = SRT_Except;
68750       }else{
68751         assert( p->op==TK_UNION );
68752         op = SRT_Union;
68753       }
68754       p->pPrior = 0;
68755       p->disallowOrderBy = 0;
68756       pLimit = p->pLimit;
68757       p->pLimit = 0;
68758       pOffset = p->pOffset;
68759       p->pOffset = 0;
68760       uniondest.eDest = op;
68761       rc = sqlite3Select(pParse, p, &uniondest, 0, 0, 0);
68762       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
68763       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
68764       sqlite3ExprListDelete(db, p->pOrderBy);
68765       pDelete = p->pPrior;
68766       p->pPrior = pPrior;
68767       p->pOrderBy = 0;
68768       sqlite3ExprDelete(db, p->pLimit);
68769       p->pLimit = pLimit;
68770       p->pOffset = pOffset;
68771       p->iLimit = 0;
68772       p->iOffset = 0;
68773       if( rc ){
68774         goto multi_select_end;
68775       }
68776
68777
68778       /* Convert the data in the temporary table into whatever form
68779       ** it is that we currently need.
68780       */      
68781       if( dest.eDest!=priorOp || unionTab!=dest.iParm ){
68782         int iCont, iBreak, iStart;
68783         assert( p->pEList );
68784         if( dest.eDest==SRT_Callback ){
68785           Select *pFirst = p;
68786           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
68787           generateColumnNames(pParse, 0, pFirst->pEList);
68788         }
68789         iBreak = sqlite3VdbeMakeLabel(v);
68790         iCont = sqlite3VdbeMakeLabel(v);
68791         computeLimitRegisters(pParse, p, iBreak);
68792         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
68793         iStart = sqlite3VdbeCurrentAddr(v);
68794         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
68795                         0, -1, &dest, iCont, iBreak);
68796         sqlite3VdbeResolveLabel(v, iCont);
68797         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
68798         sqlite3VdbeResolveLabel(v, iBreak);
68799         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
68800       }
68801       break;
68802     }
68803     case TK_INTERSECT: {
68804       int tab1, tab2;
68805       int iCont, iBreak, iStart;
68806       Expr *pLimit, *pOffset;
68807       int addr;
68808       SelectDest intersectdest;
68809       int r1;
68810
68811       /* INTERSECT is different from the others since it requires
68812       ** two temporary tables.  Hence it has its own case.  Begin
68813       ** by allocating the tables we will need.
68814       */
68815       tab1 = pParse->nTab++;
68816       tab2 = pParse->nTab++;
68817       assert( p->pOrderBy==0 );
68818
68819       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
68820       assert( p->addrOpenEphm[0] == -1 );
68821       p->addrOpenEphm[0] = addr;
68822       p->pRightmost->usesEphm = 1;
68823       assert( p->pEList );
68824
68825       /* Code the SELECTs to our left into temporary table "tab1".
68826       */
68827       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
68828       rc = sqlite3Select(pParse, pPrior, &intersectdest, 0, 0, 0);
68829       if( rc ){
68830         goto multi_select_end;
68831       }
68832
68833       /* Code the current SELECT into temporary table "tab2"
68834       */
68835       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
68836       assert( p->addrOpenEphm[1] == -1 );
68837       p->addrOpenEphm[1] = addr;
68838       p->pPrior = 0;
68839       pLimit = p->pLimit;
68840       p->pLimit = 0;
68841       pOffset = p->pOffset;
68842       p->pOffset = 0;
68843       intersectdest.iParm = tab2;
68844       rc = sqlite3Select(pParse, p, &intersectdest, 0, 0, 0);
68845       pDelete = p->pPrior;
68846       p->pPrior = pPrior;
68847       sqlite3ExprDelete(db, p->pLimit);
68848       p->pLimit = pLimit;
68849       p->pOffset = pOffset;
68850       if( rc ){
68851         goto multi_select_end;
68852       }
68853
68854       /* Generate code to take the intersection of the two temporary
68855       ** tables.
68856       */
68857       assert( p->pEList );
68858       if( dest.eDest==SRT_Callback ){
68859         Select *pFirst = p;
68860         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
68861         generateColumnNames(pParse, 0, pFirst->pEList);
68862       }
68863       iBreak = sqlite3VdbeMakeLabel(v);
68864       iCont = sqlite3VdbeMakeLabel(v);
68865       computeLimitRegisters(pParse, p, iBreak);
68866       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
68867       r1 = sqlite3GetTempReg(pParse);
68868       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
68869       sqlite3VdbeAddOp3(v, OP_NotFound, tab2, iCont, r1);
68870       sqlite3ReleaseTempReg(pParse, r1);
68871       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
68872                       0, -1, &dest, iCont, iBreak);
68873       sqlite3VdbeResolveLabel(v, iCont);
68874       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
68875       sqlite3VdbeResolveLabel(v, iBreak);
68876       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
68877       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
68878       break;
68879     }
68880   }
68881
68882   /* Compute collating sequences used by 
68883   ** temporary tables needed to implement the compound select.
68884   ** Attach the KeyInfo structure to all temporary tables.
68885   **
68886   ** This section is run by the right-most SELECT statement only.
68887   ** SELECT statements to the left always skip this part.  The right-most
68888   ** SELECT might also skip this part if it has no ORDER BY clause and
68889   ** no temp tables are required.
68890   */
68891   if( p->usesEphm ){
68892     int i;                        /* Loop counter */
68893     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
68894     Select *pLoop;                /* For looping through SELECT statements */
68895     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
68896     int nCol;                     /* Number of columns in result set */
68897
68898     assert( p->pRightmost==p );
68899     nCol = p->pEList->nExpr;
68900     pKeyInfo = sqlite3DbMallocZero(db,
68901                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
68902     if( !pKeyInfo ){
68903       rc = SQLITE_NOMEM;
68904       goto multi_select_end;
68905     }
68906
68907     pKeyInfo->enc = ENC(db);
68908     pKeyInfo->nField = nCol;
68909
68910     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
68911       *apColl = multiSelectCollSeq(pParse, p, i);
68912       if( 0==*apColl ){
68913         *apColl = db->pDfltColl;
68914       }
68915     }
68916
68917     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
68918       for(i=0; i<2; i++){
68919         int addr = pLoop->addrOpenEphm[i];
68920         if( addr<0 ){
68921           /* If [0] is unused then [1] is also unused.  So we can
68922           ** always safely abort as soon as the first unused slot is found */
68923           assert( pLoop->addrOpenEphm[1]<0 );
68924           break;
68925         }
68926         sqlite3VdbeChangeP2(v, addr, nCol);
68927         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
68928         pLoop->addrOpenEphm[i] = -1;
68929       }
68930     }
68931     sqlite3DbFree(db, pKeyInfo);
68932   }
68933
68934 multi_select_end:
68935   pDest->iMem = dest.iMem;
68936   pDest->nMem = dest.nMem;
68937   sqlite3SelectDelete(db, pDelete);
68938   return rc;
68939 }
68940 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
68941
68942 /*
68943 ** Code an output subroutine for a coroutine implementation of a
68944 ** SELECT statment.
68945 **
68946 ** The data to be output is contained in pIn->iMem.  There are
68947 ** pIn->nMem columns to be output.  pDest is where the output should
68948 ** be sent.
68949 **
68950 ** regReturn is the number of the register holding the subroutine
68951 ** return address.
68952 **
68953 ** If regPrev>0 then it is a the first register in a vector that
68954 ** records the previous output.  mem[regPrev] is a flag that is false
68955 ** if there has been no previous output.  If regPrev>0 then code is
68956 ** generated to suppress duplicates.  pKeyInfo is used for comparing
68957 ** keys.
68958 **
68959 ** If the LIMIT found in p->iLimit is reached, jump immediately to
68960 ** iBreak.
68961 */
68962 static int generateOutputSubroutine(
68963   Parse *pParse,          /* Parsing context */
68964   Select *p,              /* The SELECT statement */
68965   SelectDest *pIn,        /* Coroutine supplying data */
68966   SelectDest *pDest,      /* Where to send the data */
68967   int regReturn,          /* The return address register */
68968   int regPrev,            /* Previous result register.  No uniqueness if 0 */
68969   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
68970   int p4type,             /* The p4 type for pKeyInfo */
68971   int iBreak              /* Jump here if we hit the LIMIT */
68972 ){
68973   Vdbe *v = pParse->pVdbe;
68974   int iContinue;
68975   int addr;
68976
68977   addr = sqlite3VdbeCurrentAddr(v);
68978   iContinue = sqlite3VdbeMakeLabel(v);
68979
68980   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
68981   */
68982   if( regPrev ){
68983     int j1, j2;
68984     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
68985     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
68986                               (char*)pKeyInfo, p4type);
68987     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
68988     sqlite3VdbeJumpHere(v, j1);
68989     sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
68990     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
68991   }
68992   if( pParse->db->mallocFailed ) return 0;
68993
68994   /* Suppress the the first OFFSET entries if there is an OFFSET clause
68995   */
68996   codeOffset(v, p, iContinue);
68997
68998   switch( pDest->eDest ){
68999     /* Store the result as data using a unique key.
69000     */
69001     case SRT_Table:
69002     case SRT_EphemTab: {
69003       int r1 = sqlite3GetTempReg(pParse);
69004       int r2 = sqlite3GetTempReg(pParse);
69005       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
69006       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
69007       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
69008       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
69009       sqlite3ReleaseTempReg(pParse, r2);
69010       sqlite3ReleaseTempReg(pParse, r1);
69011       break;
69012     }
69013
69014 #ifndef SQLITE_OMIT_SUBQUERY
69015     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
69016     ** then there should be a single item on the stack.  Write this
69017     ** item into the set table with bogus data.
69018     */
69019     case SRT_Set: {
69020       int r1;
69021       assert( pIn->nMem==1 );
69022       p->affinity = 
69023          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
69024       r1 = sqlite3GetTempReg(pParse);
69025       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
69026       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
69027       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
69028       sqlite3ReleaseTempReg(pParse, r1);
69029       break;
69030     }
69031
69032 #if 0  /* Never occurs on an ORDER BY query */
69033     /* If any row exist in the result set, record that fact and abort.
69034     */
69035     case SRT_Exists: {
69036       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
69037       /* The LIMIT clause will terminate the loop for us */
69038       break;
69039     }
69040 #endif
69041
69042     /* If this is a scalar select that is part of an expression, then
69043     ** store the results in the appropriate memory cell and break out
69044     ** of the scan loop.
69045     */
69046     case SRT_Mem: {
69047       assert( pIn->nMem==1 );
69048       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
69049       /* The LIMIT clause will jump out of the loop for us */
69050       break;
69051     }
69052 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
69053
69054     /* Send the data to the callback function or to a subroutine.  In the
69055     ** case of a subroutine, the subroutine itself is responsible for
69056     ** popping the data from the stack.
69057     */
69058     case SRT_Coroutine: {
69059       if( pDest->iMem==0 ){
69060         pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
69061         pDest->nMem = pIn->nMem;
69062       }
69063       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
69064       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
69065       break;
69066     }
69067
69068     case SRT_Callback: {
69069       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
69070       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
69071       break;
69072     }
69073
69074 #if !defined(SQLITE_OMIT_TRIGGER)
69075     /* Discard the results.  This is used for SELECT statements inside
69076     ** the body of a TRIGGER.  The purpose of such selects is to call
69077     ** user-defined functions that have side effects.  We do not care
69078     ** about the actual results of the select.
69079     */
69080     default: {
69081       break;
69082     }
69083 #endif
69084   }
69085
69086   /* Jump to the end of the loop if the LIMIT is reached.
69087   */
69088   if( p->iLimit ){
69089     sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
69090     sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak);
69091   }
69092
69093   /* Generate the subroutine return
69094   */
69095   sqlite3VdbeResolveLabel(v, iContinue);
69096   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
69097
69098   return addr;
69099 }
69100
69101 /*
69102 ** Alternative compound select code generator for cases when there
69103 ** is an ORDER BY clause.
69104 **
69105 ** We assume a query of the following form:
69106 **
69107 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
69108 **
69109 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
69110 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
69111 ** co-routines.  Then run the co-routines in parallel and merge the results
69112 ** into the output.  In addition to the two coroutines (called selectA and
69113 ** selectB) there are 7 subroutines:
69114 **
69115 **    outA:    Move the output of the selectA coroutine into the output
69116 **             of the compound query.
69117 **
69118 **    outB:    Move the output of the selectB coroutine into the output
69119 **             of the compound query.  (Only generated for UNION and
69120 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
69121 **             appears only in B.)
69122 **
69123 **    AltB:    Called when there is data from both coroutines and A<B.
69124 **
69125 **    AeqB:    Called when there is data from both coroutines and A==B.
69126 **
69127 **    AgtB:    Called when there is data from both coroutines and A>B.
69128 **
69129 **    EofA:    Called when data is exhausted from selectA.
69130 **
69131 **    EofB:    Called when data is exhausted from selectB.
69132 **
69133 ** The implementation of the latter five subroutines depend on which 
69134 ** <operator> is used:
69135 **
69136 **
69137 **             UNION ALL         UNION            EXCEPT          INTERSECT
69138 **          -------------  -----------------  --------------  -----------------
69139 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
69140 **
69141 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
69142 **
69143 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
69144 **
69145 **   EofA:   outB, nextB      outB, nextB          halt             halt
69146 **
69147 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
69148 **
69149 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
69150 ** causes an immediate jump to EofA and an EOF on B following nextB causes
69151 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
69152 ** following nextX causes a jump to the end of the select processing.
69153 **
69154 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
69155 ** within the output subroutine.  The regPrev register set holds the previously
69156 ** output value.  A comparison is made against this value and the output
69157 ** is skipped if the next results would be the same as the previous.
69158 **
69159 ** The implementation plan is to implement the two coroutines and seven
69160 ** subroutines first, then put the control logic at the bottom.  Like this:
69161 **
69162 **          goto Init
69163 **     coA: coroutine for left query (A)
69164 **     coB: coroutine for right query (B)
69165 **    outA: output one row of A
69166 **    outB: output one row of B (UNION and UNION ALL only)
69167 **    EofA: ...
69168 **    EofB: ...
69169 **    AltB: ...
69170 **    AeqB: ...
69171 **    AgtB: ...
69172 **    Init: initialize coroutine registers
69173 **          yield coA
69174 **          if eof(A) goto EofA
69175 **          yield coB
69176 **          if eof(B) goto EofB
69177 **    Cmpr: Compare A, B
69178 **          Jump AltB, AeqB, AgtB
69179 **     End: ...
69180 **
69181 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
69182 ** actually called using Gosub and they do not Return.  EofA and EofB loop
69183 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
69184 ** and AgtB jump to either L2 or to one of EofA or EofB.
69185 */
69186 #ifndef SQLITE_OMIT_COMPOUND_SELECT
69187 static int multiSelectOrderBy(
69188   Parse *pParse,        /* Parsing context */
69189   Select *p,            /* The right-most of SELECTs to be coded */
69190   SelectDest *pDest     /* What to do with query results */
69191 ){
69192   int i, j;             /* Loop counters */
69193   Select *pPrior;       /* Another SELECT immediately to our left */
69194   Vdbe *v;              /* Generate code to this VDBE */
69195   SelectDest destA;     /* Destination for coroutine A */
69196   SelectDest destB;     /* Destination for coroutine B */
69197   int regAddrA;         /* Address register for select-A coroutine */
69198   int regEofA;          /* Flag to indicate when select-A is complete */
69199   int regAddrB;         /* Address register for select-B coroutine */
69200   int regEofB;          /* Flag to indicate when select-B is complete */
69201   int addrSelectA;      /* Address of the select-A coroutine */
69202   int addrSelectB;      /* Address of the select-B coroutine */
69203   int regOutA;          /* Address register for the output-A subroutine */
69204   int regOutB;          /* Address register for the output-B subroutine */
69205   int addrOutA;         /* Address of the output-A subroutine */
69206   int addrOutB;         /* Address of the output-B subroutine */
69207   int addrEofA;         /* Address of the select-A-exhausted subroutine */
69208   int addrEofB;         /* Address of the select-B-exhausted subroutine */
69209   int addrAltB;         /* Address of the A<B subroutine */
69210   int addrAeqB;         /* Address of the A==B subroutine */
69211   int addrAgtB;         /* Address of the A>B subroutine */
69212   int regLimitA;        /* Limit register for select-A */
69213   int regLimitB;        /* Limit register for select-A */
69214   int regPrev;          /* A range of registers to hold previous output */
69215   int savedLimit;       /* Saved value of p->iLimit */
69216   int savedOffset;      /* Saved value of p->iOffset */
69217   int labelCmpr;        /* Label for the start of the merge algorithm */
69218   int labelEnd;         /* Label for the end of the overall SELECT stmt */
69219   int j1;               /* Jump instructions that get retargetted */
69220   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
69221   KeyInfo *pKeyDup;     /* Comparison information for duplicate removal */
69222   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
69223   sqlite3 *db;          /* Database connection */
69224   ExprList *pOrderBy;   /* The ORDER BY clause */
69225   int nOrderBy;         /* Number of terms in the ORDER BY clause */
69226   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
69227   u8 NotUsed;           /* Dummy variables */
69228
69229   assert( p->pOrderBy!=0 );
69230   db = pParse->db;
69231   v = pParse->pVdbe;
69232   if( v==0 ) return SQLITE_NOMEM;
69233   labelEnd = sqlite3VdbeMakeLabel(v);
69234   labelCmpr = sqlite3VdbeMakeLabel(v);
69235
69236
69237   /* Patch up the ORDER BY clause
69238   */
69239   op = p->op;  
69240   pPrior = p->pPrior;
69241   assert( pPrior->pOrderBy==0 );
69242   pOrderBy = p->pOrderBy;
69243   assert( pOrderBy );
69244   if( processCompoundOrderBy(pParse, p) ){
69245     return SQLITE_ERROR;
69246   }
69247   nOrderBy = pOrderBy->nExpr;
69248
69249   /* For operators other than UNION ALL we have to make sure that
69250   ** the ORDER BY clause covers every term of the result set.  Add
69251   ** terms to the ORDER BY clause as necessary.
69252   */
69253   if( op!=TK_ALL ){
69254     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
69255       for(j=0; j<nOrderBy; j++){
69256         Expr *pTerm = pOrderBy->a[j].pExpr;
69257         assert( pTerm->op==TK_INTEGER );
69258         assert( (pTerm->flags & EP_IntValue)!=0 );
69259         if( pTerm->iTable==i ) break;
69260       }
69261       if( j==nOrderBy ){
69262         Expr *pNew = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, 0);
69263         if( pNew==0 ) return SQLITE_NOMEM;
69264         pNew->flags |= EP_IntValue;
69265         pNew->iTable = i;
69266         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew, 0);
69267         nOrderBy++;
69268       }
69269     }
69270   }
69271
69272   /* Compute the comparison permutation and keyinfo that is used with
69273   ** the permutation in order to comparisons to determine if the next
69274   ** row of results comes from selectA or selectB.  Also add explicit
69275   ** collations to the ORDER BY clause terms so that when the subqueries
69276   ** to the right and the left are evaluated, they use the correct
69277   ** collation.
69278   */
69279   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
69280   if( aPermute ){
69281     for(i=0; i<nOrderBy; i++){
69282       Expr *pTerm = pOrderBy->a[i].pExpr;
69283       assert( pTerm->op==TK_INTEGER );
69284       assert( (pTerm->flags & EP_IntValue)!=0 );
69285       aPermute[i] = pTerm->iTable-1;
69286       assert( aPermute[i]>=0 && aPermute[i]<p->pEList->nExpr );
69287     }
69288     pKeyMerge =
69289       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
69290     if( pKeyMerge ){
69291       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
69292       pKeyMerge->nField = nOrderBy;
69293       pKeyMerge->enc = ENC(db);
69294       for(i=0; i<nOrderBy; i++){
69295         CollSeq *pColl;
69296         Expr *pTerm = pOrderBy->a[i].pExpr;
69297         if( pTerm->flags & EP_ExpCollate ){
69298           pColl = pTerm->pColl;
69299         }else{
69300           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
69301           pTerm->flags |= EP_ExpCollate;
69302           pTerm->pColl = pColl;
69303         }
69304         pKeyMerge->aColl[i] = pColl;
69305         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
69306       }
69307     }
69308   }else{
69309     pKeyMerge = 0;
69310   }
69311
69312   /* Reattach the ORDER BY clause to the query.
69313   */
69314   p->pOrderBy = pOrderBy;
69315   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy);
69316
69317   /* Allocate a range of temporary registers and the KeyInfo needed
69318   ** for the logic that removes duplicate result rows when the
69319   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
69320   */
69321   if( op==TK_ALL ){
69322     regPrev = 0;
69323   }else{
69324     int nExpr = p->pEList->nExpr;
69325     assert( nOrderBy>=nExpr );
69326     regPrev = sqlite3GetTempRange(pParse, nExpr+1);
69327     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
69328     pKeyDup = sqlite3DbMallocZero(db,
69329                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
69330     if( pKeyDup ){
69331       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
69332       pKeyDup->nField = nExpr;
69333       pKeyDup->enc = ENC(db);
69334       for(i=0; i<nExpr; i++){
69335         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
69336         pKeyDup->aSortOrder[i] = 0;
69337       }
69338     }
69339   }
69340  
69341   /* Separate the left and the right query from one another
69342   */
69343   p->pPrior = 0;
69344   pPrior->pRightmost = 0;
69345   processOrderGroupBy(pParse, p, p->pOrderBy, 1, &NotUsed);
69346   if( pPrior->pPrior==0 ){
69347     processOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, 1, &NotUsed);
69348   }
69349
69350   /* Compute the limit registers */
69351   computeLimitRegisters(pParse, p, labelEnd);
69352   if( p->iLimit && op==TK_ALL ){
69353     regLimitA = ++pParse->nMem;
69354     regLimitB = ++pParse->nMem;
69355     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
69356                                   regLimitA);
69357     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
69358   }else{
69359     regLimitA = regLimitB = 0;
69360   }
69361   sqlite3ExprDelete(db, p->pLimit);
69362   p->pLimit = 0;
69363   sqlite3ExprDelete(db, p->pOffset);
69364   p->pOffset = 0;
69365
69366   regAddrA = ++pParse->nMem;
69367   regEofA = ++pParse->nMem;
69368   regAddrB = ++pParse->nMem;
69369   regEofB = ++pParse->nMem;
69370   regOutA = ++pParse->nMem;
69371   regOutB = ++pParse->nMem;
69372   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
69373   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
69374
69375   /* Jump past the various subroutines and coroutines to the main
69376   ** merge loop
69377   */
69378   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
69379   addrSelectA = sqlite3VdbeCurrentAddr(v);
69380
69381
69382   /* Generate a coroutine to evaluate the SELECT statement to the
69383   ** left of the compound operator - the "A" select.
69384   */
69385   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
69386   pPrior->iLimit = regLimitA;
69387   sqlite3Select(pParse, pPrior, &destA, 0, 0, 0);
69388   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
69389   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
69390   VdbeNoopComment((v, "End coroutine for left SELECT"));
69391
69392   /* Generate a coroutine to evaluate the SELECT statement on 
69393   ** the right - the "B" select
69394   */
69395   addrSelectB = sqlite3VdbeCurrentAddr(v);
69396   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
69397   savedLimit = p->iLimit;
69398   savedOffset = p->iOffset;
69399   p->iLimit = regLimitB;
69400   p->iOffset = 0;  
69401   sqlite3Select(pParse, p, &destB, 0, 0, 0);
69402   p->iLimit = savedLimit;
69403   p->iOffset = savedOffset;
69404   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
69405   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
69406   VdbeNoopComment((v, "End coroutine for right SELECT"));
69407
69408   /* Generate a subroutine that outputs the current row of the A
69409   ** select as the next output row of the compound select.
69410   */
69411   VdbeNoopComment((v, "Output routine for A"));
69412   addrOutA = generateOutputSubroutine(pParse,
69413                  p, &destA, pDest, regOutA,
69414                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
69415   
69416   /* Generate a subroutine that outputs the current row of the B
69417   ** select as the next output row of the compound select.
69418   */
69419   if( op==TK_ALL || op==TK_UNION ){
69420     VdbeNoopComment((v, "Output routine for B"));
69421     addrOutB = generateOutputSubroutine(pParse,
69422                  p, &destB, pDest, regOutB,
69423                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
69424   }
69425
69426   /* Generate a subroutine to run when the results from select A
69427   ** are exhausted and only data in select B remains.
69428   */
69429   VdbeNoopComment((v, "eof-A subroutine"));
69430   if( op==TK_EXCEPT || op==TK_INTERSECT ){
69431     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
69432   }else{  
69433     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
69434     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
69435     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
69436     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
69437   }
69438
69439   /* Generate a subroutine to run when the results from select B
69440   ** are exhausted and only data in select A remains.
69441   */
69442   if( op==TK_INTERSECT ){
69443     addrEofB = addrEofA;
69444   }else{  
69445     VdbeNoopComment((v, "eof-B subroutine"));
69446     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
69447     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
69448     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
69449     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
69450   }
69451
69452   /* Generate code to handle the case of A<B
69453   */
69454   VdbeNoopComment((v, "A-lt-B subroutine"));
69455   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
69456   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
69457   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
69458   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
69459
69460   /* Generate code to handle the case of A==B
69461   */
69462   if( op==TK_ALL ){
69463     addrAeqB = addrAltB;
69464   }else if( op==TK_INTERSECT ){
69465     addrAeqB = addrAltB;
69466     addrAltB++;
69467   }else{
69468     VdbeNoopComment((v, "A-eq-B subroutine"));
69469     addrAeqB =
69470     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
69471     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
69472     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
69473   }
69474
69475   /* Generate code to handle the case of A>B
69476   */
69477   VdbeNoopComment((v, "A-gt-B subroutine"));
69478   addrAgtB = sqlite3VdbeCurrentAddr(v);
69479   if( op==TK_ALL || op==TK_UNION ){
69480     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
69481   }
69482   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
69483   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
69484   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
69485
69486   /* This code runs once to initialize everything.
69487   */
69488   sqlite3VdbeJumpHere(v, j1);
69489   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
69490   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
69491   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
69492   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
69493   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
69494   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
69495
69496   /* Implement the main merge loop
69497   */
69498   sqlite3VdbeResolveLabel(v, labelCmpr);
69499   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
69500   sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
69501                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
69502   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
69503
69504   /* Release temporary registers
69505   */
69506   if( regPrev ){
69507     sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
69508   }
69509
69510   /* Jump to the this point in order to terminate the query.
69511   */
69512   sqlite3VdbeResolveLabel(v, labelEnd);
69513
69514   /* Set the number of output columns
69515   */
69516   if( pDest->eDest==SRT_Callback ){
69517     Select *pFirst = pPrior;
69518     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
69519     generateColumnNames(pParse, 0, pFirst->pEList);
69520   }
69521
69522   /* Reassembly the compound query so that it will be freed correctly
69523   ** by the calling function */
69524   if( p->pPrior ){
69525     sqlite3SelectDelete(db, p->pPrior);
69526   }
69527   p->pPrior = pPrior;
69528
69529   /*** TBD:  Insert subroutine calls to close cursors on incomplete
69530   **** subqueries ****/
69531   return SQLITE_OK;
69532 }
69533 #endif
69534
69535 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
69536 /* Forward Declarations */
69537 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
69538 static void substSelect(sqlite3*, Select *, int, ExprList *);
69539
69540 /*
69541 ** Scan through the expression pExpr.  Replace every reference to
69542 ** a column in table number iTable with a copy of the iColumn-th
69543 ** entry in pEList.  (But leave references to the ROWID column 
69544 ** unchanged.)
69545 **
69546 ** This routine is part of the flattening procedure.  A subquery
69547 ** whose result set is defined by pEList appears as entry in the
69548 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
69549 ** FORM clause entry is iTable.  This routine make the necessary 
69550 ** changes to pExpr so that it refers directly to the source table
69551 ** of the subquery rather the result set of the subquery.
69552 */
69553 static void substExpr(
69554   sqlite3 *db,        /* Report malloc errors to this connection */
69555   Expr *pExpr,        /* Expr in which substitution occurs */
69556   int iTable,         /* Table to be substituted */
69557   ExprList *pEList    /* Substitute expressions */
69558 ){
69559   if( pExpr==0 ) return;
69560   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
69561     if( pExpr->iColumn<0 ){
69562       pExpr->op = TK_NULL;
69563     }else{
69564       Expr *pNew;
69565       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
69566       assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
69567       pNew = pEList->a[pExpr->iColumn].pExpr;
69568       assert( pNew!=0 );
69569       pExpr->op = pNew->op;
69570       assert( pExpr->pLeft==0 );
69571       pExpr->pLeft = sqlite3ExprDup(db, pNew->pLeft);
69572       assert( pExpr->pRight==0 );
69573       pExpr->pRight = sqlite3ExprDup(db, pNew->pRight);
69574       assert( pExpr->pList==0 );
69575       pExpr->pList = sqlite3ExprListDup(db, pNew->pList);
69576       pExpr->iTable = pNew->iTable;
69577       pExpr->pTab = pNew->pTab;
69578       pExpr->iColumn = pNew->iColumn;
69579       pExpr->iAgg = pNew->iAgg;
69580       sqlite3TokenCopy(db, &pExpr->token, &pNew->token);
69581       sqlite3TokenCopy(db, &pExpr->span, &pNew->span);
69582       pExpr->pSelect = sqlite3SelectDup(db, pNew->pSelect);
69583       pExpr->flags = pNew->flags;
69584     }
69585   }else{
69586     substExpr(db, pExpr->pLeft, iTable, pEList);
69587     substExpr(db, pExpr->pRight, iTable, pEList);
69588     substSelect(db, pExpr->pSelect, iTable, pEList);
69589     substExprList(db, pExpr->pList, iTable, pEList);
69590   }
69591 }
69592 static void substExprList(
69593   sqlite3 *db,         /* Report malloc errors here */
69594   ExprList *pList,     /* List to scan and in which to make substitutes */
69595   int iTable,          /* Table to be substituted */
69596   ExprList *pEList     /* Substitute values */
69597 ){
69598   int i;
69599   if( pList==0 ) return;
69600   for(i=0; i<pList->nExpr; i++){
69601     substExpr(db, pList->a[i].pExpr, iTable, pEList);
69602   }
69603 }
69604 static void substSelect(
69605   sqlite3 *db,         /* Report malloc errors here */
69606   Select *p,           /* SELECT statement in which to make substitutions */
69607   int iTable,          /* Table to be replaced */
69608   ExprList *pEList     /* Substitute values */
69609 ){
69610   if( !p ) return;
69611   substExprList(db, p->pEList, iTable, pEList);
69612   substExprList(db, p->pGroupBy, iTable, pEList);
69613   substExprList(db, p->pOrderBy, iTable, pEList);
69614   substExpr(db, p->pHaving, iTable, pEList);
69615   substExpr(db, p->pWhere, iTable, pEList);
69616   substSelect(db, p->pPrior, iTable, pEList);
69617 }
69618 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
69619
69620 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
69621 /*
69622 ** This routine attempts to flatten subqueries in order to speed
69623 ** execution.  It returns 1 if it makes changes and 0 if no flattening
69624 ** occurs.
69625 **
69626 ** To understand the concept of flattening, consider the following
69627 ** query:
69628 **
69629 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
69630 **
69631 ** The default way of implementing this query is to execute the
69632 ** subquery first and store the results in a temporary table, then
69633 ** run the outer query on that temporary table.  This requires two
69634 ** passes over the data.  Furthermore, because the temporary table
69635 ** has no indices, the WHERE clause on the outer query cannot be
69636 ** optimized.
69637 **
69638 ** This routine attempts to rewrite queries such as the above into
69639 ** a single flat select, like this:
69640 **
69641 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
69642 **
69643 ** The code generated for this simpification gives the same result
69644 ** but only has to scan the data once.  And because indices might 
69645 ** exist on the table t1, a complete scan of the data might be
69646 ** avoided.
69647 **
69648 ** Flattening is only attempted if all of the following are true:
69649 **
69650 **   (1)  The subquery and the outer query do not both use aggregates.
69651 **
69652 **   (2)  The subquery is not an aggregate or the outer query is not a join.
69653 **
69654 **   (3)  The subquery is not the right operand of a left outer join, or
69655 **        the subquery is not itself a join.  (Ticket #306)
69656 **
69657 **   (4)  The subquery is not DISTINCT or the outer query is not a join.
69658 **
69659 **   (5)  The subquery is not DISTINCT or the outer query does not use
69660 **        aggregates.
69661 **
69662 **   (6)  The subquery does not use aggregates or the outer query is not
69663 **        DISTINCT.
69664 **
69665 **   (7)  The subquery has a FROM clause.
69666 **
69667 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
69668 **
69669 **   (9)  The subquery does not use LIMIT or the outer query does not use
69670 **        aggregates.
69671 **
69672 **  (10)  The subquery does not use aggregates or the outer query does not
69673 **        use LIMIT.
69674 **
69675 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
69676 **
69677 **  (12)  The subquery is not the right term of a LEFT OUTER JOIN or the
69678 **        subquery has no WHERE clause.  (added by ticket #350)
69679 **
69680 **  (13)  The subquery and outer query do not both use LIMIT
69681 **
69682 **  (14)  The subquery does not use OFFSET
69683 **
69684 **  (15)  The outer query is not part of a compound select or the
69685 **        subquery does not have both an ORDER BY and a LIMIT clause.
69686 **        (See ticket #2339)
69687 **
69688 **  (16)  The outer query is not an aggregate or the subquery does
69689 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
69690 **        until we introduced the group_concat() function.  
69691 **
69692 **  (17)  The sub-query is not a compound select, or it is a UNION ALL 
69693 **        compound clause made up entirely of non-aggregate queries, and 
69694 **        the parent query:
69695 **
69696 **          * is not itself part of a compound select,
69697 **          * is not an aggregate or DISTINCT query, and
69698 **          * has no other tables or sub-selects in the FROM clause.
69699 **
69700 **        The parent and sub-query may contain WHERE clauses. Subject to
69701 **        rules (11), (13) and (14), they may also contain ORDER BY,
69702 **        LIMIT and OFFSET clauses.
69703 **
69704 **  (18)  If the sub-query is a compound select, then all terms of the
69705 **        ORDER by clause of the parent must be simple references to 
69706 **        columns of the sub-query.
69707 **
69708 ** In this routine, the "p" parameter is a pointer to the outer query.
69709 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
69710 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
69711 **
69712 ** If flattening is not attempted, this routine is a no-op and returns 0.
69713 ** If flattening is attempted this routine returns 1.
69714 **
69715 ** All of the expression analysis must occur on both the outer query and
69716 ** the subquery before this routine runs.
69717 */
69718 static int flattenSubquery(
69719   Parse *pParse,       /* Parsing context */
69720   Select *p,           /* The parent or outer SELECT statement */
69721   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
69722   int isAgg,           /* True if outer SELECT uses aggregate functions */
69723   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
69724 ){
69725   const char *zSavedAuthContext = pParse->zAuthContext;
69726   Select *pParent;
69727   Select *pSub;       /* The inner query or "subquery" */
69728   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
69729   SrcList *pSrc;      /* The FROM clause of the outer query */
69730   SrcList *pSubSrc;   /* The FROM clause of the subquery */
69731   ExprList *pList;    /* The result set of the outer query */
69732   int iParent;        /* VDBE cursor number of the pSub result set temp table */
69733   int i;              /* Loop counter */
69734   Expr *pWhere;                    /* The WHERE clause */
69735   struct SrcList_item *pSubitem;   /* The subquery */
69736   sqlite3 *db = pParse->db;
69737
69738   /* Check to see if flattening is permitted.  Return 0 if not.
69739   */
69740   if( p==0 ) return 0;
69741   pSrc = p->pSrc;
69742   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
69743   pSubitem = &pSrc->a[iFrom];
69744   iParent = pSubitem->iCursor;
69745   pSub = pSubitem->pSelect;
69746   assert( pSub!=0 );
69747   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
69748   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
69749   pSubSrc = pSub->pSrc;
69750   assert( pSubSrc );
69751   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
69752   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
69753   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
69754   ** became arbitrary expressions, we were forced to add restrictions (13)
69755   ** and (14). */
69756   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
69757   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
69758   if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
69759     return 0;                                            /* Restriction (15) */
69760   }
69761   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
69762   if( (pSub->isDistinct || pSub->pLimit) 
69763          && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
69764      return 0;       
69765   }
69766   if( p->isDistinct && subqueryIsAgg ) return 0;         /* Restriction (6)  */
69767   if( (p->disallowOrderBy || p->pOrderBy) && pSub->pOrderBy ){
69768      return 0;                                           /* Restriction (11) */
69769   }
69770   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
69771
69772   /* Restriction 3:  If the subquery is a join, make sure the subquery is 
69773   ** not used as the right operand of an outer join.  Examples of why this
69774   ** is not allowed:
69775   **
69776   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
69777   **
69778   ** If we flatten the above, we would get
69779   **
69780   **         (t1 LEFT OUTER JOIN t2) JOIN t3
69781   **
69782   ** which is not at all the same thing.
69783   */
69784   if( pSubSrc->nSrc>1 && (pSubitem->jointype & JT_OUTER)!=0 ){
69785     return 0;
69786   }
69787
69788   /* Restriction 12:  If the subquery is the right operand of a left outer
69789   ** join, make sure the subquery has no WHERE clause.
69790   ** An examples of why this is not allowed:
69791   **
69792   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
69793   **
69794   ** If we flatten the above, we would get
69795   **
69796   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
69797   **
69798   ** But the t2.x>0 test will always fail on a NULL row of t2, which
69799   ** effectively converts the OUTER JOIN into an INNER JOIN.
69800   */
69801   if( (pSubitem->jointype & JT_OUTER)!=0 && pSub->pWhere!=0 ){
69802     return 0;
69803   }
69804
69805   /* Restriction 17: If the sub-query is a compound SELECT, then it must
69806   ** use only the UNION ALL operator. And none of the simple select queries
69807   ** that make up the compound SELECT are allowed to be aggregate or distinct
69808   ** queries.
69809   */
69810   if( pSub->pPrior ){
69811     if( p->pPrior || isAgg || p->isDistinct || pSrc->nSrc!=1 ){
69812       return 0;
69813     }
69814     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
69815       if( pSub1->isAgg || pSub1->isDistinct 
69816        || (pSub1->pPrior && pSub1->op!=TK_ALL) 
69817        || !pSub1->pSrc || pSub1->pSrc->nSrc!=1
69818       ){
69819         return 0;
69820       }
69821     }
69822
69823     /* Restriction 18. */
69824     if( p->pOrderBy ){
69825       int ii;
69826       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
69827         Expr *pExpr = p->pOrderBy->a[ii].pExpr;
69828         if( pExpr->op!=TK_COLUMN || pExpr->iTable!=iParent ){ 
69829           return 0;
69830         }
69831       }
69832     }
69833   }
69834
69835   pParse->zAuthContext = pSubitem->zName;
69836   sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
69837   pParse->zAuthContext = zSavedAuthContext;
69838
69839   /* If the sub-query is a compound SELECT statement, then it must be
69840   ** a UNION ALL and the parent query must be of the form:
69841   **
69842   **     SELECT <expr-list> FROM (<sub-query>) <where-clause> 
69843   **
69844   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
69845   ** creates N copies of the parent query without any ORDER BY, LIMIT or 
69846   ** OFFSET clauses and joins them to the left-hand-side of the original
69847   ** using UNION ALL operators. In this case N is the number of simple
69848   ** select statements in the compound sub-query.
69849   */
69850   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
69851     Select *pNew;
69852     ExprList *pOrderBy = p->pOrderBy;
69853     Expr *pLimit = p->pLimit;
69854     Expr *pOffset = p->pOffset;
69855     Select *pPrior = p->pPrior;
69856     p->pOrderBy = 0;
69857     p->pSrc = 0;
69858     p->pPrior = 0;
69859     p->pLimit = 0;
69860     pNew = sqlite3SelectDup(db, p);
69861     pNew->pPrior = pPrior;
69862     p->pPrior = pNew;
69863     p->pOrderBy = pOrderBy;
69864     p->op = TK_ALL;
69865     p->pSrc = pSrc;
69866     p->pLimit = pLimit;
69867     p->pOffset = pOffset;
69868     p->pRightmost = 0;
69869     pNew->pRightmost = 0;
69870   }
69871
69872   /* If we reach this point, it means flattening is permitted for the
69873   ** iFrom-th entry of the FROM clause in the outer query.
69874   */
69875   pSub = pSub1 = pSubitem->pSelect;
69876   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
69877     int nSubSrc = pSubSrc->nSrc;
69878     int jointype = 0;
69879     pSubSrc = pSub->pSrc;
69880     pSrc = pParent->pSrc;
69881
69882     /* Move all of the FROM elements of the subquery into the
69883     ** the FROM clause of the outer query.  Before doing this, remember
69884     ** the cursor number for the original outer query FROM element in
69885     ** iParent.  The iParent cursor will never be used.  Subsequent code
69886     ** will scan expressions looking for iParent references and replace
69887     ** those references with expressions that resolve to the subquery FROM
69888     ** elements we are now copying in.
69889     */
69890     if( pSrc ){
69891       pSubitem = &pSrc->a[iFrom];
69892       nSubSrc = pSubSrc->nSrc;
69893       jointype = pSubitem->jointype;
69894       sqlite3DeleteTable(pSubitem->pTab);
69895       sqlite3DbFree(db, pSubitem->zDatabase);
69896       sqlite3DbFree(db, pSubitem->zName);
69897       sqlite3DbFree(db, pSubitem->zAlias);
69898       pSubitem->pTab = 0;
69899       pSubitem->zDatabase = 0;
69900       pSubitem->zName = 0;
69901       pSubitem->zAlias = 0;
69902     }
69903     if( nSubSrc!=1 || !pSrc ){
69904       int extra = nSubSrc - 1;
69905       for(i=(pSrc?1:0); i<nSubSrc; i++){
69906         pSrc = sqlite3SrcListAppend(db, pSrc, 0, 0);
69907         if( pSrc==0 ){
69908           pParent->pSrc = 0;
69909           return 1;
69910         }
69911       }
69912       pParent->pSrc = pSrc;
69913       for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
69914         pSrc->a[i] = pSrc->a[i-extra];
69915       }
69916     }
69917     for(i=0; i<nSubSrc; i++){
69918       pSrc->a[i+iFrom] = pSubSrc->a[i];
69919       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
69920     }
69921     pSrc->a[iFrom].jointype = jointype;
69922   
69923     /* Now begin substituting subquery result set expressions for 
69924     ** references to the iParent in the outer query.
69925     ** 
69926     ** Example:
69927     **
69928     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
69929     **   \                     \_____________ subquery __________/          /
69930     **    \_____________________ outer query ______________________________/
69931     **
69932     ** We look at every expression in the outer query and every place we see
69933     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
69934     */
69935     pList = pParent->pEList;
69936     for(i=0; i<pList->nExpr; i++){
69937       Expr *pExpr;
69938       if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
69939         pList->a[i].zName = 
69940                sqlite3DbStrNDup(db, (char*)pExpr->span.z, pExpr->span.n);
69941       }
69942     }
69943     substExprList(db, pParent->pEList, iParent, pSub->pEList);
69944     if( isAgg ){
69945       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
69946       substExpr(db, pParent->pHaving, iParent, pSub->pEList);
69947     }
69948     if( pSub->pOrderBy ){
69949       assert( pParent->pOrderBy==0 );
69950       pParent->pOrderBy = pSub->pOrderBy;
69951       pSub->pOrderBy = 0;
69952     }else if( pParent->pOrderBy ){
69953       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
69954     }
69955     if( pSub->pWhere ){
69956       pWhere = sqlite3ExprDup(db, pSub->pWhere);
69957     }else{
69958       pWhere = 0;
69959     }
69960     if( subqueryIsAgg ){
69961       assert( pParent->pHaving==0 );
69962       pParent->pHaving = pParent->pWhere;
69963       pParent->pWhere = pWhere;
69964       substExpr(db, pParent->pHaving, iParent, pSub->pEList);
69965       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 
69966                                   sqlite3ExprDup(db, pSub->pHaving));
69967       assert( pParent->pGroupBy==0 );
69968       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy);
69969     }else{
69970       substExpr(db, pParent->pWhere, iParent, pSub->pEList);
69971       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
69972     }
69973   
69974     /* The flattened query is distinct if either the inner or the
69975     ** outer query is distinct. 
69976     */
69977     pParent->isDistinct = pParent->isDistinct || pSub->isDistinct;
69978   
69979     /*
69980     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
69981     **
69982     ** One is tempted to try to add a and b to combine the limits.  But this
69983     ** does not work if either limit is negative.
69984     */
69985     if( pSub->pLimit ){
69986       pParent->pLimit = pSub->pLimit;
69987       pSub->pLimit = 0;
69988     }
69989   }
69990
69991   /* Finially, delete what is left of the subquery and return
69992   ** success.
69993   */
69994   sqlite3SelectDelete(db, pSub1);
69995
69996   return 1;
69997 }
69998 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
69999
70000 /*
70001 ** Analyze the SELECT statement passed as an argument to see if it
70002 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if 
70003 ** it is, or 0 otherwise. At present, a query is considered to be
70004 ** a min()/max() query if:
70005 **
70006 **   1. There is a single object in the FROM clause.
70007 **
70008 **   2. There is a single expression in the result set, and it is
70009 **      either min(x) or max(x), where x is a column reference.
70010 */
70011 static int minMaxQuery(Parse *pParse, Select *p){
70012   Expr *pExpr;
70013   ExprList *pEList = p->pEList;
70014
70015   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
70016   pExpr = pEList->a[0].pExpr;
70017   pEList = pExpr->pList;
70018   if( pExpr->op!=TK_AGG_FUNCTION || pEList==0 || pEList->nExpr!=1 ) return 0;
70019   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
70020   if( pExpr->token.n!=3 ) return WHERE_ORDERBY_NORMAL;
70021   if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){
70022     return WHERE_ORDERBY_MIN;
70023   }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){
70024     return WHERE_ORDERBY_MAX;
70025   }
70026   return WHERE_ORDERBY_NORMAL;
70027 }
70028
70029 /*
70030 ** This routine resolves any names used in the result set of the
70031 ** supplied SELECT statement. If the SELECT statement being resolved
70032 ** is a sub-select, then pOuterNC is a pointer to the NameContext 
70033 ** of the parent SELECT.
70034 */
70035 SQLITE_PRIVATE int sqlite3SelectResolve(
70036   Parse *pParse,         /* The parser context */
70037   Select *p,             /* The SELECT statement being coded. */
70038   NameContext *pOuterNC  /* The outer name context. May be NULL. */
70039 ){
70040   ExprList *pEList;          /* Result set. */
70041   int i;                     /* For-loop variable used in multiple places */
70042   NameContext sNC;           /* Local name-context */
70043   ExprList *pGroupBy;        /* The group by clause */
70044
70045   /* If this routine has run before, return immediately. */
70046   if( p->isResolved ){
70047     assert( !pOuterNC );
70048     return SQLITE_OK;
70049   }
70050   p->isResolved = 1;
70051
70052   /* If there have already been errors, do nothing. */
70053   if( pParse->nErr>0 ){
70054     return SQLITE_ERROR;
70055   }
70056
70057   /* Prepare the select statement. This call will allocate all cursors
70058   ** required to handle the tables and subqueries in the FROM clause.
70059   */
70060   if( prepSelectStmt(pParse, p) ){
70061     return SQLITE_ERROR;
70062   }
70063
70064   /* Resolve the expressions in the LIMIT and OFFSET clauses. These
70065   ** are not allowed to refer to any names, so pass an empty NameContext.
70066   */
70067   memset(&sNC, 0, sizeof(sNC));
70068   sNC.pParse = pParse;
70069   if( sqlite3ExprResolveNames(&sNC, p->pLimit) ||
70070       sqlite3ExprResolveNames(&sNC, p->pOffset) ){
70071     return SQLITE_ERROR;
70072   }
70073
70074   /* Set up the local name-context to pass to ExprResolveNames() to
70075   ** resolve the expression-list.
70076   */
70077   sNC.allowAgg = 1;
70078   sNC.pSrcList = p->pSrc;
70079   sNC.pNext = pOuterNC;
70080
70081   /* Resolve names in the result set. */
70082   pEList = p->pEList;
70083   if( !pEList ) return SQLITE_ERROR;
70084   for(i=0; i<pEList->nExpr; i++){
70085     Expr *pX = pEList->a[i].pExpr;
70086     if( sqlite3ExprResolveNames(&sNC, pX) ){
70087       return SQLITE_ERROR;
70088     }
70089   }
70090
70091   /* If there are no aggregate functions in the result-set, and no GROUP BY 
70092   ** expression, do not allow aggregates in any of the other expressions.
70093   */
70094   assert( !p->isAgg );
70095   pGroupBy = p->pGroupBy;
70096   if( pGroupBy || sNC.hasAgg ){
70097     p->isAgg = 1;
70098   }else{
70099     sNC.allowAgg = 0;
70100   }
70101
70102   /* If a HAVING clause is present, then there must be a GROUP BY clause.
70103   */
70104   if( p->pHaving && !pGroupBy ){
70105     sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
70106     return SQLITE_ERROR;
70107   }
70108
70109   /* Add the expression list to the name-context before parsing the
70110   ** other expressions in the SELECT statement. This is so that
70111   ** expressions in the WHERE clause (etc.) can refer to expressions by
70112   ** aliases in the result set.
70113   **
70114   ** Minor point: If this is the case, then the expression will be
70115   ** re-evaluated for each reference to it.
70116   */
70117   sNC.pEList = p->pEList;
70118   if( sqlite3ExprResolveNames(&sNC, p->pWhere) ||
70119      sqlite3ExprResolveNames(&sNC, p->pHaving) ){
70120     return SQLITE_ERROR;
70121   }
70122   if( p->pPrior==0 ){
70123     if( processOrderGroupBy(pParse, p, p->pOrderBy, 1, &sNC.hasAgg) ){
70124       return SQLITE_ERROR;
70125     }
70126   }
70127   if( processOrderGroupBy(pParse, p, pGroupBy, 0, &sNC.hasAgg) ){
70128     return SQLITE_ERROR;
70129   }
70130
70131   if( pParse->db->mallocFailed ){
70132     return SQLITE_NOMEM;
70133   }
70134
70135   /* Make sure the GROUP BY clause does not contain aggregate functions.
70136   */
70137   if( pGroupBy ){
70138     struct ExprList_item *pItem;
70139   
70140     for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
70141       if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
70142         sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
70143             "the GROUP BY clause");
70144         return SQLITE_ERROR;
70145       }
70146     }
70147   }
70148
70149   /* If this is one SELECT of a compound, be sure to resolve names
70150   ** in the other SELECTs.
70151   */
70152   if( p->pPrior ){
70153     return sqlite3SelectResolve(pParse, p->pPrior, pOuterNC);
70154   }else{
70155     return SQLITE_OK;
70156   }
70157 }
70158
70159 /*
70160 ** Reset the aggregate accumulator.
70161 **
70162 ** The aggregate accumulator is a set of memory cells that hold
70163 ** intermediate results while calculating an aggregate.  This
70164 ** routine simply stores NULLs in all of those memory cells.
70165 */
70166 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
70167   Vdbe *v = pParse->pVdbe;
70168   int i;
70169   struct AggInfo_func *pFunc;
70170   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
70171     return;
70172   }
70173   for(i=0; i<pAggInfo->nColumn; i++){
70174     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
70175   }
70176   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
70177     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
70178     if( pFunc->iDistinct>=0 ){
70179       Expr *pE = pFunc->pExpr;
70180       if( pE->pList==0 || pE->pList->nExpr!=1 ){
70181         sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed "
70182            "by an expression");
70183         pFunc->iDistinct = -1;
70184       }else{
70185         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList);
70186         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
70187                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
70188       }
70189     }
70190   }
70191 }
70192
70193 /*
70194 ** Invoke the OP_AggFinalize opcode for every aggregate function
70195 ** in the AggInfo structure.
70196 */
70197 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
70198   Vdbe *v = pParse->pVdbe;
70199   int i;
70200   struct AggInfo_func *pF;
70201   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
70202     ExprList *pList = pF->pExpr->pList;
70203     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
70204                       (void*)pF->pFunc, P4_FUNCDEF);
70205   }
70206 }
70207
70208 /*
70209 ** Update the accumulator memory cells for an aggregate based on
70210 ** the current cursor position.
70211 */
70212 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
70213   Vdbe *v = pParse->pVdbe;
70214   int i;
70215   struct AggInfo_func *pF;
70216   struct AggInfo_col *pC;
70217
70218   pAggInfo->directMode = 1;
70219   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
70220     int nArg;
70221     int addrNext = 0;
70222     int regAgg;
70223     ExprList *pList = pF->pExpr->pList;
70224     if( pList ){
70225       nArg = pList->nExpr;
70226       regAgg = sqlite3GetTempRange(pParse, nArg);
70227       sqlite3ExprCodeExprList(pParse, pList, regAgg, 0);
70228     }else{
70229       nArg = 0;
70230       regAgg = 0;
70231     }
70232     if( pF->iDistinct>=0 ){
70233       addrNext = sqlite3VdbeMakeLabel(v);
70234       assert( nArg==1 );
70235       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
70236     }
70237     if( pF->pFunc->needCollSeq ){
70238       CollSeq *pColl = 0;
70239       struct ExprList_item *pItem;
70240       int j;
70241       assert( pList!=0 );  /* pList!=0 if pF->pFunc->needCollSeq is true */
70242       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
70243         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
70244       }
70245       if( !pColl ){
70246         pColl = pParse->db->pDfltColl;
70247       }
70248       sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
70249     }
70250     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
70251                       (void*)pF->pFunc, P4_FUNCDEF);
70252     sqlite3VdbeChangeP5(v, nArg);
70253     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
70254     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
70255     if( addrNext ){
70256       sqlite3VdbeResolveLabel(v, addrNext);
70257     }
70258   }
70259   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
70260     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
70261   }
70262   pAggInfo->directMode = 0;
70263 }
70264
70265 /*
70266 ** Generate code for the given SELECT statement.
70267 **
70268 ** The results are distributed in various ways depending on the
70269 ** contents of the SelectDest structure pointed to by argument pDest
70270 ** as follows:
70271 **
70272 **     pDest->eDest    Result
70273 **     ------------    -------------------------------------------
70274 **     SRT_Callback    Invoke the callback for each row of the result.
70275 **
70276 **     SRT_Mem         Store first result in memory cell pDest->iParm
70277 **
70278 **     SRT_Set         Store results as keys of table pDest->iParm. 
70279 **                     Apply the affinity pDest->affinity before storing them.
70280 **
70281 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
70282 **
70283 **     SRT_Except      Remove results from the temporary table pDest->iParm.
70284 **
70285 **     SRT_Table       Store results in temporary table pDest->iParm
70286 **
70287 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
70288 **                     the result there. The cursor is left open after
70289 **                     returning.
70290 **
70291 **     SRT_Coroutine   Invoke a co-routine to compute a single row of 
70292 **                     the result
70293 **
70294 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
70295 **                     set is not empty.
70296 **
70297 **     SRT_Discard     Throw the results away.
70298 **
70299 ** See the selectInnerLoop() function for a canonical listing of the 
70300 ** allowed values of eDest and their meanings.
70301 **
70302 ** This routine returns the number of errors.  If any errors are
70303 ** encountered, then an appropriate error message is left in
70304 ** pParse->zErrMsg.
70305 **
70306 ** This routine does NOT free the Select structure passed in.  The
70307 ** calling function needs to do that.
70308 **
70309 ** The pParent, parentTab, and *pParentAgg fields are filled in if this
70310 ** SELECT is a subquery.  This routine may try to combine this SELECT
70311 ** with its parent to form a single flat query.  In so doing, it might
70312 ** change the parent query from a non-aggregate to an aggregate query.
70313 ** For that reason, the pParentAgg flag is passed as a pointer, so it
70314 ** can be changed.
70315 **
70316 ** Example 1:   The meaning of the pParent parameter.
70317 **
70318 **    SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
70319 **    \                      \_______ subquery _______/        /
70320 **     \                                                      /
70321 **      \____________________ outer query ___________________/
70322 **
70323 ** This routine is called for the outer query first.   For that call,
70324 ** pParent will be NULL.  During the processing of the outer query, this 
70325 ** routine is called recursively to handle the subquery.  For the recursive
70326 ** call, pParent will point to the outer query.  Because the subquery is
70327 ** the second element in a three-way join, the parentTab parameter will
70328 ** be 1 (the 2nd value of a 0-indexed array.)
70329 */
70330 SQLITE_PRIVATE int sqlite3Select(
70331   Parse *pParse,         /* The parser context */
70332   Select *p,             /* The SELECT statement being coded. */
70333   SelectDest *pDest,     /* What to do with the query results */
70334   Select *pParent,       /* Another SELECT for which this is a sub-query */
70335   int parentTab,         /* Index in pParent->pSrc of this query */
70336   int *pParentAgg        /* True if pParent uses aggregate functions */
70337 ){
70338   int i, j;              /* Loop counters */
70339   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
70340   Vdbe *v;               /* The virtual machine under construction */
70341   int isAgg;             /* True for select lists like "count(*)" */
70342   ExprList *pEList;      /* List of columns to extract. */
70343   SrcList *pTabList;     /* List of tables to select from */
70344   Expr *pWhere;          /* The WHERE clause.  May be NULL */
70345   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
70346   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
70347   Expr *pHaving;         /* The HAVING clause.  May be NULL */
70348   int isDistinct;        /* True if the DISTINCT keyword is present */
70349   int distinct;          /* Table to use for the distinct set */
70350   int rc = 1;            /* Value to return from this function */
70351   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
70352   AggInfo sAggInfo;      /* Information used by aggregate queries */
70353   int iEnd;              /* Address of the end of the query */
70354   sqlite3 *db;           /* The database connection */
70355
70356   db = pParse->db;
70357   if( p==0 || db->mallocFailed || pParse->nErr ){
70358     return 1;
70359   }
70360   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
70361   memset(&sAggInfo, 0, sizeof(sAggInfo));
70362
70363   pOrderBy = p->pOrderBy;
70364   if( IgnorableOrderby(pDest) ){
70365     p->pOrderBy = 0;
70366
70367     /* In these cases the DISTINCT operator makes no difference to the
70368     ** results, so remove it if it were specified.
70369     */
70370     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
70371            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
70372     p->isDistinct = 0;
70373   }
70374   if( sqlite3SelectResolve(pParse, p, 0) ){
70375     goto select_end;
70376   }
70377   p->pOrderBy = pOrderBy;
70378
70379
70380   /* Make local copies of the parameters for this query.
70381   */
70382   pTabList = p->pSrc;
70383   isAgg = p->isAgg;
70384   pEList = p->pEList;
70385   if( pEList==0 ) goto select_end;
70386
70387   /* 
70388   ** Do not even attempt to generate any code if we have already seen
70389   ** errors before this routine starts.
70390   */
70391   if( pParse->nErr>0 ) goto select_end;
70392
70393   /* ORDER BY is ignored for some destinations.
70394   */
70395   if( IgnorableOrderby(pDest) ){
70396     pOrderBy = 0;
70397   }
70398
70399   /* Begin generating code.
70400   */
70401   v = sqlite3GetVdbe(pParse);
70402   if( v==0 ) goto select_end;
70403
70404   /* Generate code for all sub-queries in the FROM clause
70405   */
70406 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
70407   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
70408     struct SrcList_item *pItem = &pTabList->a[i];
70409     SelectDest dest;
70410     Select *pSub = pItem->pSelect;
70411     int isAggSub;
70412     char *zName = pItem->zName;
70413
70414     if( pSub==0 || pItem->isPopulated ) continue;
70415     if( zName!=0 ){   /* An sql view */
70416       const char *zSavedAuthContext = pParse->zAuthContext;
70417       pParse->zAuthContext = zName;
70418       rc = sqlite3SelectResolve(pParse, pSub, 0);
70419       pParse->zAuthContext = zSavedAuthContext;
70420       if( rc ){
70421         goto select_end;
70422       }
70423     }
70424
70425     /* Increment Parse.nHeight by the height of the largest expression
70426     ** tree refered to by this, the parent select. The child select
70427     ** may contain expression trees of at most
70428     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
70429     ** more conservative than necessary, but much easier than enforcing
70430     ** an exact limit.
70431     */
70432     pParse->nHeight += sqlite3SelectExprHeight(p);
70433
70434     /* Check to see if the subquery can be absorbed into the parent. */
70435     isAggSub = pSub->isAgg;
70436     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
70437       if( isAggSub ){
70438         p->isAgg = isAgg = 1;
70439       }
70440       i = -1;
70441     }else{
70442       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
70443       sqlite3Select(pParse, pSub, &dest, p, i, &isAgg);
70444     }
70445     if( pParse->nErr || db->mallocFailed ){
70446       goto select_end;
70447     }
70448     pParse->nHeight -= sqlite3SelectExprHeight(p);
70449     pTabList = p->pSrc;
70450     if( !IgnorableOrderby(pDest) ){
70451       pOrderBy = p->pOrderBy;
70452     }
70453   }
70454   pEList = p->pEList;
70455 #endif
70456   pWhere = p->pWhere;
70457   pGroupBy = p->pGroupBy;
70458   pHaving = p->pHaving;
70459   isDistinct = p->isDistinct;
70460
70461 #ifndef SQLITE_OMIT_COMPOUND_SELECT
70462   /* If there is are a sequence of queries, do the earlier ones first.
70463   */
70464   if( p->pPrior ){
70465     if( p->pRightmost==0 ){
70466       Select *pLoop, *pRight = 0;
70467       int cnt = 0;
70468       int mxSelect;
70469       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
70470         pLoop->pRightmost = p;
70471         pLoop->pNext = pRight;
70472         pRight = pLoop;
70473       }
70474       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
70475       if( mxSelect && cnt>mxSelect ){
70476         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
70477         return 1;
70478       }
70479     }
70480     return multiSelect(pParse, p, pDest);
70481   }
70482 #endif
70483
70484   /* If writing to memory or generating a set
70485   ** only a single column may be output.
70486   */
70487 #ifndef SQLITE_OMIT_SUBQUERY
70488   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
70489     goto select_end;
70490   }
70491 #endif
70492
70493   /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
70494   ** GROUP BY may use an index, DISTINCT never does.
70495   */
70496   if( p->isDistinct && !p->isAgg && !p->pGroupBy ){
70497     p->pGroupBy = sqlite3ExprListDup(db, p->pEList);
70498     pGroupBy = p->pGroupBy;
70499     p->isDistinct = 0;
70500     isDistinct = 0;
70501   }
70502
70503   /* If there is an ORDER BY clause, then this sorting
70504   ** index might end up being unused if the data can be 
70505   ** extracted in pre-sorted order.  If that is the case, then the
70506   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
70507   ** we figure out that the sorting index is not needed.  The addrSortIndex
70508   ** variable is used to facilitate that change.
70509   */
70510   if( pOrderBy ){
70511     KeyInfo *pKeyInfo;
70512     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
70513     pOrderBy->iECursor = pParse->nTab++;
70514     p->addrOpenEphm[2] = addrSortIndex =
70515       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
70516                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
70517                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
70518   }else{
70519     addrSortIndex = -1;
70520   }
70521
70522   /* If the output is destined for a temporary table, open that table.
70523   */
70524   if( pDest->eDest==SRT_EphemTab ){
70525     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
70526   }
70527
70528   /* Set the limiter.
70529   */
70530   iEnd = sqlite3VdbeMakeLabel(v);
70531   computeLimitRegisters(pParse, p, iEnd);
70532
70533   /* Open a virtual index to use for the distinct set.
70534   */
70535   if( isDistinct ){
70536     KeyInfo *pKeyInfo;
70537     assert( isAgg || pGroupBy );
70538     distinct = pParse->nTab++;
70539     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
70540     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
70541                         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
70542   }else{
70543     distinct = -1;
70544   }
70545
70546   /* Aggregate and non-aggregate queries are handled differently */
70547   if( !isAgg && pGroupBy==0 ){
70548     /* This case is for non-aggregate queries
70549     ** Begin the database scan
70550     */
70551     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
70552     if( pWInfo==0 ) goto select_end;
70553
70554     /* If sorting index that was created by a prior OP_OpenEphemeral 
70555     ** instruction ended up not being needed, then change the OP_OpenEphemeral
70556     ** into an OP_Noop.
70557     */
70558     if( addrSortIndex>=0 && pOrderBy==0 ){
70559       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
70560       p->addrOpenEphm[2] = -1;
70561     }
70562
70563     /* Use the standard inner loop
70564     */
70565     assert(!isDistinct);
70566     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
70567                     pWInfo->iContinue, pWInfo->iBreak);
70568
70569     /* End the database scan loop.
70570     */
70571     sqlite3WhereEnd(pWInfo);
70572   }else{
70573     /* This is the processing for aggregate queries */
70574     NameContext sNC;    /* Name context for processing aggregate information */
70575     int iAMem;          /* First Mem address for storing current GROUP BY */
70576     int iBMem;          /* First Mem address for previous GROUP BY */
70577     int iUseFlag;       /* Mem address holding flag indicating that at least
70578                         ** one row of the input to the aggregator has been
70579                         ** processed */
70580     int iAbortFlag;     /* Mem address which causes query abort if positive */
70581     int groupBySort;    /* Rows come from source in GROUP BY order */
70582
70583
70584     /* The following variables hold addresses or labels for parts of the
70585     ** virtual machine program we are putting together */
70586     int addrOutputRow;      /* Start of subroutine that outputs a result row */
70587     int regOutputRow;       /* Return address register for output subroutine */
70588     int addrSetAbort;       /* Set the abort flag and return */
70589     int addrInitializeLoop; /* Start of code that initializes the input loop */
70590     int addrTopOfLoop;      /* Top of the input loop */
70591     int addrEnd;            /* End of all processing */
70592     int addrSortingIdx;     /* The OP_OpenEphemeral for the sorting index */
70593     int addrReset;          /* Subroutine for resetting the accumulator */
70594     int regReset;           /* Return address register for reset subroutine */
70595
70596     addrEnd = sqlite3VdbeMakeLabel(v);
70597
70598     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
70599     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
70600     ** SELECT statement.
70601     */
70602     memset(&sNC, 0, sizeof(sNC));
70603     sNC.pParse = pParse;
70604     sNC.pSrcList = pTabList;
70605     sNC.pAggInfo = &sAggInfo;
70606     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
70607     sAggInfo.pGroupBy = pGroupBy;
70608     sqlite3ExprAnalyzeAggList(&sNC, pEList);
70609     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
70610     if( pHaving ){
70611       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
70612     }
70613     sAggInfo.nAccumulator = sAggInfo.nColumn;
70614     for(i=0; i<sAggInfo.nFunc; i++){
70615       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList);
70616     }
70617     if( db->mallocFailed ) goto select_end;
70618
70619     /* Processing for aggregates with GROUP BY is very different and
70620     ** much more complex than aggregates without a GROUP BY.
70621     */
70622     if( pGroupBy ){
70623       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
70624       int j1;
70625
70626       /* Create labels that we will be needing
70627       */
70628       addrInitializeLoop = sqlite3VdbeMakeLabel(v);
70629
70630       /* If there is a GROUP BY clause we might need a sorting index to
70631       ** implement it.  Allocate that sorting index now.  If it turns out
70632       ** that we do not need it after all, the OpenEphemeral instruction
70633       ** will be converted into a Noop.  
70634       */
70635       sAggInfo.sortingIdx = pParse->nTab++;
70636       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
70637       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 
70638           sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
70639           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
70640
70641       /* Initialize memory locations used by GROUP BY aggregate processing
70642       */
70643       iUseFlag = ++pParse->nMem;
70644       iAbortFlag = ++pParse->nMem;
70645       iAMem = pParse->nMem + 1;
70646       pParse->nMem += pGroupBy->nExpr;
70647       iBMem = pParse->nMem + 1;
70648       pParse->nMem += pGroupBy->nExpr;
70649       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
70650       VdbeComment((v, "clear abort flag"));
70651       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
70652       VdbeComment((v, "indicate accumulator empty"));
70653       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrInitializeLoop);
70654
70655       /* Generate a subroutine that outputs a single row of the result
70656       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
70657       ** is less than or equal to zero, the subroutine is a no-op.  If
70658       ** the processing calls for the query to abort, this subroutine
70659       ** increments the iAbortFlag memory location before returning in
70660       ** order to signal the caller to abort.
70661       */
70662       addrSetAbort = sqlite3VdbeCurrentAddr(v);
70663       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
70664       VdbeComment((v, "set abort flag"));
70665       regOutputRow = ++pParse->nMem;
70666       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
70667       addrOutputRow = sqlite3VdbeCurrentAddr(v);
70668       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
70669       VdbeComment((v, "Groupby result generator entry point"));
70670       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
70671       finalizeAggFunctions(pParse, &sAggInfo);
70672       if( pHaving ){
70673         sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
70674       }
70675       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
70676                       distinct, pDest,
70677                       addrOutputRow+1, addrSetAbort);
70678       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
70679       VdbeComment((v, "end groupby result generator"));
70680
70681       /* Generate a subroutine that will reset the group-by accumulator
70682       */
70683       addrReset = sqlite3VdbeCurrentAddr(v);
70684       regReset = ++pParse->nMem;
70685       resetAccumulator(pParse, &sAggInfo);
70686       sqlite3VdbeAddOp1(v, OP_Return, regReset);
70687
70688       /* Begin a loop that will extract all source rows in GROUP BY order.
70689       ** This might involve two separate loops with an OP_Sort in between, or
70690       ** it might be a single loop that uses an index to extract information
70691       ** in the right order to begin with.
70692       */
70693       sqlite3VdbeResolveLabel(v, addrInitializeLoop);
70694       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
70695       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
70696       if( pWInfo==0 ) goto select_end;
70697       if( pGroupBy==0 ){
70698         /* The optimizer is able to deliver rows in group by order so
70699         ** we do not have to sort.  The OP_OpenEphemeral table will be
70700         ** cancelled later because we still need to use the pKeyInfo
70701         */
70702         pGroupBy = p->pGroupBy;
70703         groupBySort = 0;
70704       }else{
70705         /* Rows are coming out in undetermined order.  We have to push
70706         ** each row into a sorting index, terminate the first loop,
70707         ** then loop over the sorting index in order to get the output
70708         ** in sorted order
70709         */
70710         int regBase;
70711         int regRecord;
70712         int nCol;
70713         int nGroupBy;
70714
70715         groupBySort = 1;
70716         nGroupBy = pGroupBy->nExpr;
70717         nCol = nGroupBy + 1;
70718         j = nGroupBy+1;
70719         for(i=0; i<sAggInfo.nColumn; i++){
70720           if( sAggInfo.aCol[i].iSorterColumn>=j ){
70721             nCol++;
70722             j++;
70723           }
70724         }
70725         regBase = sqlite3GetTempRange(pParse, nCol);
70726         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
70727         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
70728         j = nGroupBy+1;
70729         for(i=0; i<sAggInfo.nColumn; i++){
70730           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
70731           if( pCol->iSorterColumn>=j ){
70732             int r1 = j + regBase;
70733 #ifndef NDEBUG
70734             int r2 = 
70735 #endif
70736                      sqlite3ExprCodeGetColumn(pParse, 
70737                                pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
70738             j++;
70739
70740             /* sAggInfo.aCol[] only contains one entry per column.  So
70741             ** The reference to pCol->iColumn,pCol->iTable must have been
70742             ** the first reference to that column.  Hence, 
70743             ** sqliteExprCodeGetColumn is guaranteed to put the result in
70744             ** the column requested. 
70745             */
70746             assert( r1==r2 );
70747           }
70748         }
70749         regRecord = sqlite3GetTempReg(pParse);
70750         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
70751         sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
70752         sqlite3ReleaseTempReg(pParse, regRecord);
70753         sqlite3ReleaseTempRange(pParse, regBase, nCol);
70754         sqlite3WhereEnd(pWInfo);
70755         sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
70756         VdbeComment((v, "GROUP BY sort"));
70757         sAggInfo.useSortingIdx = 1;
70758       }
70759
70760       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
70761       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
70762       ** Then compare the current GROUP BY terms against the GROUP BY terms
70763       ** from the previous row currently stored in a0, a1, a2...
70764       */
70765       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
70766       for(j=0; j<pGroupBy->nExpr; j++){
70767         if( groupBySort ){
70768           sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
70769         }else{
70770           sAggInfo.directMode = 1;
70771           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
70772         }
70773       }
70774       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
70775                           (char*)pKeyInfo, P4_KEYINFO);
70776       j1 = sqlite3VdbeCurrentAddr(v);
70777       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
70778
70779       /* Generate code that runs whenever the GROUP BY changes.
70780       ** Changes in the GROUP BY are detected by the previous code
70781       ** block.  If there were no changes, this block is skipped.
70782       **
70783       ** This code copies current group by terms in b0,b1,b2,...
70784       ** over to a0,a1,a2.  It then calls the output subroutine
70785       ** and resets the aggregate accumulator registers in preparation
70786       ** for the next GROUP BY batch.
70787       */
70788       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
70789       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
70790       VdbeComment((v, "output one row"));
70791       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
70792       VdbeComment((v, "check abort flag"));
70793       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
70794       VdbeComment((v, "reset accumulator"));
70795
70796       /* Update the aggregate accumulators based on the content of
70797       ** the current row
70798       */
70799       sqlite3VdbeJumpHere(v, j1);
70800       updateAccumulator(pParse, &sAggInfo);
70801       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
70802       VdbeComment((v, "indicate data in accumulator"));
70803
70804       /* End of the loop
70805       */
70806       if( groupBySort ){
70807         sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
70808       }else{
70809         sqlite3WhereEnd(pWInfo);
70810         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
70811       }
70812
70813       /* Output the final row of result
70814       */
70815       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
70816       VdbeComment((v, "output final row"));
70817       
70818     } /* endif pGroupBy */
70819     else {
70820       ExprList *pMinMax = 0;
70821       ExprList *pDel = 0;
70822       u8 flag;
70823
70824       /* Check if the query is of one of the following forms:
70825       **
70826       **   SELECT min(x) FROM ...
70827       **   SELECT max(x) FROM ...
70828       **
70829       ** If it is, then ask the code in where.c to attempt to sort results
70830       ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 
70831       ** If where.c is able to produce results sorted in this order, then
70832       ** add vdbe code to break out of the processing loop after the 
70833       ** first iteration (since the first iteration of the loop is 
70834       ** guaranteed to operate on the row with the minimum or maximum 
70835       ** value of x, the only row required).
70836       **
70837       ** A special flag must be passed to sqlite3WhereBegin() to slightly
70838       ** modify behaviour as follows:
70839       **
70840       **   + If the query is a "SELECT min(x)", then the loop coded by
70841       **     where.c should not iterate over any values with a NULL value
70842       **     for x.
70843       **
70844       **   + The optimizer code in where.c (the thing that decides which
70845       **     index or indices to use) should place a different priority on 
70846       **     satisfying the 'ORDER BY' clause than it does in other cases.
70847       **     Refer to code and comments in where.c for details.
70848       */
70849       flag = minMaxQuery(pParse, p);
70850       if( flag ){
70851         pDel = pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->pList);
70852         if( pMinMax && !db->mallocFailed ){
70853           pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN;
70854           pMinMax->a[0].pExpr->op = TK_COLUMN;
70855         }
70856       }
70857
70858       /* This case runs if the aggregate has no GROUP BY clause.  The
70859       ** processing is much simpler since there is only a single row
70860       ** of output.
70861       */
70862       resetAccumulator(pParse, &sAggInfo);
70863       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
70864       if( pWInfo==0 ){
70865         sqlite3ExprListDelete(db, pDel);
70866         goto select_end;
70867       }
70868       updateAccumulator(pParse, &sAggInfo);
70869       if( !pMinMax && flag ){
70870         sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
70871         VdbeComment((v, "%s() by index",(flag==WHERE_ORDERBY_MIN?"min":"max")));
70872       }
70873       sqlite3WhereEnd(pWInfo);
70874       finalizeAggFunctions(pParse, &sAggInfo);
70875       pOrderBy = 0;
70876       if( pHaving ){
70877         sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
70878       }
70879       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 
70880                       pDest, addrEnd, addrEnd);
70881
70882       sqlite3ExprListDelete(db, pDel);
70883     }
70884     sqlite3VdbeResolveLabel(v, addrEnd);
70885     
70886   } /* endif aggregate query */
70887
70888   /* If there is an ORDER BY clause, then we need to sort the results
70889   ** and send them to the callback one by one.
70890   */
70891   if( pOrderBy ){
70892     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
70893   }
70894
70895 #ifndef SQLITE_OMIT_SUBQUERY
70896   /* If this was a subquery, we have now converted the subquery into a
70897   ** temporary table.  So set the SrcList_item.isPopulated flag to prevent
70898   ** this subquery from being evaluated again and to force the use of
70899   ** the temporary table.
70900   */
70901   if( pParent ){
70902     assert( pParent->pSrc->nSrc>parentTab );
70903     assert( pParent->pSrc->a[parentTab].pSelect==p );
70904     pParent->pSrc->a[parentTab].isPopulated = 1;
70905   }
70906 #endif
70907
70908   /* Jump here to skip this query
70909   */
70910   sqlite3VdbeResolveLabel(v, iEnd);
70911
70912   /* The SELECT was successfully coded.   Set the return code to 0
70913   ** to indicate no errors.
70914   */
70915   rc = 0;
70916
70917   /* Control jumps to here if an error is encountered above, or upon
70918   ** successful coding of the SELECT.
70919   */
70920 select_end:
70921
70922   /* Identify column names if we will be using them in a callback.  This
70923   ** step is skipped if the output is going to some other destination.
70924   */
70925   if( rc==SQLITE_OK && pDest->eDest==SRT_Callback ){
70926     generateColumnNames(pParse, pTabList, pEList);
70927   }
70928
70929   sqlite3DbFree(db, sAggInfo.aCol);
70930   sqlite3DbFree(db, sAggInfo.aFunc);
70931   return rc;
70932 }
70933
70934 #if defined(SQLITE_DEBUG)
70935 /*
70936 *******************************************************************************
70937 ** The following code is used for testing and debugging only.  The code
70938 ** that follows does not appear in normal builds.
70939 **
70940 ** These routines are used to print out the content of all or part of a 
70941 ** parse structures such as Select or Expr.  Such printouts are useful
70942 ** for helping to understand what is happening inside the code generator
70943 ** during the execution of complex SELECT statements.
70944 **
70945 ** These routine are not called anywhere from within the normal
70946 ** code base.  Then are intended to be called from within the debugger
70947 ** or from temporary "printf" statements inserted for debugging.
70948 */
70949 SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
70950   if( p->token.z && p->token.n>0 ){
70951     sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z);
70952   }else{
70953     sqlite3DebugPrintf("(%d", p->op);
70954   }
70955   if( p->pLeft ){
70956     sqlite3DebugPrintf(" ");
70957     sqlite3PrintExpr(p->pLeft);
70958   }
70959   if( p->pRight ){
70960     sqlite3DebugPrintf(" ");
70961     sqlite3PrintExpr(p->pRight);
70962   }
70963   sqlite3DebugPrintf(")");
70964 }
70965 SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
70966   int i;
70967   for(i=0; i<pList->nExpr; i++){
70968     sqlite3PrintExpr(pList->a[i].pExpr);
70969     if( i<pList->nExpr-1 ){
70970       sqlite3DebugPrintf(", ");
70971     }
70972   }
70973 }
70974 SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
70975   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
70976   sqlite3PrintExprList(p->pEList);
70977   sqlite3DebugPrintf("\n");
70978   if( p->pSrc ){
70979     char *zPrefix;
70980     int i;
70981     zPrefix = "FROM";
70982     for(i=0; i<p->pSrc->nSrc; i++){
70983       struct SrcList_item *pItem = &p->pSrc->a[i];
70984       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
70985       zPrefix = "";
70986       if( pItem->pSelect ){
70987         sqlite3DebugPrintf("(\n");
70988         sqlite3PrintSelect(pItem->pSelect, indent+10);
70989         sqlite3DebugPrintf("%*s)", indent+8, "");
70990       }else if( pItem->zName ){
70991         sqlite3DebugPrintf("%s", pItem->zName);
70992       }
70993       if( pItem->pTab ){
70994         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
70995       }
70996       if( pItem->zAlias ){
70997         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
70998       }
70999       if( i<p->pSrc->nSrc-1 ){
71000         sqlite3DebugPrintf(",");
71001       }
71002       sqlite3DebugPrintf("\n");
71003     }
71004   }
71005   if( p->pWhere ){
71006     sqlite3DebugPrintf("%*s WHERE ", indent, "");
71007     sqlite3PrintExpr(p->pWhere);
71008     sqlite3DebugPrintf("\n");
71009   }
71010   if( p->pGroupBy ){
71011     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
71012     sqlite3PrintExprList(p->pGroupBy);
71013     sqlite3DebugPrintf("\n");
71014   }
71015   if( p->pHaving ){
71016     sqlite3DebugPrintf("%*s HAVING ", indent, "");
71017     sqlite3PrintExpr(p->pHaving);
71018     sqlite3DebugPrintf("\n");
71019   }
71020   if( p->pOrderBy ){
71021     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
71022     sqlite3PrintExprList(p->pOrderBy);
71023     sqlite3DebugPrintf("\n");
71024   }
71025 }
71026 /* End of the structure debug printing code
71027 *****************************************************************************/
71028 #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
71029
71030 /************** End of select.c **********************************************/
71031 /************** Begin file table.c *******************************************/
71032 /*
71033 ** 2001 September 15
71034 **
71035 ** The author disclaims copyright to this source code.  In place of
71036 ** a legal notice, here is a blessing:
71037 **
71038 **    May you do good and not evil.
71039 **    May you find forgiveness for yourself and forgive others.
71040 **    May you share freely, never taking more than you give.
71041 **
71042 *************************************************************************
71043 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
71044 ** interface routines.  These are just wrappers around the main
71045 ** interface routine of sqlite3_exec().
71046 **
71047 ** These routines are in a separate files so that they will not be linked
71048 ** if they are not used.
71049 **
71050 ** $Id: table.c,v 1.36 2008/07/08 22:28:49 shane Exp $
71051 */
71052
71053 #ifndef SQLITE_OMIT_GET_TABLE
71054
71055 /*
71056 ** This structure is used to pass data from sqlite3_get_table() through
71057 ** to the callback function is uses to build the result.
71058 */
71059 typedef struct TabResult {
71060   char **azResult;
71061   char *zErrMsg;
71062   int nResult;
71063   int nAlloc;
71064   int nRow;
71065   int nColumn;
71066   int nData;
71067   int rc;
71068 } TabResult;
71069
71070 /*
71071 ** This routine is called once for each row in the result table.  Its job
71072 ** is to fill in the TabResult structure appropriately, allocating new
71073 ** memory as necessary.
71074 */
71075 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
71076   TabResult *p = (TabResult*)pArg;
71077   int need;
71078   int i;
71079   char *z;
71080
71081   /* Make sure there is enough space in p->azResult to hold everything
71082   ** we need to remember from this invocation of the callback.
71083   */
71084   if( p->nRow==0 && argv!=0 ){
71085     need = nCol*2;
71086   }else{
71087     need = nCol;
71088   }
71089   if( p->nData + need >= p->nAlloc ){
71090     char **azNew;
71091     p->nAlloc = p->nAlloc*2 + need + 1;
71092     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
71093     if( azNew==0 ) goto malloc_failed;
71094     p->azResult = azNew;
71095   }
71096
71097   /* If this is the first row, then generate an extra row containing
71098   ** the names of all columns.
71099   */
71100   if( p->nRow==0 ){
71101     p->nColumn = nCol;
71102     for(i=0; i<nCol; i++){
71103       z = sqlite3_mprintf("%s", colv[i]);
71104       if( z==0 ) goto malloc_failed;
71105       p->azResult[p->nData++] = z;
71106     }
71107   }else if( p->nColumn!=nCol ){
71108     sqlite3_free(p->zErrMsg);
71109     p->zErrMsg = sqlite3_mprintf(
71110        "sqlite3_get_table() called with two or more incompatible queries"
71111     );
71112     p->rc = SQLITE_ERROR;
71113     return 1;
71114   }
71115
71116   /* Copy over the row data
71117   */
71118   if( argv!=0 ){
71119     for(i=0; i<nCol; i++){
71120       if( argv[i]==0 ){
71121         z = 0;
71122       }else{
71123         int n = strlen(argv[i])+1;
71124         z = sqlite3_malloc( n );
71125         if( z==0 ) goto malloc_failed;
71126         memcpy(z, argv[i], n);
71127       }
71128       p->azResult[p->nData++] = z;
71129     }
71130     p->nRow++;
71131   }
71132   return 0;
71133
71134 malloc_failed:
71135   p->rc = SQLITE_NOMEM;
71136   return 1;
71137 }
71138
71139 /*
71140 ** Query the database.  But instead of invoking a callback for each row,
71141 ** malloc() for space to hold the result and return the entire results
71142 ** at the conclusion of the call.
71143 **
71144 ** The result that is written to ***pazResult is held in memory obtained
71145 ** from malloc().  But the caller cannot free this memory directly.  
71146 ** Instead, the entire table should be passed to sqlite3_free_table() when
71147 ** the calling procedure is finished using it.
71148 */
71149 SQLITE_API int sqlite3_get_table(
71150   sqlite3 *db,                /* The database on which the SQL executes */
71151   const char *zSql,           /* The SQL to be executed */
71152   char ***pazResult,          /* Write the result table here */
71153   int *pnRow,                 /* Write the number of rows in the result here */
71154   int *pnColumn,              /* Write the number of columns of result here */
71155   char **pzErrMsg             /* Write error messages here */
71156 ){
71157   int rc;
71158   TabResult res;
71159
71160   *pazResult = 0;
71161   if( pnColumn ) *pnColumn = 0;
71162   if( pnRow ) *pnRow = 0;
71163   res.zErrMsg = 0;
71164   res.nResult = 0;
71165   res.nRow = 0;
71166   res.nColumn = 0;
71167   res.nData = 1;
71168   res.nAlloc = 20;
71169   res.rc = SQLITE_OK;
71170   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
71171   if( res.azResult==0 ){
71172      db->errCode = SQLITE_NOMEM;
71173      return SQLITE_NOMEM;
71174   }
71175   res.azResult[0] = 0;
71176   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
71177   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
71178   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
71179   if( (rc&0xff)==SQLITE_ABORT ){
71180     sqlite3_free_table(&res.azResult[1]);
71181     if( res.zErrMsg ){
71182       if( pzErrMsg ){
71183         sqlite3_free(*pzErrMsg);
71184         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
71185       }
71186       sqlite3_free(res.zErrMsg);
71187     }
71188     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
71189     return res.rc;
71190   }
71191   sqlite3_free(res.zErrMsg);
71192   if( rc!=SQLITE_OK ){
71193     sqlite3_free_table(&res.azResult[1]);
71194     return rc;
71195   }
71196   if( res.nAlloc>res.nData ){
71197     char **azNew;
71198     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*(res.nData+1) );
71199     if( azNew==0 ){
71200       sqlite3_free_table(&res.azResult[1]);
71201       db->errCode = SQLITE_NOMEM;
71202       return SQLITE_NOMEM;
71203     }
71204     res.nAlloc = res.nData+1;
71205     res.azResult = azNew;
71206   }
71207   *pazResult = &res.azResult[1];
71208   if( pnColumn ) *pnColumn = res.nColumn;
71209   if( pnRow ) *pnRow = res.nRow;
71210   return rc;
71211 }
71212
71213 /*
71214 ** This routine frees the space the sqlite3_get_table() malloced.
71215 */
71216 SQLITE_API void sqlite3_free_table(
71217   char **azResult            /* Result returned from from sqlite3_get_table() */
71218 ){
71219   if( azResult ){
71220     int i, n;
71221     azResult--;
71222     assert( azResult!=0 );
71223     n = SQLITE_PTR_TO_INT(azResult[0]);
71224     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
71225     sqlite3_free(azResult);
71226   }
71227 }
71228
71229 #endif /* SQLITE_OMIT_GET_TABLE */
71230
71231 /************** End of table.c ***********************************************/
71232 /************** Begin file trigger.c *****************************************/
71233 /*
71234 **
71235 ** The author disclaims copyright to this source code.  In place of
71236 ** a legal notice, here is a blessing:
71237 **
71238 **    May you do good and not evil.
71239 **    May you find forgiveness for yourself and forgive others.
71240 **    May you share freely, never taking more than you give.
71241 **
71242 *************************************************************************
71243 **
71244 **
71245 ** $Id: trigger.c,v 1.128 2008/07/28 19:34:54 drh Exp $
71246 */
71247
71248 #ifndef SQLITE_OMIT_TRIGGER
71249 /*
71250 ** Delete a linked list of TriggerStep structures.
71251 */
71252 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
71253   while( pTriggerStep ){
71254     TriggerStep * pTmp = pTriggerStep;
71255     pTriggerStep = pTriggerStep->pNext;
71256
71257     if( pTmp->target.dyn ) sqlite3DbFree(db, (char*)pTmp->target.z);
71258     sqlite3ExprDelete(db, pTmp->pWhere);
71259     sqlite3ExprListDelete(db, pTmp->pExprList);
71260     sqlite3SelectDelete(db, pTmp->pSelect);
71261     sqlite3IdListDelete(db, pTmp->pIdList);
71262
71263     sqlite3DbFree(db, pTmp);
71264   }
71265 }
71266
71267 /*
71268 ** This is called by the parser when it sees a CREATE TRIGGER statement
71269 ** up to the point of the BEGIN before the trigger actions.  A Trigger
71270 ** structure is generated based on the information available and stored
71271 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
71272 ** sqlite3FinishTrigger() function is called to complete the trigger
71273 ** construction process.
71274 */
71275 SQLITE_PRIVATE void sqlite3BeginTrigger(
71276   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
71277   Token *pName1,      /* The name of the trigger */
71278   Token *pName2,      /* The name of the trigger */
71279   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
71280   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
71281   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
71282   SrcList *pTableName,/* The name of the table/view the trigger applies to */
71283   Expr *pWhen,        /* WHEN clause */
71284   int isTemp,         /* True if the TEMPORARY keyword is present */
71285   int noErr           /* Suppress errors if the trigger already exists */
71286 ){
71287   Trigger *pTrigger = 0;
71288   Table *pTab;
71289   char *zName = 0;        /* Name of the trigger */
71290   sqlite3 *db = pParse->db;
71291   int iDb;                /* The database to store the trigger in */
71292   Token *pName;           /* The unqualified db name */
71293   DbFixer sFix;
71294   int iTabDb;
71295
71296   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
71297   assert( pName2!=0 );
71298   if( isTemp ){
71299     /* If TEMP was specified, then the trigger name may not be qualified. */
71300     if( pName2->n>0 ){
71301       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
71302       goto trigger_cleanup;
71303     }
71304     iDb = 1;
71305     pName = pName1;
71306   }else{
71307     /* Figure out the db that the the trigger will be created in */
71308     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
71309     if( iDb<0 ){
71310       goto trigger_cleanup;
71311     }
71312   }
71313
71314   /* If the trigger name was unqualified, and the table is a temp table,
71315   ** then set iDb to 1 to create the trigger in the temporary database.
71316   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
71317   ** exist, the error is caught by the block below.
71318   */
71319   if( !pTableName || db->mallocFailed ){
71320     goto trigger_cleanup;
71321   }
71322   pTab = sqlite3SrcListLookup(pParse, pTableName);
71323   if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
71324     iDb = 1;
71325   }
71326
71327   /* Ensure the table name matches database name and that the table exists */
71328   if( db->mallocFailed ) goto trigger_cleanup;
71329   assert( pTableName->nSrc==1 );
71330   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) && 
71331       sqlite3FixSrcList(&sFix, pTableName) ){
71332     goto trigger_cleanup;
71333   }
71334   pTab = sqlite3SrcListLookup(pParse, pTableName);
71335   if( !pTab ){
71336     /* The table does not exist. */
71337     goto trigger_cleanup;
71338   }
71339   if( IsVirtual(pTab) ){
71340     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
71341     goto trigger_cleanup;
71342   }
71343
71344   /* Check that the trigger name is not reserved and that no trigger of the
71345   ** specified name exists */
71346   zName = sqlite3NameFromToken(db, pName);
71347   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
71348     goto trigger_cleanup;
71349   }
71350   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash), zName,strlen(zName)) ){
71351     if( !noErr ){
71352       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
71353     }
71354     goto trigger_cleanup;
71355   }
71356
71357   /* Do not create a trigger on a system table */
71358   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
71359     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
71360     pParse->nErr++;
71361     goto trigger_cleanup;
71362   }
71363
71364   /* INSTEAD of triggers are only for views and views only support INSTEAD
71365   ** of triggers.
71366   */
71367   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
71368     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
71369         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
71370     goto trigger_cleanup;
71371   }
71372   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
71373     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
71374         " trigger on table: %S", pTableName, 0);
71375     goto trigger_cleanup;
71376   }
71377   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
71378
71379 #ifndef SQLITE_OMIT_AUTHORIZATION
71380   {
71381     int code = SQLITE_CREATE_TRIGGER;
71382     const char *zDb = db->aDb[iTabDb].zName;
71383     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
71384     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
71385     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
71386       goto trigger_cleanup;
71387     }
71388     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
71389       goto trigger_cleanup;
71390     }
71391   }
71392 #endif
71393
71394   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
71395   ** cannot appear on views.  So we might as well translate every
71396   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
71397   ** elsewhere.
71398   */
71399   if (tr_tm == TK_INSTEAD){
71400     tr_tm = TK_BEFORE;
71401   }
71402
71403   /* Build the Trigger object */
71404   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
71405   if( pTrigger==0 ) goto trigger_cleanup;
71406   pTrigger->name = zName;
71407   zName = 0;
71408   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
71409   pTrigger->pSchema = db->aDb[iDb].pSchema;
71410   pTrigger->pTabSchema = pTab->pSchema;
71411   pTrigger->op = op;
71412   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
71413   pTrigger->pWhen = sqlite3ExprDup(db, pWhen);
71414   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
71415   sqlite3TokenCopy(db, &pTrigger->nameToken,pName);
71416   assert( pParse->pNewTrigger==0 );
71417   pParse->pNewTrigger = pTrigger;
71418
71419 trigger_cleanup:
71420   sqlite3DbFree(db, zName);
71421   sqlite3SrcListDelete(db, pTableName);
71422   sqlite3IdListDelete(db, pColumns);
71423   sqlite3ExprDelete(db, pWhen);
71424   if( !pParse->pNewTrigger ){
71425     sqlite3DeleteTrigger(db, pTrigger);
71426   }else{
71427     assert( pParse->pNewTrigger==pTrigger );
71428   }
71429 }
71430
71431 /*
71432 ** This routine is called after all of the trigger actions have been parsed
71433 ** in order to complete the process of building the trigger.
71434 */
71435 SQLITE_PRIVATE void sqlite3FinishTrigger(
71436   Parse *pParse,          /* Parser context */
71437   TriggerStep *pStepList, /* The triggered program */
71438   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
71439 ){
71440   Trigger *pTrig = 0;     /* The trigger whose construction is finishing up */
71441   sqlite3 *db = pParse->db;  /* The database */
71442   DbFixer sFix;
71443   int iDb;                   /* Database containing the trigger */
71444
71445   pTrig = pParse->pNewTrigger;
71446   pParse->pNewTrigger = 0;
71447   if( pParse->nErr || !pTrig ) goto triggerfinish_cleanup;
71448   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
71449   pTrig->step_list = pStepList;
71450   while( pStepList ){
71451     pStepList->pTrig = pTrig;
71452     pStepList = pStepList->pNext;
71453   }
71454   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &pTrig->nameToken) 
71455           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
71456     goto triggerfinish_cleanup;
71457   }
71458
71459   /* if we are not initializing, and this trigger is not on a TEMP table, 
71460   ** build the sqlite_master entry
71461   */
71462   if( !db->init.busy ){
71463     Vdbe *v;
71464     char *z;
71465
71466     /* Make an entry in the sqlite_master table */
71467     v = sqlite3GetVdbe(pParse);
71468     if( v==0 ) goto triggerfinish_cleanup;
71469     sqlite3BeginWriteOperation(pParse, 0, iDb);
71470     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
71471     sqlite3NestedParse(pParse,
71472        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
71473        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pTrig->name,
71474        pTrig->table, z);
71475     sqlite3DbFree(db, z);
71476     sqlite3ChangeCookie(pParse, iDb);
71477     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
71478         db, "type='trigger' AND name='%q'", pTrig->name), P4_DYNAMIC
71479     );
71480   }
71481
71482   if( db->init.busy ){
71483     int n;
71484     Table *pTab;
71485     Trigger *pDel;
71486     pDel = sqlite3HashInsert(&db->aDb[iDb].pSchema->trigHash, 
71487                      pTrig->name, strlen(pTrig->name), pTrig);
71488     if( pDel ){
71489       assert( pDel==pTrig );
71490       db->mallocFailed = 1;
71491       goto triggerfinish_cleanup;
71492     }
71493     n = strlen(pTrig->table) + 1;
71494     pTab = sqlite3HashFind(&pTrig->pTabSchema->tblHash, pTrig->table, n);
71495     assert( pTab!=0 );
71496     pTrig->pNext = pTab->pTrigger;
71497     pTab->pTrigger = pTrig;
71498     pTrig = 0;
71499   }
71500
71501 triggerfinish_cleanup:
71502   sqlite3DeleteTrigger(db, pTrig);
71503   assert( !pParse->pNewTrigger );
71504   sqlite3DeleteTriggerStep(db, pStepList);
71505 }
71506
71507 /*
71508 ** Make a copy of all components of the given trigger step.  This has
71509 ** the effect of copying all Expr.token.z values into memory obtained
71510 ** from sqlite3_malloc().  As initially created, the Expr.token.z values
71511 ** all point to the input string that was fed to the parser.  But that
71512 ** string is ephemeral - it will go away as soon as the sqlite3_exec()
71513 ** call that started the parser exits.  This routine makes a persistent
71514 ** copy of all the Expr.token.z strings so that the TriggerStep structure
71515 ** will be valid even after the sqlite3_exec() call returns.
71516 */
71517 static void sqlitePersistTriggerStep(sqlite3 *db, TriggerStep *p){
71518   if( p->target.z ){
71519     p->target.z = (u8*)sqlite3DbStrNDup(db, (char*)p->target.z, p->target.n);
71520     p->target.dyn = 1;
71521   }
71522   if( p->pSelect ){
71523     Select *pNew = sqlite3SelectDup(db, p->pSelect);
71524     sqlite3SelectDelete(db, p->pSelect);
71525     p->pSelect = pNew;
71526   }
71527   if( p->pWhere ){
71528     Expr *pNew = sqlite3ExprDup(db, p->pWhere);
71529     sqlite3ExprDelete(db, p->pWhere);
71530     p->pWhere = pNew;
71531   }
71532   if( p->pExprList ){
71533     ExprList *pNew = sqlite3ExprListDup(db, p->pExprList);
71534     sqlite3ExprListDelete(db, p->pExprList);
71535     p->pExprList = pNew;
71536   }
71537   if( p->pIdList ){
71538     IdList *pNew = sqlite3IdListDup(db, p->pIdList);
71539     sqlite3IdListDelete(db, p->pIdList);
71540     p->pIdList = pNew;
71541   }
71542 }
71543
71544 /*
71545 ** Turn a SELECT statement (that the pSelect parameter points to) into
71546 ** a trigger step.  Return a pointer to a TriggerStep structure.
71547 **
71548 ** The parser calls this routine when it finds a SELECT statement in
71549 ** body of a TRIGGER.  
71550 */
71551 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
71552   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
71553   if( pTriggerStep==0 ) {
71554     sqlite3SelectDelete(db, pSelect);
71555     return 0;
71556   }
71557
71558   pTriggerStep->op = TK_SELECT;
71559   pTriggerStep->pSelect = pSelect;
71560   pTriggerStep->orconf = OE_Default;
71561   sqlitePersistTriggerStep(db, pTriggerStep);
71562
71563   return pTriggerStep;
71564 }
71565
71566 /*
71567 ** Build a trigger step out of an INSERT statement.  Return a pointer
71568 ** to the new trigger step.
71569 **
71570 ** The parser calls this routine when it sees an INSERT inside the
71571 ** body of a trigger.
71572 */
71573 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
71574   sqlite3 *db,        /* The database connection */
71575   Token *pTableName,  /* Name of the table into which we insert */
71576   IdList *pColumn,    /* List of columns in pTableName to insert into */
71577   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
71578   Select *pSelect,    /* A SELECT statement that supplies values */
71579   int orconf          /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
71580 ){
71581   TriggerStep *pTriggerStep;
71582
71583   assert(pEList == 0 || pSelect == 0);
71584   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
71585
71586   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
71587   if( pTriggerStep ){
71588     pTriggerStep->op = TK_INSERT;
71589     pTriggerStep->pSelect = pSelect;
71590     pTriggerStep->target  = *pTableName;
71591     pTriggerStep->pIdList = pColumn;
71592     pTriggerStep->pExprList = pEList;
71593     pTriggerStep->orconf = orconf;
71594     sqlitePersistTriggerStep(db, pTriggerStep);
71595   }else{
71596     sqlite3IdListDelete(db, pColumn);
71597     sqlite3ExprListDelete(db, pEList);
71598     sqlite3SelectDelete(db, pSelect);
71599   }
71600
71601   return pTriggerStep;
71602 }
71603
71604 /*
71605 ** Construct a trigger step that implements an UPDATE statement and return
71606 ** a pointer to that trigger step.  The parser calls this routine when it
71607 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
71608 */
71609 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
71610   sqlite3 *db,         /* The database connection */
71611   Token *pTableName,   /* Name of the table to be updated */
71612   ExprList *pEList,    /* The SET clause: list of column and new values */
71613   Expr *pWhere,        /* The WHERE clause */
71614   int orconf           /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
71615 ){
71616   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
71617   if( pTriggerStep==0 ){
71618      sqlite3ExprListDelete(db, pEList);
71619      sqlite3ExprDelete(db, pWhere);
71620      return 0;
71621   }
71622
71623   pTriggerStep->op = TK_UPDATE;
71624   pTriggerStep->target  = *pTableName;
71625   pTriggerStep->pExprList = pEList;
71626   pTriggerStep->pWhere = pWhere;
71627   pTriggerStep->orconf = orconf;
71628   sqlitePersistTriggerStep(db, pTriggerStep);
71629
71630   return pTriggerStep;
71631 }
71632
71633 /*
71634 ** Construct a trigger step that implements a DELETE statement and return
71635 ** a pointer to that trigger step.  The parser calls this routine when it
71636 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
71637 */
71638 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
71639   sqlite3 *db,            /* Database connection */
71640   Token *pTableName,      /* The table from which rows are deleted */
71641   Expr *pWhere            /* The WHERE clause */
71642 ){
71643   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
71644   if( pTriggerStep==0 ){
71645     sqlite3ExprDelete(db, pWhere);
71646     return 0;
71647   }
71648
71649   pTriggerStep->op = TK_DELETE;
71650   pTriggerStep->target  = *pTableName;
71651   pTriggerStep->pWhere = pWhere;
71652   pTriggerStep->orconf = OE_Default;
71653   sqlitePersistTriggerStep(db, pTriggerStep);
71654
71655   return pTriggerStep;
71656 }
71657
71658 /* 
71659 ** Recursively delete a Trigger structure
71660 */
71661 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
71662   if( pTrigger==0 ) return;
71663   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
71664   sqlite3DbFree(db, pTrigger->name);
71665   sqlite3DbFree(db, pTrigger->table);
71666   sqlite3ExprDelete(db, pTrigger->pWhen);
71667   sqlite3IdListDelete(db, pTrigger->pColumns);
71668   if( pTrigger->nameToken.dyn ) sqlite3DbFree(db, (char*)pTrigger->nameToken.z);
71669   sqlite3DbFree(db, pTrigger);
71670 }
71671
71672 /*
71673 ** This function is called to drop a trigger from the database schema. 
71674 **
71675 ** This may be called directly from the parser and therefore identifies
71676 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
71677 ** same job as this routine except it takes a pointer to the trigger
71678 ** instead of the trigger name.
71679 **/
71680 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
71681   Trigger *pTrigger = 0;
71682   int i;
71683   const char *zDb;
71684   const char *zName;
71685   int nName;
71686   sqlite3 *db = pParse->db;
71687
71688   if( db->mallocFailed ) goto drop_trigger_cleanup;
71689   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
71690     goto drop_trigger_cleanup;
71691   }
71692
71693   assert( pName->nSrc==1 );
71694   zDb = pName->a[0].zDatabase;
71695   zName = pName->a[0].zName;
71696   nName = strlen(zName);
71697   for(i=OMIT_TEMPDB; i<db->nDb; i++){
71698     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
71699     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
71700     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
71701     if( pTrigger ) break;
71702   }
71703   if( !pTrigger ){
71704     if( !noErr ){
71705       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
71706     }
71707     goto drop_trigger_cleanup;
71708   }
71709   sqlite3DropTriggerPtr(pParse, pTrigger);
71710
71711 drop_trigger_cleanup:
71712   sqlite3SrcListDelete(db, pName);
71713 }
71714
71715 /*
71716 ** Return a pointer to the Table structure for the table that a trigger
71717 ** is set on.
71718 */
71719 static Table *tableOfTrigger(Trigger *pTrigger){
71720   int n = strlen(pTrigger->table) + 1;
71721   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
71722 }
71723
71724
71725 /*
71726 ** Drop a trigger given a pointer to that trigger. 
71727 */
71728 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
71729   Table   *pTable;
71730   Vdbe *v;
71731   sqlite3 *db = pParse->db;
71732   int iDb;
71733
71734   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
71735   assert( iDb>=0 && iDb<db->nDb );
71736   pTable = tableOfTrigger(pTrigger);
71737   assert( pTable );
71738   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
71739 #ifndef SQLITE_OMIT_AUTHORIZATION
71740   {
71741     int code = SQLITE_DROP_TRIGGER;
71742     const char *zDb = db->aDb[iDb].zName;
71743     const char *zTab = SCHEMA_TABLE(iDb);
71744     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
71745     if( sqlite3AuthCheck(pParse, code, pTrigger->name, pTable->zName, zDb) ||
71746       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
71747       return;
71748     }
71749   }
71750 #endif
71751
71752   /* Generate code to destroy the database record of the trigger.
71753   */
71754   assert( pTable!=0 );
71755   if( (v = sqlite3GetVdbe(pParse))!=0 ){
71756     int base;
71757     static const VdbeOpList dropTrigger[] = {
71758       { OP_Rewind,     0, ADDR(9),  0},
71759       { OP_String8,    0, 1,        0}, /* 1 */
71760       { OP_Column,     0, 1,        2},
71761       { OP_Ne,         2, ADDR(8),  1},
71762       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
71763       { OP_Column,     0, 0,        2},
71764       { OP_Ne,         2, ADDR(8),  1},
71765       { OP_Delete,     0, 0,        0},
71766       { OP_Next,       0, ADDR(1),  0}, /* 8 */
71767     };
71768
71769     sqlite3BeginWriteOperation(pParse, 0, iDb);
71770     sqlite3OpenMasterTable(pParse, iDb);
71771     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
71772     sqlite3VdbeChangeP4(v, base+1, pTrigger->name, 0);
71773     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
71774     sqlite3ChangeCookie(pParse, iDb);
71775     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
71776     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->name, 0);
71777   }
71778 }
71779
71780 /*
71781 ** Remove a trigger from the hash tables of the sqlite* pointer.
71782 */
71783 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
71784   Trigger *pTrigger;
71785   int nName = strlen(zName);
71786   pTrigger = sqlite3HashInsert(&(db->aDb[iDb].pSchema->trigHash),
71787                                zName, nName, 0);
71788   if( pTrigger ){
71789     Table *pTable = tableOfTrigger(pTrigger);
71790     assert( pTable!=0 );
71791     if( pTable->pTrigger == pTrigger ){
71792       pTable->pTrigger = pTrigger->pNext;
71793     }else{
71794       Trigger *cc = pTable->pTrigger;
71795       while( cc ){ 
71796         if( cc->pNext == pTrigger ){
71797           cc->pNext = cc->pNext->pNext;
71798           break;
71799         }
71800         cc = cc->pNext;
71801       }
71802       assert(cc);
71803     }
71804     sqlite3DeleteTrigger(db, pTrigger);
71805     db->flags |= SQLITE_InternChanges;
71806   }
71807 }
71808
71809 /*
71810 ** pEList is the SET clause of an UPDATE statement.  Each entry
71811 ** in pEList is of the format <id>=<expr>.  If any of the entries
71812 ** in pEList have an <id> which matches an identifier in pIdList,
71813 ** then return TRUE.  If pIdList==NULL, then it is considered a
71814 ** wildcard that matches anything.  Likewise if pEList==NULL then
71815 ** it matches anything so always return true.  Return false only
71816 ** if there is no match.
71817 */
71818 static int checkColumnOverLap(IdList *pIdList, ExprList *pEList){
71819   int e;
71820   if( !pIdList || !pEList ) return 1;
71821   for(e=0; e<pEList->nExpr; e++){
71822     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
71823   }
71824   return 0; 
71825 }
71826
71827 /*
71828 ** Return a bit vector to indicate what kind of triggers exist for operation
71829 ** "op" on table pTab.  If pChanges is not NULL then it is a list of columns
71830 ** that are being updated.  Triggers only match if the ON clause of the
71831 ** trigger definition overlaps the set of columns being updated.
71832 **
71833 ** The returned bit vector is some combination of TRIGGER_BEFORE and
71834 ** TRIGGER_AFTER.
71835 */
71836 SQLITE_PRIVATE int sqlite3TriggersExist(
71837   Parse *pParse,          /* Used to check for recursive triggers */
71838   Table *pTab,            /* The table the contains the triggers */
71839   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
71840   ExprList *pChanges      /* Columns that change in an UPDATE statement */
71841 ){
71842   Trigger *pTrigger;
71843   int mask = 0;
71844
71845   pTrigger = IsVirtual(pTab) ? 0 : pTab->pTrigger;
71846   while( pTrigger ){
71847     if( pTrigger->op==op && checkColumnOverLap(pTrigger->pColumns, pChanges) ){
71848       mask |= pTrigger->tr_tm;
71849     }
71850     pTrigger = pTrigger->pNext;
71851   }
71852   return mask;
71853 }
71854
71855 /*
71856 ** Convert the pStep->target token into a SrcList and return a pointer
71857 ** to that SrcList.
71858 **
71859 ** This routine adds a specific database name, if needed, to the target when
71860 ** forming the SrcList.  This prevents a trigger in one database from
71861 ** referring to a target in another database.  An exception is when the
71862 ** trigger is in TEMP in which case it can refer to any other database it
71863 ** wants.
71864 */
71865 static SrcList *targetSrcList(
71866   Parse *pParse,       /* The parsing context */
71867   TriggerStep *pStep   /* The trigger containing the target token */
71868 ){
71869   Token sDb;           /* Dummy database name token */
71870   int iDb;             /* Index of the database to use */
71871   SrcList *pSrc;       /* SrcList to be returned */
71872
71873   iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
71874   if( iDb==0 || iDb>=2 ){
71875     assert( iDb<pParse->db->nDb );
71876     sDb.z = (u8*)pParse->db->aDb[iDb].zName;
71877     sDb.n = strlen((char*)sDb.z);
71878     pSrc = sqlite3SrcListAppend(pParse->db, 0, &sDb, &pStep->target);
71879   } else {
71880     pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
71881   }
71882   return pSrc;
71883 }
71884
71885 /*
71886 ** Generate VDBE code for zero or more statements inside the body of a
71887 ** trigger.  
71888 */
71889 static int codeTriggerProgram(
71890   Parse *pParse,            /* The parser context */
71891   TriggerStep *pStepList,   /* List of statements inside the trigger body */
71892   int orconfin              /* Conflict algorithm. (OE_Abort, etc) */  
71893 ){
71894   TriggerStep * pTriggerStep = pStepList;
71895   int orconf;
71896   Vdbe *v = pParse->pVdbe;
71897   sqlite3 *db = pParse->db;
71898
71899   assert( pTriggerStep!=0 );
71900   assert( v!=0 );
71901   sqlite3VdbeAddOp2(v, OP_ContextPush, 0, 0);
71902   VdbeComment((v, "begin trigger %s", pStepList->pTrig->name));
71903   while( pTriggerStep ){
71904     orconf = (orconfin == OE_Default)?pTriggerStep->orconf:orconfin;
71905     pParse->trigStack->orconf = orconf;
71906     switch( pTriggerStep->op ){
71907       case TK_SELECT: {
71908         Select *ss = sqlite3SelectDup(db, pTriggerStep->pSelect);
71909         if( ss ){
71910           SelectDest dest;
71911
71912           sqlite3SelectDestInit(&dest, SRT_Discard, 0);
71913           sqlite3SelectResolve(pParse, ss, 0);
71914           sqlite3Select(pParse, ss, &dest, 0, 0, 0);
71915           sqlite3SelectDelete(db, ss);
71916         }
71917         break;
71918       }
71919       case TK_UPDATE: {
71920         SrcList *pSrc;
71921         pSrc = targetSrcList(pParse, pTriggerStep);
71922         sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
71923         sqlite3Update(pParse, pSrc,
71924                 sqlite3ExprListDup(db, pTriggerStep->pExprList), 
71925                 sqlite3ExprDup(db, pTriggerStep->pWhere), orconf);
71926         sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
71927         break;
71928       }
71929       case TK_INSERT: {
71930         SrcList *pSrc;
71931         pSrc = targetSrcList(pParse, pTriggerStep);
71932         sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
71933         sqlite3Insert(pParse, pSrc,
71934           sqlite3ExprListDup(db, pTriggerStep->pExprList), 
71935           sqlite3SelectDup(db, pTriggerStep->pSelect), 
71936           sqlite3IdListDup(db, pTriggerStep->pIdList), orconf);
71937         sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
71938         break;
71939       }
71940       case TK_DELETE: {
71941         SrcList *pSrc;
71942         sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
71943         pSrc = targetSrcList(pParse, pTriggerStep);
71944         sqlite3DeleteFrom(pParse, pSrc, 
71945                           sqlite3ExprDup(db, pTriggerStep->pWhere));
71946         sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
71947         break;
71948       }
71949       default:
71950         assert(0);
71951     } 
71952     pTriggerStep = pTriggerStep->pNext;
71953   }
71954   sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0);
71955   VdbeComment((v, "end trigger %s", pStepList->pTrig->name));
71956
71957   return 0;
71958 }
71959
71960 /*
71961 ** This is called to code FOR EACH ROW triggers.
71962 **
71963 ** When the code that this function generates is executed, the following 
71964 ** must be true:
71965 **
71966 ** 1. No cursors may be open in the main database.  (But newIdx and oldIdx
71967 **    can be indices of cursors in temporary tables.  See below.)
71968 **
71969 ** 2. If the triggers being coded are ON INSERT or ON UPDATE triggers, then
71970 **    a temporary vdbe cursor (index newIdx) must be open and pointing at
71971 **    a row containing values to be substituted for new.* expressions in the
71972 **    trigger program(s).
71973 **
71974 ** 3. If the triggers being coded are ON DELETE or ON UPDATE triggers, then
71975 **    a temporary vdbe cursor (index oldIdx) must be open and pointing at
71976 **    a row containing values to be substituted for old.* expressions in the
71977 **    trigger program(s).
71978 **
71979 ** If they are not NULL, the piOldColMask and piNewColMask output variables
71980 ** are set to values that describe the columns used by the trigger program
71981 ** in the OLD.* and NEW.* tables respectively. If column N of the 
71982 ** pseudo-table is read at least once, the corresponding bit of the output
71983 ** mask is set. If a column with an index greater than 32 is read, the
71984 ** output mask is set to the special value 0xffffffff.
71985 **
71986 */
71987 SQLITE_PRIVATE int sqlite3CodeRowTrigger(
71988   Parse *pParse,       /* Parse context */
71989   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
71990   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
71991   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
71992   Table *pTab,         /* The table to code triggers from */
71993   int newIdx,          /* The indice of the "new" row to access */
71994   int oldIdx,          /* The indice of the "old" row to access */
71995   int orconf,          /* ON CONFLICT policy */
71996   int ignoreJump,      /* Instruction to jump to for RAISE(IGNORE) */
71997   u32 *piOldColMask,   /* OUT: Mask of columns used from the OLD.* table */
71998   u32 *piNewColMask    /* OUT: Mask of columns used from the NEW.* table */
71999 ){
72000   Trigger *p;
72001   sqlite3 *db = pParse->db;
72002   TriggerStack trigStackEntry;
72003
72004   trigStackEntry.oldColMask = 0;
72005   trigStackEntry.newColMask = 0;
72006
72007   assert(op == TK_UPDATE || op == TK_INSERT || op == TK_DELETE);
72008   assert(tr_tm == TRIGGER_BEFORE || tr_tm == TRIGGER_AFTER );
72009
72010   assert(newIdx != -1 || oldIdx != -1);
72011
72012   for(p=pTab->pTrigger; p; p=p->pNext){
72013     int fire_this = 0;
72014
72015     /* Determine whether we should code this trigger */
72016     if( 
72017       p->op==op && 
72018       p->tr_tm==tr_tm && 
72019       (p->pSchema==p->pTabSchema || p->pSchema==db->aDb[1].pSchema) &&
72020       (op!=TK_UPDATE||!p->pColumns||checkColumnOverLap(p->pColumns,pChanges))
72021     ){
72022       TriggerStack *pS;      /* Pointer to trigger-stack entry */
72023       for(pS=pParse->trigStack; pS && p!=pS->pTrigger; pS=pS->pNext){}
72024       if( !pS ){
72025         fire_this = 1;
72026       }
72027 #if 0    /* Give no warning for recursive triggers.  Just do not do them */
72028       else{
72029         sqlite3ErrorMsg(pParse, "recursive triggers not supported (%s)",
72030             p->name);
72031         return SQLITE_ERROR;
72032       }
72033 #endif
72034     }
72035  
72036     if( fire_this ){
72037       int endTrigger;
72038       Expr * whenExpr;
72039       AuthContext sContext;
72040       NameContext sNC;
72041
72042 #ifndef SQLITE_OMIT_TRACE
72043       sqlite3VdbeAddOp4(pParse->pVdbe, OP_Trace, 0, 0, 0,
72044                         sqlite3MPrintf(db, "-- TRIGGER %s", p->name),
72045                         P4_DYNAMIC);
72046 #endif
72047       memset(&sNC, 0, sizeof(sNC));
72048       sNC.pParse = pParse;
72049
72050       /* Push an entry on to the trigger stack */
72051       trigStackEntry.pTrigger = p;
72052       trigStackEntry.newIdx = newIdx;
72053       trigStackEntry.oldIdx = oldIdx;
72054       trigStackEntry.pTab = pTab;
72055       trigStackEntry.pNext = pParse->trigStack;
72056       trigStackEntry.ignoreJump = ignoreJump;
72057       pParse->trigStack = &trigStackEntry;
72058       sqlite3AuthContextPush(pParse, &sContext, p->name);
72059
72060       /* code the WHEN clause */
72061       endTrigger = sqlite3VdbeMakeLabel(pParse->pVdbe);
72062       whenExpr = sqlite3ExprDup(db, p->pWhen);
72063       if( db->mallocFailed || sqlite3ExprResolveNames(&sNC, whenExpr) ){
72064         pParse->trigStack = trigStackEntry.pNext;
72065         sqlite3ExprDelete(db, whenExpr);
72066         return 1;
72067       }
72068       sqlite3ExprIfFalse(pParse, whenExpr, endTrigger, SQLITE_JUMPIFNULL);
72069       sqlite3ExprDelete(db, whenExpr);
72070
72071       codeTriggerProgram(pParse, p->step_list, orconf); 
72072
72073       /* Pop the entry off the trigger stack */
72074       pParse->trigStack = trigStackEntry.pNext;
72075       sqlite3AuthContextPop(&sContext);
72076
72077       sqlite3VdbeResolveLabel(pParse->pVdbe, endTrigger);
72078     }
72079   }
72080   if( piOldColMask ) *piOldColMask |= trigStackEntry.oldColMask;
72081   if( piNewColMask ) *piNewColMask |= trigStackEntry.newColMask;
72082   return 0;
72083 }
72084 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
72085
72086 /************** End of trigger.c *********************************************/
72087 /************** Begin file update.c ******************************************/
72088 /*
72089 ** 2001 September 15
72090 **
72091 ** The author disclaims copyright to this source code.  In place of
72092 ** a legal notice, here is a blessing:
72093 **
72094 **    May you do good and not evil.
72095 **    May you find forgiveness for yourself and forgive others.
72096 **    May you share freely, never taking more than you give.
72097 **
72098 *************************************************************************
72099 ** This file contains C code routines that are called by the parser
72100 ** to handle UPDATE statements.
72101 **
72102 ** $Id: update.c,v 1.181 2008/07/28 19:34:54 drh Exp $
72103 */
72104
72105 #ifndef SQLITE_OMIT_VIRTUALTABLE
72106 /* Forward declaration */
72107 static void updateVirtualTable(
72108   Parse *pParse,       /* The parsing context */
72109   SrcList *pSrc,       /* The virtual table to be modified */
72110   Table *pTab,         /* The virtual table */
72111   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
72112   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
72113   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
72114   Expr *pWhere         /* WHERE clause of the UPDATE statement */
72115 );
72116 #endif /* SQLITE_OMIT_VIRTUALTABLE */
72117
72118 /*
72119 ** The most recently coded instruction was an OP_Column to retrieve the
72120 ** i-th column of table pTab. This routine sets the P4 parameter of the 
72121 ** OP_Column to the default value, if any.
72122 **
72123 ** The default value of a column is specified by a DEFAULT clause in the 
72124 ** column definition. This was either supplied by the user when the table
72125 ** was created, or added later to the table definition by an ALTER TABLE
72126 ** command. If the latter, then the row-records in the table btree on disk
72127 ** may not contain a value for the column and the default value, taken
72128 ** from the P4 parameter of the OP_Column instruction, is returned instead.
72129 ** If the former, then all row-records are guaranteed to include a value
72130 ** for the column and the P4 value is not required.
72131 **
72132 ** Column definitions created by an ALTER TABLE command may only have 
72133 ** literal default values specified: a number, null or a string. (If a more
72134 ** complicated default expression value was provided, it is evaluated 
72135 ** when the ALTER TABLE is executed and one of the literal values written
72136 ** into the sqlite_master table.)
72137 **
72138 ** Therefore, the P4 parameter is only required if the default value for
72139 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
72140 ** function is capable of transforming these types of expressions into
72141 ** sqlite3_value objects.
72142 */
72143 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i){
72144   if( pTab && !pTab->pSelect ){
72145     sqlite3_value *pValue;
72146     u8 enc = ENC(sqlite3VdbeDb(v));
72147     Column *pCol = &pTab->aCol[i];
72148     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
72149     assert( i<pTab->nCol );
72150     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, 
72151                          pCol->affinity, &pValue);
72152     if( pValue ){
72153       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
72154     }
72155   }
72156 }
72157
72158 /*
72159 ** Process an UPDATE statement.
72160 **
72161 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
72162 **          \_______/ \________/     \______/       \________________/
72163 *            onError   pTabList      pChanges             pWhere
72164 */
72165 SQLITE_PRIVATE void sqlite3Update(
72166   Parse *pParse,         /* The parser context */
72167   SrcList *pTabList,     /* The table in which we should change things */
72168   ExprList *pChanges,    /* Things to be changed */
72169   Expr *pWhere,          /* The WHERE clause.  May be null */
72170   int onError            /* How to handle constraint errors */
72171 ){
72172   int i, j;              /* Loop counters */
72173   Table *pTab;           /* The table to be updated */
72174   int addr = 0;          /* VDBE instruction address of the start of the loop */
72175   WhereInfo *pWInfo;     /* Information about the WHERE clause */
72176   Vdbe *v;               /* The virtual database engine */
72177   Index *pIdx;           /* For looping over indices */
72178   int nIdx;              /* Number of indices that need updating */
72179   int iCur;              /* VDBE Cursor number of pTab */
72180   sqlite3 *db;           /* The database structure */
72181   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
72182   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
72183                          ** an expression for the i-th column of the table.
72184                          ** aXRef[i]==-1 if the i-th column is not changed. */
72185   int chngRowid;         /* True if the record number is being changed */
72186   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
72187   int openAll = 0;       /* True if all indices need to be opened */
72188   AuthContext sContext;  /* The authorization context */
72189   NameContext sNC;       /* The name-context to resolve expressions in */
72190   int iDb;               /* Database containing the table being updated */
72191   int j1;                /* Addresses of jump instructions */
72192   int okOnePass;         /* True for one-pass algorithm without the FIFO */
72193
72194 #ifndef SQLITE_OMIT_TRIGGER
72195   int isView;                  /* Trying to update a view */
72196   int triggers_exist = 0;      /* True if any row triggers exist */
72197 #endif
72198   int iBeginAfterTrigger;      /* Address of after trigger program */
72199   int iEndAfterTrigger;        /* Exit of after trigger program */
72200   int iBeginBeforeTrigger;     /* Address of before trigger program */
72201   int iEndBeforeTrigger;       /* Exit of before trigger program */
72202   u32 old_col_mask = 0;        /* Mask of OLD.* columns in use */
72203   u32 new_col_mask = 0;        /* Mask of NEW.* columns in use */
72204
72205   int newIdx      = -1;  /* index of trigger "new" temp table       */
72206   int oldIdx      = -1;  /* index of trigger "old" temp table       */
72207
72208   /* Register Allocations */
72209   int regRowCount = 0;   /* A count of rows changed */
72210   int regOldRowid;       /* The old rowid */
72211   int regNewRowid;       /* The new rowid */
72212   int regData;           /* New data for the row */
72213
72214   sContext.pParse = 0;
72215   db = pParse->db;
72216   if( pParse->nErr || db->mallocFailed ){
72217     goto update_cleanup;
72218   }
72219   assert( pTabList->nSrc==1 );
72220
72221   /* Locate the table which we want to update. 
72222   */
72223   pTab = sqlite3SrcListLookup(pParse, pTabList);
72224   if( pTab==0 ) goto update_cleanup;
72225   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
72226
72227   /* Figure out if we have any triggers and if the table being
72228   ** updated is a view
72229   */
72230 #ifndef SQLITE_OMIT_TRIGGER
72231   triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges);
72232   isView = pTab->pSelect!=0;
72233 #else
72234 # define triggers_exist 0
72235 # define isView 0
72236 #endif
72237 #ifdef SQLITE_OMIT_VIEW
72238 # undef isView
72239 # define isView 0
72240 #endif
72241
72242   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
72243     goto update_cleanup;
72244   }
72245   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
72246     goto update_cleanup;
72247   }
72248   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
72249   if( aXRef==0 ) goto update_cleanup;
72250   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
72251
72252   /* If there are FOR EACH ROW triggers, allocate cursors for the
72253   ** special OLD and NEW tables
72254   */
72255   if( triggers_exist ){
72256     newIdx = pParse->nTab++;
72257     oldIdx = pParse->nTab++;
72258   }
72259
72260   /* Allocate a cursors for the main database table and for all indices.
72261   ** The index cursors might not be used, but if they are used they
72262   ** need to occur right after the database cursor.  So go ahead and
72263   ** allocate enough space, just in case.
72264   */
72265   pTabList->a[0].iCursor = iCur = pParse->nTab++;
72266   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
72267     pParse->nTab++;
72268   }
72269
72270   /* Initialize the name-context */
72271   memset(&sNC, 0, sizeof(sNC));
72272   sNC.pParse = pParse;
72273   sNC.pSrcList = pTabList;
72274
72275   /* Resolve the column names in all the expressions of the
72276   ** of the UPDATE statement.  Also find the column index
72277   ** for each column to be updated in the pChanges array.  For each
72278   ** column to be updated, make sure we have authorization to change
72279   ** that column.
72280   */
72281   chngRowid = 0;
72282   for(i=0; i<pChanges->nExpr; i++){
72283     if( sqlite3ExprResolveNames(&sNC, pChanges->a[i].pExpr) ){
72284       goto update_cleanup;
72285     }
72286     for(j=0; j<pTab->nCol; j++){
72287       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
72288         if( j==pTab->iPKey ){
72289           chngRowid = 1;
72290           pRowidExpr = pChanges->a[i].pExpr;
72291         }
72292         aXRef[j] = i;
72293         break;
72294       }
72295     }
72296     if( j>=pTab->nCol ){
72297       if( sqlite3IsRowid(pChanges->a[i].zName) ){
72298         chngRowid = 1;
72299         pRowidExpr = pChanges->a[i].pExpr;
72300       }else{
72301         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
72302         goto update_cleanup;
72303       }
72304     }
72305 #ifndef SQLITE_OMIT_AUTHORIZATION
72306     {
72307       int rc;
72308       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
72309                            pTab->aCol[j].zName, db->aDb[iDb].zName);
72310       if( rc==SQLITE_DENY ){
72311         goto update_cleanup;
72312       }else if( rc==SQLITE_IGNORE ){
72313         aXRef[j] = -1;
72314       }
72315     }
72316 #endif
72317   }
72318
72319   /* Allocate memory for the array aRegIdx[].  There is one entry in the
72320   ** array for each index associated with table being updated.  Fill in
72321   ** the value with a register number for indices that are to be used
72322   ** and with zero for unused indices.
72323   */
72324   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
72325   if( nIdx>0 ){
72326     aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
72327     if( aRegIdx==0 ) goto update_cleanup;
72328   }
72329   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
72330     int reg;
72331     if( chngRowid ){
72332       reg = ++pParse->nMem;
72333     }else{
72334       reg = 0;
72335       for(i=0; i<pIdx->nColumn; i++){
72336         if( aXRef[pIdx->aiColumn[i]]>=0 ){
72337           reg = ++pParse->nMem;
72338           break;
72339         }
72340       }
72341     }
72342     aRegIdx[j] = reg;
72343   }
72344
72345   /* Allocate a block of register used to store the change record
72346   ** sent to sqlite3GenerateConstraintChecks().  There are either
72347   ** one or two registers for holding the rowid.  One rowid register
72348   ** is used if chngRowid is false and two are used if chngRowid is
72349   ** true.  Following these are pTab->nCol register holding column
72350   ** data.
72351   */
72352   regOldRowid = regNewRowid = pParse->nMem + 1;
72353   pParse->nMem += pTab->nCol + 1;
72354   if( chngRowid ){
72355     regNewRowid++;
72356     pParse->nMem++;
72357   }
72358   regData = regNewRowid+1;
72359  
72360
72361   /* Begin generating code.
72362   */
72363   v = sqlite3GetVdbe(pParse);
72364   if( v==0 ) goto update_cleanup;
72365   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
72366   sqlite3BeginWriteOperation(pParse, 1, iDb);
72367
72368 #ifndef SQLITE_OMIT_VIRTUALTABLE
72369   /* Virtual tables must be handled separately */
72370   if( IsVirtual(pTab) ){
72371     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
72372                        pWhere);
72373     pWhere = 0;
72374     pTabList = 0;
72375     goto update_cleanup;
72376   }
72377 #endif
72378
72379   /* Start the view context
72380   */
72381   if( isView ){
72382     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
72383   }
72384
72385   /* Generate the code for triggers.
72386   */
72387   if( triggers_exist ){
72388     int iGoto;
72389
72390     /* Create pseudo-tables for NEW and OLD
72391     */
72392     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
72393     sqlite3VdbeAddOp2(v, OP_OpenPseudo, oldIdx, 0);
72394     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
72395     sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0);
72396
72397     iGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
72398     addr = sqlite3VdbeMakeLabel(v);
72399     iBeginBeforeTrigger = sqlite3VdbeCurrentAddr(v);
72400     if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_BEFORE, pTab,
72401           newIdx, oldIdx, onError, addr, &old_col_mask, &new_col_mask) ){
72402       goto update_cleanup;
72403     }
72404     iEndBeforeTrigger = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
72405     iBeginAfterTrigger = sqlite3VdbeCurrentAddr(v);
72406     if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_AFTER, pTab, 
72407           newIdx, oldIdx, onError, addr, &old_col_mask, &new_col_mask) ){
72408       goto update_cleanup;
72409     }
72410     iEndAfterTrigger = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
72411     sqlite3VdbeJumpHere(v, iGoto);
72412   }
72413
72414   /* If we are trying to update a view, realize that view into
72415   ** a ephemeral table.
72416   */
72417   if( isView ){
72418     sqlite3MaterializeView(pParse, pTab->pSelect, pWhere, iCur);
72419   }
72420
72421   /* Resolve the column names in all the expressions in the
72422   ** WHERE clause.
72423   */
72424   if( sqlite3ExprResolveNames(&sNC, pWhere) ){
72425     goto update_cleanup;
72426   }
72427
72428   /* Begin the database scan
72429   */
72430   sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
72431   pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0,
72432                              WHERE_ONEPASS_DESIRED);
72433   if( pWInfo==0 ) goto update_cleanup;
72434   okOnePass = pWInfo->okOnePass;
72435
72436   /* Remember the rowid of every item to be updated.
72437   */
72438   sqlite3VdbeAddOp2(v, IsVirtual(pTab)?OP_VRowid:OP_Rowid, iCur, regOldRowid);
72439   if( !okOnePass ) sqlite3VdbeAddOp2(v, OP_FifoWrite, regOldRowid, 0);
72440
72441   /* End the database scan loop.
72442   */
72443   sqlite3WhereEnd(pWInfo);
72444
72445   /* Initialize the count of updated rows
72446   */
72447   if( db->flags & SQLITE_CountRows && !pParse->trigStack ){
72448     regRowCount = ++pParse->nMem;
72449     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
72450   }
72451
72452   if( !isView && !IsVirtual(pTab) ){
72453     /* 
72454     ** Open every index that needs updating.  Note that if any
72455     ** index could potentially invoke a REPLACE conflict resolution 
72456     ** action, then we need to open all indices because we might need
72457     ** to be deleting some records.
72458     */
72459     if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); 
72460     if( onError==OE_Replace ){
72461       openAll = 1;
72462     }else{
72463       openAll = 0;
72464       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
72465         if( pIdx->onError==OE_Replace ){
72466           openAll = 1;
72467           break;
72468         }
72469       }
72470     }
72471     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
72472       if( openAll || aRegIdx[i]>0 ){
72473         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
72474         sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
72475                        (char*)pKey, P4_KEYINFO_HANDOFF);
72476         assert( pParse->nTab>iCur+i+1 );
72477       }
72478     }
72479   }
72480   
72481   /* Jump back to this point if a trigger encounters an IGNORE constraint. */
72482   if( triggers_exist ){
72483     sqlite3VdbeResolveLabel(v, addr);
72484   }
72485
72486   /* Top of the update loop */
72487   if( okOnePass ){
72488     int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
72489     addr = sqlite3VdbeAddOp0(v, OP_Goto);
72490     sqlite3VdbeJumpHere(v, a1);
72491   }else{
72492     addr = sqlite3VdbeAddOp2(v, OP_FifoRead, regOldRowid, 0);
72493   }
72494
72495   if( triggers_exist ){
72496     int regRowid;
72497     int regRow;
72498     int regCols;
72499
72500     /* Make cursor iCur point to the record that is being updated.
72501     */
72502     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
72503
72504     /* Generate the OLD table
72505     */
72506     regRowid = sqlite3GetTempReg(pParse);
72507     regRow = sqlite3GetTempReg(pParse);
72508     sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regRowid);
72509     if( !old_col_mask ){
72510       sqlite3VdbeAddOp2(v, OP_Null, 0, regRow);
72511     }else{
72512       sqlite3VdbeAddOp2(v, OP_RowData, iCur, regRow);
72513     }
72514     sqlite3VdbeAddOp3(v, OP_Insert, oldIdx, regRow, regRowid);
72515
72516     /* Generate the NEW table
72517     */
72518     if( chngRowid ){
72519       sqlite3ExprCodeAndCache(pParse, pRowidExpr, regRowid);
72520     }else{
72521       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regRowid);
72522     }
72523     regCols = sqlite3GetTempRange(pParse, pTab->nCol);
72524     for(i=0; i<pTab->nCol; i++){
72525       if( i==pTab->iPKey ){
72526         sqlite3VdbeAddOp2(v, OP_Null, 0, regCols+i);
72527         continue;
72528       }
72529       j = aXRef[i];
72530       if( new_col_mask&((u32)1<<i) || new_col_mask==0xffffffff ){
72531         if( j<0 ){
72532           sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regCols+i);
72533           sqlite3ColumnDefault(v, pTab, i);
72534         }else{
72535           sqlite3ExprCodeAndCache(pParse, pChanges->a[j].pExpr, regCols+i);
72536         }
72537       }else{
72538         sqlite3VdbeAddOp2(v, OP_Null, 0, regCols+i);
72539       }
72540     }
72541     sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRow);
72542     if( !isView ){
72543       sqlite3TableAffinityStr(v, pTab);
72544       sqlite3ExprCacheAffinityChange(pParse, regCols, pTab->nCol);
72545     }
72546     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol);
72547     /* if( pParse->nErr ) goto update_cleanup; */
72548     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRow, regRowid);
72549     sqlite3ReleaseTempReg(pParse, regRowid);
72550     sqlite3ReleaseTempReg(pParse, regRow);
72551
72552     sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginBeforeTrigger);
72553     sqlite3VdbeJumpHere(v, iEndBeforeTrigger);
72554   }
72555
72556   if( !isView && !IsVirtual(pTab) ){
72557     /* Loop over every record that needs updating.  We have to load
72558     ** the old data for each record to be updated because some columns
72559     ** might not change and we will need to copy the old value.
72560     ** Also, the old data is needed to delete the old index entries.
72561     ** So make the cursor point at the old record.
72562     */
72563     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
72564
72565     /* If the record number will change, push the record number as it
72566     ** will be after the update. (The old record number is currently
72567     ** on top of the stack.)
72568     */
72569     if( chngRowid ){
72570       sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
72571       sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
72572     }
72573
72574     /* Compute new data for this record.  
72575     */
72576     for(i=0; i<pTab->nCol; i++){
72577       if( i==pTab->iPKey ){
72578         sqlite3VdbeAddOp2(v, OP_Null, 0, regData+i);
72579         continue;
72580       }
72581       j = aXRef[i];
72582       if( j<0 ){
72583         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regData+i);
72584         sqlite3ColumnDefault(v, pTab, i);
72585       }else{
72586         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regData+i);
72587       }
72588     }
72589
72590     /* Do constraint checks
72591     */
72592     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
72593                                     aRegIdx, chngRowid, 1,
72594                                     onError, addr);
72595
72596     /* Delete the old indices for the current record.
72597     */
72598     j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
72599     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
72600
72601     /* If changing the record number, delete the old record.
72602     */
72603     if( chngRowid ){
72604       sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
72605     }
72606     sqlite3VdbeJumpHere(v, j1);
72607
72608     /* Create the new index entries and the new record.
72609     */
72610     sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, 
72611                              aRegIdx, chngRowid, 1, -1, 0);
72612   }
72613
72614   /* Increment the row counter 
72615   */
72616   if( db->flags & SQLITE_CountRows && !pParse->trigStack){
72617     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
72618   }
72619
72620   /* If there are triggers, close all the cursors after each iteration
72621   ** through the loop.  The fire the after triggers.
72622   */
72623   if( triggers_exist ){
72624     sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginAfterTrigger);
72625     sqlite3VdbeJumpHere(v, iEndAfterTrigger);
72626   }
72627
72628   /* Repeat the above with the next record to be updated, until
72629   ** all record selected by the WHERE clause have been updated.
72630   */
72631   sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
72632   sqlite3VdbeJumpHere(v, addr);
72633
72634   /* Close all tables */
72635   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
72636     if( openAll || aRegIdx[i]>0 ){
72637       sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
72638     }
72639   }
72640   sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
72641   if( triggers_exist ){
72642     sqlite3VdbeAddOp2(v, OP_Close, newIdx, 0);
72643     sqlite3VdbeAddOp2(v, OP_Close, oldIdx, 0);
72644   }
72645
72646   /*
72647   ** Return the number of rows that were changed. If this routine is 
72648   ** generating code because of a call to sqlite3NestedParse(), do not
72649   ** invoke the callback function.
72650   */
72651   if( db->flags & SQLITE_CountRows && !pParse->trigStack && pParse->nested==0 ){
72652     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
72653     sqlite3VdbeSetNumCols(v, 1);
72654     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", P4_STATIC);
72655   }
72656
72657 update_cleanup:
72658   sqlite3AuthContextPop(&sContext);
72659   sqlite3DbFree(db, aRegIdx);
72660   sqlite3DbFree(db, aXRef);
72661   sqlite3SrcListDelete(db, pTabList);
72662   sqlite3ExprListDelete(db, pChanges);
72663   sqlite3ExprDelete(db, pWhere);
72664   return;
72665 }
72666
72667 #ifndef SQLITE_OMIT_VIRTUALTABLE
72668 /*
72669 ** Generate code for an UPDATE of a virtual table.
72670 **
72671 ** The strategy is that we create an ephemerial table that contains
72672 ** for each row to be changed:
72673 **
72674 **   (A)  The original rowid of that row.
72675 **   (B)  The revised rowid for the row. (note1)
72676 **   (C)  The content of every column in the row.
72677 **
72678 ** Then we loop over this ephemeral table and for each row in
72679 ** the ephermeral table call VUpdate.
72680 **
72681 ** When finished, drop the ephemeral table.
72682 **
72683 ** (note1) Actually, if we know in advance that (A) is always the same
72684 ** as (B) we only store (A), then duplicate (A) when pulling
72685 ** it out of the ephemeral table before calling VUpdate.
72686 */
72687 static void updateVirtualTable(
72688   Parse *pParse,       /* The parsing context */
72689   SrcList *pSrc,       /* The virtual table to be modified */
72690   Table *pTab,         /* The virtual table */
72691   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
72692   Expr *pRowid,        /* Expression used to recompute the rowid */
72693   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
72694   Expr *pWhere         /* WHERE clause of the UPDATE statement */
72695 ){
72696   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
72697   ExprList *pEList = 0;     /* The result set of the SELECT statement */
72698   Select *pSelect = 0;      /* The SELECT statement */
72699   Expr *pExpr;              /* Temporary expression */
72700   int ephemTab;             /* Table holding the result of the SELECT */
72701   int i;                    /* Loop counter */
72702   int addr;                 /* Address of top of loop */
72703   int iReg;                 /* First register in set passed to OP_VUpdate */
72704   sqlite3 *db = pParse->db; /* Database connection */
72705   const char *pVtab = (const char*)pTab->pVtab;
72706   SelectDest dest;
72707
72708   /* Construct the SELECT statement that will find the new values for
72709   ** all updated rows. 
72710   */
72711   pEList = sqlite3ExprListAppend(pParse, 0, 
72712                                  sqlite3CreateIdExpr(pParse, "_rowid_"), 0);
72713   if( pRowid ){
72714     pEList = sqlite3ExprListAppend(pParse, pEList,
72715                                    sqlite3ExprDup(db, pRowid), 0);
72716   }
72717   assert( pTab->iPKey<0 );
72718   for(i=0; i<pTab->nCol; i++){
72719     if( aXRef[i]>=0 ){
72720       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr);
72721     }else{
72722       pExpr = sqlite3CreateIdExpr(pParse, pTab->aCol[i].zName);
72723     }
72724     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr, 0);
72725   }
72726   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
72727   
72728   /* Create the ephemeral table into which the update results will
72729   ** be stored.
72730   */
72731   assert( v );
72732   ephemTab = pParse->nTab++;
72733   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
72734
72735   /* fill the ephemeral table 
72736   */
72737   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
72738   sqlite3Select(pParse, pSelect, &dest, 0, 0, 0);
72739
72740   /* Generate code to scan the ephemeral table and call VUpdate. */
72741   iReg = ++pParse->nMem;
72742   pParse->nMem += pTab->nCol+1;
72743   sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
72744   addr = sqlite3VdbeCurrentAddr(v);
72745   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
72746   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
72747   for(i=0; i<pTab->nCol; i++){
72748     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
72749   }
72750   sqlite3VtabMakeWritable(pParse, pTab);
72751   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVtab, P4_VTAB);
72752   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr);
72753   sqlite3VdbeJumpHere(v, addr-1);
72754   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
72755
72756   /* Cleanup */
72757   sqlite3SelectDelete(db, pSelect);  
72758 }
72759 #endif /* SQLITE_OMIT_VIRTUALTABLE */
72760
72761 /* Make sure "isView" gets undefined in case this file becomes part of
72762 ** the amalgamation - so that subsequent files do not see isView as a
72763 ** macro. */
72764 #undef isView
72765
72766 /************** End of update.c **********************************************/
72767 /************** Begin file vacuum.c ******************************************/
72768 /*
72769 ** 2003 April 6
72770 **
72771 ** The author disclaims copyright to this source code.  In place of
72772 ** a legal notice, here is a blessing:
72773 **
72774 **    May you do good and not evil.
72775 **    May you find forgiveness for yourself and forgive others.
72776 **    May you share freely, never taking more than you give.
72777 **
72778 *************************************************************************
72779 ** This file contains code used to implement the VACUUM command.
72780 **
72781 ** Most of the code in this file may be omitted by defining the
72782 ** SQLITE_OMIT_VACUUM macro.
72783 **
72784 ** $Id: vacuum.c,v 1.81 2008/07/08 19:34:07 drh Exp $
72785 */
72786
72787 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
72788 /*
72789 ** Execute zSql on database db. Return an error code.
72790 */
72791 static int execSql(sqlite3 *db, const char *zSql){
72792   sqlite3_stmt *pStmt;
72793   if( !zSql ){
72794     return SQLITE_NOMEM;
72795   }
72796   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
72797     return sqlite3_errcode(db);
72798   }
72799   while( SQLITE_ROW==sqlite3_step(pStmt) ){}
72800   return sqlite3_finalize(pStmt);
72801 }
72802
72803 /*
72804 ** Execute zSql on database db. The statement returns exactly
72805 ** one column. Execute this as SQL on the same database.
72806 */
72807 static int execExecSql(sqlite3 *db, const char *zSql){
72808   sqlite3_stmt *pStmt;
72809   int rc;
72810
72811   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
72812   if( rc!=SQLITE_OK ) return rc;
72813
72814   while( SQLITE_ROW==sqlite3_step(pStmt) ){
72815     rc = execSql(db, (char*)sqlite3_column_text(pStmt, 0));
72816     if( rc!=SQLITE_OK ){
72817       sqlite3_finalize(pStmt);
72818       return rc;
72819     }
72820   }
72821
72822   return sqlite3_finalize(pStmt);
72823 }
72824
72825 /*
72826 ** The non-standard VACUUM command is used to clean up the database,
72827 ** collapse free space, etc.  It is modelled after the VACUUM command
72828 ** in PostgreSQL.
72829 **
72830 ** In version 1.0.x of SQLite, the VACUUM command would call
72831 ** gdbm_reorganize() on all the database tables.  But beginning
72832 ** with 2.0.0, SQLite no longer uses GDBM so this command has
72833 ** become a no-op.
72834 */
72835 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
72836   Vdbe *v = sqlite3GetVdbe(pParse);
72837   if( v ){
72838     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
72839   }
72840   return;
72841 }
72842
72843 /*
72844 ** This routine implements the OP_Vacuum opcode of the VDBE.
72845 */
72846 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
72847   int rc = SQLITE_OK;     /* Return code from service routines */
72848   Btree *pMain;           /* The database being vacuumed */
72849   Btree *pTemp;           /* The temporary database we vacuum into */
72850   char *zSql = 0;         /* SQL statements */
72851   int saved_flags;        /* Saved value of the db->flags */
72852   int saved_nChange;      /* Saved value of db->nChange */
72853   int saved_nTotalChange; /* Saved value of db->nTotalChange */
72854   Db *pDb = 0;            /* Database to detach at end of vacuum */
72855   int nRes;
72856
72857   /* Save the current value of the write-schema flag before setting it. */
72858   saved_flags = db->flags;
72859   saved_nChange = db->nChange;
72860   saved_nTotalChange = db->nTotalChange;
72861   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
72862
72863   if( !db->autoCommit ){
72864     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
72865     rc = SQLITE_ERROR;
72866     goto end_of_vacuum;
72867   }
72868   pMain = db->aDb[0].pBt;
72869
72870   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
72871   ** can be set to 'off' for this file, as it is not recovered if a crash
72872   ** occurs anyway. The integrity of the database is maintained by a
72873   ** (possibly synchronous) transaction opened on the main database before
72874   ** sqlite3BtreeCopyFile() is called.
72875   **
72876   ** An optimisation would be to use a non-journaled pager.
72877   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
72878   ** that actually made the VACUUM run slower.  Very little journalling
72879   ** actually occurs when doing a vacuum since the vacuum_db is initially
72880   ** empty.  Only the journal header is written.  Apparently it takes more
72881   ** time to parse and run the PRAGMA to turn journalling off than it does
72882   ** to write the journal header file.
72883   */
72884   zSql = "ATTACH '' AS vacuum_db;";
72885   rc = execSql(db, zSql);
72886   if( rc!=SQLITE_OK ) goto end_of_vacuum;
72887   pDb = &db->aDb[db->nDb-1];
72888   assert( strcmp(db->aDb[db->nDb-1].zName,"vacuum_db")==0 );
72889   pTemp = db->aDb[db->nDb-1].pBt;
72890
72891   nRes = sqlite3BtreeGetReserve(pMain);
72892
72893   /* A VACUUM cannot change the pagesize of an encrypted database. */
72894 #ifdef SQLITE_HAS_CODEC
72895   if( db->nextPagesize ){
72896     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
72897     int nKey;
72898     char *zKey;
72899     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
72900     if( nKey ) db->nextPagesize = 0;
72901   }
72902 #endif
72903
72904   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes)
72905    || sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes)
72906    || db->mallocFailed 
72907   ){
72908     rc = SQLITE_NOMEM;
72909     goto end_of_vacuum;
72910   }
72911   rc = execSql(db, "PRAGMA vacuum_db.synchronous=OFF");
72912   if( rc!=SQLITE_OK ){
72913     goto end_of_vacuum;
72914   }
72915
72916 #ifndef SQLITE_OMIT_AUTOVACUUM
72917   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
72918                                            sqlite3BtreeGetAutoVacuum(pMain));
72919 #endif
72920
72921   /* Begin a transaction */
72922   rc = execSql(db, "BEGIN EXCLUSIVE;");
72923   if( rc!=SQLITE_OK ) goto end_of_vacuum;
72924
72925   /* Query the schema of the main database. Create a mirror schema
72926   ** in the temporary database.
72927   */
72928   rc = execExecSql(db, 
72929       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
72930       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
72931       "   AND rootpage>0"
72932   );
72933   if( rc!=SQLITE_OK ) goto end_of_vacuum;
72934   rc = execExecSql(db, 
72935       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
72936       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
72937   if( rc!=SQLITE_OK ) goto end_of_vacuum;
72938   rc = execExecSql(db, 
72939       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
72940       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
72941   if( rc!=SQLITE_OK ) goto end_of_vacuum;
72942
72943   /* Loop through the tables in the main database. For each, do
72944   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM xxx;" to copy
72945   ** the contents to the temporary database.
72946   */
72947   rc = execExecSql(db, 
72948       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
72949       "|| ' SELECT * FROM ' || quote(name) || ';'"
72950       "FROM sqlite_master "
72951       "WHERE type = 'table' AND name!='sqlite_sequence' "
72952       "  AND rootpage>0"
72953
72954   );
72955   if( rc!=SQLITE_OK ) goto end_of_vacuum;
72956
72957   /* Copy over the sequence table
72958   */
72959   rc = execExecSql(db, 
72960       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
72961       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
72962   );
72963   if( rc!=SQLITE_OK ) goto end_of_vacuum;
72964   rc = execExecSql(db, 
72965       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
72966       "|| ' SELECT * FROM ' || quote(name) || ';' "
72967       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
72968   );
72969   if( rc!=SQLITE_OK ) goto end_of_vacuum;
72970
72971
72972   /* Copy the triggers, views, and virtual tables from the main database
72973   ** over to the temporary database.  None of these objects has any
72974   ** associated storage, so all we have to do is copy their entries
72975   ** from the SQLITE_MASTER table.
72976   */
72977   rc = execSql(db,
72978       "INSERT INTO vacuum_db.sqlite_master "
72979       "  SELECT type, name, tbl_name, rootpage, sql"
72980       "    FROM sqlite_master"
72981       "   WHERE type='view' OR type='trigger'"
72982       "      OR (type='table' AND rootpage=0)"
72983   );
72984   if( rc ) goto end_of_vacuum;
72985
72986   /* At this point, unless the main db was completely empty, there is now a
72987   ** transaction open on the vacuum database, but not on the main database.
72988   ** Open a btree level transaction on the main database. This allows a
72989   ** call to sqlite3BtreeCopyFile(). The main database btree level
72990   ** transaction is then committed, so the SQL level never knows it was
72991   ** opened for writing. This way, the SQL transaction used to create the
72992   ** temporary database never needs to be committed.
72993   */
72994   if( rc==SQLITE_OK ){
72995     u32 meta;
72996     int i;
72997
72998     /* This array determines which meta meta values are preserved in the
72999     ** vacuum.  Even entries are the meta value number and odd entries
73000     ** are an increment to apply to the meta value after the vacuum.
73001     ** The increment is used to increase the schema cookie so that other
73002     ** connections to the same database will know to reread the schema.
73003     */
73004     static const unsigned char aCopy[] = {
73005        1, 1,    /* Add one to the old schema cookie */
73006        3, 0,    /* Preserve the default page cache size */
73007        5, 0,    /* Preserve the default text encoding */
73008        6, 0,    /* Preserve the user version */
73009     };
73010
73011     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
73012     assert( 1==sqlite3BtreeIsInTrans(pMain) );
73013
73014     /* Copy Btree meta values */
73015     for(i=0; i<sizeof(aCopy)/sizeof(aCopy[0]); i+=2){
73016       rc = sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
73017       if( rc!=SQLITE_OK ) goto end_of_vacuum;
73018       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
73019       if( rc!=SQLITE_OK ) goto end_of_vacuum;
73020     }
73021
73022     rc = sqlite3BtreeCopyFile(pMain, pTemp);
73023     if( rc!=SQLITE_OK ) goto end_of_vacuum;
73024     rc = sqlite3BtreeCommit(pTemp);
73025     if( rc!=SQLITE_OK ) goto end_of_vacuum;
73026     rc = sqlite3BtreeCommit(pMain);
73027   }
73028
73029   if( rc==SQLITE_OK ){
73030     rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes);
73031   }
73032
73033 end_of_vacuum:
73034   /* Restore the original value of db->flags */
73035   db->flags = saved_flags;
73036   db->nChange = saved_nChange;
73037   db->nTotalChange = saved_nTotalChange;
73038
73039   /* Currently there is an SQL level transaction open on the vacuum
73040   ** database. No locks are held on any other files (since the main file
73041   ** was committed at the btree level). So it safe to end the transaction
73042   ** by manually setting the autoCommit flag to true and detaching the
73043   ** vacuum database. The vacuum_db journal file is deleted when the pager
73044   ** is closed by the DETACH.
73045   */
73046   db->autoCommit = 1;
73047
73048   if( pDb ){
73049     sqlite3BtreeClose(pDb->pBt);
73050     pDb->pBt = 0;
73051     pDb->pSchema = 0;
73052   }
73053
73054   sqlite3ResetInternalSchema(db, 0);
73055
73056   return rc;
73057 }
73058 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
73059
73060 /************** End of vacuum.c **********************************************/
73061 /************** Begin file vtab.c ********************************************/
73062 /*
73063 ** 2006 June 10
73064 **
73065 ** The author disclaims copyright to this source code.  In place of
73066 ** a legal notice, here is a blessing:
73067 **
73068 **    May you do good and not evil.
73069 **    May you find forgiveness for yourself and forgive others.
73070 **    May you share freely, never taking more than you give.
73071 **
73072 *************************************************************************
73073 ** This file contains code used to help implement virtual tables.
73074 **
73075 ** $Id: vtab.c,v 1.74 2008/08/02 03:50:39 drh Exp $
73076 */
73077 #ifndef SQLITE_OMIT_VIRTUALTABLE
73078
73079 static int createModule(
73080   sqlite3 *db,                    /* Database in which module is registered */
73081   const char *zName,              /* Name assigned to this module */
73082   const sqlite3_module *pModule,  /* The definition of the module */
73083   void *pAux,                     /* Context pointer for xCreate/xConnect */
73084   void (*xDestroy)(void *)        /* Module destructor function */
73085 ) {
73086   int rc, nName;
73087   Module *pMod;
73088
73089   sqlite3_mutex_enter(db->mutex);
73090   nName = strlen(zName);
73091   pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
73092   if( pMod ){
73093     Module *pDel;
73094     char *zCopy = (char *)(&pMod[1]);
73095     memcpy(zCopy, zName, nName+1);
73096     pMod->zName = zCopy;
73097     pMod->pModule = pModule;
73098     pMod->pAux = pAux;
73099     pMod->xDestroy = xDestroy;
73100     pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
73101     if( pDel && pDel->xDestroy ){
73102       pDel->xDestroy(pDel->pAux);
73103     }
73104     sqlite3DbFree(db, pDel);
73105     if( pDel==pMod ){
73106       db->mallocFailed = 1;
73107     }
73108     sqlite3ResetInternalSchema(db, 0);
73109   }
73110   rc = sqlite3ApiExit(db, SQLITE_OK);
73111   sqlite3_mutex_leave(db->mutex);
73112   return rc;
73113 }
73114
73115
73116 /*
73117 ** External API function used to create a new virtual-table module.
73118 */
73119 SQLITE_API int sqlite3_create_module(
73120   sqlite3 *db,                    /* Database in which module is registered */
73121   const char *zName,              /* Name assigned to this module */
73122   const sqlite3_module *pModule,  /* The definition of the module */
73123   void *pAux                      /* Context pointer for xCreate/xConnect */
73124 ){
73125   return createModule(db, zName, pModule, pAux, 0);
73126 }
73127
73128 /*
73129 ** External API function used to create a new virtual-table module.
73130 */
73131 SQLITE_API int sqlite3_create_module_v2(
73132   sqlite3 *db,                    /* Database in which module is registered */
73133   const char *zName,              /* Name assigned to this module */
73134   const sqlite3_module *pModule,  /* The definition of the module */
73135   void *pAux,                     /* Context pointer for xCreate/xConnect */
73136   void (*xDestroy)(void *)        /* Module destructor function */
73137 ){
73138   return createModule(db, zName, pModule, pAux, xDestroy);
73139 }
73140
73141 /*
73142 ** Lock the virtual table so that it cannot be disconnected.
73143 ** Locks nest.  Every lock should have a corresponding unlock.
73144 ** If an unlock is omitted, resources leaks will occur.  
73145 **
73146 ** If a disconnect is attempted while a virtual table is locked,
73147 ** the disconnect is deferred until all locks have been removed.
73148 */
73149 SQLITE_PRIVATE void sqlite3VtabLock(sqlite3_vtab *pVtab){
73150   pVtab->nRef++;
73151 }
73152
73153 /*
73154 ** Unlock a virtual table.  When the last lock is removed,
73155 ** disconnect the virtual table.
73156 */
73157 SQLITE_PRIVATE void sqlite3VtabUnlock(sqlite3 *db, sqlite3_vtab *pVtab){
73158   pVtab->nRef--;
73159   assert(db);
73160   assert( sqlite3SafetyCheckOk(db) );
73161   if( pVtab->nRef==0 ){
73162     if( db->magic==SQLITE_MAGIC_BUSY ){
73163       (void)sqlite3SafetyOff(db);
73164       pVtab->pModule->xDisconnect(pVtab);
73165       (void)sqlite3SafetyOn(db);
73166     } else {
73167       pVtab->pModule->xDisconnect(pVtab);
73168     }
73169   }
73170 }
73171
73172 /*
73173 ** Clear any and all virtual-table information from the Table record.
73174 ** This routine is called, for example, just before deleting the Table
73175 ** record.
73176 */
73177 SQLITE_PRIVATE void sqlite3VtabClear(Table *p){
73178   sqlite3_vtab *pVtab = p->pVtab;
73179   sqlite3 *db = p->db;
73180   if( pVtab ){
73181     assert( p->pMod && p->pMod->pModule );
73182     sqlite3VtabUnlock(db, pVtab);
73183     p->pVtab = 0;
73184   }
73185   if( p->azModuleArg ){
73186     int i;
73187     for(i=0; i<p->nModuleArg; i++){
73188       sqlite3DbFree(db, p->azModuleArg[i]);
73189     }
73190     sqlite3DbFree(db, p->azModuleArg);
73191   }
73192 }
73193
73194 /*
73195 ** Add a new module argument to pTable->azModuleArg[].
73196 ** The string is not copied - the pointer is stored.  The
73197 ** string will be freed automatically when the table is
73198 ** deleted.
73199 */
73200 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
73201   int i = pTable->nModuleArg++;
73202   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
73203   char **azModuleArg;
73204   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
73205   if( azModuleArg==0 ){
73206     int j;
73207     for(j=0; j<i; j++){
73208       sqlite3DbFree(db, pTable->azModuleArg[j]);
73209     }
73210     sqlite3DbFree(db, zArg);
73211     sqlite3DbFree(db, pTable->azModuleArg);
73212     pTable->nModuleArg = 0;
73213   }else{
73214     azModuleArg[i] = zArg;
73215     azModuleArg[i+1] = 0;
73216   }
73217   pTable->azModuleArg = azModuleArg;
73218 }
73219
73220 /*
73221 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
73222 ** statement.  The module name has been parsed, but the optional list
73223 ** of parameters that follow the module name are still pending.
73224 */
73225 SQLITE_PRIVATE void sqlite3VtabBeginParse(
73226   Parse *pParse,        /* Parsing context */
73227   Token *pName1,        /* Name of new table, or database name */
73228   Token *pName2,        /* Name of new table or NULL */
73229   Token *pModuleName    /* Name of the module for the virtual table */
73230 ){
73231   int iDb;              /* The database the table is being created in */
73232   Table *pTable;        /* The new virtual table */
73233   sqlite3 *db;          /* Database connection */
73234
73235   if( pParse->db->flags & SQLITE_SharedCache ){
73236     sqlite3ErrorMsg(pParse, "Cannot use virtual tables in shared-cache mode");
73237     return;
73238   }
73239
73240   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
73241   pTable = pParse->pNewTable;
73242   if( pTable==0 || pParse->nErr ) return;
73243   assert( 0==pTable->pIndex );
73244
73245   db = pParse->db;
73246   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
73247   assert( iDb>=0 );
73248
73249   pTable->isVirtual = 1;
73250   pTable->nModuleArg = 0;
73251   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
73252   addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
73253   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
73254   pParse->sNameToken.n = pModuleName->z + pModuleName->n - pName1->z;
73255
73256 #ifndef SQLITE_OMIT_AUTHORIZATION
73257   /* Creating a virtual table invokes the authorization callback twice.
73258   ** The first invocation, to obtain permission to INSERT a row into the
73259   ** sqlite_master table, has already been made by sqlite3StartTable().
73260   ** The second call, to obtain permission to create the table, is made now.
73261   */
73262   if( pTable->azModuleArg ){
73263     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
73264             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
73265   }
73266 #endif
73267 }
73268
73269 /*
73270 ** This routine takes the module argument that has been accumulating
73271 ** in pParse->zArg[] and appends it to the list of arguments on the
73272 ** virtual table currently under construction in pParse->pTable.
73273 */
73274 static void addArgumentToVtab(Parse *pParse){
73275   if( pParse->sArg.z && pParse->pNewTable ){
73276     const char *z = (const char*)pParse->sArg.z;
73277     int n = pParse->sArg.n;
73278     sqlite3 *db = pParse->db;
73279     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
73280   }
73281 }
73282
73283 /*
73284 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
73285 ** has been completely parsed.
73286 */
73287 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
73288   Table *pTab;        /* The table being constructed */
73289   sqlite3 *db;        /* The database connection */
73290   char *zModule;      /* The module name of the table: USING modulename */
73291   Module *pMod = 0;
73292
73293   addArgumentToVtab(pParse);
73294   pParse->sArg.z = 0;
73295
73296   /* Lookup the module name. */
73297   pTab = pParse->pNewTable;
73298   if( pTab==0 ) return;
73299   db = pParse->db;
73300   if( pTab->nModuleArg<1 ) return;
73301   zModule = pTab->azModuleArg[0];
73302   pMod = (Module *)sqlite3HashFind(&db->aModule, zModule, strlen(zModule));
73303   pTab->pMod = pMod;
73304   
73305   /* If the CREATE VIRTUAL TABLE statement is being entered for the
73306   ** first time (in other words if the virtual table is actually being
73307   ** created now instead of just being read out of sqlite_master) then
73308   ** do additional initialization work and store the statement text
73309   ** in the sqlite_master table.
73310   */
73311   if( !db->init.busy ){
73312     char *zStmt;
73313     char *zWhere;
73314     int iDb;
73315     Vdbe *v;
73316
73317     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
73318     if( pEnd ){
73319       pParse->sNameToken.n = pEnd->z - pParse->sNameToken.z + pEnd->n;
73320     }
73321     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
73322
73323     /* A slot for the record has already been allocated in the 
73324     ** SQLITE_MASTER table.  We just need to update that slot with all
73325     ** the information we've collected.  
73326     **
73327     ** The VM register number pParse->regRowid holds the rowid of an
73328     ** entry in the sqlite_master table tht was created for this vtab
73329     ** by sqlite3StartTable().
73330     */
73331     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
73332     sqlite3NestedParse(pParse,
73333       "UPDATE %Q.%s "
73334          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
73335        "WHERE rowid=#%d",
73336       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
73337       pTab->zName,
73338       pTab->zName,
73339       zStmt,
73340       pParse->regRowid
73341     );
73342     sqlite3DbFree(db, zStmt);
73343     v = sqlite3GetVdbe(pParse);
73344     sqlite3ChangeCookie(pParse, iDb);
73345
73346     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
73347     zWhere = sqlite3MPrintf(db, "name='%q'", pTab->zName);
73348     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 1, 0, zWhere, P4_DYNAMIC);
73349     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, 
73350                          pTab->zName, strlen(pTab->zName) + 1);
73351   }
73352
73353   /* If we are rereading the sqlite_master table create the in-memory
73354   ** record of the table. If the module has already been registered,
73355   ** also call the xConnect method here.
73356   */
73357   else {
73358     Table *pOld;
73359     Schema *pSchema = pTab->pSchema;
73360     const char *zName = pTab->zName;
73361     int nName = strlen(zName) + 1;
73362     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
73363     if( pOld ){
73364       db->mallocFailed = 1;
73365       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
73366       return;
73367     }
73368     pSchema->db = pParse->db;
73369     pParse->pNewTable = 0;
73370   }
73371 }
73372
73373 /*
73374 ** The parser calls this routine when it sees the first token
73375 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
73376 */
73377 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
73378   addArgumentToVtab(pParse);
73379   pParse->sArg.z = 0;
73380   pParse->sArg.n = 0;
73381 }
73382
73383 /*
73384 ** The parser calls this routine for each token after the first token
73385 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
73386 */
73387 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
73388   Token *pArg = &pParse->sArg;
73389   if( pArg->z==0 ){
73390     pArg->z = p->z;
73391     pArg->n = p->n;
73392   }else{
73393     assert(pArg->z < p->z);
73394     pArg->n = (p->z + p->n - pArg->z);
73395   }
73396 }
73397
73398 /*
73399 ** Invoke a virtual table constructor (either xCreate or xConnect). The
73400 ** pointer to the function to invoke is passed as the fourth parameter
73401 ** to this procedure.
73402 */
73403 static int vtabCallConstructor(
73404   sqlite3 *db, 
73405   Table *pTab,
73406   Module *pMod,
73407   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
73408   char **pzErr
73409 ){
73410   int rc;
73411   int rc2;
73412   sqlite3_vtab *pVtab = 0;
73413   const char *const*azArg = (const char *const*)pTab->azModuleArg;
73414   int nArg = pTab->nModuleArg;
73415   char *zErr = 0;
73416   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
73417
73418   if( !zModuleName ){
73419     return SQLITE_NOMEM;
73420   }
73421
73422   assert( !db->pVTab );
73423   assert( xConstruct );
73424
73425   db->pVTab = pTab;
73426   rc = sqlite3SafetyOff(db);
73427   assert( rc==SQLITE_OK );
73428   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVtab, &zErr);
73429   rc2 = sqlite3SafetyOn(db);
73430   if( rc==SQLITE_OK && pVtab ){
73431     pVtab->pModule = pMod->pModule;
73432     pVtab->nRef = 1;
73433     pTab->pVtab = pVtab;
73434   }
73435
73436   if( SQLITE_OK!=rc ){
73437     if( zErr==0 ){
73438       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
73439     }else {
73440       *pzErr = sqlite3MPrintf(db, "%s", zErr);
73441       sqlite3DbFree(db, zErr);
73442     }
73443   }else if( db->pVTab ){
73444     const char *zFormat = "vtable constructor did not declare schema: %s";
73445     *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
73446     rc = SQLITE_ERROR;
73447   } 
73448   if( rc==SQLITE_OK ){
73449     rc = rc2;
73450   }
73451   db->pVTab = 0;
73452   sqlite3DbFree(db, zModuleName);
73453
73454   /* If everything went according to plan, loop through the columns
73455   ** of the table to see if any of them contain the token "hidden".
73456   ** If so, set the Column.isHidden flag and remove the token from
73457   ** the type string.
73458   */
73459   if( rc==SQLITE_OK ){
73460     int iCol;
73461     for(iCol=0; iCol<pTab->nCol; iCol++){
73462       char *zType = pTab->aCol[iCol].zType;
73463       int nType;
73464       int i = 0;
73465       if( !zType ) continue;
73466       nType = strlen(zType);
73467       if( sqlite3StrNICmp("hidden", zType, 6) || (zType[6] && zType[6]!=' ') ){
73468         for(i=0; i<nType; i++){
73469           if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
73470            && (zType[i+7]=='\0' || zType[i+7]==' ')
73471           ){
73472             i++;
73473             break;
73474           }
73475         }
73476       }
73477       if( i<nType ){
73478         int j;
73479         int nDel = 6 + (zType[i+6] ? 1 : 0);
73480         for(j=i; (j+nDel)<=nType; j++){
73481           zType[j] = zType[j+nDel];
73482         }
73483         if( zType[i]=='\0' && i>0 ){
73484           assert(zType[i-1]==' ');
73485           zType[i-1] = '\0';
73486         }
73487         pTab->aCol[iCol].isHidden = 1;
73488       }
73489     }
73490   }
73491   return rc;
73492 }
73493
73494 /*
73495 ** This function is invoked by the parser to call the xConnect() method
73496 ** of the virtual table pTab. If an error occurs, an error code is returned 
73497 ** and an error left in pParse.
73498 **
73499 ** This call is a no-op if table pTab is not a virtual table.
73500 */
73501 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
73502   Module *pMod;
73503   int rc = SQLITE_OK;
73504
73505   if( !pTab || !pTab->isVirtual || pTab->pVtab ){
73506     return SQLITE_OK;
73507   }
73508
73509   pMod = pTab->pMod;
73510   if( !pMod ){
73511     const char *zModule = pTab->azModuleArg[0];
73512     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
73513     rc = SQLITE_ERROR;
73514   } else {
73515     char *zErr = 0;
73516     sqlite3 *db = pParse->db;
73517     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
73518     if( rc!=SQLITE_OK ){
73519       sqlite3ErrorMsg(pParse, "%s", zErr);
73520     }
73521     sqlite3DbFree(db, zErr);
73522   }
73523
73524   return rc;
73525 }
73526
73527 /*
73528 ** Add the virtual table pVtab to the array sqlite3.aVTrans[].
73529 */
73530 static int addToVTrans(sqlite3 *db, sqlite3_vtab *pVtab){
73531   const int ARRAY_INCR = 5;
73532
73533   /* Grow the sqlite3.aVTrans array if required */
73534   if( (db->nVTrans%ARRAY_INCR)==0 ){
73535     sqlite3_vtab **aVTrans;
73536     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
73537     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
73538     if( !aVTrans ){
73539       return SQLITE_NOMEM;
73540     }
73541     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
73542     db->aVTrans = aVTrans;
73543   }
73544
73545   /* Add pVtab to the end of sqlite3.aVTrans */
73546   db->aVTrans[db->nVTrans++] = pVtab;
73547   sqlite3VtabLock(pVtab);
73548   return SQLITE_OK;
73549 }
73550
73551 /*
73552 ** This function is invoked by the vdbe to call the xCreate method
73553 ** of the virtual table named zTab in database iDb. 
73554 **
73555 ** If an error occurs, *pzErr is set to point an an English language
73556 ** description of the error and an SQLITE_XXX error code is returned.
73557 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
73558 */
73559 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
73560   int rc = SQLITE_OK;
73561   Table *pTab;
73562   Module *pMod;
73563   const char *zModule;
73564
73565   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
73566   assert(pTab && pTab->isVirtual && !pTab->pVtab);
73567   pMod = pTab->pMod;
73568   zModule = pTab->azModuleArg[0];
73569
73570   /* If the module has been registered and includes a Create method, 
73571   ** invoke it now. If the module has not been registered, return an 
73572   ** error. Otherwise, do nothing.
73573   */
73574   if( !pMod ){
73575     *pzErr = sqlite3MPrintf(db, "no such module: %s", zModule);
73576     rc = SQLITE_ERROR;
73577   }else{
73578     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
73579   }
73580
73581   if( rc==SQLITE_OK && pTab->pVtab ){
73582       rc = addToVTrans(db, pTab->pVtab);
73583   }
73584
73585   return rc;
73586 }
73587
73588 /*
73589 ** This function is used to set the schema of a virtual table.  It is only
73590 ** valid to call this function from within the xCreate() or xConnect() of a
73591 ** virtual table module.
73592 */
73593 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
73594   Parse sParse;
73595
73596   int rc = SQLITE_OK;
73597   Table *pTab;
73598   char *zErr = 0;
73599
73600   sqlite3_mutex_enter(db->mutex);
73601   pTab = db->pVTab;
73602   if( !pTab ){
73603     sqlite3Error(db, SQLITE_MISUSE, 0);
73604     sqlite3_mutex_leave(db->mutex);
73605     return SQLITE_MISUSE;
73606   }
73607   assert(pTab->isVirtual && pTab->nCol==0 && pTab->aCol==0);
73608
73609   memset(&sParse, 0, sizeof(Parse));
73610   sParse.declareVtab = 1;
73611   sParse.db = db;
73612
73613   if( 
73614       SQLITE_OK == sqlite3RunParser(&sParse, zCreateTable, &zErr) && 
73615       sParse.pNewTable && 
73616       !sParse.pNewTable->pSelect && 
73617       !sParse.pNewTable->isVirtual 
73618   ){
73619     pTab->aCol = sParse.pNewTable->aCol;
73620     pTab->nCol = sParse.pNewTable->nCol;
73621     sParse.pNewTable->nCol = 0;
73622     sParse.pNewTable->aCol = 0;
73623     db->pVTab = 0;
73624   } else {
73625     sqlite3Error(db, SQLITE_ERROR, zErr);
73626     sqlite3DbFree(db, zErr);
73627     rc = SQLITE_ERROR;
73628   }
73629   sParse.declareVtab = 0;
73630
73631   sqlite3_finalize((sqlite3_stmt*)sParse.pVdbe);
73632   sqlite3DeleteTable(sParse.pNewTable);
73633   sParse.pNewTable = 0;
73634
73635   assert( (rc&0xff)==rc );
73636   rc = sqlite3ApiExit(db, rc);
73637   sqlite3_mutex_leave(db->mutex);
73638   return rc;
73639 }
73640
73641 /*
73642 ** This function is invoked by the vdbe to call the xDestroy method
73643 ** of the virtual table named zTab in database iDb. This occurs
73644 ** when a DROP TABLE is mentioned.
73645 **
73646 ** This call is a no-op if zTab is not a virtual table.
73647 */
73648 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab)
73649 {
73650   int rc = SQLITE_OK;
73651   Table *pTab;
73652
73653   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
73654   assert(pTab);
73655   if( pTab->pVtab ){
73656     int (*xDestroy)(sqlite3_vtab *pVTab) = pTab->pMod->pModule->xDestroy;
73657     rc = sqlite3SafetyOff(db);
73658     assert( rc==SQLITE_OK );
73659     if( xDestroy ){
73660       rc = xDestroy(pTab->pVtab);
73661     }
73662     (void)sqlite3SafetyOn(db);
73663     if( rc==SQLITE_OK ){
73664       int i;
73665       for(i=0; i<db->nVTrans; i++){
73666         if( db->aVTrans[i]==pTab->pVtab ){
73667           db->aVTrans[i] = db->aVTrans[--db->nVTrans];
73668           break;
73669         }
73670       }
73671       pTab->pVtab = 0;
73672     }
73673   }
73674
73675   return rc;
73676 }
73677
73678 /*
73679 ** This function invokes either the xRollback or xCommit method
73680 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
73681 ** called is identified by the second argument, "offset", which is
73682 ** the offset of the method to call in the sqlite3_module structure.
73683 **
73684 ** The array is cleared after invoking the callbacks. 
73685 */
73686 static void callFinaliser(sqlite3 *db, int offset){
73687   int i;
73688   if( db->aVTrans ){
73689     for(i=0; i<db->nVTrans && db->aVTrans[i]; i++){
73690       sqlite3_vtab *pVtab = db->aVTrans[i];
73691       int (*x)(sqlite3_vtab *);
73692       x = *(int (**)(sqlite3_vtab *))((char *)pVtab->pModule + offset);
73693       if( x ) x(pVtab);
73694       sqlite3VtabUnlock(db, pVtab);
73695     }
73696     sqlite3DbFree(db, db->aVTrans);
73697     db->nVTrans = 0;
73698     db->aVTrans = 0;
73699   }
73700 }
73701
73702 /*
73703 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
73704 ** array. Return the error code for the first error that occurs, or
73705 ** SQLITE_OK if all xSync operations are successful.
73706 **
73707 ** Set *pzErrmsg to point to a buffer that should be released using 
73708 ** sqlite3DbFree() containing an error message, if one is available.
73709 */
73710 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
73711   int i;
73712   int rc = SQLITE_OK;
73713   int rcsafety;
73714   sqlite3_vtab **aVTrans = db->aVTrans;
73715
73716   rc = sqlite3SafetyOff(db);
73717   db->aVTrans = 0;
73718   for(i=0; rc==SQLITE_OK && i<db->nVTrans && aVTrans[i]; i++){
73719     sqlite3_vtab *pVtab = aVTrans[i];
73720     int (*x)(sqlite3_vtab *);
73721     x = pVtab->pModule->xSync;
73722     if( x ){
73723       rc = x(pVtab);
73724       sqlite3DbFree(db, *pzErrmsg);
73725       *pzErrmsg = pVtab->zErrMsg;
73726       pVtab->zErrMsg = 0;
73727     }
73728   }
73729   db->aVTrans = aVTrans;
73730   rcsafety = sqlite3SafetyOn(db);
73731
73732   if( rc==SQLITE_OK ){
73733     rc = rcsafety;
73734   }
73735   return rc;
73736 }
73737
73738 /*
73739 ** Invoke the xRollback method of all virtual tables in the 
73740 ** sqlite3.aVTrans array. Then clear the array itself.
73741 */
73742 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
73743   callFinaliser(db, offsetof(sqlite3_module,xRollback));
73744   return SQLITE_OK;
73745 }
73746
73747 /*
73748 ** Invoke the xCommit method of all virtual tables in the 
73749 ** sqlite3.aVTrans array. Then clear the array itself.
73750 */
73751 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
73752   callFinaliser(db, offsetof(sqlite3_module,xCommit));
73753   return SQLITE_OK;
73754 }
73755
73756 /*
73757 ** If the virtual table pVtab supports the transaction interface
73758 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
73759 ** not currently open, invoke the xBegin method now.
73760 **
73761 ** If the xBegin call is successful, place the sqlite3_vtab pointer
73762 ** in the sqlite3.aVTrans array.
73763 */
73764 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, sqlite3_vtab *pVtab){
73765   int rc = SQLITE_OK;
73766   const sqlite3_module *pModule;
73767
73768   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
73769   ** than zero, then this function is being called from within a
73770   ** virtual module xSync() callback. It is illegal to write to 
73771   ** virtual module tables in this case, so return SQLITE_LOCKED.
73772   */
73773   if( 0==db->aVTrans && db->nVTrans>0 ){
73774     return SQLITE_LOCKED;
73775   }
73776   if( !pVtab ){
73777     return SQLITE_OK;
73778   } 
73779   pModule = pVtab->pModule;
73780
73781   if( pModule->xBegin ){
73782     int i;
73783
73784
73785     /* If pVtab is already in the aVTrans array, return early */
73786     for(i=0; (i<db->nVTrans) && 0!=db->aVTrans[i]; i++){
73787       if( db->aVTrans[i]==pVtab ){
73788         return SQLITE_OK;
73789       }
73790     }
73791
73792     /* Invoke the xBegin method */
73793     rc = pModule->xBegin(pVtab);
73794     if( rc==SQLITE_OK ){
73795       rc = addToVTrans(db, pVtab);
73796     }
73797   }
73798   return rc;
73799 }
73800
73801 /*
73802 ** The first parameter (pDef) is a function implementation.  The
73803 ** second parameter (pExpr) is the first argument to this function.
73804 ** If pExpr is a column in a virtual table, then let the virtual
73805 ** table implementation have an opportunity to overload the function.
73806 **
73807 ** This routine is used to allow virtual table implementations to
73808 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
73809 **
73810 ** Return either the pDef argument (indicating no change) or a 
73811 ** new FuncDef structure that is marked as ephemeral using the
73812 ** SQLITE_FUNC_EPHEM flag.
73813 */
73814 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
73815   sqlite3 *db,    /* Database connection for reporting malloc problems */
73816   FuncDef *pDef,  /* Function to possibly overload */
73817   int nArg,       /* Number of arguments to the function */
73818   Expr *pExpr     /* First argument to the function */
73819 ){
73820   Table *pTab;
73821   sqlite3_vtab *pVtab;
73822   sqlite3_module *pMod;
73823   void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
73824   void *pArg;
73825   FuncDef *pNew;
73826   int rc = 0;
73827   char *zLowerName;
73828   unsigned char *z;
73829
73830
73831   /* Check to see the left operand is a column in a virtual table */
73832   if( pExpr==0 ) return pDef;
73833   if( pExpr->op!=TK_COLUMN ) return pDef;
73834   pTab = pExpr->pTab;
73835   if( pTab==0 ) return pDef;
73836   if( !pTab->isVirtual ) return pDef;
73837   pVtab = pTab->pVtab;
73838   assert( pVtab!=0 );
73839   assert( pVtab->pModule!=0 );
73840   pMod = (sqlite3_module *)pVtab->pModule;
73841   if( pMod->xFindFunction==0 ) return pDef;
73842  
73843   /* Call the xFindFunction method on the virtual table implementation
73844   ** to see if the implementation wants to overload this function 
73845   */
73846   zLowerName = sqlite3DbStrDup(db, pDef->zName);
73847   if( zLowerName ){
73848     for(z=(unsigned char*)zLowerName; *z; z++){
73849       *z = sqlite3UpperToLower[*z];
73850     }
73851     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
73852     sqlite3DbFree(db, zLowerName);
73853     if( pVtab->zErrMsg ){
73854       sqlite3Error(db, rc, "%s", pVtab->zErrMsg);
73855       sqlite3DbFree(db, pVtab->zErrMsg);
73856       pVtab->zErrMsg = 0;
73857     }
73858   }
73859   if( rc==0 ){
73860     return pDef;
73861   }
73862
73863   /* Create a new ephemeral function definition for the overloaded
73864   ** function */
73865   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) + strlen(pDef->zName) );
73866   if( pNew==0 ){
73867     return pDef;
73868   }
73869   *pNew = *pDef;
73870   memcpy(pNew->zName, pDef->zName, strlen(pDef->zName)+1);
73871   pNew->xFunc = xFunc;
73872   pNew->pUserData = pArg;
73873   pNew->flags |= SQLITE_FUNC_EPHEM;
73874   return pNew;
73875 }
73876
73877 /*
73878 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
73879 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
73880 ** array if it is missing.  If pTab is already in the array, this routine
73881 ** is a no-op.
73882 */
73883 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
73884   int i, n;
73885   assert( IsVirtual(pTab) );
73886   for(i=0; i<pParse->nVtabLock; i++){
73887     if( pTab==pParse->apVtabLock[i] ) return;
73888   }
73889   n = (pParse->nVtabLock+1)*sizeof(pParse->apVtabLock[0]);
73890   pParse->apVtabLock = sqlite3_realloc(pParse->apVtabLock, n);
73891   if( pParse->apVtabLock ){
73892     pParse->apVtabLock[pParse->nVtabLock++] = pTab;
73893   }else{
73894     pParse->db->mallocFailed = 1;
73895   }
73896 }
73897
73898 #endif /* SQLITE_OMIT_VIRTUALTABLE */
73899
73900 /************** End of vtab.c ************************************************/
73901 /************** Begin file where.c *******************************************/
73902 /*
73903 ** 2001 September 15
73904 **
73905 ** The author disclaims copyright to this source code.  In place of
73906 ** a legal notice, here is a blessing:
73907 **
73908 **    May you do good and not evil.
73909 **    May you find forgiveness for yourself and forgive others.
73910 **    May you share freely, never taking more than you give.
73911 **
73912 *************************************************************************
73913 ** This module contains C code that generates VDBE code used to process
73914 ** the WHERE clause of SQL statements.  This module is responsible for
73915 ** generating the code that loops through a table looking for applicable
73916 ** rows.  Indices are selected and used to speed the search when doing
73917 ** so is applicable.  Because this module is responsible for selecting
73918 ** indices, you might also think of this module as the "query optimizer".
73919 **
73920 ** $Id: where.c,v 1.319 2008/08/01 17:37:41 danielk1977 Exp $
73921 */
73922
73923 /*
73924 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
73925 */
73926 #define BMS  (sizeof(Bitmask)*8)
73927
73928 /*
73929 ** Trace output macros
73930 */
73931 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
73932 SQLITE_PRIVATE int sqlite3WhereTrace = 0;
73933 #endif
73934 #if 0
73935 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
73936 #else
73937 # define WHERETRACE(X)
73938 #endif
73939
73940 /* Forward reference
73941 */
73942 typedef struct WhereClause WhereClause;
73943 typedef struct ExprMaskSet ExprMaskSet;
73944
73945 /*
73946 ** The query generator uses an array of instances of this structure to
73947 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
73948 ** clause subexpression is separated from the others by an AND operator.
73949 **
73950 ** All WhereTerms are collected into a single WhereClause structure.  
73951 ** The following identity holds:
73952 **
73953 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
73954 **
73955 ** When a term is of the form:
73956 **
73957 **              X <op> <expr>
73958 **
73959 ** where X is a column name and <op> is one of certain operators,
73960 ** then WhereTerm.leftCursor and WhereTerm.leftColumn record the
73961 ** cursor number and column number for X.  WhereTerm.operator records
73962 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
73963 ** use of a bitmask encoding for the operator allows us to search
73964 ** quickly for terms that match any of several different operators.
73965 **
73966 ** prereqRight and prereqAll record sets of cursor numbers,
73967 ** but they do so indirectly.  A single ExprMaskSet structure translates
73968 ** cursor number into bits and the translated bit is stored in the prereq
73969 ** fields.  The translation is used in order to maximize the number of
73970 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
73971 ** spread out over the non-negative integers.  For example, the cursor
73972 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The ExprMaskSet
73973 ** translates these sparse cursor numbers into consecutive integers
73974 ** beginning with 0 in order to make the best possible use of the available
73975 ** bits in the Bitmask.  So, in the example above, the cursor numbers
73976 ** would be mapped into integers 0 through 7.
73977 */
73978 typedef struct WhereTerm WhereTerm;
73979 struct WhereTerm {
73980   Expr *pExpr;            /* Pointer to the subexpression */
73981   i16 iParent;            /* Disable pWC->a[iParent] when this term disabled */
73982   i16 leftCursor;         /* Cursor number of X in "X <op> <expr>" */
73983   i16 leftColumn;         /* Column number of X in "X <op> <expr>" */
73984   u16 eOperator;          /* A WO_xx value describing <op> */
73985   u8 flags;               /* Bit flags.  See below */
73986   u8 nChild;              /* Number of children that must disable us */
73987   WhereClause *pWC;       /* The clause this term is part of */
73988   Bitmask prereqRight;    /* Bitmask of tables used by pRight */
73989   Bitmask prereqAll;      /* Bitmask of tables referenced by p */
73990 };
73991
73992 /*
73993 ** Allowed values of WhereTerm.flags
73994 */
73995 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
73996 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
73997 #define TERM_CODED      0x04   /* This term is already coded */
73998 #define TERM_COPIED     0x08   /* Has a child */
73999 #define TERM_OR_OK      0x10   /* Used during OR-clause processing */
74000
74001 /*
74002 ** An instance of the following structure holds all information about a
74003 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
74004 */
74005 struct WhereClause {
74006   Parse *pParse;           /* The parser context */
74007   ExprMaskSet *pMaskSet;   /* Mapping of table indices to bitmasks */
74008   int nTerm;               /* Number of terms */
74009   int nSlot;               /* Number of entries in a[] */
74010   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
74011   WhereTerm aStatic[10];   /* Initial static space for a[] */
74012 };
74013
74014 /*
74015 ** An instance of the following structure keeps track of a mapping
74016 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
74017 **
74018 ** The VDBE cursor numbers are small integers contained in 
74019 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
74020 ** clause, the cursor numbers might not begin with 0 and they might
74021 ** contain gaps in the numbering sequence.  But we want to make maximum
74022 ** use of the bits in our bitmasks.  This structure provides a mapping
74023 ** from the sparse cursor numbers into consecutive integers beginning
74024 ** with 0.
74025 **
74026 ** If ExprMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
74027 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
74028 **
74029 ** For example, if the WHERE clause expression used these VDBE
74030 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  ExprMaskSet structure
74031 ** would map those cursor numbers into bits 0 through 5.
74032 **
74033 ** Note that the mapping is not necessarily ordered.  In the example
74034 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
74035 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
74036 ** does not really matter.  What is important is that sparse cursor
74037 ** numbers all get mapped into bit numbers that begin with 0 and contain
74038 ** no gaps.
74039 */
74040 struct ExprMaskSet {
74041   int n;                        /* Number of assigned cursor values */
74042   int ix[sizeof(Bitmask)*8];    /* Cursor assigned to each bit */
74043 };
74044
74045
74046 /*
74047 ** Bitmasks for the operators that indices are able to exploit.  An
74048 ** OR-ed combination of these values can be used when searching for
74049 ** terms in the where clause.
74050 */
74051 #define WO_IN     1
74052 #define WO_EQ     2
74053 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
74054 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
74055 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
74056 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
74057 #define WO_MATCH  64
74058 #define WO_ISNULL 128
74059
74060 /*
74061 ** Value for flags returned by bestIndex().  
74062 **
74063 ** The least significant byte is reserved as a mask for WO_ values above.
74064 ** The WhereLevel.flags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
74065 ** But if the table is the right table of a left join, WhereLevel.flags
74066 ** is set to WO_IN|WO_EQ.  The WhereLevel.flags field can then be used as
74067 ** the "op" parameter to findTerm when we are resolving equality constraints.
74068 ** ISNULL constraints will then not be used on the right table of a left
74069 ** join.  Tickets #2177 and #2189.
74070 */
74071 #define WHERE_ROWID_EQ     0x000100   /* rowid=EXPR or rowid IN (...) */
74072 #define WHERE_ROWID_RANGE  0x000200   /* rowid<EXPR and/or rowid>EXPR */
74073 #define WHERE_COLUMN_EQ    0x001000   /* x=EXPR or x IN (...) */
74074 #define WHERE_COLUMN_RANGE 0x002000   /* x<EXPR and/or x>EXPR */
74075 #define WHERE_COLUMN_IN    0x004000   /* x IN (...) */
74076 #define WHERE_TOP_LIMIT    0x010000   /* x<EXPR or x<=EXPR constraint */
74077 #define WHERE_BTM_LIMIT    0x020000   /* x>EXPR or x>=EXPR constraint */
74078 #define WHERE_IDX_ONLY     0x080000   /* Use index only - omit table */
74079 #define WHERE_ORDERBY      0x100000   /* Output will appear in correct order */
74080 #define WHERE_REVERSE      0x200000   /* Scan in reverse order */
74081 #define WHERE_UNIQUE       0x400000   /* Selects no more than one row */
74082 #define WHERE_VIRTUALTABLE 0x800000   /* Use virtual-table processing */
74083
74084 /*
74085 ** Initialize a preallocated WhereClause structure.
74086 */
74087 static void whereClauseInit(
74088   WhereClause *pWC,        /* The WhereClause to be initialized */
74089   Parse *pParse,           /* The parsing context */
74090   ExprMaskSet *pMaskSet    /* Mapping from table indices to bitmasks */
74091 ){
74092   pWC->pParse = pParse;
74093   pWC->pMaskSet = pMaskSet;
74094   pWC->nTerm = 0;
74095   pWC->nSlot = ArraySize(pWC->aStatic);
74096   pWC->a = pWC->aStatic;
74097 }
74098
74099 /*
74100 ** Deallocate a WhereClause structure.  The WhereClause structure
74101 ** itself is not freed.  This routine is the inverse of whereClauseInit().
74102 */
74103 static void whereClauseClear(WhereClause *pWC){
74104   int i;
74105   WhereTerm *a;
74106   sqlite3 *db = pWC->pParse->db;
74107   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
74108     if( a->flags & TERM_DYNAMIC ){
74109       sqlite3ExprDelete(db, a->pExpr);
74110     }
74111   }
74112   if( pWC->a!=pWC->aStatic ){
74113     sqlite3DbFree(db, pWC->a);
74114   }
74115 }
74116
74117 /*
74118 ** Add a new entries to the WhereClause structure.  Increase the allocated
74119 ** space as necessary.
74120 **
74121 ** If the flags argument includes TERM_DYNAMIC, then responsibility
74122 ** for freeing the expression p is assumed by the WhereClause object.
74123 **
74124 ** WARNING:  This routine might reallocate the space used to store
74125 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
74126 ** calling this routine.  Such pointers may be reinitialized by referencing
74127 ** the pWC->a[] array.
74128 */
74129 static int whereClauseInsert(WhereClause *pWC, Expr *p, int flags){
74130   WhereTerm *pTerm;
74131   int idx;
74132   if( pWC->nTerm>=pWC->nSlot ){
74133     WhereTerm *pOld = pWC->a;
74134     sqlite3 *db = pWC->pParse->db;
74135     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
74136     if( pWC->a==0 ){
74137       if( flags & TERM_DYNAMIC ){
74138         sqlite3ExprDelete(db, p);
74139       }
74140       pWC->a = pOld;
74141       return 0;
74142     }
74143     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
74144     if( pOld!=pWC->aStatic ){
74145       sqlite3DbFree(db, pOld);
74146     }
74147     pWC->nSlot *= 2;
74148   }
74149   pTerm = &pWC->a[idx = pWC->nTerm];
74150   pWC->nTerm++;
74151   pTerm->pExpr = p;
74152   pTerm->flags = flags;
74153   pTerm->pWC = pWC;
74154   pTerm->iParent = -1;
74155   return idx;
74156 }
74157
74158 /*
74159 ** This routine identifies subexpressions in the WHERE clause where
74160 ** each subexpression is separated by the AND operator or some other
74161 ** operator specified in the op parameter.  The WhereClause structure
74162 ** is filled with pointers to subexpressions.  For example:
74163 **
74164 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
74165 **           \________/     \_______________/     \________________/
74166 **            slot[0]            slot[1]               slot[2]
74167 **
74168 ** The original WHERE clause in pExpr is unaltered.  All this routine
74169 ** does is make slot[] entries point to substructure within pExpr.
74170 **
74171 ** In the previous sentence and in the diagram, "slot[]" refers to
74172 ** the WhereClause.a[] array.  This array grows as needed to contain
74173 ** all terms of the WHERE clause.
74174 */
74175 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
74176   if( pExpr==0 ) return;
74177   if( pExpr->op!=op ){
74178     whereClauseInsert(pWC, pExpr, 0);
74179   }else{
74180     whereSplit(pWC, pExpr->pLeft, op);
74181     whereSplit(pWC, pExpr->pRight, op);
74182   }
74183 }
74184
74185 /*
74186 ** Initialize an expression mask set
74187 */
74188 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
74189
74190 /*
74191 ** Return the bitmask for the given cursor number.  Return 0 if
74192 ** iCursor is not in the set.
74193 */
74194 static Bitmask getMask(ExprMaskSet *pMaskSet, int iCursor){
74195   int i;
74196   for(i=0; i<pMaskSet->n; i++){
74197     if( pMaskSet->ix[i]==iCursor ){
74198       return ((Bitmask)1)<<i;
74199     }
74200   }
74201   return 0;
74202 }
74203
74204 /*
74205 ** Create a new mask for cursor iCursor.
74206 **
74207 ** There is one cursor per table in the FROM clause.  The number of
74208 ** tables in the FROM clause is limited by a test early in the
74209 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
74210 ** array will never overflow.
74211 */
74212 static void createMask(ExprMaskSet *pMaskSet, int iCursor){
74213   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
74214   pMaskSet->ix[pMaskSet->n++] = iCursor;
74215 }
74216
74217 /*
74218 ** This routine walks (recursively) an expression tree and generates
74219 ** a bitmask indicating which tables are used in that expression
74220 ** tree.
74221 **
74222 ** In order for this routine to work, the calling function must have
74223 ** previously invoked sqlite3ExprResolveNames() on the expression.  See
74224 ** the header comment on that routine for additional information.
74225 ** The sqlite3ExprResolveNames() routines looks for column names and
74226 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
74227 ** the VDBE cursor number of the table.  This routine just has to
74228 ** translate the cursor numbers into bitmask values and OR all
74229 ** the bitmasks together.
74230 */
74231 static Bitmask exprListTableUsage(ExprMaskSet*, ExprList*);
74232 static Bitmask exprSelectTableUsage(ExprMaskSet*, Select*);
74233 static Bitmask exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
74234   Bitmask mask = 0;
74235   if( p==0 ) return 0;
74236   if( p->op==TK_COLUMN ){
74237     mask = getMask(pMaskSet, p->iTable);
74238     return mask;
74239   }
74240   mask = exprTableUsage(pMaskSet, p->pRight);
74241   mask |= exprTableUsage(pMaskSet, p->pLeft);
74242   mask |= exprListTableUsage(pMaskSet, p->pList);
74243   mask |= exprSelectTableUsage(pMaskSet, p->pSelect);
74244   return mask;
74245 }
74246 static Bitmask exprListTableUsage(ExprMaskSet *pMaskSet, ExprList *pList){
74247   int i;
74248   Bitmask mask = 0;
74249   if( pList ){
74250     for(i=0; i<pList->nExpr; i++){
74251       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
74252     }
74253   }
74254   return mask;
74255 }
74256 static Bitmask exprSelectTableUsage(ExprMaskSet *pMaskSet, Select *pS){
74257   Bitmask mask = 0;
74258   while( pS ){
74259     mask |= exprListTableUsage(pMaskSet, pS->pEList);
74260     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
74261     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
74262     mask |= exprTableUsage(pMaskSet, pS->pWhere);
74263     mask |= exprTableUsage(pMaskSet, pS->pHaving);
74264     pS = pS->pPrior;
74265   }
74266   return mask;
74267 }
74268
74269 /*
74270 ** Return TRUE if the given operator is one of the operators that is
74271 ** allowed for an indexable WHERE clause term.  The allowed operators are
74272 ** "=", "<", ">", "<=", ">=", and "IN".
74273 */
74274 static int allowedOp(int op){
74275   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
74276   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
74277   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
74278   assert( TK_GE==TK_EQ+4 );
74279   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
74280 }
74281
74282 /*
74283 ** Swap two objects of type T.
74284 */
74285 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
74286
74287 /*
74288 ** Commute a comparison operator.  Expressions of the form "X op Y"
74289 ** are converted into "Y op X".
74290 **
74291 ** If a collation sequence is associated with either the left or right
74292 ** side of the comparison, it remains associated with the same side after
74293 ** the commutation. So "Y collate NOCASE op X" becomes 
74294 ** "X collate NOCASE op Y". This is because any collation sequence on
74295 ** the left hand side of a comparison overrides any collation sequence 
74296 ** attached to the right. For the same reason the EP_ExpCollate flag
74297 ** is not commuted.
74298 */
74299 static void exprCommute(Expr *pExpr){
74300   u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
74301   u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
74302   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
74303   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
74304   pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
74305   pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
74306   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
74307   if( pExpr->op>=TK_GT ){
74308     assert( TK_LT==TK_GT+2 );
74309     assert( TK_GE==TK_LE+2 );
74310     assert( TK_GT>TK_EQ );
74311     assert( TK_GT<TK_LE );
74312     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
74313     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
74314   }
74315 }
74316
74317 /*
74318 ** Translate from TK_xx operator to WO_xx bitmask.
74319 */
74320 static int operatorMask(int op){
74321   int c;
74322   assert( allowedOp(op) );
74323   if( op==TK_IN ){
74324     c = WO_IN;
74325   }else if( op==TK_ISNULL ){
74326     c = WO_ISNULL;
74327   }else{
74328     c = WO_EQ<<(op-TK_EQ);
74329   }
74330   assert( op!=TK_ISNULL || c==WO_ISNULL );
74331   assert( op!=TK_IN || c==WO_IN );
74332   assert( op!=TK_EQ || c==WO_EQ );
74333   assert( op!=TK_LT || c==WO_LT );
74334   assert( op!=TK_LE || c==WO_LE );
74335   assert( op!=TK_GT || c==WO_GT );
74336   assert( op!=TK_GE || c==WO_GE );
74337   return c;
74338 }
74339
74340 /*
74341 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
74342 ** where X is a reference to the iColumn of table iCur and <op> is one of
74343 ** the WO_xx operator codes specified by the op parameter.
74344 ** Return a pointer to the term.  Return 0 if not found.
74345 */
74346 static WhereTerm *findTerm(
74347   WhereClause *pWC,     /* The WHERE clause to be searched */
74348   int iCur,             /* Cursor number of LHS */
74349   int iColumn,          /* Column number of LHS */
74350   Bitmask notReady,     /* RHS must not overlap with this mask */
74351   u16 op,               /* Mask of WO_xx values describing operator */
74352   Index *pIdx           /* Must be compatible with this index, if not NULL */
74353 ){
74354   WhereTerm *pTerm;
74355   int k;
74356   assert( iCur>=0 );
74357   for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
74358     if( pTerm->leftCursor==iCur
74359        && (pTerm->prereqRight & notReady)==0
74360        && pTerm->leftColumn==iColumn
74361        && (pTerm->eOperator & op)!=0
74362     ){
74363       if( pIdx && pTerm->eOperator!=WO_ISNULL ){
74364         Expr *pX = pTerm->pExpr;
74365         CollSeq *pColl;
74366         char idxaff;
74367         int j;
74368         Parse *pParse = pWC->pParse;
74369
74370         idxaff = pIdx->pTable->aCol[iColumn].affinity;
74371         if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
74372
74373         /* Figure out the collation sequence required from an index for
74374         ** it to be useful for optimising expression pX. Store this
74375         ** value in variable pColl.
74376         */
74377         assert(pX->pLeft);
74378         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
74379         if( !pColl ){
74380           pColl = pParse->db->pDfltColl;
74381         }
74382
74383         for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
74384           if( NEVER(j>=pIdx->nColumn) ) return 0;
74385         }
74386         if( sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
74387       }
74388       return pTerm;
74389     }
74390   }
74391   return 0;
74392 }
74393
74394 /* Forward reference */
74395 static void exprAnalyze(SrcList*, WhereClause*, int);
74396
74397 /*
74398 ** Call exprAnalyze on all terms in a WHERE clause.  
74399 **
74400 **
74401 */
74402 static void exprAnalyzeAll(
74403   SrcList *pTabList,       /* the FROM clause */
74404   WhereClause *pWC         /* the WHERE clause to be analyzed */
74405 ){
74406   int i;
74407   for(i=pWC->nTerm-1; i>=0; i--){
74408     exprAnalyze(pTabList, pWC, i);
74409   }
74410 }
74411
74412 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
74413 /*
74414 ** Check to see if the given expression is a LIKE or GLOB operator that
74415 ** can be optimized using inequality constraints.  Return TRUE if it is
74416 ** so and false if not.
74417 **
74418 ** In order for the operator to be optimizible, the RHS must be a string
74419 ** literal that does not begin with a wildcard.  
74420 */
74421 static int isLikeOrGlob(
74422   sqlite3 *db,      /* The database */
74423   Expr *pExpr,      /* Test this expression */
74424   int *pnPattern,   /* Number of non-wildcard prefix characters */
74425   int *pisComplete, /* True if the only wildcard is % in the last character */
74426   int *pnoCase      /* True if uppercase is equivalent to lowercase */
74427 ){
74428   const char *z;
74429   Expr *pRight, *pLeft;
74430   ExprList *pList;
74431   int c, cnt;
74432   char wc[3];
74433   CollSeq *pColl;
74434
74435   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
74436     return 0;
74437   }
74438 #ifdef SQLITE_EBCDIC
74439   if( *pnoCase ) return 0;
74440 #endif
74441   pList = pExpr->pList;
74442   pRight = pList->a[0].pExpr;
74443   if( pRight->op!=TK_STRING
74444    && (pRight->op!=TK_REGISTER || pRight->iColumn!=TK_STRING) ){
74445     return 0;
74446   }
74447   pLeft = pList->a[1].pExpr;
74448   if( pLeft->op!=TK_COLUMN ){
74449     return 0;
74450   }
74451   pColl = pLeft->pColl;
74452   assert( pColl!=0 || pLeft->iColumn==-1 );
74453   if( pColl==0 ){
74454     /* No collation is defined for the ROWID.  Use the default. */
74455     pColl = db->pDfltColl;
74456   }
74457   if( (pColl->type!=SQLITE_COLL_BINARY || *pnoCase) &&
74458       (pColl->type!=SQLITE_COLL_NOCASE || !*pnoCase) ){
74459     return 0;
74460   }
74461   sqlite3DequoteExpr(db, pRight);
74462   z = (char *)pRight->token.z;
74463   cnt = 0;
74464   if( z ){
74465     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){ cnt++; }
74466   }
74467   if( cnt==0 || 255==(u8)z[cnt] ){
74468     return 0;
74469   }
74470   *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
74471   *pnPattern = cnt;
74472   return 1;
74473 }
74474 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
74475
74476
74477 #ifndef SQLITE_OMIT_VIRTUALTABLE
74478 /*
74479 ** Check to see if the given expression is of the form
74480 **
74481 **         column MATCH expr
74482 **
74483 ** If it is then return TRUE.  If not, return FALSE.
74484 */
74485 static int isMatchOfColumn(
74486   Expr *pExpr      /* Test this expression */
74487 ){
74488   ExprList *pList;
74489
74490   if( pExpr->op!=TK_FUNCTION ){
74491     return 0;
74492   }
74493   if( pExpr->token.n!=5 ||
74494        sqlite3StrNICmp((const char*)pExpr->token.z,"match",5)!=0 ){
74495     return 0;
74496   }
74497   pList = pExpr->pList;
74498   if( pList->nExpr!=2 ){
74499     return 0;
74500   }
74501   if( pList->a[1].pExpr->op != TK_COLUMN ){
74502     return 0;
74503   }
74504   return 1;
74505 }
74506 #endif /* SQLITE_OMIT_VIRTUALTABLE */
74507
74508 /*
74509 ** If the pBase expression originated in the ON or USING clause of
74510 ** a join, then transfer the appropriate markings over to derived.
74511 */
74512 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
74513   pDerived->flags |= pBase->flags & EP_FromJoin;
74514   pDerived->iRightJoinTable = pBase->iRightJoinTable;
74515 }
74516
74517 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
74518 /*
74519 ** Return TRUE if the given term of an OR clause can be converted
74520 ** into an IN clause.  The iCursor and iColumn define the left-hand
74521 ** side of the IN clause.
74522 **
74523 ** The context is that we have multiple OR-connected equality terms
74524 ** like this:
74525 **
74526 **           a=<expr1> OR  a=<expr2> OR b=<expr3>  OR ...
74527 **
74528 ** The pOrTerm input to this routine corresponds to a single term of
74529 ** this OR clause.  In order for the term to be a candidate for
74530 ** conversion to an IN operator, the following must be true:
74531 **
74532 **     *  The left-hand side of the term must be the column which
74533 **        is identified by iCursor and iColumn.
74534 **
74535 **     *  If the right-hand side is also a column, then the affinities
74536 **        of both right and left sides must be such that no type
74537 **        conversions are required on the right.  (Ticket #2249)
74538 **
74539 ** If both of these conditions are true, then return true.  Otherwise
74540 ** return false.
74541 */
74542 static int orTermIsOptCandidate(WhereTerm *pOrTerm, int iCursor, int iColumn){
74543   int affLeft, affRight;
74544   assert( pOrTerm->eOperator==WO_EQ );
74545   if( pOrTerm->leftCursor!=iCursor ){
74546     return 0;
74547   }
74548   if( pOrTerm->leftColumn!=iColumn ){
74549     return 0;
74550   }
74551   affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
74552   if( affRight==0 ){
74553     return 1;
74554   }
74555   affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
74556   if( affRight!=affLeft ){
74557     return 0;
74558   }
74559   return 1;
74560 }
74561
74562 /*
74563 ** Return true if the given term of an OR clause can be ignored during
74564 ** a check to make sure all OR terms are candidates for optimization.
74565 ** In other words, return true if a call to the orTermIsOptCandidate()
74566 ** above returned false but it is not necessary to disqualify the
74567 ** optimization.
74568 **
74569 ** Suppose the original OR phrase was this:
74570 **
74571 **           a=4  OR  a=11  OR  a=b
74572 **
74573 ** During analysis, the third term gets flipped around and duplicate
74574 ** so that we are left with this:
74575 **
74576 **           a=4  OR  a=11  OR  a=b  OR  b=a
74577 **
74578 ** Since the last two terms are duplicates, only one of them
74579 ** has to qualify in order for the whole phrase to qualify.  When
74580 ** this routine is called, we know that pOrTerm did not qualify.
74581 ** This routine merely checks to see if pOrTerm has a duplicate that
74582 ** might qualify.  If there is a duplicate that has not yet been
74583 ** disqualified, then return true.  If there are no duplicates, or
74584 ** the duplicate has also been disqualified, return false.
74585 */
74586 static int orTermHasOkDuplicate(WhereClause *pOr, WhereTerm *pOrTerm){
74587   if( pOrTerm->flags & TERM_COPIED ){
74588     /* This is the original term.  The duplicate is to the left had
74589     ** has not yet been analyzed and thus has not yet been disqualified. */
74590     return 1;
74591   }
74592   if( (pOrTerm->flags & TERM_VIRTUAL)!=0
74593      && (pOr->a[pOrTerm->iParent].flags & TERM_OR_OK)!=0 ){
74594     /* This is a duplicate term.  The original qualified so this one
74595     ** does not have to. */
74596     return 1;
74597   }
74598   /* This is either a singleton term or else it is a duplicate for
74599   ** which the original did not qualify.  Either way we are done for. */
74600   return 0;
74601 }
74602 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
74603
74604 /*
74605 ** The input to this routine is an WhereTerm structure with only the
74606 ** "pExpr" field filled in.  The job of this routine is to analyze the
74607 ** subexpression and populate all the other fields of the WhereTerm
74608 ** structure.
74609 **
74610 ** If the expression is of the form "<expr> <op> X" it gets commuted
74611 ** to the standard form of "X <op> <expr>".  If the expression is of
74612 ** the form "X <op> Y" where both X and Y are columns, then the original
74613 ** expression is unchanged and a new virtual expression of the form
74614 ** "Y <op> X" is added to the WHERE clause and analyzed separately.
74615 */
74616 static void exprAnalyze(
74617   SrcList *pSrc,            /* the FROM clause */
74618   WhereClause *pWC,         /* the WHERE clause */
74619   int idxTerm               /* Index of the term to be analyzed */
74620 ){
74621   WhereTerm *pTerm;
74622   ExprMaskSet *pMaskSet;
74623   Expr *pExpr;
74624   Bitmask prereqLeft;
74625   Bitmask prereqAll;
74626   Bitmask extraRight = 0;
74627   int nPattern;
74628   int isComplete;
74629   int noCase;
74630   int op;
74631   Parse *pParse = pWC->pParse;
74632   sqlite3 *db = pParse->db;
74633
74634   if( db->mallocFailed ){
74635     return;
74636   }
74637   pTerm = &pWC->a[idxTerm];
74638   pMaskSet = pWC->pMaskSet;
74639   pExpr = pTerm->pExpr;
74640   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
74641   op = pExpr->op;
74642   if( op==TK_IN ){
74643     assert( pExpr->pRight==0 );
74644     pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->pList)
74645                           | exprSelectTableUsage(pMaskSet, pExpr->pSelect);
74646   }else if( op==TK_ISNULL ){
74647     pTerm->prereqRight = 0;
74648   }else{
74649     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
74650   }
74651   prereqAll = exprTableUsage(pMaskSet, pExpr);
74652   if( ExprHasProperty(pExpr, EP_FromJoin) ){
74653     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
74654     prereqAll |= x;
74655     extraRight = x-1;  /* ON clause terms may not be used with an index
74656                        ** on left table of a LEFT JOIN.  Ticket #3015 */
74657   }
74658   pTerm->prereqAll = prereqAll;
74659   pTerm->leftCursor = -1;
74660   pTerm->iParent = -1;
74661   pTerm->eOperator = 0;
74662   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
74663     Expr *pLeft = pExpr->pLeft;
74664     Expr *pRight = pExpr->pRight;
74665     if( pLeft->op==TK_COLUMN ){
74666       pTerm->leftCursor = pLeft->iTable;
74667       pTerm->leftColumn = pLeft->iColumn;
74668       pTerm->eOperator = operatorMask(op);
74669     }
74670     if( pRight && pRight->op==TK_COLUMN ){
74671       WhereTerm *pNew;
74672       Expr *pDup;
74673       if( pTerm->leftCursor>=0 ){
74674         int idxNew;
74675         pDup = sqlite3ExprDup(db, pExpr);
74676         if( db->mallocFailed ){
74677           sqlite3ExprDelete(db, pDup);
74678           return;
74679         }
74680         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
74681         if( idxNew==0 ) return;
74682         pNew = &pWC->a[idxNew];
74683         pNew->iParent = idxTerm;
74684         pTerm = &pWC->a[idxTerm];
74685         pTerm->nChild = 1;
74686         pTerm->flags |= TERM_COPIED;
74687       }else{
74688         pDup = pExpr;
74689         pNew = pTerm;
74690       }
74691       exprCommute(pDup);
74692       pLeft = pDup->pLeft;
74693       pNew->leftCursor = pLeft->iTable;
74694       pNew->leftColumn = pLeft->iColumn;
74695       pNew->prereqRight = prereqLeft;
74696       pNew->prereqAll = prereqAll;
74697       pNew->eOperator = operatorMask(pDup->op);
74698     }
74699   }
74700
74701 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
74702   /* If a term is the BETWEEN operator, create two new virtual terms
74703   ** that define the range that the BETWEEN implements.
74704   */
74705   else if( pExpr->op==TK_BETWEEN ){
74706     ExprList *pList = pExpr->pList;
74707     int i;
74708     static const u8 ops[] = {TK_GE, TK_LE};
74709     assert( pList!=0 );
74710     assert( pList->nExpr==2 );
74711     for(i=0; i<2; i++){
74712       Expr *pNewExpr;
74713       int idxNew;
74714       pNewExpr = sqlite3Expr(db, ops[i], sqlite3ExprDup(db, pExpr->pLeft),
74715                              sqlite3ExprDup(db, pList->a[i].pExpr), 0);
74716       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
74717       exprAnalyze(pSrc, pWC, idxNew);
74718       pTerm = &pWC->a[idxTerm];
74719       pWC->a[idxNew].iParent = idxTerm;
74720     }
74721     pTerm->nChild = 2;
74722   }
74723 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
74724
74725 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
74726   /* Attempt to convert OR-connected terms into an IN operator so that
74727   ** they can make use of indices.  Example:
74728   **
74729   **      x = expr1  OR  expr2 = x  OR  x = expr3
74730   **
74731   ** is converted into
74732   **
74733   **      x IN (expr1,expr2,expr3)
74734   **
74735   ** This optimization must be omitted if OMIT_SUBQUERY is defined because
74736   ** the compiler for the the IN operator is part of sub-queries.
74737   */
74738   else if( pExpr->op==TK_OR ){
74739     int ok;
74740     int i, j;
74741     int iColumn, iCursor;
74742     WhereClause sOr;
74743     WhereTerm *pOrTerm;
74744
74745     assert( (pTerm->flags & TERM_DYNAMIC)==0 );
74746     whereClauseInit(&sOr, pWC->pParse, pMaskSet);
74747     whereSplit(&sOr, pExpr, TK_OR);
74748     exprAnalyzeAll(pSrc, &sOr);
74749     assert( sOr.nTerm>=2 );
74750     j = 0;
74751     if( db->mallocFailed ) goto or_not_possible;
74752     do{
74753       assert( j<sOr.nTerm );
74754       iColumn = sOr.a[j].leftColumn;
74755       iCursor = sOr.a[j].leftCursor;
74756       ok = iCursor>=0;
74757       for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0 && ok; i--, pOrTerm++){
74758         if( pOrTerm->eOperator!=WO_EQ ){
74759           goto or_not_possible;
74760         }
74761         if( orTermIsOptCandidate(pOrTerm, iCursor, iColumn) ){
74762           pOrTerm->flags |= TERM_OR_OK;
74763         }else if( orTermHasOkDuplicate(&sOr, pOrTerm) ){
74764           pOrTerm->flags &= ~TERM_OR_OK;
74765         }else{
74766           ok = 0;
74767         }
74768       }
74769     }while( !ok && (sOr.a[j++].flags & TERM_COPIED)!=0 && j<2 );
74770     if( ok ){
74771       ExprList *pList = 0;
74772       Expr *pNew, *pDup;
74773       Expr *pLeft = 0;
74774       for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0; i--, pOrTerm++){
74775         if( (pOrTerm->flags & TERM_OR_OK)==0 ) continue;
74776         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight);
74777         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup, 0);
74778         pLeft = pOrTerm->pExpr->pLeft;
74779       }
74780       assert( pLeft!=0 );
74781       pDup = sqlite3ExprDup(db, pLeft);
74782       pNew = sqlite3Expr(db, TK_IN, pDup, 0, 0);
74783       if( pNew ){
74784         int idxNew;
74785         transferJoinMarkings(pNew, pExpr);
74786         pNew->pList = pList;
74787         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
74788         exprAnalyze(pSrc, pWC, idxNew);
74789         pTerm = &pWC->a[idxTerm];
74790         pWC->a[idxNew].iParent = idxTerm;
74791         pTerm->nChild = 1;
74792       }else{
74793         sqlite3ExprListDelete(db, pList);
74794       }
74795     }
74796 or_not_possible:
74797     whereClauseClear(&sOr);
74798   }
74799 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
74800
74801 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
74802   /* Add constraints to reduce the search space on a LIKE or GLOB
74803   ** operator.
74804   **
74805   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
74806   **
74807   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
74808   **
74809   ** The last character of the prefix "abc" is incremented to form the
74810   ** termination condition "abd".
74811   */
74812   if( isLikeOrGlob(db, pExpr, &nPattern, &isComplete, &noCase) ){
74813     Expr *pLeft, *pRight;
74814     Expr *pStr1, *pStr2;
74815     Expr *pNewExpr1, *pNewExpr2;
74816     int idxNew1, idxNew2;
74817
74818     pLeft = pExpr->pList->a[1].pExpr;
74819     pRight = pExpr->pList->a[0].pExpr;
74820     pStr1 = sqlite3PExpr(pParse, TK_STRING, 0, 0, 0);
74821     if( pStr1 ){
74822       sqlite3TokenCopy(db, &pStr1->token, &pRight->token);
74823       pStr1->token.n = nPattern;
74824       pStr1->flags = EP_Dequoted;
74825     }
74826     pStr2 = sqlite3ExprDup(db, pStr1);
74827     if( !db->mallocFailed ){
74828       u8 c, *pC;
74829       assert( pStr2->token.dyn );
74830       pC = (u8*)&pStr2->token.z[nPattern-1];
74831       c = *pC;
74832       if( noCase ){
74833         if( c=='@' ) isComplete = 0;
74834         c = sqlite3UpperToLower[c];
74835       }
74836       *pC = c + 1;
74837     }
74838     pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprDup(db,pLeft), pStr1, 0);
74839     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
74840     exprAnalyze(pSrc, pWC, idxNew1);
74841     pNewExpr2 = sqlite3PExpr(pParse, TK_LT, sqlite3ExprDup(db,pLeft), pStr2, 0);
74842     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
74843     exprAnalyze(pSrc, pWC, idxNew2);
74844     pTerm = &pWC->a[idxTerm];
74845     if( isComplete ){
74846       pWC->a[idxNew1].iParent = idxTerm;
74847       pWC->a[idxNew2].iParent = idxTerm;
74848       pTerm->nChild = 2;
74849     }
74850   }
74851 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
74852
74853 #ifndef SQLITE_OMIT_VIRTUALTABLE
74854   /* Add a WO_MATCH auxiliary term to the constraint set if the
74855   ** current expression is of the form:  column MATCH expr.
74856   ** This information is used by the xBestIndex methods of
74857   ** virtual tables.  The native query optimizer does not attempt
74858   ** to do anything with MATCH functions.
74859   */
74860   if( isMatchOfColumn(pExpr) ){
74861     int idxNew;
74862     Expr *pRight, *pLeft;
74863     WhereTerm *pNewTerm;
74864     Bitmask prereqColumn, prereqExpr;
74865
74866     pRight = pExpr->pList->a[0].pExpr;
74867     pLeft = pExpr->pList->a[1].pExpr;
74868     prereqExpr = exprTableUsage(pMaskSet, pRight);
74869     prereqColumn = exprTableUsage(pMaskSet, pLeft);
74870     if( (prereqExpr & prereqColumn)==0 ){
74871       Expr *pNewExpr;
74872       pNewExpr = sqlite3Expr(db, TK_MATCH, 0, sqlite3ExprDup(db, pRight), 0);
74873       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
74874       pNewTerm = &pWC->a[idxNew];
74875       pNewTerm->prereqRight = prereqExpr;
74876       pNewTerm->leftCursor = pLeft->iTable;
74877       pNewTerm->leftColumn = pLeft->iColumn;
74878       pNewTerm->eOperator = WO_MATCH;
74879       pNewTerm->iParent = idxTerm;
74880       pTerm = &pWC->a[idxTerm];
74881       pTerm->nChild = 1;
74882       pTerm->flags |= TERM_COPIED;
74883       pNewTerm->prereqAll = pTerm->prereqAll;
74884     }
74885   }
74886 #endif /* SQLITE_OMIT_VIRTUALTABLE */
74887
74888   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
74889   ** an index for tables to the left of the join.
74890   */
74891   pTerm->prereqRight |= extraRight;
74892 }
74893
74894 /*
74895 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
74896 ** a reference to any table other than the iBase table.
74897 */
74898 static int referencesOtherTables(
74899   ExprList *pList,          /* Search expressions in ths list */
74900   ExprMaskSet *pMaskSet,    /* Mapping from tables to bitmaps */
74901   int iFirst,               /* Be searching with the iFirst-th expression */
74902   int iBase                 /* Ignore references to this table */
74903 ){
74904   Bitmask allowed = ~getMask(pMaskSet, iBase);
74905   while( iFirst<pList->nExpr ){
74906     if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
74907       return 1;
74908     }
74909   }
74910   return 0;
74911 }
74912
74913
74914 /*
74915 ** This routine decides if pIdx can be used to satisfy the ORDER BY
74916 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
74917 ** ORDER BY clause, this routine returns 0.
74918 **
74919 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
74920 ** left-most table in the FROM clause of that same SELECT statement and
74921 ** the table has a cursor number of "base".  pIdx is an index on pTab.
74922 **
74923 ** nEqCol is the number of columns of pIdx that are used as equality
74924 ** constraints.  Any of these columns may be missing from the ORDER BY
74925 ** clause and the match can still be a success.
74926 **
74927 ** All terms of the ORDER BY that match against the index must be either
74928 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
74929 ** index do not need to satisfy this constraint.)  The *pbRev value is
74930 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
74931 ** the ORDER BY clause is all ASC.
74932 */
74933 static int isSortingIndex(
74934   Parse *pParse,          /* Parsing context */
74935   ExprMaskSet *pMaskSet,  /* Mapping from table indices to bitmaps */
74936   Index *pIdx,            /* The index we are testing */
74937   int base,               /* Cursor number for the table to be sorted */
74938   ExprList *pOrderBy,     /* The ORDER BY clause */
74939   int nEqCol,             /* Number of index columns with == constraints */
74940   int *pbRev              /* Set to 1 if ORDER BY is DESC */
74941 ){
74942   int i, j;                       /* Loop counters */
74943   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
74944   int nTerm;                      /* Number of ORDER BY terms */
74945   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
74946   sqlite3 *db = pParse->db;
74947
74948   assert( pOrderBy!=0 );
74949   nTerm = pOrderBy->nExpr;
74950   assert( nTerm>0 );
74951
74952   /* Match terms of the ORDER BY clause against columns of
74953   ** the index.
74954   **
74955   ** Note that indices have pIdx->nColumn regular columns plus
74956   ** one additional column containing the rowid.  The rowid column
74957   ** of the index is also allowed to match against the ORDER BY
74958   ** clause.
74959   */
74960   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
74961     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
74962     CollSeq *pColl;    /* The collating sequence of pExpr */
74963     int termSortOrder; /* Sort order for this term */
74964     int iColumn;       /* The i-th column of the index.  -1 for rowid */
74965     int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
74966     const char *zColl; /* Name of the collating sequence for i-th index term */
74967
74968     pExpr = pTerm->pExpr;
74969     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
74970       /* Can not use an index sort on anything that is not a column in the
74971       ** left-most table of the FROM clause */
74972       break;
74973     }
74974     pColl = sqlite3ExprCollSeq(pParse, pExpr);
74975     if( !pColl ){
74976       pColl = db->pDfltColl;
74977     }
74978     if( i<pIdx->nColumn ){
74979       iColumn = pIdx->aiColumn[i];
74980       if( iColumn==pIdx->pTable->iPKey ){
74981         iColumn = -1;
74982       }
74983       iSortOrder = pIdx->aSortOrder[i];
74984       zColl = pIdx->azColl[i];
74985     }else{
74986       iColumn = -1;
74987       iSortOrder = 0;
74988       zColl = pColl->zName;
74989     }
74990     if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
74991       /* Term j of the ORDER BY clause does not match column i of the index */
74992       if( i<nEqCol ){
74993         /* If an index column that is constrained by == fails to match an
74994         ** ORDER BY term, that is OK.  Just ignore that column of the index
74995         */
74996         continue;
74997       }else if( i==pIdx->nColumn ){
74998         /* Index column i is the rowid.  All other terms match. */
74999         break;
75000       }else{
75001         /* If an index column fails to match and is not constrained by ==
75002         ** then the index cannot satisfy the ORDER BY constraint.
75003         */
75004         return 0;
75005       }
75006     }
75007     assert( pIdx->aSortOrder!=0 );
75008     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
75009     assert( iSortOrder==0 || iSortOrder==1 );
75010     termSortOrder = iSortOrder ^ pTerm->sortOrder;
75011     if( i>nEqCol ){
75012       if( termSortOrder!=sortOrder ){
75013         /* Indices can only be used if all ORDER BY terms past the
75014         ** equality constraints are all either DESC or ASC. */
75015         return 0;
75016       }
75017     }else{
75018       sortOrder = termSortOrder;
75019     }
75020     j++;
75021     pTerm++;
75022     if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
75023       /* If the indexed column is the primary key and everything matches
75024       ** so far and none of the ORDER BY terms to the right reference other
75025       ** tables in the join, then we are assured that the index can be used 
75026       ** to sort because the primary key is unique and so none of the other
75027       ** columns will make any difference
75028       */
75029       j = nTerm;
75030     }
75031   }
75032
75033   *pbRev = sortOrder!=0;
75034   if( j>=nTerm ){
75035     /* All terms of the ORDER BY clause are covered by this index so
75036     ** this index can be used for sorting. */
75037     return 1;
75038   }
75039   if( pIdx->onError!=OE_None && i==pIdx->nColumn
75040       && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
75041     /* All terms of this index match some prefix of the ORDER BY clause
75042     ** and the index is UNIQUE and no terms on the tail of the ORDER BY
75043     ** clause reference other tables in a join.  If this is all true then
75044     ** the order by clause is superfluous. */
75045     return 1;
75046   }
75047   return 0;
75048 }
75049
75050 /*
75051 ** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
75052 ** by sorting in order of ROWID.  Return true if so and set *pbRev to be
75053 ** true for reverse ROWID and false for forward ROWID order.
75054 */
75055 static int sortableByRowid(
75056   int base,               /* Cursor number for table to be sorted */
75057   ExprList *pOrderBy,     /* The ORDER BY clause */
75058   ExprMaskSet *pMaskSet,  /* Mapping from tables to bitmaps */
75059   int *pbRev              /* Set to 1 if ORDER BY is DESC */
75060 ){
75061   Expr *p;
75062
75063   assert( pOrderBy!=0 );
75064   assert( pOrderBy->nExpr>0 );
75065   p = pOrderBy->a[0].pExpr;
75066   if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1
75067     && !referencesOtherTables(pOrderBy, pMaskSet, 1, base) ){
75068     *pbRev = pOrderBy->a[0].sortOrder;
75069     return 1;
75070   }
75071   return 0;
75072 }
75073
75074 /*
75075 ** Prepare a crude estimate of the logarithm of the input value.
75076 ** The results need not be exact.  This is only used for estimating
75077 ** the total cost of performing operations with O(logN) or O(NlogN)
75078 ** complexity.  Because N is just a guess, it is no great tragedy if
75079 ** logN is a little off.
75080 */
75081 static double estLog(double N){
75082   double logN = 1;
75083   double x = 10;
75084   while( N>x ){
75085     logN += 1;
75086     x *= 10;
75087   }
75088   return logN;
75089 }
75090
75091 /*
75092 ** Two routines for printing the content of an sqlite3_index_info
75093 ** structure.  Used for testing and debugging only.  If neither
75094 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
75095 ** are no-ops.
75096 */
75097 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
75098 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
75099   int i;
75100   if( !sqlite3WhereTrace ) return;
75101   for(i=0; i<p->nConstraint; i++){
75102     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
75103        i,
75104        p->aConstraint[i].iColumn,
75105        p->aConstraint[i].iTermOffset,
75106        p->aConstraint[i].op,
75107        p->aConstraint[i].usable);
75108   }
75109   for(i=0; i<p->nOrderBy; i++){
75110     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
75111        i,
75112        p->aOrderBy[i].iColumn,
75113        p->aOrderBy[i].desc);
75114   }
75115 }
75116 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
75117   int i;
75118   if( !sqlite3WhereTrace ) return;
75119   for(i=0; i<p->nConstraint; i++){
75120     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
75121        i,
75122        p->aConstraintUsage[i].argvIndex,
75123        p->aConstraintUsage[i].omit);
75124   }
75125   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
75126   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
75127   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
75128   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
75129 }
75130 #else
75131 #define TRACE_IDX_INPUTS(A)
75132 #define TRACE_IDX_OUTPUTS(A)
75133 #endif
75134
75135 #ifndef SQLITE_OMIT_VIRTUALTABLE
75136 /*
75137 ** Compute the best index for a virtual table.
75138 **
75139 ** The best index is computed by the xBestIndex method of the virtual
75140 ** table module.  This routine is really just a wrapper that sets up
75141 ** the sqlite3_index_info structure that is used to communicate with
75142 ** xBestIndex.
75143 **
75144 ** In a join, this routine might be called multiple times for the
75145 ** same virtual table.  The sqlite3_index_info structure is created
75146 ** and initialized on the first invocation and reused on all subsequent
75147 ** invocations.  The sqlite3_index_info structure is also used when
75148 ** code is generated to access the virtual table.  The whereInfoDelete() 
75149 ** routine takes care of freeing the sqlite3_index_info structure after
75150 ** everybody has finished with it.
75151 */
75152 static double bestVirtualIndex(
75153   Parse *pParse,                 /* The parsing context */
75154   WhereClause *pWC,              /* The WHERE clause */
75155   struct SrcList_item *pSrc,     /* The FROM clause term to search */
75156   Bitmask notReady,              /* Mask of cursors that are not available */
75157   ExprList *pOrderBy,            /* The order by clause */
75158   int orderByUsable,             /* True if we can potential sort */
75159   sqlite3_index_info **ppIdxInfo /* Index information passed to xBestIndex */
75160 ){
75161   Table *pTab = pSrc->pTab;
75162   sqlite3_vtab *pVtab = pTab->pVtab;
75163   sqlite3_index_info *pIdxInfo;
75164   struct sqlite3_index_constraint *pIdxCons;
75165   struct sqlite3_index_orderby *pIdxOrderBy;
75166   struct sqlite3_index_constraint_usage *pUsage;
75167   WhereTerm *pTerm;
75168   int i, j;
75169   int nOrderBy;
75170   int rc;
75171
75172   /* If the sqlite3_index_info structure has not been previously
75173   ** allocated and initialized for this virtual table, then allocate
75174   ** and initialize it now
75175   */
75176   pIdxInfo = *ppIdxInfo;
75177   if( pIdxInfo==0 ){
75178     WhereTerm *pTerm;
75179     int nTerm;
75180     WHERETRACE(("Recomputing index info for %s...\n", pTab->zName));
75181
75182     /* Count the number of possible WHERE clause constraints referring
75183     ** to this virtual table */
75184     for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
75185       if( pTerm->leftCursor != pSrc->iCursor ) continue;
75186       if( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
75187       testcase( pTerm->eOperator==WO_IN );
75188       testcase( pTerm->eOperator==WO_ISNULL );
75189       if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
75190       nTerm++;
75191     }
75192
75193     /* If the ORDER BY clause contains only columns in the current 
75194     ** virtual table then allocate space for the aOrderBy part of
75195     ** the sqlite3_index_info structure.
75196     */
75197     nOrderBy = 0;
75198     if( pOrderBy ){
75199       for(i=0; i<pOrderBy->nExpr; i++){
75200         Expr *pExpr = pOrderBy->a[i].pExpr;
75201         if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
75202       }
75203       if( i==pOrderBy->nExpr ){
75204         nOrderBy = pOrderBy->nExpr;
75205       }
75206     }
75207
75208     /* Allocate the sqlite3_index_info structure
75209     */
75210     pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
75211                              + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
75212                              + sizeof(*pIdxOrderBy)*nOrderBy );
75213     if( pIdxInfo==0 ){
75214       sqlite3ErrorMsg(pParse, "out of memory");
75215       return 0.0;
75216     }
75217     *ppIdxInfo = pIdxInfo;
75218
75219     /* Initialize the structure.  The sqlite3_index_info structure contains
75220     ** many fields that are declared "const" to prevent xBestIndex from
75221     ** changing them.  We have to do some funky casting in order to
75222     ** initialize those fields.
75223     */
75224     pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
75225     pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
75226     pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
75227     *(int*)&pIdxInfo->nConstraint = nTerm;
75228     *(int*)&pIdxInfo->nOrderBy = nOrderBy;
75229     *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
75230     *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
75231     *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
75232                                                                      pUsage;
75233
75234     for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
75235       if( pTerm->leftCursor != pSrc->iCursor ) continue;
75236       if( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
75237       testcase( pTerm->eOperator==WO_IN );
75238       testcase( pTerm->eOperator==WO_ISNULL );
75239       if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
75240       pIdxCons[j].iColumn = pTerm->leftColumn;
75241       pIdxCons[j].iTermOffset = i;
75242       pIdxCons[j].op = pTerm->eOperator;
75243       /* The direct assignment in the previous line is possible only because
75244       ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
75245       ** following asserts verify this fact. */
75246       assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
75247       assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
75248       assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
75249       assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
75250       assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
75251       assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
75252       assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
75253       j++;
75254     }
75255     for(i=0; i<nOrderBy; i++){
75256       Expr *pExpr = pOrderBy->a[i].pExpr;
75257       pIdxOrderBy[i].iColumn = pExpr->iColumn;
75258       pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
75259     }
75260   }
75261
75262   /* At this point, the sqlite3_index_info structure that pIdxInfo points
75263   ** to will have been initialized, either during the current invocation or
75264   ** during some prior invocation.  Now we just have to customize the
75265   ** details of pIdxInfo for the current invocation and pass it to
75266   ** xBestIndex.
75267   */
75268
75269   /* The module name must be defined. Also, by this point there must
75270   ** be a pointer to an sqlite3_vtab structure. Otherwise
75271   ** sqlite3ViewGetColumnNames() would have picked up the error. 
75272   */
75273   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
75274   assert( pVtab );
75275 #if 0
75276   if( pTab->pVtab==0 ){
75277     sqlite3ErrorMsg(pParse, "undefined module %s for table %s",
75278         pTab->azModuleArg[0], pTab->zName);
75279     return 0.0;
75280   }
75281 #endif
75282
75283   /* Set the aConstraint[].usable fields and initialize all 
75284   ** output variables to zero.
75285   **
75286   ** aConstraint[].usable is true for constraints where the right-hand
75287   ** side contains only references to tables to the left of the current
75288   ** table.  In other words, if the constraint is of the form:
75289   **
75290   **           column = expr
75291   **
75292   ** and we are evaluating a join, then the constraint on column is 
75293   ** only valid if all tables referenced in expr occur to the left
75294   ** of the table containing column.
75295   **
75296   ** The aConstraints[] array contains entries for all constraints
75297   ** on the current table.  That way we only have to compute it once
75298   ** even though we might try to pick the best index multiple times.
75299   ** For each attempt at picking an index, the order of tables in the
75300   ** join might be different so we have to recompute the usable flag
75301   ** each time.
75302   */
75303   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
75304   pUsage = pIdxInfo->aConstraintUsage;
75305   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
75306     j = pIdxCons->iTermOffset;
75307     pTerm = &pWC->a[j];
75308     pIdxCons->usable =  (pTerm->prereqRight & notReady)==0;
75309   }
75310   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
75311   if( pIdxInfo->needToFreeIdxStr ){
75312     sqlite3_free(pIdxInfo->idxStr);
75313   }
75314   pIdxInfo->idxStr = 0;
75315   pIdxInfo->idxNum = 0;
75316   pIdxInfo->needToFreeIdxStr = 0;
75317   pIdxInfo->orderByConsumed = 0;
75318   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / 2.0;
75319   nOrderBy = pIdxInfo->nOrderBy;
75320   if( pIdxInfo->nOrderBy && !orderByUsable ){
75321     *(int*)&pIdxInfo->nOrderBy = 0;
75322   }
75323
75324   (void)sqlite3SafetyOff(pParse->db);
75325   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
75326   TRACE_IDX_INPUTS(pIdxInfo);
75327   rc = pVtab->pModule->xBestIndex(pVtab, pIdxInfo);
75328   TRACE_IDX_OUTPUTS(pIdxInfo);
75329   (void)sqlite3SafetyOn(pParse->db);
75330
75331   if( rc!=SQLITE_OK ){
75332     if( rc==SQLITE_NOMEM ){
75333       pParse->db->mallocFailed = 1;
75334     }else if( !pVtab->zErrMsg ){
75335       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
75336     }else{
75337       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
75338     }
75339   }
75340   sqlite3DbFree(pParse->db, pVtab->zErrMsg);
75341   pVtab->zErrMsg = 0;
75342
75343   for(i=0; i<pIdxInfo->nConstraint; i++){
75344     if( !pIdxInfo->aConstraint[i].usable && pUsage[i].argvIndex>0 ){
75345       sqlite3ErrorMsg(pParse, 
75346           "table %s: xBestIndex returned an invalid plan", pTab->zName);
75347       return 0.0;
75348     }
75349   }
75350
75351   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
75352   return pIdxInfo->estimatedCost;
75353 }
75354 #endif /* SQLITE_OMIT_VIRTUALTABLE */
75355
75356 /*
75357 ** Find the best index for accessing a particular table.  Return a pointer
75358 ** to the index, flags that describe how the index should be used, the
75359 ** number of equality constraints, and the "cost" for this index.
75360 **
75361 ** The lowest cost index wins.  The cost is an estimate of the amount of
75362 ** CPU and disk I/O need to process the request using the selected index.
75363 ** Factors that influence cost include:
75364 **
75365 **    *  The estimated number of rows that will be retrieved.  (The
75366 **       fewer the better.)
75367 **
75368 **    *  Whether or not sorting must occur.
75369 **
75370 **    *  Whether or not there must be separate lookups in the
75371 **       index and in the main table.
75372 **
75373 */
75374 static double bestIndex(
75375   Parse *pParse,              /* The parsing context */
75376   WhereClause *pWC,           /* The WHERE clause */
75377   struct SrcList_item *pSrc,  /* The FROM clause term to search */
75378   Bitmask notReady,           /* Mask of cursors that are not available */
75379   ExprList *pOrderBy,         /* The order by clause */
75380   Index **ppIndex,            /* Make *ppIndex point to the best index */
75381   int *pFlags,                /* Put flags describing this choice in *pFlags */
75382   int *pnEq                   /* Put the number of == or IN constraints here */
75383 ){
75384   WhereTerm *pTerm;
75385   Index *bestIdx = 0;         /* Index that gives the lowest cost */
75386   double lowestCost;          /* The cost of using bestIdx */
75387   int bestFlags = 0;          /* Flags associated with bestIdx */
75388   int bestNEq = 0;            /* Best value for nEq */
75389   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
75390   Index *pProbe;              /* An index we are evaluating */
75391   int rev;                    /* True to scan in reverse order */
75392   int flags;                  /* Flags associated with pProbe */
75393   int nEq;                    /* Number of == or IN constraints */
75394   int eqTermMask;             /* Mask of valid equality operators */
75395   double cost;                /* Cost of using pProbe */
75396
75397   WHERETRACE(("bestIndex: tbl=%s notReady=%llx\n", pSrc->pTab->zName, notReady));
75398   lowestCost = SQLITE_BIG_DBL;
75399   pProbe = pSrc->pTab->pIndex;
75400
75401   /* If the table has no indices and there are no terms in the where
75402   ** clause that refer to the ROWID, then we will never be able to do
75403   ** anything other than a full table scan on this table.  We might as
75404   ** well put it first in the join order.  That way, perhaps it can be
75405   ** referenced by other tables in the join.
75406   */
75407   if( pProbe==0 &&
75408      findTerm(pWC, iCur, -1, 0, WO_EQ|WO_IN|WO_LT|WO_LE|WO_GT|WO_GE,0)==0 &&
75409      (pOrderBy==0 || !sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev)) ){
75410     *pFlags = 0;
75411     *ppIndex = 0;
75412     *pnEq = 0;
75413     return 0.0;
75414   }
75415
75416   /* Check for a rowid=EXPR or rowid IN (...) constraints
75417   */
75418   pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
75419   if( pTerm ){
75420     Expr *pExpr;
75421     *ppIndex = 0;
75422     bestFlags = WHERE_ROWID_EQ;
75423     if( pTerm->eOperator & WO_EQ ){
75424       /* Rowid== is always the best pick.  Look no further.  Because only
75425       ** a single row is generated, output is always in sorted order */
75426       *pFlags = WHERE_ROWID_EQ | WHERE_UNIQUE;
75427       *pnEq = 1;
75428       WHERETRACE(("... best is rowid\n"));
75429       return 0.0;
75430     }else if( (pExpr = pTerm->pExpr)->pList!=0 ){
75431       /* Rowid IN (LIST): cost is NlogN where N is the number of list
75432       ** elements.  */
75433       lowestCost = pExpr->pList->nExpr;
75434       lowestCost *= estLog(lowestCost);
75435     }else{
75436       /* Rowid IN (SELECT): cost is NlogN where N is the number of rows
75437       ** in the result of the inner select.  We have no way to estimate
75438       ** that value so make a wild guess. */
75439       lowestCost = 200;
75440     }
75441     WHERETRACE(("... rowid IN cost: %.9g\n", lowestCost));
75442   }
75443
75444   /* Estimate the cost of a table scan.  If we do not know how many
75445   ** entries are in the table, use 1 million as a guess.
75446   */
75447   cost = pProbe ? pProbe->aiRowEst[0] : 1000000;
75448   WHERETRACE(("... table scan base cost: %.9g\n", cost));
75449   flags = WHERE_ROWID_RANGE;
75450
75451   /* Check for constraints on a range of rowids in a table scan.
75452   */
75453   pTerm = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE|WO_GT|WO_GE, 0);
75454   if( pTerm ){
75455     if( findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0) ){
75456       flags |= WHERE_TOP_LIMIT;
75457       cost /= 3;  /* Guess that rowid<EXPR eliminates two-thirds or rows */
75458     }
75459     if( findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0) ){
75460       flags |= WHERE_BTM_LIMIT;
75461       cost /= 3;  /* Guess that rowid>EXPR eliminates two-thirds of rows */
75462     }
75463     WHERETRACE(("... rowid range reduces cost to %.9g\n", cost));
75464   }else{
75465     flags = 0;
75466   }
75467
75468   /* If the table scan does not satisfy the ORDER BY clause, increase
75469   ** the cost by NlogN to cover the expense of sorting. */
75470   if( pOrderBy ){
75471     if( sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev) ){
75472       flags |= WHERE_ORDERBY|WHERE_ROWID_RANGE;
75473       if( rev ){
75474         flags |= WHERE_REVERSE;
75475       }
75476     }else{
75477       cost += cost*estLog(cost);
75478       WHERETRACE(("... sorting increases cost to %.9g\n", cost));
75479     }
75480   }
75481   if( cost<lowestCost ){
75482     lowestCost = cost;
75483     bestFlags = flags;
75484   }
75485
75486   /* If the pSrc table is the right table of a LEFT JOIN then we may not
75487   ** use an index to satisfy IS NULL constraints on that table.  This is
75488   ** because columns might end up being NULL if the table does not match -
75489   ** a circumstance which the index cannot help us discover.  Ticket #2177.
75490   */
75491   if( (pSrc->jointype & JT_LEFT)!=0 ){
75492     eqTermMask = WO_EQ|WO_IN;
75493   }else{
75494     eqTermMask = WO_EQ|WO_IN|WO_ISNULL;
75495   }
75496
75497   /* Look at each index.
75498   */
75499   for(; pProbe; pProbe=pProbe->pNext){
75500     int i;                       /* Loop counter */
75501     double inMultiplier = 1;
75502
75503     WHERETRACE(("... index %s:\n", pProbe->zName));
75504
75505     /* Count the number of columns in the index that are satisfied
75506     ** by x=EXPR constraints or x IN (...) constraints.
75507     */
75508     flags = 0;
75509     for(i=0; i<pProbe->nColumn; i++){
75510       int j = pProbe->aiColumn[i];
75511       pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pProbe);
75512       if( pTerm==0 ) break;
75513       flags |= WHERE_COLUMN_EQ;
75514       if( pTerm->eOperator & WO_IN ){
75515         Expr *pExpr = pTerm->pExpr;
75516         flags |= WHERE_COLUMN_IN;
75517         if( pExpr->pSelect!=0 ){
75518           inMultiplier *= 25;
75519         }else if( ALWAYS(pExpr->pList) ){
75520           inMultiplier *= pExpr->pList->nExpr + 1;
75521         }
75522       }
75523     }
75524     cost = pProbe->aiRowEst[i] * inMultiplier * estLog(inMultiplier);
75525     nEq = i;
75526     if( pProbe->onError!=OE_None && (flags & WHERE_COLUMN_IN)==0
75527          && nEq==pProbe->nColumn ){
75528       flags |= WHERE_UNIQUE;
75529     }
75530     WHERETRACE(("...... nEq=%d inMult=%.9g cost=%.9g\n",nEq,inMultiplier,cost));
75531
75532     /* Look for range constraints
75533     */
75534     if( nEq<pProbe->nColumn ){
75535       int j = pProbe->aiColumn[nEq];
75536       pTerm = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pProbe);
75537       if( pTerm ){
75538         flags |= WHERE_COLUMN_RANGE;
75539         if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pProbe) ){
75540           flags |= WHERE_TOP_LIMIT;
75541           cost /= 3;
75542         }
75543         if( findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pProbe) ){
75544           flags |= WHERE_BTM_LIMIT;
75545           cost /= 3;
75546         }
75547         WHERETRACE(("...... range reduces cost to %.9g\n", cost));
75548       }
75549     }
75550
75551     /* Add the additional cost of sorting if that is a factor.
75552     */
75553     if( pOrderBy ){
75554       if( (flags & WHERE_COLUMN_IN)==0 &&
75555            isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev) ){
75556         if( flags==0 ){
75557           flags = WHERE_COLUMN_RANGE;
75558         }
75559         flags |= WHERE_ORDERBY;
75560         if( rev ){
75561           flags |= WHERE_REVERSE;
75562         }
75563       }else{
75564         cost += cost*estLog(cost);
75565         WHERETRACE(("...... orderby increases cost to %.9g\n", cost));
75566       }
75567     }
75568
75569     /* Check to see if we can get away with using just the index without
75570     ** ever reading the table.  If that is the case, then halve the
75571     ** cost of this index.
75572     */
75573     if( flags && pSrc->colUsed < (((Bitmask)1)<<(BMS-1)) ){
75574       Bitmask m = pSrc->colUsed;
75575       int j;
75576       for(j=0; j<pProbe->nColumn; j++){
75577         int x = pProbe->aiColumn[j];
75578         if( x<BMS-1 ){
75579           m &= ~(((Bitmask)1)<<x);
75580         }
75581       }
75582       if( m==0 ){
75583         flags |= WHERE_IDX_ONLY;
75584         cost /= 2;
75585         WHERETRACE(("...... idx-only reduces cost to %.9g\n", cost));
75586       }
75587     }
75588
75589     /* If this index has achieved the lowest cost so far, then use it.
75590     */
75591     if( flags && cost < lowestCost ){
75592       bestIdx = pProbe;
75593       lowestCost = cost;
75594       bestFlags = flags;
75595       bestNEq = nEq;
75596     }
75597   }
75598
75599   /* Report the best result
75600   */
75601   *ppIndex = bestIdx;
75602   WHERETRACE(("best index is %s, cost=%.9g, flags=%x, nEq=%d\n",
75603         bestIdx ? bestIdx->zName : "(none)", lowestCost, bestFlags, bestNEq));
75604   *pFlags = bestFlags | eqTermMask;
75605   *pnEq = bestNEq;
75606   return lowestCost;
75607 }
75608
75609
75610 /*
75611 ** Disable a term in the WHERE clause.  Except, do not disable the term
75612 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
75613 ** or USING clause of that join.
75614 **
75615 ** Consider the term t2.z='ok' in the following queries:
75616 **
75617 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
75618 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
75619 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
75620 **
75621 ** The t2.z='ok' is disabled in the in (2) because it originates
75622 ** in the ON clause.  The term is disabled in (3) because it is not part
75623 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
75624 **
75625 ** Disabling a term causes that term to not be tested in the inner loop
75626 ** of the join.  Disabling is an optimization.  When terms are satisfied
75627 ** by indices, we disable them to prevent redundant tests in the inner
75628 ** loop.  We would get the correct results if nothing were ever disabled,
75629 ** but joins might run a little slower.  The trick is to disable as much
75630 ** as we can without disabling too much.  If we disabled in (1), we'd get
75631 ** the wrong answer.  See ticket #813.
75632 */
75633 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
75634   if( pTerm
75635       && ALWAYS((pTerm->flags & TERM_CODED)==0)
75636       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
75637   ){
75638     pTerm->flags |= TERM_CODED;
75639     if( pTerm->iParent>=0 ){
75640       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
75641       if( (--pOther->nChild)==0 ){
75642         disableTerm(pLevel, pOther);
75643       }
75644     }
75645   }
75646 }
75647
75648 /*
75649 ** Apply the affinities associated with the first n columns of index
75650 ** pIdx to the values in the n registers starting at base.
75651 */
75652 static void codeApplyAffinity(Parse *pParse, int base, int n, Index *pIdx){
75653   if( n>0 ){
75654     Vdbe *v = pParse->pVdbe;
75655     assert( v!=0 );
75656     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
75657     sqlite3IndexAffinityStr(v, pIdx);
75658     sqlite3ExprCacheAffinityChange(pParse, base, n);
75659   }
75660 }
75661
75662
75663 /*
75664 ** Generate code for a single equality term of the WHERE clause.  An equality
75665 ** term can be either X=expr or X IN (...).   pTerm is the term to be 
75666 ** coded.
75667 **
75668 ** The current value for the constraint is left in register iReg.
75669 **
75670 ** For a constraint of the form X=expr, the expression is evaluated and its
75671 ** result is left on the stack.  For constraints of the form X IN (...)
75672 ** this routine sets up a loop that will iterate over all values of X.
75673 */
75674 static int codeEqualityTerm(
75675   Parse *pParse,      /* The parsing context */
75676   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
75677   WhereLevel *pLevel, /* When level of the FROM clause we are working on */
75678   int iTarget         /* Attempt to leave results in this register */
75679 ){
75680   Expr *pX = pTerm->pExpr;
75681   Vdbe *v = pParse->pVdbe;
75682   int iReg;                  /* Register holding results */
75683
75684   if( iTarget<=0 ){
75685     iReg = iTarget = sqlite3GetTempReg(pParse);
75686   }
75687   if( pX->op==TK_EQ ){
75688     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
75689   }else if( pX->op==TK_ISNULL ){
75690     iReg = iTarget;
75691     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
75692 #ifndef SQLITE_OMIT_SUBQUERY
75693   }else{
75694     int eType;
75695     int iTab;
75696     struct InLoop *pIn;
75697
75698     assert( pX->op==TK_IN );
75699     iReg = iTarget;
75700     eType = sqlite3FindInIndex(pParse, pX, 0);
75701     iTab = pX->iTable;
75702     sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
75703     VdbeComment((v, "%.*s", pX->span.n, pX->span.z));
75704     if( pLevel->nIn==0 ){
75705       pLevel->nxt = sqlite3VdbeMakeLabel(v);
75706     }
75707     pLevel->nIn++;
75708     pLevel->aInLoop = sqlite3DbReallocOrFree(pParse->db, pLevel->aInLoop,
75709                                     sizeof(pLevel->aInLoop[0])*pLevel->nIn);
75710     pIn = pLevel->aInLoop;
75711     if( pIn ){
75712       pIn += pLevel->nIn - 1;
75713       pIn->iCur = iTab;
75714       if( eType==IN_INDEX_ROWID ){
75715         pIn->topAddr = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
75716       }else{
75717         pIn->topAddr = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
75718       }
75719       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
75720     }else{
75721       pLevel->nIn = 0;
75722     }
75723 #endif
75724   }
75725   disableTerm(pLevel, pTerm);
75726   return iReg;
75727 }
75728
75729 /*
75730 ** Generate code that will evaluate all == and IN constraints for an
75731 ** index.  The values for all constraints are left on the stack.
75732 **
75733 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
75734 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
75735 ** The index has as many as three equality constraints, but in this
75736 ** example, the third "c" value is an inequality.  So only two 
75737 ** constraints are coded.  This routine will generate code to evaluate
75738 ** a==5 and b IN (1,2,3).  The current values for a and b will be left
75739 ** on the stack - a is the deepest and b the shallowest.
75740 **
75741 ** In the example above nEq==2.  But this subroutine works for any value
75742 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
75743 ** The only thing it does is allocate the pLevel->iMem memory cell.
75744 **
75745 ** This routine always allocates at least one memory cell and puts
75746 ** the address of that memory cell in pLevel->iMem.  The code that
75747 ** calls this routine will use pLevel->iMem to store the termination
75748 ** key value of the loop.  If one or more IN operators appear, then
75749 ** this routine allocates an additional nEq memory cells for internal
75750 ** use.
75751 */
75752 static int codeAllEqualityTerms(
75753   Parse *pParse,        /* Parsing context */
75754   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
75755   WhereClause *pWC,     /* The WHERE clause */
75756   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
75757   int nExtraReg         /* Number of extra registers to allocate */
75758 ){
75759   int nEq = pLevel->nEq;        /* The number of == or IN constraints to code */
75760   Vdbe *v = pParse->pVdbe;      /* The virtual machine under construction */
75761   Index *pIdx = pLevel->pIdx;   /* The index being used for this loop */
75762   int iCur = pLevel->iTabCur;   /* The cursor of the table */
75763   WhereTerm *pTerm;             /* A single constraint term */
75764   int j;                        /* Loop counter */
75765   int regBase;                  /* Base register */
75766
75767   /* Figure out how many memory cells we will need then allocate them.
75768   ** We always need at least one used to store the loop terminator
75769   ** value.  If there are IN operators we'll need one for each == or
75770   ** IN constraint.
75771   */
75772   pLevel->iMem = pParse->nMem + 1;
75773   regBase = pParse->nMem + 2;
75774   pParse->nMem += pLevel->nEq + 2 + nExtraReg;
75775
75776   /* Evaluate the equality constraints
75777   */
75778   assert( pIdx->nColumn>=nEq );
75779   for(j=0; j<nEq; j++){
75780     int r1;
75781     int k = pIdx->aiColumn[j];
75782     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->flags, pIdx);
75783     if( NEVER(pTerm==0) ) break;
75784     assert( (pTerm->flags & TERM_CODED)==0 );
75785     r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
75786     if( r1!=regBase+j ){
75787       sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
75788     }
75789     testcase( pTerm->eOperator & WO_ISNULL );
75790     testcase( pTerm->eOperator & WO_IN );
75791     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
75792       sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->brk);
75793     }
75794   }
75795   return regBase;
75796 }
75797
75798 #if defined(SQLITE_TEST)
75799 /*
75800 ** The following variable holds a text description of query plan generated
75801 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
75802 ** overwrites the previous.  This information is used for testing and
75803 ** analysis only.
75804 */
75805 SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
75806 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
75807
75808 #endif /* SQLITE_TEST */
75809
75810
75811 /*
75812 ** Free a WhereInfo structure
75813 */
75814 static void whereInfoFree(WhereInfo *pWInfo){
75815   if( pWInfo ){
75816     int i;
75817     sqlite3 *db = pWInfo->pParse->db;
75818     for(i=0; i<pWInfo->nLevel; i++){
75819       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
75820       if( pInfo ){
75821         assert( pInfo->needToFreeIdxStr==0 );
75822         sqlite3DbFree(db, pInfo);
75823       }
75824     }
75825     sqlite3DbFree(db, pWInfo);
75826   }
75827 }
75828
75829
75830 /*
75831 ** Generate the beginning of the loop used for WHERE clause processing.
75832 ** The return value is a pointer to an opaque structure that contains
75833 ** information needed to terminate the loop.  Later, the calling routine
75834 ** should invoke sqlite3WhereEnd() with the return value of this function
75835 ** in order to complete the WHERE clause processing.
75836 **
75837 ** If an error occurs, this routine returns NULL.
75838 **
75839 ** The basic idea is to do a nested loop, one loop for each table in
75840 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
75841 ** same as a SELECT with only a single table in the FROM clause.)  For
75842 ** example, if the SQL is this:
75843 **
75844 **       SELECT * FROM t1, t2, t3 WHERE ...;
75845 **
75846 ** Then the code generated is conceptually like the following:
75847 **
75848 **      foreach row1 in t1 do       \    Code generated
75849 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
75850 **          foreach row3 in t3 do   /
75851 **            ...
75852 **          end                     \    Code generated
75853 **        end                        |-- by sqlite3WhereEnd()
75854 **      end                         /
75855 **
75856 ** Note that the loops might not be nested in the order in which they
75857 ** appear in the FROM clause if a different order is better able to make
75858 ** use of indices.  Note also that when the IN operator appears in
75859 ** the WHERE clause, it might result in additional nested loops for
75860 ** scanning through all values on the right-hand side of the IN.
75861 **
75862 ** There are Btree cursors associated with each table.  t1 uses cursor
75863 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
75864 ** And so forth.  This routine generates code to open those VDBE cursors
75865 ** and sqlite3WhereEnd() generates the code to close them.
75866 **
75867 ** The code that sqlite3WhereBegin() generates leaves the cursors named
75868 ** in pTabList pointing at their appropriate entries.  The [...] code
75869 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
75870 ** data from the various tables of the loop.
75871 **
75872 ** If the WHERE clause is empty, the foreach loops must each scan their
75873 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
75874 ** the tables have indices and there are terms in the WHERE clause that
75875 ** refer to those indices, a complete table scan can be avoided and the
75876 ** code will run much faster.  Most of the work of this routine is checking
75877 ** to see if there are indices that can be used to speed up the loop.
75878 **
75879 ** Terms of the WHERE clause are also used to limit which rows actually
75880 ** make it to the "..." in the middle of the loop.  After each "foreach",
75881 ** terms of the WHERE clause that use only terms in that loop and outer
75882 ** loops are evaluated and if false a jump is made around all subsequent
75883 ** inner loops (or around the "..." if the test occurs within the inner-
75884 ** most loop)
75885 **
75886 ** OUTER JOINS
75887 **
75888 ** An outer join of tables t1 and t2 is conceptally coded as follows:
75889 **
75890 **    foreach row1 in t1 do
75891 **      flag = 0
75892 **      foreach row2 in t2 do
75893 **        start:
75894 **          ...
75895 **          flag = 1
75896 **      end
75897 **      if flag==0 then
75898 **        move the row2 cursor to a null row
75899 **        goto start
75900 **      fi
75901 **    end
75902 **
75903 ** ORDER BY CLAUSE PROCESSING
75904 **
75905 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
75906 ** if there is one.  If there is no ORDER BY clause or if this routine
75907 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
75908 **
75909 ** If an index can be used so that the natural output order of the table
75910 ** scan is correct for the ORDER BY clause, then that index is used and
75911 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
75912 ** unnecessary sort of the result set if an index appropriate for the
75913 ** ORDER BY clause already exists.
75914 **
75915 ** If the where clause loops cannot be arranged to provide the correct
75916 ** output order, then the *ppOrderBy is unchanged.
75917 */
75918 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
75919   Parse *pParse,        /* The parser context */
75920   SrcList *pTabList,    /* A list of all tables to be scanned */
75921   Expr *pWhere,         /* The WHERE clause */
75922   ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
75923   u8 wflags             /* One of the WHERE_* flags defined in sqliteInt.h */
75924 ){
75925   int i;                     /* Loop counter */
75926   WhereInfo *pWInfo;         /* Will become the return value of this function */
75927   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
75928   int brk, cont = 0;         /* Addresses used during code generation */
75929   Bitmask notReady;          /* Cursors that are not yet positioned */
75930   WhereTerm *pTerm;          /* A single term in the WHERE clause */
75931   ExprMaskSet maskSet;       /* The expression mask set */
75932   WhereClause wc;            /* The WHERE clause is divided into these terms */
75933   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
75934   WhereLevel *pLevel;             /* A single level in the pWInfo list */
75935   int iFrom;                      /* First unused FROM clause element */
75936   int andFlags;              /* AND-ed combination of all wc.a[].flags */
75937   sqlite3 *db;               /* Database connection */
75938   ExprList *pOrderBy = 0;
75939
75940   /* The number of tables in the FROM clause is limited by the number of
75941   ** bits in a Bitmask 
75942   */
75943   if( pTabList->nSrc>BMS ){
75944     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
75945     return 0;
75946   }
75947
75948   if( ppOrderBy ){
75949     pOrderBy = *ppOrderBy;
75950   }
75951
75952   /* Split the WHERE clause into separate subexpressions where each
75953   ** subexpression is separated by an AND operator.
75954   */
75955   initMaskSet(&maskSet);
75956   whereClauseInit(&wc, pParse, &maskSet);
75957   sqlite3ExprCodeConstants(pParse, pWhere);
75958   whereSplit(&wc, pWhere, TK_AND);
75959     
75960   /* Allocate and initialize the WhereInfo structure that will become the
75961   ** return value.
75962   */
75963   db = pParse->db;
75964   pWInfo = sqlite3DbMallocZero(db,  
75965                       sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
75966   if( db->mallocFailed ){
75967     goto whereBeginNoMem;
75968   }
75969   pWInfo->nLevel = pTabList->nSrc;
75970   pWInfo->pParse = pParse;
75971   pWInfo->pTabList = pTabList;
75972   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
75973
75974   /* Special case: a WHERE clause that is constant.  Evaluate the
75975   ** expression and either jump over all of the code or fall thru.
75976   */
75977   if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
75978     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
75979     pWhere = 0;
75980   }
75981
75982   /* Assign a bit from the bitmask to every term in the FROM clause.
75983   **
75984   ** When assigning bitmask values to FROM clause cursors, it must be
75985   ** the case that if X is the bitmask for the N-th FROM clause term then
75986   ** the bitmask for all FROM clause terms to the left of the N-th term
75987   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
75988   ** its Expr.iRightJoinTable value to find the bitmask of the right table
75989   ** of the join.  Subtracting one from the right table bitmask gives a
75990   ** bitmask for all tables to the left of the join.  Knowing the bitmask
75991   ** for all tables to the left of a left join is important.  Ticket #3015.
75992   */
75993   for(i=0; i<pTabList->nSrc; i++){
75994     createMask(&maskSet, pTabList->a[i].iCursor);
75995   }
75996 #ifndef NDEBUG
75997   {
75998     Bitmask toTheLeft = 0;
75999     for(i=0; i<pTabList->nSrc; i++){
76000       Bitmask m = getMask(&maskSet, pTabList->a[i].iCursor);
76001       assert( (m-1)==toTheLeft );
76002       toTheLeft |= m;
76003     }
76004   }
76005 #endif
76006
76007   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
76008   ** add new virtual terms onto the end of the WHERE clause.  We do not
76009   ** want to analyze these virtual terms, so start analyzing at the end
76010   ** and work forward so that the added virtual terms are never processed.
76011   */
76012   exprAnalyzeAll(pTabList, &wc);
76013   if( db->mallocFailed ){
76014     goto whereBeginNoMem;
76015   }
76016
76017   /* Chose the best index to use for each table in the FROM clause.
76018   **
76019   ** This loop fills in the following fields:
76020   **
76021   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
76022   **   pWInfo->a[].flags     WHERE_xxx flags associated with pIdx
76023   **   pWInfo->a[].nEq       The number of == and IN constraints
76024   **   pWInfo->a[].iFrom     When term of the FROM clause is being coded
76025   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
76026   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
76027   **
76028   ** This loop also figures out the nesting order of tables in the FROM
76029   ** clause.
76030   */
76031   notReady = ~(Bitmask)0;
76032   pTabItem = pTabList->a;
76033   pLevel = pWInfo->a;
76034   andFlags = ~0;
76035   WHERETRACE(("*** Optimizer Start ***\n"));
76036   for(i=iFrom=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
76037     Index *pIdx;                /* Index for FROM table at pTabItem */
76038     int flags;                  /* Flags asssociated with pIdx */
76039     int nEq;                    /* Number of == or IN constraints */
76040     double cost;                /* The cost for pIdx */
76041     int j;                      /* For looping over FROM tables */
76042     Index *pBest = 0;           /* The best index seen so far */
76043     int bestFlags = 0;          /* Flags associated with pBest */
76044     int bestNEq = 0;            /* nEq associated with pBest */
76045     double lowestCost;          /* Cost of the pBest */
76046     int bestJ = 0;              /* The value of j */
76047     Bitmask m;                  /* Bitmask value for j or bestJ */
76048     int once = 0;               /* True when first table is seen */
76049     sqlite3_index_info *pIndex; /* Current virtual index */
76050
76051     lowestCost = SQLITE_BIG_DBL;
76052     for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
76053       int doNotReorder;  /* True if this table should not be reordered */
76054
76055       doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
76056       if( once && doNotReorder ) break;
76057       m = getMask(&maskSet, pTabItem->iCursor);
76058       if( (m & notReady)==0 ){
76059         if( j==iFrom ) iFrom++;
76060         continue;
76061       }
76062       assert( pTabItem->pTab );
76063 #ifndef SQLITE_OMIT_VIRTUALTABLE
76064       if( IsVirtual(pTabItem->pTab) ){
76065         sqlite3_index_info **ppIdxInfo = &pWInfo->a[j].pIdxInfo;
76066         cost = bestVirtualIndex(pParse, &wc, pTabItem, notReady,
76067                                 ppOrderBy ? *ppOrderBy : 0, i==0,
76068                                 ppIdxInfo);
76069         flags = WHERE_VIRTUALTABLE;
76070         pIndex = *ppIdxInfo;
76071         if( pIndex && pIndex->orderByConsumed ){
76072           flags = WHERE_VIRTUALTABLE | WHERE_ORDERBY;
76073         }
76074         pIdx = 0;
76075         nEq = 0;
76076         if( (SQLITE_BIG_DBL/2.0)<cost ){
76077           /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
76078           ** inital value of lowestCost in this loop. If it is, then
76079           ** the (cost<lowestCost) test below will never be true and
76080           ** pLevel->pBestIdx never set.
76081           */ 
76082           cost = (SQLITE_BIG_DBL/2.0);
76083         }
76084       }else 
76085 #endif
76086       {
76087         cost = bestIndex(pParse, &wc, pTabItem, notReady,
76088                          (i==0 && ppOrderBy) ? *ppOrderBy : 0,
76089                          &pIdx, &flags, &nEq);
76090         pIndex = 0;
76091       }
76092       if( cost<lowestCost ){
76093         once = 1;
76094         lowestCost = cost;
76095         pBest = pIdx;
76096         bestFlags = flags;
76097         bestNEq = nEq;
76098         bestJ = j;
76099         pLevel->pBestIdx = pIndex;
76100       }
76101       if( doNotReorder ) break;
76102     }
76103     WHERETRACE(("*** Optimizer selects table %d for loop %d\n", bestJ,
76104            pLevel-pWInfo->a));
76105     if( (bestFlags & WHERE_ORDERBY)!=0 ){
76106       *ppOrderBy = 0;
76107     }
76108     andFlags &= bestFlags;
76109     pLevel->flags = bestFlags;
76110     pLevel->pIdx = pBest;
76111     pLevel->nEq = bestNEq;
76112     pLevel->aInLoop = 0;
76113     pLevel->nIn = 0;
76114     if( pBest ){
76115       pLevel->iIdxCur = pParse->nTab++;
76116     }else{
76117       pLevel->iIdxCur = -1;
76118     }
76119     notReady &= ~getMask(&maskSet, pTabList->a[bestJ].iCursor);
76120     pLevel->iFrom = bestJ;
76121   }
76122   WHERETRACE(("*** Optimizer Finished ***\n"));
76123
76124   /* If the total query only selects a single row, then the ORDER BY
76125   ** clause is irrelevant.
76126   */
76127   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
76128     *ppOrderBy = 0;
76129   }
76130
76131   /* If the caller is an UPDATE or DELETE statement that is requesting
76132   ** to use a one-pass algorithm, determine if this is appropriate.
76133   ** The one-pass algorithm only works if the WHERE clause constraints
76134   ** the statement to update a single row.
76135   */
76136   assert( (wflags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
76137   if( (wflags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
76138     pWInfo->okOnePass = 1;
76139     pWInfo->a[0].flags &= ~WHERE_IDX_ONLY;
76140   }
76141
76142   /* Open all tables in the pTabList and any indices selected for
76143   ** searching those tables.
76144   */
76145   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
76146   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
76147     Table *pTab;     /* Table to open */
76148     Index *pIx;      /* Index used to access pTab (if any) */
76149     int iDb;         /* Index of database containing table/index */
76150     int iIdxCur = pLevel->iIdxCur;
76151
76152 #ifndef SQLITE_OMIT_EXPLAIN
76153     if( pParse->explain==2 ){
76154       char *zMsg;
76155       struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
76156       zMsg = sqlite3MPrintf(db, "TABLE %s", pItem->zName);
76157       if( pItem->zAlias ){
76158         zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
76159       }
76160       if( (pIx = pLevel->pIdx)!=0 ){
76161         zMsg = sqlite3MAppendf(db, zMsg, "%s WITH INDEX %s", zMsg, pIx->zName);
76162       }else if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
76163         zMsg = sqlite3MAppendf(db, zMsg, "%s USING PRIMARY KEY", zMsg);
76164       }
76165 #ifndef SQLITE_OMIT_VIRTUALTABLE
76166       else if( pLevel->pBestIdx ){
76167         sqlite3_index_info *pBestIdx = pLevel->pBestIdx;
76168         zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
76169                     pBestIdx->idxNum, pBestIdx->idxStr);
76170       }
76171 #endif
76172       if( pLevel->flags & WHERE_ORDERBY ){
76173         zMsg = sqlite3MAppendf(db, zMsg, "%s ORDER BY", zMsg);
76174       }
76175       sqlite3VdbeAddOp4(v, OP_Explain, i, pLevel->iFrom, 0, zMsg, P4_DYNAMIC);
76176     }
76177 #endif /* SQLITE_OMIT_EXPLAIN */
76178     pTabItem = &pTabList->a[pLevel->iFrom];
76179     pTab = pTabItem->pTab;
76180     iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
76181     if( pTab->isEphem || pTab->pSelect ) continue;
76182 #ifndef SQLITE_OMIT_VIRTUALTABLE
76183     if( pLevel->pBestIdx ){
76184       int iCur = pTabItem->iCursor;
76185       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0,
76186                         (const char*)pTab->pVtab, P4_VTAB);
76187     }else
76188 #endif
76189     if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
76190       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
76191       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
76192       if( !pWInfo->okOnePass && pTab->nCol<(sizeof(Bitmask)*8) ){
76193         Bitmask b = pTabItem->colUsed;
76194         int n = 0;
76195         for(; b; b=b>>1, n++){}
76196         sqlite3VdbeChangeP2(v, sqlite3VdbeCurrentAddr(v)-2, n);
76197         assert( n<=pTab->nCol );
76198       }
76199     }else{
76200       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
76201     }
76202     pLevel->iTabCur = pTabItem->iCursor;
76203     if( (pIx = pLevel->pIdx)!=0 ){
76204       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
76205       assert( pIx->pSchema==pTab->pSchema );
76206       sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pIx->nColumn+1);
76207       sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
76208                         (char*)pKey, P4_KEYINFO_HANDOFF);
76209       VdbeComment((v, "%s", pIx->zName));
76210     }
76211     sqlite3CodeVerifySchema(pParse, iDb);
76212   }
76213   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
76214
76215   /* Generate the code to do the search.  Each iteration of the for
76216   ** loop below generates code for a single nested loop of the VM
76217   ** program.
76218   */
76219   notReady = ~(Bitmask)0;
76220   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
76221     int j;
76222     int iCur = pTabItem->iCursor;  /* The VDBE cursor for the table */
76223     Index *pIdx;       /* The index we will be using */
76224     int nxt;           /* Where to jump to continue with the next IN case */
76225     int iIdxCur;       /* The VDBE cursor for the index */
76226     int omitTable;     /* True if we use the index only */
76227     int bRev;          /* True if we need to scan in reverse order */
76228
76229     pTabItem = &pTabList->a[pLevel->iFrom];
76230     iCur = pTabItem->iCursor;
76231     pIdx = pLevel->pIdx;
76232     iIdxCur = pLevel->iIdxCur;
76233     bRev = (pLevel->flags & WHERE_REVERSE)!=0;
76234     omitTable = (pLevel->flags & WHERE_IDX_ONLY)!=0;
76235
76236     /* Create labels for the "break" and "continue" instructions
76237     ** for the current loop.  Jump to brk to break out of a loop.
76238     ** Jump to cont to go immediately to the next iteration of the
76239     ** loop.
76240     **
76241     ** When there is an IN operator, we also have a "nxt" label that
76242     ** means to continue with the next IN value combination.  When
76243     ** there are no IN operators in the constraints, the "nxt" label
76244     ** is the same as "brk".
76245     */
76246     brk = pLevel->brk = pLevel->nxt = sqlite3VdbeMakeLabel(v);
76247     cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
76248
76249     /* If this is the right table of a LEFT OUTER JOIN, allocate and
76250     ** initialize a memory cell that records if this table matches any
76251     ** row of the left table of the join.
76252     */
76253     if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
76254       pLevel->iLeftJoin = ++pParse->nMem;
76255       sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
76256       VdbeComment((v, "init LEFT JOIN no-match flag"));
76257     }
76258
76259 #ifndef SQLITE_OMIT_VIRTUALTABLE
76260     if( pLevel->pBestIdx ){
76261       /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
76262       **          to access the data.
76263       */
76264       int j;
76265       int iReg;   /* P3 Value for OP_VFilter */
76266       sqlite3_index_info *pBestIdx = pLevel->pBestIdx;
76267       int nConstraint = pBestIdx->nConstraint;
76268       struct sqlite3_index_constraint_usage *aUsage =
76269                                                   pBestIdx->aConstraintUsage;
76270       const struct sqlite3_index_constraint *aConstraint =
76271                                                   pBestIdx->aConstraint;
76272
76273       iReg = sqlite3GetTempRange(pParse, nConstraint+2);
76274       pParse->disableColCache++;
76275       for(j=1; j<=nConstraint; j++){
76276         int k;
76277         for(k=0; k<nConstraint; k++){
76278           if( aUsage[k].argvIndex==j ){
76279             int iTerm = aConstraint[k].iTermOffset;
76280             assert( pParse->disableColCache );
76281             sqlite3ExprCode(pParse, wc.a[iTerm].pExpr->pRight, iReg+j+1);
76282             break;
76283           }
76284         }
76285         if( k==nConstraint ) break;
76286       }
76287       assert( pParse->disableColCache );
76288       pParse->disableColCache--;
76289       sqlite3VdbeAddOp2(v, OP_Integer, pBestIdx->idxNum, iReg);
76290       sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
76291       sqlite3VdbeAddOp4(v, OP_VFilter, iCur, brk, iReg, pBestIdx->idxStr,
76292                         pBestIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
76293       sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
76294       pBestIdx->needToFreeIdxStr = 0;
76295       for(j=0; j<nConstraint; j++){
76296         if( aUsage[j].omit ){
76297           int iTerm = aConstraint[j].iTermOffset;
76298           disableTerm(pLevel, &wc.a[iTerm]);
76299         }
76300       }
76301       pLevel->op = OP_VNext;
76302       pLevel->p1 = iCur;
76303       pLevel->p2 = sqlite3VdbeCurrentAddr(v);
76304     }else
76305 #endif /* SQLITE_OMIT_VIRTUALTABLE */
76306
76307     if( pLevel->flags & WHERE_ROWID_EQ ){
76308       /* Case 1:  We can directly reference a single row using an
76309       **          equality comparison against the ROWID field.  Or
76310       **          we reference multiple rows using a "rowid IN (...)"
76311       **          construct.
76312       */
76313       int r1;
76314       pTerm = findTerm(&wc, iCur, -1, notReady, WO_EQ|WO_IN, 0);
76315       assert( pTerm!=0 );
76316       assert( pTerm->pExpr!=0 );
76317       assert( pTerm->leftCursor==iCur );
76318       assert( omitTable==0 );
76319       r1 = codeEqualityTerm(pParse, pTerm, pLevel, 0);
76320       nxt = pLevel->nxt;
76321       sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, nxt);
76322       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, nxt, r1);
76323       VdbeComment((v, "pk"));
76324       pLevel->op = OP_Noop;
76325     }else if( pLevel->flags & WHERE_ROWID_RANGE ){
76326       /* Case 2:  We have an inequality comparison against the ROWID field.
76327       */
76328       int testOp = OP_Noop;
76329       int start;
76330       WhereTerm *pStart, *pEnd;
76331
76332       assert( omitTable==0 );
76333       pStart = findTerm(&wc, iCur, -1, notReady, WO_GT|WO_GE, 0);
76334       pEnd = findTerm(&wc, iCur, -1, notReady, WO_LT|WO_LE, 0);
76335       if( bRev ){
76336         pTerm = pStart;
76337         pStart = pEnd;
76338         pEnd = pTerm;
76339       }
76340       if( pStart ){
76341         Expr *pX;
76342         int r1, regFree1;
76343         pX = pStart->pExpr;
76344         assert( pX!=0 );
76345         assert( pStart->leftCursor==iCur );
76346         r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &regFree1);
76347         sqlite3VdbeAddOp3(v, OP_ForceInt, r1, brk, 
76348                              pX->op==TK_LE || pX->op==TK_GT);
76349         sqlite3VdbeAddOp3(v, bRev ? OP_MoveLt : OP_MoveGe, iCur, brk, r1);
76350         VdbeComment((v, "pk"));
76351         sqlite3ReleaseTempReg(pParse, regFree1);
76352         disableTerm(pLevel, pStart);
76353       }else{
76354         sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, brk);
76355       }
76356       if( pEnd ){
76357         Expr *pX;
76358         pX = pEnd->pExpr;
76359         assert( pX!=0 );
76360         assert( pEnd->leftCursor==iCur );
76361         pLevel->iMem = ++pParse->nMem;
76362         sqlite3ExprCode(pParse, pX->pRight, pLevel->iMem);
76363         if( pX->op==TK_LT || pX->op==TK_GT ){
76364           testOp = bRev ? OP_Le : OP_Ge;
76365         }else{
76366           testOp = bRev ? OP_Lt : OP_Gt;
76367         }
76368         disableTerm(pLevel, pEnd);
76369       }
76370       start = sqlite3VdbeCurrentAddr(v);
76371       pLevel->op = bRev ? OP_Prev : OP_Next;
76372       pLevel->p1 = iCur;
76373       pLevel->p2 = start;
76374       if( testOp!=OP_Noop ){
76375         int r1 = sqlite3GetTempReg(pParse);
76376         sqlite3VdbeAddOp2(v, OP_Rowid, iCur, r1);
76377         /* sqlite3VdbeAddOp2(v, OP_SCopy, pLevel->iMem, 0); */
76378         sqlite3VdbeAddOp3(v, testOp, pLevel->iMem, brk, r1);
76379         sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
76380         sqlite3ReleaseTempReg(pParse, r1);
76381       }
76382     }else if( pLevel->flags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
76383       /* Case 3: A scan using an index.
76384       **
76385       **         The WHERE clause may contain zero or more equality 
76386       **         terms ("==" or "IN" operators) that refer to the N
76387       **         left-most columns of the index. It may also contain
76388       **         inequality constraints (>, <, >= or <=) on the indexed
76389       **         column that immediately follows the N equalities. Only 
76390       **         the right-most column can be an inequality - the rest must
76391       **         use the "==" and "IN" operators. For example, if the 
76392       **         index is on (x,y,z), then the following clauses are all 
76393       **         optimized:
76394       **
76395       **            x=5
76396       **            x=5 AND y=10
76397       **            x=5 AND y<10
76398       **            x=5 AND y>5 AND y<10
76399       **            x=5 AND y=5 AND z<=10
76400       **
76401       **         The z<10 term of the following cannot be used, only
76402       **         the x=5 term:
76403       **
76404       **            x=5 AND z<10
76405       **
76406       **         N may be zero if there are inequality constraints.
76407       **         If there are no inequality constraints, then N is at
76408       **         least one.
76409       **
76410       **         This case is also used when there are no WHERE clause
76411       **         constraints but an index is selected anyway, in order
76412       **         to force the output order to conform to an ORDER BY.
76413       */  
76414       int aStartOp[] = {
76415         0,
76416         0,
76417         OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
76418         OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
76419         OP_MoveGt,           /* 4: (start_constraints  && !startEq && !bRev) */
76420         OP_MoveLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
76421         OP_MoveGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
76422         OP_MoveLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
76423       };
76424       int aEndOp[] = {
76425         OP_Noop,             /* 0: (!end_constraints) */
76426         OP_IdxGE,            /* 1: (end_constraints && !bRev) */
76427         OP_IdxLT             /* 2: (end_constraints && bRev) */
76428       };
76429       int nEq = pLevel->nEq;
76430       int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
76431       int regBase;                 /* Base register holding constraint values */
76432       int r1;                      /* Temp register */
76433       WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
76434       WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
76435       int startEq;                 /* True if range start uses ==, >= or <= */
76436       int endEq;                   /* True if range end uses ==, >= or <= */
76437       int start_constraints;       /* Start of range is constrained */
76438       int k = pIdx->aiColumn[nEq]; /* Column for inequality constraints */
76439       int nConstraint;             /* Number of constraint terms */
76440       int op;
76441
76442       /* Generate code to evaluate all constraint terms using == or IN
76443       ** and store the values of those terms in an array of registers
76444       ** starting at regBase.
76445       */
76446       regBase = codeAllEqualityTerms(pParse, pLevel, &wc, notReady, 2);
76447       nxt = pLevel->nxt;
76448
76449       /* If this loop satisfies a sort order (pOrderBy) request that 
76450       ** was passed to this function to implement a "SELECT min(x) ..." 
76451       ** query, then the caller will only allow the loop to run for
76452       ** a single iteration. This means that the first row returned
76453       ** should not have a NULL value stored in 'x'. If column 'x' is
76454       ** the first one after the nEq equality constraints in the index,
76455       ** this requires some special handling.
76456       */
76457       if( (wflags&WHERE_ORDERBY_MIN)!=0
76458        && (pLevel->flags&WHERE_ORDERBY)
76459        && (pIdx->nColumn>nEq)
76460       ){
76461         assert( pOrderBy->nExpr==1 );
76462         assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] );
76463         isMinQuery = 1;
76464       }
76465
76466       /* Find any inequality constraint terms for the start and end 
76467       ** of the range. 
76468       */
76469       if( pLevel->flags & WHERE_TOP_LIMIT ){
76470         pRangeEnd = findTerm(&wc, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
76471       }
76472       if( pLevel->flags & WHERE_BTM_LIMIT ){
76473         pRangeStart = findTerm(&wc, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
76474       }
76475
76476       /* If we are doing a reverse order scan on an ascending index, or
76477       ** a forward order scan on a descending index, interchange the 
76478       ** start and end terms (pRangeStart and pRangeEnd).
76479       */
76480       if( bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
76481         SWAP(WhereTerm *, pRangeEnd, pRangeStart);
76482       }
76483
76484       testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
76485       testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
76486       testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
76487       testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
76488       startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
76489       endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
76490       start_constraints = pRangeStart || nEq>0;
76491
76492       /* Seek the index cursor to the start of the range. */
76493       nConstraint = nEq;
76494       if( pRangeStart ){
76495         int dcc = pParse->disableColCache;
76496         if( pRangeEnd ){
76497           pParse->disableColCache++;
76498         }
76499         sqlite3ExprCode(pParse, pRangeStart->pExpr->pRight, regBase+nEq);
76500         pParse->disableColCache = dcc;
76501         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, nxt);
76502         nConstraint++;
76503       }else if( isMinQuery ){
76504         sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
76505         nConstraint++;
76506         startEq = 0;
76507         start_constraints = 1;
76508       }
76509       codeApplyAffinity(pParse, regBase, nConstraint, pIdx);
76510       op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
76511       assert( op!=0 );
76512       testcase( op==OP_Rewind );
76513       testcase( op==OP_Last );
76514       testcase( op==OP_MoveGt );
76515       testcase( op==OP_MoveGe );
76516       testcase( op==OP_MoveLe );
76517       testcase( op==OP_MoveLt );
76518       sqlite3VdbeAddOp4(v, op, iIdxCur, nxt, regBase, 
76519                         SQLITE_INT_TO_PTR(nConstraint), P4_INT32);
76520
76521       /* Load the value for the inequality constraint at the end of the
76522       ** range (if any).
76523       */
76524       nConstraint = nEq;
76525       if( pRangeEnd ){
76526         sqlite3ExprCode(pParse, pRangeEnd->pExpr->pRight, regBase+nEq);
76527         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, nxt);
76528         codeApplyAffinity(pParse, regBase, nEq+1, pIdx);
76529         nConstraint++;
76530       }
76531
76532       /* Top of the loop body */
76533       pLevel->p2 = sqlite3VdbeCurrentAddr(v);
76534
76535       /* Check if the index cursor is past the end of the range. */
76536       op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
76537       testcase( op==OP_Noop );
76538       testcase( op==OP_IdxGE );
76539       testcase( op==OP_IdxLT );
76540       sqlite3VdbeAddOp4(v, op, iIdxCur, nxt, regBase,
76541                         SQLITE_INT_TO_PTR(nConstraint), P4_INT32);
76542       sqlite3VdbeChangeP5(v, endEq!=bRev);
76543
76544       /* If there are inequality constraints, check that the value
76545       ** of the table column that the inequality contrains is not NULL.
76546       ** If it is, jump to the next iteration of the loop.
76547       */
76548       r1 = sqlite3GetTempReg(pParse);
76549       testcase( pLevel->flags & WHERE_BTM_LIMIT );
76550       testcase( pLevel->flags & WHERE_TOP_LIMIT );
76551       if( pLevel->flags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT) ){
76552         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
76553         sqlite3VdbeAddOp2(v, OP_IsNull, r1, cont);
76554       }
76555
76556       /* Seek the table cursor, if required */
76557       if( !omitTable ){
76558         sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, r1);
76559         sqlite3VdbeAddOp3(v, OP_MoveGe, iCur, 0, r1);  /* Deferred seek */
76560       }
76561       sqlite3ReleaseTempReg(pParse, r1);
76562
76563       /* Record the instruction used to terminate the loop. Disable 
76564       ** WHERE clause terms made redundant by the index range scan.
76565       */
76566       pLevel->op = bRev ? OP_Prev : OP_Next;
76567       pLevel->p1 = iIdxCur;
76568       disableTerm(pLevel, pRangeStart);
76569       disableTerm(pLevel, pRangeEnd);
76570     }else{
76571       /* Case 4:  There is no usable index.  We must do a complete
76572       **          scan of the entire table.
76573       */
76574       assert( omitTable==0 );
76575       assert( bRev==0 );
76576       pLevel->op = OP_Next;
76577       pLevel->p1 = iCur;
76578       pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, OP_Rewind, iCur, brk);
76579     }
76580     notReady &= ~getMask(&maskSet, iCur);
76581
76582     /* Insert code to test every subexpression that can be completely
76583     ** computed using the current set of tables.
76584     */
76585     for(pTerm=wc.a, j=wc.nTerm; j>0; j--, pTerm++){
76586       Expr *pE;
76587       testcase( pTerm->flags & TERM_VIRTUAL );
76588       testcase( pTerm->flags & TERM_CODED );
76589       if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
76590       if( (pTerm->prereqAll & notReady)!=0 ) continue;
76591       pE = pTerm->pExpr;
76592       assert( pE!=0 );
76593       if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
76594         continue;
76595       }
76596       sqlite3ExprIfFalse(pParse, pE, cont, SQLITE_JUMPIFNULL);
76597       pTerm->flags |= TERM_CODED;
76598     }
76599
76600     /* For a LEFT OUTER JOIN, generate code that will record the fact that
76601     ** at least one row of the right table has matched the left table.  
76602     */
76603     if( pLevel->iLeftJoin ){
76604       pLevel->top = sqlite3VdbeCurrentAddr(v);
76605       sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
76606       VdbeComment((v, "record LEFT JOIN hit"));
76607       sqlite3ExprClearColumnCache(pParse, pLevel->iTabCur);
76608       sqlite3ExprClearColumnCache(pParse, pLevel->iIdxCur);
76609       for(pTerm=wc.a, j=0; j<wc.nTerm; j++, pTerm++){
76610         testcase( pTerm->flags & TERM_VIRTUAL );
76611         testcase( pTerm->flags & TERM_CODED );
76612         if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
76613         if( (pTerm->prereqAll & notReady)!=0 ) continue;
76614         assert( pTerm->pExpr );
76615         sqlite3ExprIfFalse(pParse, pTerm->pExpr, cont, SQLITE_JUMPIFNULL);
76616         pTerm->flags |= TERM_CODED;
76617       }
76618     }
76619   }
76620
76621 #ifdef SQLITE_TEST  /* For testing and debugging use only */
76622   /* Record in the query plan information about the current table
76623   ** and the index used to access it (if any).  If the table itself
76624   ** is not used, its name is just '{}'.  If no index is used
76625   ** the index is listed as "{}".  If the primary key is used the
76626   ** index name is '*'.
76627   */
76628   for(i=0; i<pTabList->nSrc; i++){
76629     char *z;
76630     int n;
76631     pLevel = &pWInfo->a[i];
76632     pTabItem = &pTabList->a[pLevel->iFrom];
76633     z = pTabItem->zAlias;
76634     if( z==0 ) z = pTabItem->pTab->zName;
76635     n = strlen(z);
76636     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
76637       if( pLevel->flags & WHERE_IDX_ONLY ){
76638         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
76639         nQPlan += 2;
76640       }else{
76641         memcpy(&sqlite3_query_plan[nQPlan], z, n);
76642         nQPlan += n;
76643       }
76644       sqlite3_query_plan[nQPlan++] = ' ';
76645     }
76646     testcase( pLevel->flags & WHERE_ROWID_EQ );
76647     testcase( pLevel->flags & WHERE_ROWID_RANGE );
76648     if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
76649       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
76650       nQPlan += 2;
76651     }else if( pLevel->pIdx==0 ){
76652       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
76653       nQPlan += 3;
76654     }else{
76655       n = strlen(pLevel->pIdx->zName);
76656       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
76657         memcpy(&sqlite3_query_plan[nQPlan], pLevel->pIdx->zName, n);
76658         nQPlan += n;
76659         sqlite3_query_plan[nQPlan++] = ' ';
76660       }
76661     }
76662   }
76663   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
76664     sqlite3_query_plan[--nQPlan] = 0;
76665   }
76666   sqlite3_query_plan[nQPlan] = 0;
76667   nQPlan = 0;
76668 #endif /* SQLITE_TEST // Testing and debugging use only */
76669
76670   /* Record the continuation address in the WhereInfo structure.  Then
76671   ** clean up and return.
76672   */
76673   pWInfo->iContinue = cont;
76674   whereClauseClear(&wc);
76675   return pWInfo;
76676
76677   /* Jump here if malloc fails */
76678 whereBeginNoMem:
76679   whereClauseClear(&wc);
76680   whereInfoFree(pWInfo);
76681   return 0;
76682 }
76683
76684 /*
76685 ** Generate the end of the WHERE loop.  See comments on 
76686 ** sqlite3WhereBegin() for additional information.
76687 */
76688 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
76689   Parse *pParse = pWInfo->pParse;
76690   Vdbe *v = pParse->pVdbe;
76691   int i;
76692   WhereLevel *pLevel;
76693   SrcList *pTabList = pWInfo->pTabList;
76694   sqlite3 *db = pParse->db;
76695
76696   /* Generate loop termination code.
76697   */
76698   sqlite3ExprClearColumnCache(pParse, -1);
76699   for(i=pTabList->nSrc-1; i>=0; i--){
76700     pLevel = &pWInfo->a[i];
76701     sqlite3VdbeResolveLabel(v, pLevel->cont);
76702     if( pLevel->op!=OP_Noop ){
76703       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
76704     }
76705     if( pLevel->nIn ){
76706       struct InLoop *pIn;
76707       int j;
76708       sqlite3VdbeResolveLabel(v, pLevel->nxt);
76709       for(j=pLevel->nIn, pIn=&pLevel->aInLoop[j-1]; j>0; j--, pIn--){
76710         sqlite3VdbeJumpHere(v, pIn->topAddr+1);
76711         sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->topAddr);
76712         sqlite3VdbeJumpHere(v, pIn->topAddr-1);
76713       }
76714       sqlite3DbFree(db, pLevel->aInLoop);
76715     }
76716     sqlite3VdbeResolveLabel(v, pLevel->brk);
76717     if( pLevel->iLeftJoin ){
76718       int addr;
76719       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
76720       sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
76721       if( pLevel->iIdxCur>=0 ){
76722         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
76723       }
76724       sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->top);
76725       sqlite3VdbeJumpHere(v, addr);
76726     }
76727   }
76728
76729   /* The "break" point is here, just past the end of the outer loop.
76730   ** Set it.
76731   */
76732   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
76733
76734   /* Close all of the cursors that were opened by sqlite3WhereBegin.
76735   */
76736   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
76737     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
76738     Table *pTab = pTabItem->pTab;
76739     assert( pTab!=0 );
76740     if( pTab->isEphem || pTab->pSelect ) continue;
76741     if( !pWInfo->okOnePass && (pLevel->flags & WHERE_IDX_ONLY)==0 ){
76742       sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
76743     }
76744     if( pLevel->pIdx!=0 ){
76745       sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
76746     }
76747
76748     /* If this scan uses an index, make code substitutions to read data
76749     ** from the index in preference to the table. Sometimes, this means
76750     ** the table need never be read from. This is a performance boost,
76751     ** as the vdbe level waits until the table is read before actually
76752     ** seeking the table cursor to the record corresponding to the current
76753     ** position in the index.
76754     ** 
76755     ** Calls to the code generator in between sqlite3WhereBegin and
76756     ** sqlite3WhereEnd will have created code that references the table
76757     ** directly.  This loop scans all that code looking for opcodes
76758     ** that reference the table and converts them into opcodes that
76759     ** reference the index.
76760     */
76761     if( pLevel->pIdx ){
76762       int k, j, last;
76763       VdbeOp *pOp;
76764       Index *pIdx = pLevel->pIdx;
76765       int useIndexOnly = pLevel->flags & WHERE_IDX_ONLY;
76766
76767       assert( pIdx!=0 );
76768       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
76769       last = sqlite3VdbeCurrentAddr(v);
76770       for(k=pWInfo->iTop; k<last; k++, pOp++){
76771         if( pOp->p1!=pLevel->iTabCur ) continue;
76772         if( pOp->opcode==OP_Column ){
76773           for(j=0; j<pIdx->nColumn; j++){
76774             if( pOp->p2==pIdx->aiColumn[j] ){
76775               pOp->p2 = j;
76776               pOp->p1 = pLevel->iIdxCur;
76777               break;
76778             }
76779           }
76780           assert(!useIndexOnly || j<pIdx->nColumn);
76781         }else if( pOp->opcode==OP_Rowid ){
76782           pOp->p1 = pLevel->iIdxCur;
76783           pOp->opcode = OP_IdxRowid;
76784         }else if( pOp->opcode==OP_NullRow && useIndexOnly ){
76785           pOp->opcode = OP_Noop;
76786         }
76787       }
76788     }
76789   }
76790
76791   /* Final cleanup
76792   */
76793   whereInfoFree(pWInfo);
76794   return;
76795 }
76796
76797 /************** End of where.c ***********************************************/
76798 /************** Begin file parse.c *******************************************/
76799 /* Driver template for the LEMON parser generator.
76800 ** The author disclaims copyright to this source code.
76801 */
76802 /* First off, code is included that follows the "include" declaration
76803 ** in the input grammar file. */
76804
76805
76806 /*
76807 ** An instance of this structure holds information about the
76808 ** LIMIT clause of a SELECT statement.
76809 */
76810 struct LimitVal {
76811   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
76812   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
76813 };
76814
76815 /*
76816 ** An instance of this structure is used to store the LIKE,
76817 ** GLOB, NOT LIKE, and NOT GLOB operators.
76818 */
76819 struct LikeOp {
76820   Token eOperator;  /* "like" or "glob" or "regexp" */
76821   int not;         /* True if the NOT keyword is present */
76822 };
76823
76824 /*
76825 ** An instance of the following structure describes the event of a
76826 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
76827 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
76828 **
76829 **      UPDATE ON (a,b,c)
76830 **
76831 ** Then the "b" IdList records the list "a,b,c".
76832 */
76833 struct TrigEvent { int a; IdList * b; };
76834
76835 /*
76836 ** An instance of this structure holds the ATTACH key and the key type.
76837 */
76838 struct AttachKey { int type;  Token key; };
76839
76840 /* Next is all token values, in a form suitable for use by makeheaders.
76841 ** This section will be null unless lemon is run with the -m switch.
76842 */
76843 /* 
76844 ** These constants (all generated automatically by the parser generator)
76845 ** specify the various kinds of tokens (terminals) that the parser
76846 ** understands. 
76847 **
76848 ** Each symbol here is a terminal symbol in the grammar.
76849 */
76850 /* Make sure the INTERFACE macro is defined.
76851 */
76852 #ifndef INTERFACE
76853 # define INTERFACE 1
76854 #endif
76855 /* The next thing included is series of defines which control
76856 ** various aspects of the generated parser.
76857 **    YYCODETYPE         is the data type used for storing terminal
76858 **                       and nonterminal numbers.  "unsigned char" is
76859 **                       used if there are fewer than 250 terminals
76860 **                       and nonterminals.  "int" is used otherwise.
76861 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
76862 **                       to no legal terminal or nonterminal number.  This
76863 **                       number is used to fill in empty slots of the hash 
76864 **                       table.
76865 **    YYFALLBACK         If defined, this indicates that one or more tokens
76866 **                       have fall-back values which should be used if the
76867 **                       original value of the token will not parse.
76868 **    YYACTIONTYPE       is the data type used for storing terminal
76869 **                       and nonterminal numbers.  "unsigned char" is
76870 **                       used if there are fewer than 250 rules and
76871 **                       states combined.  "int" is used otherwise.
76872 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given 
76873 **                       directly to the parser from the tokenizer.
76874 **    YYMINORTYPE        is the data type used for all minor tokens.
76875 **                       This is typically a union of many types, one of
76876 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
76877 **                       for base tokens is called "yy0".
76878 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
76879 **                       zero the stack is dynamically sized using realloc()
76880 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
76881 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
76882 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
76883 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
76884 **    YYNSTATE           the combined number of states.
76885 **    YYNRULE            the number of rules in the grammar
76886 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
76887 **                       defined, then do no error processing.
76888 */
76889 #define YYCODETYPE unsigned char
76890 #define YYNOCODE 248
76891 #define YYACTIONTYPE unsigned short int
76892 #define YYWILDCARD 59
76893 #define sqlite3ParserTOKENTYPE Token
76894 typedef union {
76895   sqlite3ParserTOKENTYPE yy0;
76896   int yy46;
76897   struct LikeOp yy72;
76898   Expr* yy172;
76899   ExprList* yy174;
76900   Select* yy219;
76901   struct LimitVal yy234;
76902   TriggerStep* yy243;
76903   struct TrigEvent yy370;
76904   SrcList* yy373;
76905   struct {int value; int mask;} yy405;
76906   IdList* yy432;
76907 } YYMINORTYPE;
76908 #ifndef YYSTACKDEPTH
76909 #define YYSTACKDEPTH 100
76910 #endif
76911 #define sqlite3ParserARG_SDECL Parse *pParse;
76912 #define sqlite3ParserARG_PDECL ,Parse *pParse
76913 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
76914 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
76915 #define YYNSTATE 589
76916 #define YYNRULE 313
76917 #define YYFALLBACK 1
76918 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
76919 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
76920 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
76921
76922 /* The yyzerominor constant is used to initialize instances of
76923 ** YYMINORTYPE objects to zero. */
76924 static const YYMINORTYPE yyzerominor;
76925
76926 /* Next are the tables used to determine what action to take based on the
76927 ** current state and lookahead token.  These tables are used to implement
76928 ** functions that take a state number and lookahead value and return an
76929 ** action integer.  
76930 **
76931 ** Suppose the action integer is N.  Then the action is determined as
76932 ** follows
76933 **
76934 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
76935 **                                      token onto the stack and goto state N.
76936 **
76937 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
76938 **
76939 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
76940 **
76941 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
76942 **
76943 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
76944 **                                      slots in the yy_action[] table.
76945 **
76946 ** The action table is constructed as a single large table named yy_action[].
76947 ** Given state S and lookahead X, the action is computed as
76948 **
76949 **      yy_action[ yy_shift_ofst[S] + X ]
76950 **
76951 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
76952 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
76953 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
76954 ** and that yy_default[S] should be used instead.  
76955 **
76956 ** The formula above is for computing the action when the lookahead is
76957 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
76958 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
76959 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
76960 ** YY_SHIFT_USE_DFLT.
76961 **
76962 ** The following are the tables generated in this section:
76963 **
76964 **  yy_action[]        A single table containing all actions.
76965 **  yy_lookahead[]     A table containing the lookahead for each entry in
76966 **                     yy_action.  Used to detect hash collisions.
76967 **  yy_shift_ofst[]    For each state, the offset into yy_action for
76968 **                     shifting terminals.
76969 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
76970 **                     shifting non-terminals after a reduce.
76971 **  yy_default[]       Default action for each state.
76972 */
76973 static const YYACTIONTYPE yy_action[] = {
76974  /*     0 */   292,  903,  124,  588,  409,  172,    2,  418,   61,   61,
76975  /*    10 */    61,   61,  519,   63,   63,   63,   63,   64,   64,   65,
76976  /*    20 */    65,   65,   66,  210,  447,  212,  425,  431,   68,   63,
76977  /*    30 */    63,   63,   63,   64,   64,   65,   65,   65,   66,  210,
76978  /*    40 */   391,  388,  396,  451,   60,   59,  297,  435,  436,  432,
76979  /*    50 */   432,   62,   62,   61,   61,   61,   61,  263,   63,   63,
76980  /*    60 */    63,   63,   64,   64,   65,   65,   65,   66,  210,  292,
76981  /*    70 */   493,  494,  418,  489,  208,   82,   67,  420,   69,  154,
76982  /*    80 */    63,   63,   63,   63,   64,   64,   65,   65,   65,   66,
76983  /*    90 */   210,   67,  462,   69,  154,  425,  431,  574,  264,   58,
76984  /*   100 */    64,   64,   65,   65,   65,   66,  210,  397,  398,  422,
76985  /*   110 */   422,  422,  292,   60,   59,  297,  435,  436,  432,  432,
76986  /*   120 */    62,   62,   61,   61,   61,   61,  317,   63,   63,   63,
76987  /*   130 */    63,   64,   64,   65,   65,   65,   66,  210,  425,  431,
76988  /*   140 */    94,   65,   65,   65,   66,  210,  396,  210,  414,   34,
76989  /*   150 */    56,  298,  442,  443,  410,  418,   60,   59,  297,  435,
76990  /*   160 */   436,  432,  432,   62,   62,   61,   61,   61,   61,  208,
76991  /*   170 */    63,   63,   63,   63,   64,   64,   65,   65,   65,   66,
76992  /*   180 */   210,  292,  372,  524,  295,  572,  113,  408,  522,  451,
76993  /*   190 */   331,  317,  407,   20,  244,  340,  519,  396,  478,  531,
76994  /*   200 */   505,  447,  212,  571,  570,  245,  530,  425,  431,  149,
76995  /*   210 */   150,  397,  398,  414,   41,  211,  151,  533,  488,  489,
76996  /*   220 */   418,  568,  569,  420,  292,   60,   59,  297,  435,  436,
76997  /*   230 */   432,  432,   62,   62,   61,   61,   61,   61,  317,   63,
76998  /*   240 */    63,   63,   63,   64,   64,   65,   65,   65,   66,  210,
76999  /*   250 */   425,  431,  447,  333,  215,  422,  422,  422,  363,  299,
77000  /*   260 */   414,   41,  397,  398,  366,  567,  211,  292,   60,   59,
77001  /*   270 */   297,  435,  436,  432,  432,   62,   62,   61,   61,   61,
77002  /*   280 */    61,  396,   63,   63,   63,   63,   64,   64,   65,   65,
77003  /*   290 */    65,   66,  210,  425,  431,  491,  300,  524,  474,   66,
77004  /*   300 */   210,  214,  474,  229,  411,  286,  534,   20,  449,  523,
77005  /*   310 */   168,   60,   59,  297,  435,  436,  432,  432,   62,   62,
77006  /*   320 */    61,   61,   61,   61,  474,   63,   63,   63,   63,   64,
77007  /*   330 */    64,   65,   65,   65,   66,  210,  209,  480,  317,   77,
77008  /*   340 */   292,  239,  300,   55,  484,  490,  397,  398,  181,  547,
77009  /*   350 */   494,  345,  348,  349,   67,  152,   69,  154,  339,  524,
77010  /*   360 */   414,   35,  350,  241,  221,  370,  425,  431,  579,   20,
77011  /*   370 */   164,  118,  243,  343,  248,  344,  176,  322,  442,  443,
77012  /*   380 */   414,    3,   80,  252,   60,   59,  297,  435,  436,  432,
77013  /*   390 */   432,   62,   62,   61,   61,   61,   61,  174,   63,   63,
77014  /*   400 */    63,   63,   64,   64,   65,   65,   65,   66,  210,  292,
77015  /*   410 */   221,  550,  236,  487,  510,  353,  317,  118,  243,  343,
77016  /*   420 */   248,  344,  176,  181,  317,  532,  345,  348,  349,  252,
77017  /*   430 */   223,  415,  155,  464,  511,  425,  431,  350,  414,   34,
77018  /*   440 */   465,  211,  177,  175,  160,  525,  414,   34,  338,  549,
77019  /*   450 */   449,  323,  168,   60,   59,  297,  435,  436,  432,  432,
77020  /*   460 */    62,   62,   61,   61,   61,   61,  415,   63,   63,   63,
77021  /*   470 */    63,   64,   64,   65,   65,   65,   66,  210,  292,  542,
77022  /*   480 */   335,  517,  504,  541,  456,  572,  302,   19,  331,  144,
77023  /*   490 */   317,  390,  317,  330,    2,  362,  457,  294,  483,  373,
77024  /*   500 */   269,  268,  252,  571,  425,  431,  589,  391,  388,  458,
77025  /*   510 */   208,  495,  414,   49,  414,   49,  303,  586,  894,  230,
77026  /*   520 */   894,  496,   60,   59,  297,  435,  436,  432,  432,   62,
77027  /*   530 */    62,   61,   61,   61,   61,  201,   63,   63,   63,   63,
77028  /*   540 */    64,   64,   65,   65,   65,   66,  210,  292,  317,  181,
77029  /*   550 */   439,  255,  345,  348,  349,  370,  153,  583,  308,  251,
77030  /*   560 */   309,  452,   76,  350,   78,  382,  211,  426,  427,  415,
77031  /*   570 */   414,   27,  319,  425,  431,  440,    1,   22,  586,  893,
77032  /*   580 */   396,  893,  544,  478,  320,  263,  438,  438,  429,  430,
77033  /*   590 */   415,   60,   59,  297,  435,  436,  432,  432,   62,   62,
77034  /*   600 */    61,   61,   61,   61,  237,   63,   63,   63,   63,   64,
77035  /*   610 */    64,   65,   65,   65,   66,  210,  292,  428,  583,  374,
77036  /*   620 */   224,   93,  517,    9,  159,  396,  557,  396,  456,   67,
77037  /*   630 */   396,   69,  154,  399,  400,  401,  320,  328,  438,  438,
77038  /*   640 */   457,  336,  425,  431,  361,  397,  398,  320,  433,  438,
77039  /*   650 */   438,  582,  291,  458,  238,  327,  318,  222,  546,  292,
77040  /*   660 */    60,   59,  297,  435,  436,  432,  432,   62,   62,   61,
77041  /*   670 */    61,   61,   61,  225,   63,   63,   63,   63,   64,   64,
77042  /*   680 */    65,   65,   65,   66,  210,  425,  431,  482,  313,  392,
77043  /*   690 */   397,  398,  397,  398,  207,  397,  398,  825,  273,  517,
77044  /*   700 */   251,  200,  292,   60,   59,  297,  435,  436,  432,  432,
77045  /*   710 */    62,   62,   61,   61,   61,   61,  470,   63,   63,   63,
77046  /*   720 */    63,   64,   64,   65,   65,   65,   66,  210,  425,  431,
77047  /*   730 */   171,  160,  263,  263,  304,  415,  276,  395,  274,  263,
77048  /*   740 */   517,  517,  263,  517,  192,  292,   60,   70,  297,  435,
77049  /*   750 */   436,  432,  432,   62,   62,   61,   61,   61,   61,  379,
77050  /*   760 */    63,   63,   63,   63,   64,   64,   65,   65,   65,   66,
77051  /*   770 */   210,  425,  431,  384,  559,  305,  306,  251,  415,  320,
77052  /*   780 */   560,  438,  438,  561,  540,  360,  540,  387,  292,  196,
77053  /*   790 */    59,  297,  435,  436,  432,  432,   62,   62,   61,   61,
77054  /*   800 */    61,   61,  371,   63,   63,   63,   63,   64,   64,   65,
77055  /*   810 */    65,   65,   66,  210,  425,  431,  396,  275,  251,  251,
77056  /*   820 */   172,  250,  418,  415,  386,  367,  178,  179,  180,  469,
77057  /*   830 */   311,  123,  156,    5,  297,  435,  436,  432,  432,   62,
77058  /*   840 */    62,   61,   61,   61,   61,  317,   63,   63,   63,   63,
77059  /*   850 */    64,   64,   65,   65,   65,   66,  210,   72,  324,  194,
77060  /*   860 */     4,  317,  263,  317,  296,  263,  415,  414,   28,  317,
77061  /*   870 */   257,  317,  321,   72,  324,  317,    4,  119,  165,  177,
77062  /*   880 */   296,  397,  398,  414,   23,  414,   32,  418,  321,  326,
77063  /*   890 */   421,  414,   53,  414,   52,  317,  158,  414,   98,  451,
77064  /*   900 */   317,  263,  317,  277,  317,  326,  378,  471,  261,  317,
77065  /*   910 */   259,   18,  478,  445,  445,  451,  317,  414,   96,   75,
77066  /*   920 */    74,  469,  414,  101,  414,  102,  414,  112,   73,  315,
77067  /*   930 */   316,  414,  114,  420,  294,   75,   74,  481,  414,   16,
77068  /*   940 */   381,  317,  279,  467,   73,  315,  316,   72,  324,  420,
77069  /*   950 */     4,  208,  317,  183,  296,  317,  186,  128,   84,  208,
77070  /*   960 */     8,  341,  321,  414,   99,  422,  422,  422,  423,  424,
77071  /*   970 */    11,  623,  380,  307,  414,   33,  413,  414,   97,  326,
77072  /*   980 */   412,  422,  422,  422,  423,  424,   11,  415,  413,  451,
77073  /*   990 */   415,  162,  412,  317,  499,  500,  226,  227,  228,  104,
77074  /*  1000 */   448,  476,  317,  173,  507,  317,  509,  508,  317,   75,
77075  /*  1010 */    74,  329,  205,   21,  281,  414,   24,  418,   73,  315,
77076  /*  1020 */   316,  282,  317,  420,  414,   54,  460,  414,  115,  317,
77077  /*  1030 */   414,  116,  502,  203,  147,  549,  514,  468,  128,  202,
77078  /*  1040 */   317,  473,  204,  317,  414,  117,  317,  477,  317,  584,
77079  /*  1050 */   317,  414,   25,  317,  249,  422,  422,  422,  423,  424,
77080  /*  1060 */    11,  506,  414,   36,  512,  414,   37,  317,  414,   26,
77081  /*  1070 */   414,   38,  414,   39,  526,  414,   40,  317,  254,  317,
77082  /*  1080 */   128,  317,  418,  317,  256,  377,  278,  268,  585,  414,
77083  /*  1090 */    42,  293,  317,  352,  317,  128,  208,  513,  258,  414,
77084  /*  1100 */    43,  414,   44,  414,   29,  414,   30,  545,  260,  128,
77085  /*  1110 */   317,  553,  317,  173,  414,   45,  414,   46,  317,  262,
77086  /*  1120 */   383,  554,  317,   91,  564,  317,   91,  317,  581,  189,
77087  /*  1130 */   290,  357,  414,   47,  414,   48,  267,  365,  368,  369,
77088  /*  1140 */   414,   31,  270,  271,  414,   10,  272,  414,   50,  414,
77089  /*  1150 */    51,  556,  566,  280,  283,  284,  578,  146,  419,  405,
77090  /*  1160 */   231,  505,  444,  325,  516,  463,  163,  446,  552,  394,
77091  /*  1170 */   466,  563,  246,  515,  518,  520,  402,  403,  404,    7,
77092  /*  1180 */   314,   84,  232,  334,  347,   83,  332,   57,  170,   79,
77093  /*  1190 */   213,  461,  125,   85,  337,  342,  492,  502,  497,  301,
77094  /*  1200 */   498,  416,  105,  219,  247,  218,  503,  501,  233,  220,
77095  /*  1210 */   287,  234,  527,  528,  235,  529,  417,  521,  354,  288,
77096  /*  1220 */   184,  121,  185,  240,  535,  475,  242,  356,  187,  479,
77097  /*  1230 */   188,  358,  537,   88,  190,  548,  364,  193,  132,  376,
77098  /*  1240 */   555,  375,  133,  134,  135,  310,  562,  138,  136,  575,
77099  /*  1250 */   576,  577,  580,  100,  393,  406,  217,  142,  624,  625,
77100  /*  1260 */   103,  141,  265,  166,  167,  434,   71,  453,  441,  437,
77101  /*  1270 */   450,  143,  538,  157,  120,  454,  161,  472,  455,  169,
77102  /*  1280 */   459,   81,    6,   12,   13,   92,   95,  126,  216,  127,
77103  /*  1290 */   111,  485,  486,   17,   86,  346,  106,  122,  253,  107,
77104  /*  1300 */    87,  108,  182,  245,  355,  145,  351,  536,  129,  359,
77105  /*  1310 */   312,  130,  543,  173,  539,  266,  191,  109,  289,  551,
77106  /*  1320 */   195,   14,  131,  198,  197,  558,  137,  199,  139,  140,
77107  /*  1330 */    15,  565,   89,   90,  573,  110,  385,  206,  148,  389,
77108  /*  1340 */   285,  587,
77109 };
77110 static const YYCODETYPE yy_lookahead[] = {
77111  /*     0 */    16,  139,  140,  141,  168,   21,  144,   23,   69,   70,
77112  /*    10 */    71,   72,  176,   74,   75,   76,   77,   78,   79,   80,
77113  /*    20 */    81,   82,   83,   84,   78,   79,   42,   43,   73,   74,
77114  /*    30 */    75,   76,   77,   78,   79,   80,   81,   82,   83,   84,
77115  /*    40 */     1,    2,   23,   58,   60,   61,   62,   63,   64,   65,
77116  /*    50 */    66,   67,   68,   69,   70,   71,   72,  147,   74,   75,
77117  /*    60 */    76,   77,   78,   79,   80,   81,   82,   83,   84,   16,
77118  /*    70 */   185,  186,   88,   88,  110,   22,  217,   92,  219,  220,
77119  /*    80 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
77120  /*    90 */    84,  217,  218,  219,  220,   42,   43,  238,  188,   46,
77121  /*   100 */    78,   79,   80,   81,   82,   83,   84,   88,   89,  124,
77122  /*   110 */   125,  126,   16,   60,   61,   62,   63,   64,   65,   66,
77123  /*   120 */    67,   68,   69,   70,   71,   72,  147,   74,   75,   76,
77124  /*   130 */    77,   78,   79,   80,   81,   82,   83,   84,   42,   43,
77125  /*   140 */    44,   80,   81,   82,   83,   84,   23,   84,  169,  170,
77126  /*   150 */    19,  164,  165,  166,   23,   23,   60,   61,   62,   63,
77127  /*   160 */    64,   65,   66,   67,   68,   69,   70,   71,   72,  110,
77128  /*   170 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
77129  /*   180 */    84,   16,  123,  147,  150,  147,   21,  167,  168,   58,
77130  /*   190 */   211,  147,  156,  157,   92,  216,  176,   23,  147,  176,
77131  /*   200 */   177,   78,   79,  165,  166,  103,  183,   42,   43,   78,
77132  /*   210 */    79,   88,   89,  169,  170,  228,  180,  181,  169,   88,
77133  /*   220 */    88,   98,   99,   92,   16,   60,   61,   62,   63,   64,
77134  /*   230 */    65,   66,   67,   68,   69,   70,   71,   72,  147,   74,
77135  /*   240 */    75,   76,   77,   78,   79,   80,   81,   82,   83,   84,
77136  /*   250 */    42,   43,   78,  209,  210,  124,  125,  126,  224,  208,
77137  /*   260 */   169,  170,   88,   89,  230,  227,  228,   16,   60,   61,
77138  /*   270 */    62,   63,   64,   65,   66,   67,   68,   69,   70,   71,
77139  /*   280 */    72,   23,   74,   75,   76,   77,   78,   79,   80,   81,
77140  /*   290 */    82,   83,   84,   42,   43,  160,   16,  147,  161,   83,
77141  /*   300 */    84,  210,  161,  153,  169,  158,  156,  157,  161,  162,
77142  /*   310 */   163,   60,   61,   62,   63,   64,   65,   66,   67,   68,
77143  /*   320 */    69,   70,   71,   72,  161,   74,   75,   76,   77,   78,
77144  /*   330 */    79,   80,   81,   82,   83,   84,  192,  200,  147,  131,
77145  /*   340 */    16,  200,   16,  199,   20,  169,   88,   89,   90,  185,
77146  /*   350 */   186,   93,   94,   95,  217,   22,  219,  220,  147,  147,
77147  /*   360 */   169,  170,  104,  200,   84,  147,   42,   43,  156,  157,
77148  /*   370 */    90,   91,   92,   93,   94,   95,   96,  164,  165,  166,
77149  /*   380 */   169,  170,  131,  103,   60,   61,   62,   63,   64,   65,
77150  /*   390 */    66,   67,   68,   69,   70,   71,   72,  155,   74,   75,
77151  /*   400 */    76,   77,   78,   79,   80,   81,   82,   83,   84,   16,
77152  /*   410 */    84,   11,  221,   20,   30,   16,  147,   91,   92,   93,
77153  /*   420 */    94,   95,   96,   90,  147,  181,   93,   94,   95,  103,
77154  /*   430 */   212,  189,  155,   27,   50,   42,   43,  104,  169,  170,
77155  /*   440 */    34,  228,   43,  201,  202,  181,  169,  170,  206,   49,
77156  /*   450 */   161,  162,  163,   60,   61,   62,   63,   64,   65,   66,
77157  /*   460 */    67,   68,   69,   70,   71,   72,  189,   74,   75,   76,
77158  /*   470 */    77,   78,   79,   80,   81,   82,   83,   84,   16,   25,
77159  /*   480 */   211,  147,   20,   29,   12,  147,  102,   19,  211,   21,
77160  /*   490 */   147,  141,  147,  216,  144,   41,   24,   98,   20,   99,
77161  /*   500 */   100,  101,  103,  165,   42,   43,    0,    1,    2,   37,
77162  /*   510 */   110,   39,  169,  170,  169,  170,  182,   19,   20,  190,
77163  /*   520 */    22,   49,   60,   61,   62,   63,   64,   65,   66,   67,
77164  /*   530 */    68,   69,   70,   71,   72,  155,   74,   75,   76,   77,
77165  /*   540 */    78,   79,   80,   81,   82,   83,   84,   16,  147,   90,
77166  /*   550 */    20,   20,   93,   94,   95,  147,  155,   59,  215,  225,
77167  /*   560 */   215,   20,  130,  104,  132,  227,  228,   42,   43,  189,
77168  /*   570 */   169,  170,   16,   42,   43,   20,   19,   22,   19,   20,
77169  /*   580 */    23,   22,   18,  147,  106,  147,  108,  109,   63,   64,
77170  /*   590 */   189,   60,   61,   62,   63,   64,   65,   66,   67,   68,
77171  /*   600 */    69,   70,   71,   72,  147,   74,   75,   76,   77,   78,
77172  /*   610 */    79,   80,   81,   82,   83,   84,   16,   92,   59,   55,
77173  /*   620 */   212,   21,  147,   19,  147,   23,  188,   23,   12,  217,
77174  /*   630 */    23,  219,  220,    7,    8,    9,  106,  186,  108,  109,
77175  /*   640 */    24,  147,   42,   43,  208,   88,   89,  106,   92,  108,
77176  /*   650 */   109,  244,  245,   37,  147,   39,  147,  182,   94,   16,
77177  /*   660 */    60,   61,   62,   63,   64,   65,   66,   67,   68,   69,
77178  /*   670 */    70,   71,   72,  145,   74,   75,   76,   77,   78,   79,
77179  /*   680 */    80,   81,   82,   83,   84,   42,   43,   80,  142,  143,
77180  /*   690 */    88,   89,   88,   89,  148,   88,   89,  133,   14,  147,
77181  /*   700 */   225,  155,   16,   60,   61,   62,   63,   64,   65,   66,
77182  /*   710 */    67,   68,   69,   70,   71,   72,  114,   74,   75,   76,
77183  /*   720 */    77,   78,   79,   80,   81,   82,   83,   84,   42,   43,
77184  /*   730 */   201,  202,  147,  147,  182,  189,   52,  147,   54,  147,
77185  /*   740 */   147,  147,  147,  147,  155,   16,   60,   61,   62,   63,
77186  /*   750 */    64,   65,   66,   67,   68,   69,   70,   71,   72,  213,
77187  /*   760 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
77188  /*   770 */    84,   42,   43,  188,  188,  182,  182,  225,  189,  106,
77189  /*   780 */   188,  108,  109,  188,   99,  100,  101,  241,   16,  155,
77190  /*   790 */    61,   62,   63,   64,   65,   66,   67,   68,   69,   70,
77191  /*   800 */    71,   72,  213,   74,   75,   76,   77,   78,   79,   80,
77192  /*   810 */    81,   82,   83,   84,   42,   43,   23,  133,  225,  225,
77193  /*   820 */    21,  225,   23,  189,  239,  236,   99,  100,  101,   22,
77194  /*   830 */   242,  243,  155,  191,   62,   63,   64,   65,   66,   67,
77195  /*   840 */    68,   69,   70,   71,   72,  147,   74,   75,   76,   77,
77196  /*   850 */    78,   79,   80,   81,   82,   83,   84,   16,   17,   22,
77197  /*   860 */    19,  147,  147,  147,   23,  147,  189,  169,  170,  147,
77198  /*   870 */    14,  147,   31,   16,   17,  147,   19,  147,   19,   43,
77199  /*   880 */    23,   88,   89,  169,  170,  169,  170,   88,   31,   48,
77200  /*   890 */   147,  169,  170,  169,  170,  147,   89,  169,  170,   58,
77201  /*   900 */   147,  147,  147,  188,  147,   48,  188,  114,   52,  147,
77202  /*   910 */    54,   19,  147,  124,  125,   58,  147,  169,  170,   78,
77203  /*   920 */    79,  114,  169,  170,  169,  170,  169,  170,   87,   88,
77204  /*   930 */    89,  169,  170,   92,   98,   78,   79,   80,  169,  170,
77205  /*   940 */    91,  147,  188,   22,   87,   88,   89,   16,   17,   92,
77206  /*   950 */    19,  110,  147,  155,   23,  147,  155,   22,  121,  110,
77207  /*   960 */    68,   80,   31,  169,  170,  124,  125,  126,  127,  128,
77208  /*   970 */   129,  112,  123,  208,  169,  170,  107,  169,  170,   48,
77209  /*   980 */   111,  124,  125,  126,  127,  128,  129,  189,  107,   58,
77210  /*   990 */   189,    5,  111,  147,    7,    8,   10,   11,   12,   13,
77211  /*  1000 */   161,   20,  147,   22,  178,  147,   91,   92,  147,   78,
77212  /*  1010 */    79,  147,   26,   19,   28,  169,  170,   23,   87,   88,
77213  /*  1020 */    89,   35,  147,   92,  169,  170,  147,  169,  170,  147,
77214  /*  1030 */   169,  170,   97,   47,  113,   49,   20,  203,   22,   53,
77215  /*  1040 */   147,  147,   56,  147,  169,  170,  147,  147,  147,   20,
77216  /*  1050 */   147,  169,  170,  147,  147,  124,  125,  126,  127,  128,
77217  /*  1060 */   129,  147,  169,  170,  178,  169,  170,  147,  169,  170,
77218  /*  1070 */   169,  170,  169,  170,  147,  169,  170,  147,   20,  147,
77219  /*  1080 */    22,  147,   88,  147,  147,   99,  100,  101,   59,  169,
77220  /*  1090 */   170,  105,  147,   20,  147,   22,  110,  178,  147,  169,
77221  /*  1100 */   170,  169,  170,  169,  170,  169,  170,   20,  147,   22,
77222  /*  1110 */   147,   20,  147,   22,  169,  170,  169,  170,  147,  147,
77223  /*  1120 */   134,   20,  147,   22,   20,  147,   22,  147,   20,  232,
77224  /*  1130 */    22,  233,  169,  170,  169,  170,  147,  147,  147,  147,
77225  /*  1140 */   169,  170,  147,  147,  169,  170,  147,  169,  170,  169,
77226  /*  1150 */   170,  147,  147,  147,  147,  147,  147,  191,  161,  149,
77227  /*  1160 */   193,  177,  229,  223,  161,  172,    6,  229,  194,  146,
77228  /*  1170 */   172,  194,  172,  172,  172,  161,  146,  146,  146,   22,
77229  /*  1180 */   154,  121,  194,  118,  173,  119,  116,  120,  112,  130,
77230  /*  1190 */   222,  152,  152,   98,  115,   98,  171,   97,  171,   40,
77231  /*  1200 */   179,  189,   19,   84,  171,  226,  171,  173,  195,  226,
77232  /*  1210 */   174,  196,  171,  171,  197,  171,  198,  179,   15,  174,
77233  /*  1220 */   151,   60,  151,  204,  152,  205,  204,  152,  151,  205,
77234  /*  1230 */   152,   38,  152,  130,  151,  184,  152,  184,   19,   15,
77235  /*  1240 */   194,  152,  187,  187,  187,  152,  194,  184,  187,   33,
77236  /*  1250 */   152,  152,  137,  159,    1,   20,  175,  214,  112,  112,
77237  /*  1260 */   175,  214,  234,  112,  112,   92,   19,   11,   20,  107,
77238  /*  1270 */    20,   19,  235,   19,   32,   20,  112,  114,   20,   22,
77239  /*  1280 */    20,   22,  117,   22,  117,  237,  237,   19,   44,   20,
77240  /*  1290 */   240,   20,   20,  231,   19,   44,   19,  243,   20,   19,
77241  /*  1300 */    19,   19,   96,  103,   16,   21,   44,   17,   98,   36,
77242  /*  1310 */   246,   45,   45,   22,   51,  133,   98,   19,    5,    1,
77243  /*  1320 */   122,   19,  102,   14,  113,   17,  113,  115,  102,  122,
77244  /*  1330 */    19,  123,   68,   68,   20,   14,   57,  135,   19,    3,
77245  /*  1340 */   136,    4,
77246 };
77247 #define YY_SHIFT_USE_DFLT (-62)
77248 #define YY_SHIFT_MAX 389
77249 static const short yy_shift_ofst[] = {
77250  /*     0 */    39,  841,  986,  -16,  841,  931,  931,  258,  123,  -36,
77251  /*    10 */    96,  931,  931,  931,  931,  931,  -45,  400,  174,   19,
77252  /*    20 */   132,  -54,  -54,   53,  165,  208,  251,  324,  393,  462,
77253  /*    30 */   531,  600,  643,  686,  643,  643,  643,  643,  643,  643,
77254  /*    40 */   643,  643,  643,  643,  643,  643,  643,  643,  643,  643,
77255  /*    50 */   643,  643,  729,  772,  772,  857,  931,  931,  931,  931,
77256  /*    60 */   931,  931,  931,  931,  931,  931,  931,  931,  931,  931,
77257  /*    70 */   931,  931,  931,  931,  931,  931,  931,  931,  931,  931,
77258  /*    80 */   931,  931,  931,  931,  931,  931,  931,  931,  931,  931,
77259  /*    90 */   931,  931,  931,  931,  931,  931,  -61,  -61,    6,    6,
77260  /*   100 */   280,   22,   61,  399,  564,   19,   19,   19,   19,   19,
77261  /*   110 */    19,   19,  216,  132,   63,  -62,  -62,  -62,  131,  326,
77262  /*   120 */   472,  472,  498,  559,  506,  799,   19,  799,   19,   19,
77263  /*   130 */    19,   19,   19,   19,   19,   19,   19,   19,   19,   19,
77264  /*   140 */    19,  849,   59,  -36,  -36,  -36,  -62,  -62,  -62,  -15,
77265  /*   150 */   -15,  333,  459,  478,  557,  530,  541,  616,  602,  793,
77266  /*   160 */   604,  607,  626,   19,   19,  881,   19,   19,  994,   19,
77267  /*   170 */    19,  807,   19,   19,  673,  807,   19,   19,  384,  384,
77268  /*   180 */   384,   19,   19,  673,   19,   19,  673,   19,  454,  685,
77269  /*   190 */    19,   19,  673,   19,   19,   19,  673,   19,   19,   19,
77270  /*   200 */   673,  673,   19,   19,   19,   19,   19,  468,  869,  921,
77271  /*   210 */   132,  789,  789,  432,  406,  406,  406,  836,  406,  132,
77272  /*   220 */   406,  132,  935,  837,  837, 1160, 1160, 1160, 1160, 1157,
77273  /*   230 */   -36, 1060, 1065, 1066, 1070, 1067, 1059, 1076, 1076, 1095,
77274  /*   240 */  1079, 1095, 1079, 1097, 1097, 1159, 1097, 1100, 1097, 1183,
77275  /*   250 */  1119, 1119, 1159, 1097, 1097, 1097, 1183, 1203, 1076, 1203,
77276  /*   260 */  1076, 1203, 1076, 1076, 1193, 1103, 1203, 1076, 1161, 1161,
77277  /*   270 */  1219, 1060, 1076, 1224, 1224, 1224, 1224, 1060, 1161, 1219,
77278  /*   280 */  1076, 1216, 1216, 1076, 1076, 1115,  -62,  -62,  -62,  -62,
77279  /*   290 */   -62,  -62,  525,  684,  727,  856,  859,  556,  555,  981,
77280  /*   300 */   102,  987,  915, 1016, 1058, 1073, 1087, 1091, 1101, 1104,
77281  /*   310 */   892, 1108, 1029, 1253, 1235, 1146, 1147, 1151, 1152, 1173,
77282  /*   320 */  1162, 1247, 1248, 1250, 1252, 1256, 1254, 1255, 1257, 1258,
77283  /*   330 */  1260, 1259, 1165, 1261, 1167, 1259, 1163, 1268, 1269, 1164,
77284  /*   340 */  1271, 1272, 1242, 1244, 1275, 1251, 1277, 1278, 1280, 1281,
77285  /*   350 */  1262, 1282, 1206, 1200, 1288, 1290, 1284, 1210, 1273, 1263,
77286  /*   360 */  1266, 1291, 1267, 1182, 1218, 1298, 1313, 1318, 1220, 1264,
77287  /*   370 */  1265, 1198, 1302, 1211, 1309, 1212, 1308, 1213, 1226, 1207,
77288  /*   380 */  1311, 1208, 1314, 1321, 1279, 1202, 1204, 1319, 1336, 1337,
77289 };
77290 #define YY_REDUCE_USE_DFLT (-165)
77291 #define YY_REDUCE_MAX 291
77292 static const short yy_reduce_ofst[] = {
77293  /*     0 */  -138,  277,  546,  137,  401,  -21,   44,   36,   38,  242,
77294  /*    10 */  -141,  191,   91,  269,  343,  345, -126,  589,  338,  150,
77295  /*    20 */   147,  -13,  213,  412,  412,  412,  412,  412,  412,  412,
77296  /*    30 */   412,  412,  412,  412,  412,  412,  412,  412,  412,  412,
77297  /*    40 */   412,  412,  412,  412,  412,  412,  412,  412,  412,  412,
77298  /*    50 */   412,  412,  412,  412,  412,  211,  698,  714,  716,  722,
77299  /*    60 */   724,  728,  748,  753,  755,  757,  762,  769,  794,  805,
77300  /*    70 */   808,  846,  855,  858,  861,  875,  882,  893,  896,  899,
77301  /*    80 */   901,  903,  906,  920,  930,  932,  934,  936,  945,  947,
77302  /*    90 */   963,  965,  971,  975,  978,  980,  412,  412,  412,  412,
77303  /*   100 */    20,  412,  412,   23,   34,  334,  475,  552,  593,  594,
77304  /*   110 */   585,  212,  412,  289,  412,  412,  412,  412,  135, -164,
77305  /*   120 */  -115,  164,  407,  407,  350,  141,   51,  163,  596,  -90,
77306  /*   130 */   436,  218,  765,  438,  586,  592,  595,  715,  718,  408,
77307  /*   140 */   754,  380,  634,  677,  798,  801,  144,  529,  588,   49,
77308  /*   150 */   176,  244,  264,  329,  457,  329,  329,  451,  477,  494,
77309  /*   160 */   507,  509,  528,  590,  730,  642,  509,  743,  839,  864,
77310  /*   170 */   879,  834,  894,  900,  329,  834,  907,  914,  826,  886,
77311  /*   180 */   919,  927,  937,  329,  951,  961,  329,  972,  897,  898,
77312  /*   190 */   989,  990,  329,  991,  992,  995,  329,  996,  999, 1004,
77313  /*   200 */   329,  329, 1005, 1006, 1007, 1008, 1009, 1010,  966,  967,
77314  /*   210 */   997,  933,  938,  940,  993,  998, 1000,  984, 1001, 1003,
77315  /*   220 */  1002, 1014, 1011,  974,  977, 1023, 1030, 1031, 1032, 1026,
77316  /*   230 */  1012,  988, 1013, 1015, 1017, 1018,  968, 1039, 1040, 1019,
77317  /*   240 */  1020, 1022, 1024, 1025, 1027, 1021, 1033, 1034, 1035, 1036,
77318  /*   250 */   979,  983, 1038, 1041, 1042, 1044, 1045, 1069, 1072, 1071,
77319  /*   260 */  1075, 1077, 1078, 1080, 1028, 1037, 1083, 1084, 1051, 1053,
77320  /*   270 */  1043, 1046, 1089, 1055, 1056, 1057, 1061, 1052, 1063, 1047,
77321  /*   280 */  1093, 1048, 1049, 1098, 1099, 1050, 1094, 1081, 1085, 1062,
77322  /*   290 */  1054, 1064,
77323 };
77324 static const YYACTIONTYPE yy_default[] = {
77325  /*     0 */   595,  820,  902,  710,  902,  820,  902,  902,  848,  714,
77326  /*    10 */   877,  818,  902,  902,  902,  902,  792,  902,  848,  902,
77327  /*    20 */   626,  848,  848,  743,  902,  902,  902,  902,  902,  902,
77328  /*    30 */   902,  902,  744,  902,  822,  817,  813,  815,  814,  821,
77329  /*    40 */   745,  734,  741,  748,  726,  861,  750,  751,  757,  758,
77330  /*    50 */   878,  876,  780,  779,  798,  902,  902,  902,  902,  902,
77331  /*    60 */   902,  902,  902,  902,  902,  902,  902,  902,  902,  902,
77332  /*    70 */   902,  902,  902,  902,  902,  902,  902,  902,  902,  902,
77333  /*    80 */   902,  902,  902,  902,  902,  902,  902,  902,  902,  902,
77334  /*    90 */   902,  902,  902,  902,  902,  902,  782,  804,  781,  791,
77335  /*   100 */   619,  783,  784,  679,  614,  902,  902,  902,  902,  902,
77336  /*   110 */   902,  902,  785,  902,  786,  799,  800,  801,  902,  902,
77337  /*   120 */   902,  902,  902,  902,  595,  710,  902,  710,  902,  902,
77338  /*   130 */   902,  902,  902,  902,  902,  902,  902,  902,  902,  902,
77339  /*   140 */   902,  902,  902,  902,  902,  902,  704,  714,  895,  902,
77340  /*   150 */   902,  670,  902,  902,  902,  902,  902,  902,  902,  902,
77341  /*   160 */   902,  902,  602,  600,  902,  702,  902,  902,  628,  902,
77342  /*   170 */   902,  712,  902,  902,  717,  718,  902,  902,  902,  902,
77343  /*   180 */   902,  902,  902,  616,  902,  902,  691,  902,  854,  902,
77344  /*   190 */   902,  902,  868,  902,  902,  902,  866,  902,  902,  902,
77345  /*   200 */   693,  753,  834,  902,  881,  883,  902,  902,  702,  711,
77346  /*   210 */   902,  902,  902,  816,  737,  737,  737,  649,  737,  902,
77347  /*   220 */   737,  902,  652,  747,  747,  599,  599,  599,  599,  669,
77348  /*   230 */   902,  747,  738,  740,  730,  742,  902,  719,  719,  727,
77349  /*   240 */   729,  727,  729,  681,  681,  666,  681,  652,  681,  826,
77350  /*   250 */   831,  831,  666,  681,  681,  681,  826,  611,  719,  611,
77351  /*   260 */   719,  611,  719,  719,  858,  860,  611,  719,  683,  683,
77352  /*   270 */   759,  747,  719,  690,  690,  690,  690,  747,  683,  759,
77353  /*   280 */   719,  880,  880,  719,  719,  888,  636,  654,  654,  863,
77354  /*   290 */   895,  900,  902,  902,  902,  902,  766,  902,  902,  902,
77355  /*   300 */   902,  902,  902,  902,  902,  902,  902,  902,  902,  902,
77356  /*   310 */   841,  902,  902,  902,  902,  771,  767,  902,  768,  902,
77357  /*   320 */   696,  902,  902,  902,  902,  902,  902,  902,  902,  902,
77358  /*   330 */   902,  819,  902,  731,  902,  739,  902,  902,  902,  902,
77359  /*   340 */   902,  902,  902,  902,  902,  902,  902,  902,  902,  902,
77360  /*   350 */   902,  902,  902,  902,  902,  902,  902,  902,  902,  902,
77361  /*   360 */   856,  857,  902,  902,  902,  902,  902,  902,  902,  902,
77362  /*   370 */   902,  902,  902,  902,  902,  902,  902,  902,  902,  902,
77363  /*   380 */   902,  902,  902,  902,  887,  902,  902,  890,  596,  902,
77364  /*   390 */   590,  593,  592,  594,  598,  601,  623,  624,  625,  603,
77365  /*   400 */   604,  605,  606,  607,  608,  609,  615,  617,  635,  637,
77366  /*   410 */   621,  639,  700,  701,  763,  694,  695,  699,  622,  774,
77367  /*   420 */   765,  769,  770,  772,  773,  787,  788,  790,  796,  803,
77368  /*   430 */   806,  789,  794,  795,  797,  802,  805,  697,  698,  809,
77369  /*   440 */   629,  630,  633,  634,  844,  846,  845,  847,  632,  631,
77370  /*   450 */   775,  778,  811,  812,  869,  870,  871,  872,  873,  807,
77371  /*   460 */   720,  810,  793,  732,  735,  736,  733,  703,  713,  722,
77372  /*   470 */   723,  724,  725,  708,  709,  715,  728,  761,  762,  716,
77373  /*   480 */   705,  706,  707,  808,  764,  776,  777,  640,  641,  771,
77374  /*   490 */   642,  643,  644,  682,  685,  686,  687,  645,  664,  667,
77375  /*   500 */   668,  646,  653,  647,  648,  655,  656,  657,  660,  661,
77376  /*   510 */   662,  663,  658,  659,  827,  828,  832,  830,  829,  650,
77377  /*   520 */   651,  665,  638,  627,  620,  671,  674,  675,  676,  677,
77378  /*   530 */   678,  680,  672,  673,  618,  610,  612,  721,  850,  859,
77379  /*   540 */   855,  851,  852,  853,  613,  823,  824,  684,  755,  756,
77380  /*   550 */   849,  862,  864,  760,  865,  867,  892,  688,  689,  692,
77381  /*   560 */   833,  874,  746,  749,  752,  754,  835,  836,  837,  838,
77382  /*   570 */   839,  842,  843,  840,  875,  879,  882,  884,  885,  886,
77383  /*   580 */   889,  891,  896,  897,  898,  901,  899,  597,  591,
77384 };
77385 #define YY_SZ_ACTTAB (int)(sizeof(yy_action)/sizeof(yy_action[0]))
77386
77387 /* The next table maps tokens into fallback tokens.  If a construct
77388 ** like the following:
77389 ** 
77390 **      %fallback ID X Y Z.
77391 **
77392 ** appears in the grammar, then ID becomes a fallback token for X, Y,
77393 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
77394 ** but it does not parse, the type of the token is changed to ID and
77395 ** the parse is retried before an error is thrown.
77396 */
77397 #ifdef YYFALLBACK
77398 static const YYCODETYPE yyFallback[] = {
77399     0,  /*          $ => nothing */
77400     0,  /*       SEMI => nothing */
77401    23,  /*    EXPLAIN => ID */
77402    23,  /*      QUERY => ID */
77403    23,  /*       PLAN => ID */
77404    23,  /*      BEGIN => ID */
77405     0,  /* TRANSACTION => nothing */
77406    23,  /*   DEFERRED => ID */
77407    23,  /*  IMMEDIATE => ID */
77408    23,  /*  EXCLUSIVE => ID */
77409     0,  /*     COMMIT => nothing */
77410    23,  /*        END => ID */
77411     0,  /*   ROLLBACK => nothing */
77412     0,  /*     CREATE => nothing */
77413     0,  /*      TABLE => nothing */
77414    23,  /*         IF => ID */
77415     0,  /*        NOT => nothing */
77416     0,  /*     EXISTS => nothing */
77417    23,  /*       TEMP => ID */
77418     0,  /*         LP => nothing */
77419     0,  /*         RP => nothing */
77420     0,  /*         AS => nothing */
77421     0,  /*      COMMA => nothing */
77422     0,  /*         ID => nothing */
77423    23,  /*      ABORT => ID */
77424    23,  /*      AFTER => ID */
77425    23,  /*    ANALYZE => ID */
77426    23,  /*        ASC => ID */
77427    23,  /*     ATTACH => ID */
77428    23,  /*     BEFORE => ID */
77429    23,  /*    CASCADE => ID */
77430    23,  /*       CAST => ID */
77431    23,  /*   CONFLICT => ID */
77432    23,  /*   DATABASE => ID */
77433    23,  /*       DESC => ID */
77434    23,  /*     DETACH => ID */
77435    23,  /*       EACH => ID */
77436    23,  /*       FAIL => ID */
77437    23,  /*        FOR => ID */
77438    23,  /*     IGNORE => ID */
77439    23,  /*  INITIALLY => ID */
77440    23,  /*    INSTEAD => ID */
77441    23,  /*    LIKE_KW => ID */
77442    23,  /*      MATCH => ID */
77443    23,  /*        KEY => ID */
77444    23,  /*         OF => ID */
77445    23,  /*     OFFSET => ID */
77446    23,  /*     PRAGMA => ID */
77447    23,  /*      RAISE => ID */
77448    23,  /*    REPLACE => ID */
77449    23,  /*   RESTRICT => ID */
77450    23,  /*        ROW => ID */
77451    23,  /*    TRIGGER => ID */
77452    23,  /*     VACUUM => ID */
77453    23,  /*       VIEW => ID */
77454    23,  /*    VIRTUAL => ID */
77455    23,  /*    REINDEX => ID */
77456    23,  /*     RENAME => ID */
77457    23,  /*   CTIME_KW => ID */
77458     0,  /*        ANY => nothing */
77459     0,  /*         OR => nothing */
77460     0,  /*        AND => nothing */
77461     0,  /*         IS => nothing */
77462     0,  /*    BETWEEN => nothing */
77463     0,  /*         IN => nothing */
77464     0,  /*     ISNULL => nothing */
77465     0,  /*    NOTNULL => nothing */
77466     0,  /*         NE => nothing */
77467     0,  /*         EQ => nothing */
77468     0,  /*         GT => nothing */
77469     0,  /*         LE => nothing */
77470     0,  /*         LT => nothing */
77471     0,  /*         GE => nothing */
77472     0,  /*     ESCAPE => nothing */
77473     0,  /*     BITAND => nothing */
77474     0,  /*      BITOR => nothing */
77475     0,  /*     LSHIFT => nothing */
77476     0,  /*     RSHIFT => nothing */
77477     0,  /*       PLUS => nothing */
77478     0,  /*      MINUS => nothing */
77479     0,  /*       STAR => nothing */
77480     0,  /*      SLASH => nothing */
77481     0,  /*        REM => nothing */
77482     0,  /*     CONCAT => nothing */
77483     0,  /*    COLLATE => nothing */
77484     0,  /*     UMINUS => nothing */
77485     0,  /*      UPLUS => nothing */
77486     0,  /*     BITNOT => nothing */
77487     0,  /*     STRING => nothing */
77488     0,  /*    JOIN_KW => nothing */
77489     0,  /* CONSTRAINT => nothing */
77490     0,  /*    DEFAULT => nothing */
77491     0,  /*       NULL => nothing */
77492     0,  /*    PRIMARY => nothing */
77493     0,  /*     UNIQUE => nothing */
77494     0,  /*      CHECK => nothing */
77495     0,  /* REFERENCES => nothing */
77496     0,  /*   AUTOINCR => nothing */
77497     0,  /*         ON => nothing */
77498     0,  /*     DELETE => nothing */
77499     0,  /*     UPDATE => nothing */
77500     0,  /*     INSERT => nothing */
77501     0,  /*        SET => nothing */
77502     0,  /* DEFERRABLE => nothing */
77503     0,  /*    FOREIGN => nothing */
77504     0,  /*       DROP => nothing */
77505     0,  /*      UNION => nothing */
77506     0,  /*        ALL => nothing */
77507     0,  /*     EXCEPT => nothing */
77508     0,  /*  INTERSECT => nothing */
77509     0,  /*     SELECT => nothing */
77510     0,  /*   DISTINCT => nothing */
77511     0,  /*        DOT => nothing */
77512     0,  /*       FROM => nothing */
77513     0,  /*       JOIN => nothing */
77514     0,  /*      USING => nothing */
77515     0,  /*      ORDER => nothing */
77516     0,  /*         BY => nothing */
77517     0,  /*      GROUP => nothing */
77518     0,  /*     HAVING => nothing */
77519     0,  /*      LIMIT => nothing */
77520     0,  /*      WHERE => nothing */
77521     0,  /*       INTO => nothing */
77522     0,  /*     VALUES => nothing */
77523     0,  /*    INTEGER => nothing */
77524     0,  /*      FLOAT => nothing */
77525     0,  /*       BLOB => nothing */
77526     0,  /*   REGISTER => nothing */
77527     0,  /*   VARIABLE => nothing */
77528     0,  /*       CASE => nothing */
77529     0,  /*       WHEN => nothing */
77530     0,  /*       THEN => nothing */
77531     0,  /*       ELSE => nothing */
77532     0,  /*      INDEX => nothing */
77533     0,  /*      ALTER => nothing */
77534     0,  /*         TO => nothing */
77535     0,  /*        ADD => nothing */
77536     0,  /*   COLUMNKW => nothing */
77537 };
77538 #endif /* YYFALLBACK */
77539
77540 /* The following structure represents a single element of the
77541 ** parser's stack.  Information stored includes:
77542 **
77543 **   +  The state number for the parser at this level of the stack.
77544 **
77545 **   +  The value of the token stored at this level of the stack.
77546 **      (In other words, the "major" token.)
77547 **
77548 **   +  The semantic value stored at this level of the stack.  This is
77549 **      the information used by the action routines in the grammar.
77550 **      It is sometimes called the "minor" token.
77551 */
77552 struct yyStackEntry {
77553   YYACTIONTYPE stateno;  /* The state-number */
77554   YYCODETYPE major;      /* The major token value.  This is the code
77555                          ** number for the token at this stack level */
77556   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
77557                          ** is the value of the token  */
77558 };
77559 typedef struct yyStackEntry yyStackEntry;
77560
77561 /* The state of the parser is completely contained in an instance of
77562 ** the following structure */
77563 struct yyParser {
77564   int yyidx;                    /* Index of top element in stack */
77565 #ifdef YYTRACKMAXSTACKDEPTH
77566   int yyidxMax;                 /* Maximum value of yyidx */
77567 #endif
77568   int yyerrcnt;                 /* Shifts left before out of the error */
77569   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
77570 #if YYSTACKDEPTH<=0
77571   int yystksz;                  /* Current side of the stack */
77572   yyStackEntry *yystack;        /* The parser's stack */
77573 #else
77574   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
77575 #endif
77576 };
77577 typedef struct yyParser yyParser;
77578
77579 #ifndef NDEBUG
77580 static FILE *yyTraceFILE = 0;
77581 static char *yyTracePrompt = 0;
77582 #endif /* NDEBUG */
77583
77584 #ifndef NDEBUG
77585 /* 
77586 ** Turn parser tracing on by giving a stream to which to write the trace
77587 ** and a prompt to preface each trace message.  Tracing is turned off
77588 ** by making either argument NULL 
77589 **
77590 ** Inputs:
77591 ** <ul>
77592 ** <li> A FILE* to which trace output should be written.
77593 **      If NULL, then tracing is turned off.
77594 ** <li> A prefix string written at the beginning of every
77595 **      line of trace output.  If NULL, then tracing is
77596 **      turned off.
77597 ** </ul>
77598 **
77599 ** Outputs:
77600 ** None.
77601 */
77602 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
77603   yyTraceFILE = TraceFILE;
77604   yyTracePrompt = zTracePrompt;
77605   if( yyTraceFILE==0 ) yyTracePrompt = 0;
77606   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
77607 }
77608 #endif /* NDEBUG */
77609
77610 #ifndef NDEBUG
77611 /* For tracing shifts, the names of all terminals and nonterminals
77612 ** are required.  The following table supplies these names */
77613 static const char *const yyTokenName[] = { 
77614   "$",             "SEMI",          "EXPLAIN",       "QUERY",       
77615   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",    
77616   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",         
77617   "ROLLBACK",      "CREATE",        "TABLE",         "IF",          
77618   "NOT",           "EXISTS",        "TEMP",          "LP",          
77619   "RP",            "AS",            "COMMA",         "ID",          
77620   "ABORT",         "AFTER",         "ANALYZE",       "ASC",         
77621   "ATTACH",        "BEFORE",        "CASCADE",       "CAST",        
77622   "CONFLICT",      "DATABASE",      "DESC",          "DETACH",      
77623   "EACH",          "FAIL",          "FOR",           "IGNORE",      
77624   "INITIALLY",     "INSTEAD",       "LIKE_KW",       "MATCH",       
77625   "KEY",           "OF",            "OFFSET",        "PRAGMA",      
77626   "RAISE",         "REPLACE",       "RESTRICT",      "ROW",         
77627   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",     
77628   "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",         
77629   "OR",            "AND",           "IS",            "BETWEEN",     
77630   "IN",            "ISNULL",        "NOTNULL",       "NE",          
77631   "EQ",            "GT",            "LE",            "LT",          
77632   "GE",            "ESCAPE",        "BITAND",        "BITOR",       
77633   "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",       
77634   "STAR",          "SLASH",         "REM",           "CONCAT",      
77635   "COLLATE",       "UMINUS",        "UPLUS",         "BITNOT",      
77636   "STRING",        "JOIN_KW",       "CONSTRAINT",    "DEFAULT",     
77637   "NULL",          "PRIMARY",       "UNIQUE",        "CHECK",       
77638   "REFERENCES",    "AUTOINCR",      "ON",            "DELETE",      
77639   "UPDATE",        "INSERT",        "SET",           "DEFERRABLE",  
77640   "FOREIGN",       "DROP",          "UNION",         "ALL",         
77641   "EXCEPT",        "INTERSECT",     "SELECT",        "DISTINCT",    
77642   "DOT",           "FROM",          "JOIN",          "USING",       
77643   "ORDER",         "BY",            "GROUP",         "HAVING",      
77644   "LIMIT",         "WHERE",         "INTO",          "VALUES",      
77645   "INTEGER",       "FLOAT",         "BLOB",          "REGISTER",    
77646   "VARIABLE",      "CASE",          "WHEN",          "THEN",        
77647   "ELSE",          "INDEX",         "ALTER",         "TO",          
77648   "ADD",           "COLUMNKW",      "error",         "input",       
77649   "cmdlist",       "ecmd",          "cmdx",          "cmd",         
77650   "explain",       "transtype",     "trans_opt",     "nm",          
77651   "create_table",  "create_table_args",  "temp",          "ifnotexists", 
77652   "dbnm",          "columnlist",    "conslist_opt",  "select",      
77653   "column",        "columnid",      "type",          "carglist",    
77654   "id",            "ids",           "typetoken",     "typename",    
77655   "signed",        "plus_num",      "minus_num",     "carg",        
77656   "ccons",         "term",          "expr",          "onconf",      
77657   "sortorder",     "autoinc",       "idxlist_opt",   "refargs",     
77658   "defer_subclause",  "refarg",        "refact",        "init_deferred_pred_opt",
77659   "conslist",      "tcons",         "idxlist",       "defer_subclause_opt",
77660   "orconf",        "resolvetype",   "raisetype",     "ifexists",    
77661   "fullname",      "oneselect",     "multiselect_op",  "distinct",    
77662   "selcollist",    "from",          "where_opt",     "groupby_opt", 
77663   "having_opt",    "orderby_opt",   "limit_opt",     "sclp",        
77664   "as",            "seltablist",    "stl_prefix",    "joinop",      
77665   "on_opt",        "using_opt",     "seltablist_paren",  "joinop2",     
77666   "inscollist",    "sortlist",      "sortitem",      "nexprlist",   
77667   "setlist",       "insert_cmd",    "inscollist_opt",  "itemlist",    
77668   "exprlist",      "likeop",        "escape",        "between_op",  
77669   "in_op",         "case_operand",  "case_exprlist",  "case_else",   
77670   "uniqueflag",    "idxitem",       "collate",       "nmnum",       
77671   "plus_opt",      "number",        "trigger_decl",  "trigger_cmd_list",
77672   "trigger_time",  "trigger_event",  "foreach_clause",  "when_clause", 
77673   "trigger_cmd",   "database_kw_opt",  "key_opt",       "add_column_fullname",
77674   "kwcolumn_opt",  "create_vtab",   "vtabarglist",   "vtabarg",     
77675   "vtabargtoken",  "lp",            "anylist",     
77676 };
77677 #endif /* NDEBUG */
77678
77679 #ifndef NDEBUG
77680 /* For tracing reduce actions, the names of all rules are required.
77681 */
77682 static const char *const yyRuleName[] = {
77683  /*   0 */ "input ::= cmdlist",
77684  /*   1 */ "cmdlist ::= cmdlist ecmd",
77685  /*   2 */ "cmdlist ::= ecmd",
77686  /*   3 */ "cmdx ::= cmd",
77687  /*   4 */ "ecmd ::= SEMI",
77688  /*   5 */ "ecmd ::= explain cmdx SEMI",
77689  /*   6 */ "explain ::=",
77690  /*   7 */ "explain ::= EXPLAIN",
77691  /*   8 */ "explain ::= EXPLAIN QUERY PLAN",
77692  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
77693  /*  10 */ "trans_opt ::=",
77694  /*  11 */ "trans_opt ::= TRANSACTION",
77695  /*  12 */ "trans_opt ::= TRANSACTION nm",
77696  /*  13 */ "transtype ::=",
77697  /*  14 */ "transtype ::= DEFERRED",
77698  /*  15 */ "transtype ::= IMMEDIATE",
77699  /*  16 */ "transtype ::= EXCLUSIVE",
77700  /*  17 */ "cmd ::= COMMIT trans_opt",
77701  /*  18 */ "cmd ::= END trans_opt",
77702  /*  19 */ "cmd ::= ROLLBACK trans_opt",
77703  /*  20 */ "cmd ::= create_table create_table_args",
77704  /*  21 */ "create_table ::= CREATE temp TABLE ifnotexists nm dbnm",
77705  /*  22 */ "ifnotexists ::=",
77706  /*  23 */ "ifnotexists ::= IF NOT EXISTS",
77707  /*  24 */ "temp ::= TEMP",
77708  /*  25 */ "temp ::=",
77709  /*  26 */ "create_table_args ::= LP columnlist conslist_opt RP",
77710  /*  27 */ "create_table_args ::= AS select",
77711  /*  28 */ "columnlist ::= columnlist COMMA column",
77712  /*  29 */ "columnlist ::= column",
77713  /*  30 */ "column ::= columnid type carglist",
77714  /*  31 */ "columnid ::= nm",
77715  /*  32 */ "id ::= ID",
77716  /*  33 */ "ids ::= ID|STRING",
77717  /*  34 */ "nm ::= ID",
77718  /*  35 */ "nm ::= STRING",
77719  /*  36 */ "nm ::= JOIN_KW",
77720  /*  37 */ "type ::=",
77721  /*  38 */ "type ::= typetoken",
77722  /*  39 */ "typetoken ::= typename",
77723  /*  40 */ "typetoken ::= typename LP signed RP",
77724  /*  41 */ "typetoken ::= typename LP signed COMMA signed RP",
77725  /*  42 */ "typename ::= ids",
77726  /*  43 */ "typename ::= typename ids",
77727  /*  44 */ "signed ::= plus_num",
77728  /*  45 */ "signed ::= minus_num",
77729  /*  46 */ "carglist ::= carglist carg",
77730  /*  47 */ "carglist ::=",
77731  /*  48 */ "carg ::= CONSTRAINT nm ccons",
77732  /*  49 */ "carg ::= ccons",
77733  /*  50 */ "ccons ::= DEFAULT term",
77734  /*  51 */ "ccons ::= DEFAULT LP expr RP",
77735  /*  52 */ "ccons ::= DEFAULT PLUS term",
77736  /*  53 */ "ccons ::= DEFAULT MINUS term",
77737  /*  54 */ "ccons ::= DEFAULT id",
77738  /*  55 */ "ccons ::= NULL onconf",
77739  /*  56 */ "ccons ::= NOT NULL onconf",
77740  /*  57 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
77741  /*  58 */ "ccons ::= UNIQUE onconf",
77742  /*  59 */ "ccons ::= CHECK LP expr RP",
77743  /*  60 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
77744  /*  61 */ "ccons ::= defer_subclause",
77745  /*  62 */ "ccons ::= COLLATE ids",
77746  /*  63 */ "autoinc ::=",
77747  /*  64 */ "autoinc ::= AUTOINCR",
77748  /*  65 */ "refargs ::=",
77749  /*  66 */ "refargs ::= refargs refarg",
77750  /*  67 */ "refarg ::= MATCH nm",
77751  /*  68 */ "refarg ::= ON DELETE refact",
77752  /*  69 */ "refarg ::= ON UPDATE refact",
77753  /*  70 */ "refarg ::= ON INSERT refact",
77754  /*  71 */ "refact ::= SET NULL",
77755  /*  72 */ "refact ::= SET DEFAULT",
77756  /*  73 */ "refact ::= CASCADE",
77757  /*  74 */ "refact ::= RESTRICT",
77758  /*  75 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
77759  /*  76 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
77760  /*  77 */ "init_deferred_pred_opt ::=",
77761  /*  78 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
77762  /*  79 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
77763  /*  80 */ "conslist_opt ::=",
77764  /*  81 */ "conslist_opt ::= COMMA conslist",
77765  /*  82 */ "conslist ::= conslist COMMA tcons",
77766  /*  83 */ "conslist ::= conslist tcons",
77767  /*  84 */ "conslist ::= tcons",
77768  /*  85 */ "tcons ::= CONSTRAINT nm",
77769  /*  86 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
77770  /*  87 */ "tcons ::= UNIQUE LP idxlist RP onconf",
77771  /*  88 */ "tcons ::= CHECK LP expr RP onconf",
77772  /*  89 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
77773  /*  90 */ "defer_subclause_opt ::=",
77774  /*  91 */ "defer_subclause_opt ::= defer_subclause",
77775  /*  92 */ "onconf ::=",
77776  /*  93 */ "onconf ::= ON CONFLICT resolvetype",
77777  /*  94 */ "orconf ::=",
77778  /*  95 */ "orconf ::= OR resolvetype",
77779  /*  96 */ "resolvetype ::= raisetype",
77780  /*  97 */ "resolvetype ::= IGNORE",
77781  /*  98 */ "resolvetype ::= REPLACE",
77782  /*  99 */ "cmd ::= DROP TABLE ifexists fullname",
77783  /* 100 */ "ifexists ::= IF EXISTS",
77784  /* 101 */ "ifexists ::=",
77785  /* 102 */ "cmd ::= CREATE temp VIEW ifnotexists nm dbnm AS select",
77786  /* 103 */ "cmd ::= DROP VIEW ifexists fullname",
77787  /* 104 */ "cmd ::= select",
77788  /* 105 */ "select ::= oneselect",
77789  /* 106 */ "select ::= select multiselect_op oneselect",
77790  /* 107 */ "multiselect_op ::= UNION",
77791  /* 108 */ "multiselect_op ::= UNION ALL",
77792  /* 109 */ "multiselect_op ::= EXCEPT|INTERSECT",
77793  /* 110 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
77794  /* 111 */ "distinct ::= DISTINCT",
77795  /* 112 */ "distinct ::= ALL",
77796  /* 113 */ "distinct ::=",
77797  /* 114 */ "sclp ::= selcollist COMMA",
77798  /* 115 */ "sclp ::=",
77799  /* 116 */ "selcollist ::= sclp expr as",
77800  /* 117 */ "selcollist ::= sclp STAR",
77801  /* 118 */ "selcollist ::= sclp nm DOT STAR",
77802  /* 119 */ "as ::= AS nm",
77803  /* 120 */ "as ::= ids",
77804  /* 121 */ "as ::=",
77805  /* 122 */ "from ::=",
77806  /* 123 */ "from ::= FROM seltablist",
77807  /* 124 */ "stl_prefix ::= seltablist joinop",
77808  /* 125 */ "stl_prefix ::=",
77809  /* 126 */ "seltablist ::= stl_prefix nm dbnm as on_opt using_opt",
77810  /* 127 */ "seltablist ::= stl_prefix LP seltablist_paren RP as on_opt using_opt",
77811  /* 128 */ "seltablist_paren ::= select",
77812  /* 129 */ "seltablist_paren ::= seltablist",
77813  /* 130 */ "dbnm ::=",
77814  /* 131 */ "dbnm ::= DOT nm",
77815  /* 132 */ "fullname ::= nm dbnm",
77816  /* 133 */ "joinop ::= COMMA|JOIN",
77817  /* 134 */ "joinop ::= JOIN_KW JOIN",
77818  /* 135 */ "joinop ::= JOIN_KW nm JOIN",
77819  /* 136 */ "joinop ::= JOIN_KW nm nm JOIN",
77820  /* 137 */ "on_opt ::= ON expr",
77821  /* 138 */ "on_opt ::=",
77822  /* 139 */ "using_opt ::= USING LP inscollist RP",
77823  /* 140 */ "using_opt ::=",
77824  /* 141 */ "orderby_opt ::=",
77825  /* 142 */ "orderby_opt ::= ORDER BY sortlist",
77826  /* 143 */ "sortlist ::= sortlist COMMA sortitem sortorder",
77827  /* 144 */ "sortlist ::= sortitem sortorder",
77828  /* 145 */ "sortitem ::= expr",
77829  /* 146 */ "sortorder ::= ASC",
77830  /* 147 */ "sortorder ::= DESC",
77831  /* 148 */ "sortorder ::=",
77832  /* 149 */ "groupby_opt ::=",
77833  /* 150 */ "groupby_opt ::= GROUP BY nexprlist",
77834  /* 151 */ "having_opt ::=",
77835  /* 152 */ "having_opt ::= HAVING expr",
77836  /* 153 */ "limit_opt ::=",
77837  /* 154 */ "limit_opt ::= LIMIT expr",
77838  /* 155 */ "limit_opt ::= LIMIT expr OFFSET expr",
77839  /* 156 */ "limit_opt ::= LIMIT expr COMMA expr",
77840  /* 157 */ "cmd ::= DELETE FROM fullname where_opt",
77841  /* 158 */ "where_opt ::=",
77842  /* 159 */ "where_opt ::= WHERE expr",
77843  /* 160 */ "cmd ::= UPDATE orconf fullname SET setlist where_opt",
77844  /* 161 */ "setlist ::= setlist COMMA nm EQ expr",
77845  /* 162 */ "setlist ::= nm EQ expr",
77846  /* 163 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
77847  /* 164 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
77848  /* 165 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
77849  /* 166 */ "insert_cmd ::= INSERT orconf",
77850  /* 167 */ "insert_cmd ::= REPLACE",
77851  /* 168 */ "itemlist ::= itemlist COMMA expr",
77852  /* 169 */ "itemlist ::= expr",
77853  /* 170 */ "inscollist_opt ::=",
77854  /* 171 */ "inscollist_opt ::= LP inscollist RP",
77855  /* 172 */ "inscollist ::= inscollist COMMA nm",
77856  /* 173 */ "inscollist ::= nm",
77857  /* 174 */ "expr ::= term",
77858  /* 175 */ "expr ::= LP expr RP",
77859  /* 176 */ "term ::= NULL",
77860  /* 177 */ "expr ::= ID",
77861  /* 178 */ "expr ::= JOIN_KW",
77862  /* 179 */ "expr ::= nm DOT nm",
77863  /* 180 */ "expr ::= nm DOT nm DOT nm",
77864  /* 181 */ "term ::= INTEGER|FLOAT|BLOB",
77865  /* 182 */ "term ::= STRING",
77866  /* 183 */ "expr ::= REGISTER",
77867  /* 184 */ "expr ::= VARIABLE",
77868  /* 185 */ "expr ::= expr COLLATE ids",
77869  /* 186 */ "expr ::= CAST LP expr AS typetoken RP",
77870  /* 187 */ "expr ::= ID LP distinct exprlist RP",
77871  /* 188 */ "expr ::= ID LP STAR RP",
77872  /* 189 */ "term ::= CTIME_KW",
77873  /* 190 */ "expr ::= expr AND expr",
77874  /* 191 */ "expr ::= expr OR expr",
77875  /* 192 */ "expr ::= expr LT|GT|GE|LE expr",
77876  /* 193 */ "expr ::= expr EQ|NE expr",
77877  /* 194 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
77878  /* 195 */ "expr ::= expr PLUS|MINUS expr",
77879  /* 196 */ "expr ::= expr STAR|SLASH|REM expr",
77880  /* 197 */ "expr ::= expr CONCAT expr",
77881  /* 198 */ "likeop ::= LIKE_KW",
77882  /* 199 */ "likeop ::= NOT LIKE_KW",
77883  /* 200 */ "likeop ::= MATCH",
77884  /* 201 */ "likeop ::= NOT MATCH",
77885  /* 202 */ "escape ::= ESCAPE expr",
77886  /* 203 */ "escape ::=",
77887  /* 204 */ "expr ::= expr likeop expr escape",
77888  /* 205 */ "expr ::= expr ISNULL|NOTNULL",
77889  /* 206 */ "expr ::= expr IS NULL",
77890  /* 207 */ "expr ::= expr NOT NULL",
77891  /* 208 */ "expr ::= expr IS NOT NULL",
77892  /* 209 */ "expr ::= NOT expr",
77893  /* 210 */ "expr ::= BITNOT expr",
77894  /* 211 */ "expr ::= MINUS expr",
77895  /* 212 */ "expr ::= PLUS expr",
77896  /* 213 */ "between_op ::= BETWEEN",
77897  /* 214 */ "between_op ::= NOT BETWEEN",
77898  /* 215 */ "expr ::= expr between_op expr AND expr",
77899  /* 216 */ "in_op ::= IN",
77900  /* 217 */ "in_op ::= NOT IN",
77901  /* 218 */ "expr ::= expr in_op LP exprlist RP",
77902  /* 219 */ "expr ::= LP select RP",
77903  /* 220 */ "expr ::= expr in_op LP select RP",
77904  /* 221 */ "expr ::= expr in_op nm dbnm",
77905  /* 222 */ "expr ::= EXISTS LP select RP",
77906  /* 223 */ "expr ::= CASE case_operand case_exprlist case_else END",
77907  /* 224 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
77908  /* 225 */ "case_exprlist ::= WHEN expr THEN expr",
77909  /* 226 */ "case_else ::= ELSE expr",
77910  /* 227 */ "case_else ::=",
77911  /* 228 */ "case_operand ::= expr",
77912  /* 229 */ "case_operand ::=",
77913  /* 230 */ "exprlist ::= nexprlist",
77914  /* 231 */ "exprlist ::=",
77915  /* 232 */ "nexprlist ::= nexprlist COMMA expr",
77916  /* 233 */ "nexprlist ::= expr",
77917  /* 234 */ "cmd ::= CREATE uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
77918  /* 235 */ "uniqueflag ::= UNIQUE",
77919  /* 236 */ "uniqueflag ::=",
77920  /* 237 */ "idxlist_opt ::=",
77921  /* 238 */ "idxlist_opt ::= LP idxlist RP",
77922  /* 239 */ "idxlist ::= idxlist COMMA idxitem collate sortorder",
77923  /* 240 */ "idxlist ::= idxitem collate sortorder",
77924  /* 241 */ "idxitem ::= nm",
77925  /* 242 */ "collate ::=",
77926  /* 243 */ "collate ::= COLLATE ids",
77927  /* 244 */ "cmd ::= DROP INDEX ifexists fullname",
77928  /* 245 */ "cmd ::= VACUUM",
77929  /* 246 */ "cmd ::= VACUUM nm",
77930  /* 247 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
77931  /* 248 */ "cmd ::= PRAGMA nm dbnm EQ ON",
77932  /* 249 */ "cmd ::= PRAGMA nm dbnm EQ DELETE",
77933  /* 250 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
77934  /* 251 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
77935  /* 252 */ "cmd ::= PRAGMA nm dbnm",
77936  /* 253 */ "nmnum ::= plus_num",
77937  /* 254 */ "nmnum ::= nm",
77938  /* 255 */ "plus_num ::= plus_opt number",
77939  /* 256 */ "minus_num ::= MINUS number",
77940  /* 257 */ "number ::= INTEGER|FLOAT",
77941  /* 258 */ "plus_opt ::= PLUS",
77942  /* 259 */ "plus_opt ::=",
77943  /* 260 */ "cmd ::= CREATE trigger_decl BEGIN trigger_cmd_list END",
77944  /* 261 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
77945  /* 262 */ "trigger_time ::= BEFORE",
77946  /* 263 */ "trigger_time ::= AFTER",
77947  /* 264 */ "trigger_time ::= INSTEAD OF",
77948  /* 265 */ "trigger_time ::=",
77949  /* 266 */ "trigger_event ::= DELETE|INSERT",
77950  /* 267 */ "trigger_event ::= UPDATE",
77951  /* 268 */ "trigger_event ::= UPDATE OF inscollist",
77952  /* 269 */ "foreach_clause ::=",
77953  /* 270 */ "foreach_clause ::= FOR EACH ROW",
77954  /* 271 */ "when_clause ::=",
77955  /* 272 */ "when_clause ::= WHEN expr",
77956  /* 273 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
77957  /* 274 */ "trigger_cmd_list ::=",
77958  /* 275 */ "trigger_cmd ::= UPDATE orconf nm SET setlist where_opt",
77959  /* 276 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP",
77960  /* 277 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt select",
77961  /* 278 */ "trigger_cmd ::= DELETE FROM nm where_opt",
77962  /* 279 */ "trigger_cmd ::= select",
77963  /* 280 */ "expr ::= RAISE LP IGNORE RP",
77964  /* 281 */ "expr ::= RAISE LP raisetype COMMA nm RP",
77965  /* 282 */ "raisetype ::= ROLLBACK",
77966  /* 283 */ "raisetype ::= ABORT",
77967  /* 284 */ "raisetype ::= FAIL",
77968  /* 285 */ "cmd ::= DROP TRIGGER ifexists fullname",
77969  /* 286 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
77970  /* 287 */ "cmd ::= DETACH database_kw_opt expr",
77971  /* 288 */ "key_opt ::=",
77972  /* 289 */ "key_opt ::= KEY expr",
77973  /* 290 */ "database_kw_opt ::= DATABASE",
77974  /* 291 */ "database_kw_opt ::=",
77975  /* 292 */ "cmd ::= REINDEX",
77976  /* 293 */ "cmd ::= REINDEX nm dbnm",
77977  /* 294 */ "cmd ::= ANALYZE",
77978  /* 295 */ "cmd ::= ANALYZE nm dbnm",
77979  /* 296 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
77980  /* 297 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
77981  /* 298 */ "add_column_fullname ::= fullname",
77982  /* 299 */ "kwcolumn_opt ::=",
77983  /* 300 */ "kwcolumn_opt ::= COLUMNKW",
77984  /* 301 */ "cmd ::= create_vtab",
77985  /* 302 */ "cmd ::= create_vtab LP vtabarglist RP",
77986  /* 303 */ "create_vtab ::= CREATE VIRTUAL TABLE nm dbnm USING nm",
77987  /* 304 */ "vtabarglist ::= vtabarg",
77988  /* 305 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
77989  /* 306 */ "vtabarg ::=",
77990  /* 307 */ "vtabarg ::= vtabarg vtabargtoken",
77991  /* 308 */ "vtabargtoken ::= ANY",
77992  /* 309 */ "vtabargtoken ::= lp anylist RP",
77993  /* 310 */ "lp ::= LP",
77994  /* 311 */ "anylist ::=",
77995  /* 312 */ "anylist ::= anylist ANY",
77996 };
77997 #endif /* NDEBUG */
77998
77999
78000 #if YYSTACKDEPTH<=0
78001 /*
78002 ** Try to increase the size of the parser stack.
78003 */
78004 static void yyGrowStack(yyParser *p){
78005   int newSize;
78006   yyStackEntry *pNew;
78007
78008   newSize = p->yystksz*2 + 100;
78009   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
78010   if( pNew ){
78011     p->yystack = pNew;
78012     p->yystksz = newSize;
78013 #ifndef NDEBUG
78014     if( yyTraceFILE ){
78015       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
78016               yyTracePrompt, p->yystksz);
78017     }
78018 #endif
78019   }
78020 }
78021 #endif
78022
78023 /* 
78024 ** This function allocates a new parser.
78025 ** The only argument is a pointer to a function which works like
78026 ** malloc.
78027 **
78028 ** Inputs:
78029 ** A pointer to the function used to allocate memory.
78030 **
78031 ** Outputs:
78032 ** A pointer to a parser.  This pointer is used in subsequent calls
78033 ** to sqlite3Parser and sqlite3ParserFree.
78034 */
78035 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
78036   yyParser *pParser;
78037   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
78038   if( pParser ){
78039     pParser->yyidx = -1;
78040 #ifdef YYTRACKMAXSTACKDEPTH
78041     pParser->yyidxMax = 0;
78042 #endif
78043 #if YYSTACKDEPTH<=0
78044     yyGrowStack(pParser);
78045 #endif
78046   }
78047   return pParser;
78048 }
78049
78050 /* The following function deletes the value associated with a
78051 ** symbol.  The symbol can be either a terminal or nonterminal.
78052 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
78053 ** the value.
78054 */
78055 static void yy_destructor(
78056   yyParser *yypParser,    /* The parser */
78057   YYCODETYPE yymajor,     /* Type code for object to destroy */
78058   YYMINORTYPE *yypminor   /* The object to be destroyed */
78059 ){
78060   sqlite3ParserARG_FETCH;
78061   switch( yymajor ){
78062     /* Here is inserted the actions which take place when a
78063     ** terminal or non-terminal is destroyed.  This can happen
78064     ** when the symbol is popped from the stack during a
78065     ** reduce or during error processing or when a parser is 
78066     ** being destroyed before it is finished parsing.
78067     **
78068     ** Note: during a reduce, the only symbols destroyed are those
78069     ** which appear on the RHS of the rule, but which are not used
78070     ** inside the C code.
78071     */
78072     case 155: /* select */
78073     case 189: /* oneselect */
78074     case 206: /* seltablist_paren */
78075 {
78076 sqlite3SelectDelete(pParse->db, (yypminor->yy219));
78077 }
78078       break;
78079     case 169: /* term */
78080     case 170: /* expr */
78081     case 194: /* where_opt */
78082     case 196: /* having_opt */
78083     case 204: /* on_opt */
78084     case 210: /* sortitem */
78085     case 218: /* escape */
78086     case 221: /* case_operand */
78087     case 223: /* case_else */
78088     case 235: /* when_clause */
78089     case 238: /* key_opt */
78090 {
78091 sqlite3ExprDelete(pParse->db, (yypminor->yy172));
78092 }
78093       break;
78094     case 174: /* idxlist_opt */
78095     case 182: /* idxlist */
78096     case 192: /* selcollist */
78097     case 195: /* groupby_opt */
78098     case 197: /* orderby_opt */
78099     case 199: /* sclp */
78100     case 209: /* sortlist */
78101     case 211: /* nexprlist */
78102     case 212: /* setlist */
78103     case 215: /* itemlist */
78104     case 216: /* exprlist */
78105     case 222: /* case_exprlist */
78106 {
78107 sqlite3ExprListDelete(pParse->db, (yypminor->yy174));
78108 }
78109       break;
78110     case 188: /* fullname */
78111     case 193: /* from */
78112     case 201: /* seltablist */
78113     case 202: /* stl_prefix */
78114 {
78115 sqlite3SrcListDelete(pParse->db, (yypminor->yy373));
78116 }
78117       break;
78118     case 205: /* using_opt */
78119     case 208: /* inscollist */
78120     case 214: /* inscollist_opt */
78121 {
78122 sqlite3IdListDelete(pParse->db, (yypminor->yy432));
78123 }
78124       break;
78125     case 231: /* trigger_cmd_list */
78126     case 236: /* trigger_cmd */
78127 {
78128 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy243));
78129 }
78130       break;
78131     case 233: /* trigger_event */
78132 {
78133 sqlite3IdListDelete(pParse->db, (yypminor->yy370).b);
78134 }
78135       break;
78136     default:  break;   /* If no destructor action specified: do nothing */
78137   }
78138 }
78139
78140 /*
78141 ** Pop the parser's stack once.
78142 **
78143 ** If there is a destructor routine associated with the token which
78144 ** is popped from the stack, then call it.
78145 **
78146 ** Return the major token number for the symbol popped.
78147 */
78148 static int yy_pop_parser_stack(yyParser *pParser){
78149   YYCODETYPE yymajor;
78150   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
78151
78152   if( pParser->yyidx<0 ) return 0;
78153 #ifndef NDEBUG
78154   if( yyTraceFILE && pParser->yyidx>=0 ){
78155     fprintf(yyTraceFILE,"%sPopping %s\n",
78156       yyTracePrompt,
78157       yyTokenName[yytos->major]);
78158   }
78159 #endif
78160   yymajor = yytos->major;
78161   yy_destructor(pParser, yymajor, &yytos->minor);
78162   pParser->yyidx--;
78163   return yymajor;
78164 }
78165
78166 /* 
78167 ** Deallocate and destroy a parser.  Destructors are all called for
78168 ** all stack elements before shutting the parser down.
78169 **
78170 ** Inputs:
78171 ** <ul>
78172 ** <li>  A pointer to the parser.  This should be a pointer
78173 **       obtained from sqlite3ParserAlloc.
78174 ** <li>  A pointer to a function used to reclaim memory obtained
78175 **       from malloc.
78176 ** </ul>
78177 */
78178 SQLITE_PRIVATE void sqlite3ParserFree(
78179   void *p,                    /* The parser to be deleted */
78180   void (*freeProc)(void*)     /* Function used to reclaim memory */
78181 ){
78182   yyParser *pParser = (yyParser*)p;
78183   if( pParser==0 ) return;
78184   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
78185 #if YYSTACKDEPTH<=0
78186   free(pParser->yystack);
78187 #endif
78188   (*freeProc)((void*)pParser);
78189 }
78190
78191 /*
78192 ** Return the peak depth of the stack for a parser.
78193 */
78194 #ifdef YYTRACKMAXSTACKDEPTH
78195 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
78196   yyParser *pParser = (yyParser*)p;
78197   return pParser->yyidxMax;
78198 }
78199 #endif
78200
78201 /*
78202 ** Find the appropriate action for a parser given the terminal
78203 ** look-ahead token iLookAhead.
78204 **
78205 ** If the look-ahead token is YYNOCODE, then check to see if the action is
78206 ** independent of the look-ahead.  If it is, return the action, otherwise
78207 ** return YY_NO_ACTION.
78208 */
78209 static int yy_find_shift_action(
78210   yyParser *pParser,        /* The parser */
78211   YYCODETYPE iLookAhead     /* The look-ahead token */
78212 ){
78213   int i;
78214   int stateno = pParser->yystack[pParser->yyidx].stateno;
78215  
78216   if( stateno>YY_SHIFT_MAX || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
78217     return yy_default[stateno];
78218   }
78219   assert( iLookAhead!=YYNOCODE );
78220   i += iLookAhead;
78221   if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){
78222     if( iLookAhead>0 ){
78223 #ifdef YYFALLBACK
78224       int iFallback;            /* Fallback token */
78225       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
78226              && (iFallback = yyFallback[iLookAhead])!=0 ){
78227 #ifndef NDEBUG
78228         if( yyTraceFILE ){
78229           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
78230              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
78231         }
78232 #endif
78233         return yy_find_shift_action(pParser, iFallback);
78234       }
78235 #endif
78236 #ifdef YYWILDCARD
78237       {
78238         int j = i - iLookAhead + YYWILDCARD;
78239         if( j>=0 && j<YY_SZ_ACTTAB && yy_lookahead[j]==YYWILDCARD ){
78240 #ifndef NDEBUG
78241           if( yyTraceFILE ){
78242             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
78243                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
78244           }
78245 #endif /* NDEBUG */
78246           return yy_action[j];
78247         }
78248       }
78249 #endif /* YYWILDCARD */
78250     }
78251     return yy_default[stateno];
78252   }else{
78253     return yy_action[i];
78254   }
78255 }
78256
78257 /*
78258 ** Find the appropriate action for a parser given the non-terminal
78259 ** look-ahead token iLookAhead.
78260 **
78261 ** If the look-ahead token is YYNOCODE, then check to see if the action is
78262 ** independent of the look-ahead.  If it is, return the action, otherwise
78263 ** return YY_NO_ACTION.
78264 */
78265 static int yy_find_reduce_action(
78266   int stateno,              /* Current state number */
78267   YYCODETYPE iLookAhead     /* The look-ahead token */
78268 ){
78269   int i;
78270 #ifdef YYERRORSYMBOL
78271   if( stateno>YY_REDUCE_MAX ){
78272     return yy_default[stateno];
78273   }
78274 #else
78275   assert( stateno<=YY_REDUCE_MAX );
78276 #endif
78277   i = yy_reduce_ofst[stateno];
78278   assert( i!=YY_REDUCE_USE_DFLT );
78279   assert( iLookAhead!=YYNOCODE );
78280   i += iLookAhead;
78281 #ifdef YYERRORSYMBOL
78282   if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){
78283     return yy_default[stateno];
78284   }
78285 #else
78286   assert( i>=0 && i<YY_SZ_ACTTAB );
78287   assert( yy_lookahead[i]==iLookAhead );
78288 #endif
78289   return yy_action[i];
78290 }
78291
78292 /*
78293 ** The following routine is called if the stack overflows.
78294 */
78295 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
78296    sqlite3ParserARG_FETCH;
78297    yypParser->yyidx--;
78298 #ifndef NDEBUG
78299    if( yyTraceFILE ){
78300      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
78301    }
78302 #endif
78303    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
78304    /* Here code is inserted which will execute if the parser
78305    ** stack every overflows */
78306
78307   sqlite3ErrorMsg(pParse, "parser stack overflow");
78308   pParse->parseError = 1;
78309    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
78310 }
78311
78312 /*
78313 ** Perform a shift action.
78314 */
78315 static void yy_shift(
78316   yyParser *yypParser,          /* The parser to be shifted */
78317   int yyNewState,               /* The new state to shift in */
78318   int yyMajor,                  /* The major token to shift in */
78319   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
78320 ){
78321   yyStackEntry *yytos;
78322   yypParser->yyidx++;
78323 #ifdef YYTRACKMAXSTACKDEPTH
78324   if( yypParser->yyidx>yypParser->yyidxMax ){
78325     yypParser->yyidxMax = yypParser->yyidx;
78326   }
78327 #endif
78328 #if YYSTACKDEPTH>0 
78329   if( yypParser->yyidx>=YYSTACKDEPTH ){
78330     yyStackOverflow(yypParser, yypMinor);
78331     return;
78332   }
78333 #else
78334   if( yypParser->yyidx>=yypParser->yystksz ){
78335     yyGrowStack(yypParser);
78336     if( yypParser->yyidx>=yypParser->yystksz ){
78337       yyStackOverflow(yypParser, yypMinor);
78338       return;
78339     }
78340   }
78341 #endif
78342   yytos = &yypParser->yystack[yypParser->yyidx];
78343   yytos->stateno = yyNewState;
78344   yytos->major = yyMajor;
78345   yytos->minor = *yypMinor;
78346 #ifndef NDEBUG
78347   if( yyTraceFILE && yypParser->yyidx>0 ){
78348     int i;
78349     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
78350     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
78351     for(i=1; i<=yypParser->yyidx; i++)
78352       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
78353     fprintf(yyTraceFILE,"\n");
78354   }
78355 #endif
78356 }
78357
78358 /* The following table contains information about every rule that
78359 ** is used during the reduce.
78360 */
78361 static const struct {
78362   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
78363   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
78364 } yyRuleInfo[] = {
78365   { 139, 1 },
78366   { 140, 2 },
78367   { 140, 1 },
78368   { 142, 1 },
78369   { 141, 1 },
78370   { 141, 3 },
78371   { 144, 0 },
78372   { 144, 1 },
78373   { 144, 3 },
78374   { 143, 3 },
78375   { 146, 0 },
78376   { 146, 1 },
78377   { 146, 2 },
78378   { 145, 0 },
78379   { 145, 1 },
78380   { 145, 1 },
78381   { 145, 1 },
78382   { 143, 2 },
78383   { 143, 2 },
78384   { 143, 2 },
78385   { 143, 2 },
78386   { 148, 6 },
78387   { 151, 0 },
78388   { 151, 3 },
78389   { 150, 1 },
78390   { 150, 0 },
78391   { 149, 4 },
78392   { 149, 2 },
78393   { 153, 3 },
78394   { 153, 1 },
78395   { 156, 3 },
78396   { 157, 1 },
78397   { 160, 1 },
78398   { 161, 1 },
78399   { 147, 1 },
78400   { 147, 1 },
78401   { 147, 1 },
78402   { 158, 0 },
78403   { 158, 1 },
78404   { 162, 1 },
78405   { 162, 4 },
78406   { 162, 6 },
78407   { 163, 1 },
78408   { 163, 2 },
78409   { 164, 1 },
78410   { 164, 1 },
78411   { 159, 2 },
78412   { 159, 0 },
78413   { 167, 3 },
78414   { 167, 1 },
78415   { 168, 2 },
78416   { 168, 4 },
78417   { 168, 3 },
78418   { 168, 3 },
78419   { 168, 2 },
78420   { 168, 2 },
78421   { 168, 3 },
78422   { 168, 5 },
78423   { 168, 2 },
78424   { 168, 4 },
78425   { 168, 4 },
78426   { 168, 1 },
78427   { 168, 2 },
78428   { 173, 0 },
78429   { 173, 1 },
78430   { 175, 0 },
78431   { 175, 2 },
78432   { 177, 2 },
78433   { 177, 3 },
78434   { 177, 3 },
78435   { 177, 3 },
78436   { 178, 2 },
78437   { 178, 2 },
78438   { 178, 1 },
78439   { 178, 1 },
78440   { 176, 3 },
78441   { 176, 2 },
78442   { 179, 0 },
78443   { 179, 2 },
78444   { 179, 2 },
78445   { 154, 0 },
78446   { 154, 2 },
78447   { 180, 3 },
78448   { 180, 2 },
78449   { 180, 1 },
78450   { 181, 2 },
78451   { 181, 7 },
78452   { 181, 5 },
78453   { 181, 5 },
78454   { 181, 10 },
78455   { 183, 0 },
78456   { 183, 1 },
78457   { 171, 0 },
78458   { 171, 3 },
78459   { 184, 0 },
78460   { 184, 2 },
78461   { 185, 1 },
78462   { 185, 1 },
78463   { 185, 1 },
78464   { 143, 4 },
78465   { 187, 2 },
78466   { 187, 0 },
78467   { 143, 8 },
78468   { 143, 4 },
78469   { 143, 1 },
78470   { 155, 1 },
78471   { 155, 3 },
78472   { 190, 1 },
78473   { 190, 2 },
78474   { 190, 1 },
78475   { 189, 9 },
78476   { 191, 1 },
78477   { 191, 1 },
78478   { 191, 0 },
78479   { 199, 2 },
78480   { 199, 0 },
78481   { 192, 3 },
78482   { 192, 2 },
78483   { 192, 4 },
78484   { 200, 2 },
78485   { 200, 1 },
78486   { 200, 0 },
78487   { 193, 0 },
78488   { 193, 2 },
78489   { 202, 2 },
78490   { 202, 0 },
78491   { 201, 6 },
78492   { 201, 7 },
78493   { 206, 1 },
78494   { 206, 1 },
78495   { 152, 0 },
78496   { 152, 2 },
78497   { 188, 2 },
78498   { 203, 1 },
78499   { 203, 2 },
78500   { 203, 3 },
78501   { 203, 4 },
78502   { 204, 2 },
78503   { 204, 0 },
78504   { 205, 4 },
78505   { 205, 0 },
78506   { 197, 0 },
78507   { 197, 3 },
78508   { 209, 4 },
78509   { 209, 2 },
78510   { 210, 1 },
78511   { 172, 1 },
78512   { 172, 1 },
78513   { 172, 0 },
78514   { 195, 0 },
78515   { 195, 3 },
78516   { 196, 0 },
78517   { 196, 2 },
78518   { 198, 0 },
78519   { 198, 2 },
78520   { 198, 4 },
78521   { 198, 4 },
78522   { 143, 4 },
78523   { 194, 0 },
78524   { 194, 2 },
78525   { 143, 6 },
78526   { 212, 5 },
78527   { 212, 3 },
78528   { 143, 8 },
78529   { 143, 5 },
78530   { 143, 6 },
78531   { 213, 2 },
78532   { 213, 1 },
78533   { 215, 3 },
78534   { 215, 1 },
78535   { 214, 0 },
78536   { 214, 3 },
78537   { 208, 3 },
78538   { 208, 1 },
78539   { 170, 1 },
78540   { 170, 3 },
78541   { 169, 1 },
78542   { 170, 1 },
78543   { 170, 1 },
78544   { 170, 3 },
78545   { 170, 5 },
78546   { 169, 1 },
78547   { 169, 1 },
78548   { 170, 1 },
78549   { 170, 1 },
78550   { 170, 3 },
78551   { 170, 6 },
78552   { 170, 5 },
78553   { 170, 4 },
78554   { 169, 1 },
78555   { 170, 3 },
78556   { 170, 3 },
78557   { 170, 3 },
78558   { 170, 3 },
78559   { 170, 3 },
78560   { 170, 3 },
78561   { 170, 3 },
78562   { 170, 3 },
78563   { 217, 1 },
78564   { 217, 2 },
78565   { 217, 1 },
78566   { 217, 2 },
78567   { 218, 2 },
78568   { 218, 0 },
78569   { 170, 4 },
78570   { 170, 2 },
78571   { 170, 3 },
78572   { 170, 3 },
78573   { 170, 4 },
78574   { 170, 2 },
78575   { 170, 2 },
78576   { 170, 2 },
78577   { 170, 2 },
78578   { 219, 1 },
78579   { 219, 2 },
78580   { 170, 5 },
78581   { 220, 1 },
78582   { 220, 2 },
78583   { 170, 5 },
78584   { 170, 3 },
78585   { 170, 5 },
78586   { 170, 4 },
78587   { 170, 4 },
78588   { 170, 5 },
78589   { 222, 5 },
78590   { 222, 4 },
78591   { 223, 2 },
78592   { 223, 0 },
78593   { 221, 1 },
78594   { 221, 0 },
78595   { 216, 1 },
78596   { 216, 0 },
78597   { 211, 3 },
78598   { 211, 1 },
78599   { 143, 11 },
78600   { 224, 1 },
78601   { 224, 0 },
78602   { 174, 0 },
78603   { 174, 3 },
78604   { 182, 5 },
78605   { 182, 3 },
78606   { 225, 1 },
78607   { 226, 0 },
78608   { 226, 2 },
78609   { 143, 4 },
78610   { 143, 1 },
78611   { 143, 2 },
78612   { 143, 5 },
78613   { 143, 5 },
78614   { 143, 5 },
78615   { 143, 5 },
78616   { 143, 6 },
78617   { 143, 3 },
78618   { 227, 1 },
78619   { 227, 1 },
78620   { 165, 2 },
78621   { 166, 2 },
78622   { 229, 1 },
78623   { 228, 1 },
78624   { 228, 0 },
78625   { 143, 5 },
78626   { 230, 11 },
78627   { 232, 1 },
78628   { 232, 1 },
78629   { 232, 2 },
78630   { 232, 0 },
78631   { 233, 1 },
78632   { 233, 1 },
78633   { 233, 3 },
78634   { 234, 0 },
78635   { 234, 3 },
78636   { 235, 0 },
78637   { 235, 2 },
78638   { 231, 3 },
78639   { 231, 0 },
78640   { 236, 6 },
78641   { 236, 8 },
78642   { 236, 5 },
78643   { 236, 4 },
78644   { 236, 1 },
78645   { 170, 4 },
78646   { 170, 6 },
78647   { 186, 1 },
78648   { 186, 1 },
78649   { 186, 1 },
78650   { 143, 4 },
78651   { 143, 6 },
78652   { 143, 3 },
78653   { 238, 0 },
78654   { 238, 2 },
78655   { 237, 1 },
78656   { 237, 0 },
78657   { 143, 1 },
78658   { 143, 3 },
78659   { 143, 1 },
78660   { 143, 3 },
78661   { 143, 6 },
78662   { 143, 6 },
78663   { 239, 1 },
78664   { 240, 0 },
78665   { 240, 1 },
78666   { 143, 1 },
78667   { 143, 4 },
78668   { 241, 7 },
78669   { 242, 1 },
78670   { 242, 3 },
78671   { 243, 0 },
78672   { 243, 2 },
78673   { 244, 1 },
78674   { 244, 3 },
78675   { 245, 1 },
78676   { 246, 0 },
78677   { 246, 2 },
78678 };
78679
78680 static void yy_accept(yyParser*);  /* Forward Declaration */
78681
78682 /*
78683 ** Perform a reduce action and the shift that must immediately
78684 ** follow the reduce.
78685 */
78686 static void yy_reduce(
78687   yyParser *yypParser,         /* The parser */
78688   int yyruleno                 /* Number of the rule by which to reduce */
78689 ){
78690   int yygoto;                     /* The next state */
78691   int yyact;                      /* The next action */
78692   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
78693   yyStackEntry *yymsp;            /* The top of the parser's stack */
78694   int yysize;                     /* Amount to pop the stack */
78695   sqlite3ParserARG_FETCH;
78696   yymsp = &yypParser->yystack[yypParser->yyidx];
78697 #ifndef NDEBUG
78698   if( yyTraceFILE && yyruleno>=0 
78699         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
78700     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
78701       yyRuleName[yyruleno]);
78702   }
78703 #endif /* NDEBUG */
78704
78705   /* Silence complaints from purify about yygotominor being uninitialized
78706   ** in some cases when it is copied into the stack after the following
78707   ** switch.  yygotominor is uninitialized when a rule reduces that does
78708   ** not set the value of its left-hand side nonterminal.  Leaving the
78709   ** value of the nonterminal uninitialized is utterly harmless as long
78710   ** as the value is never used.  So really the only thing this code
78711   ** accomplishes is to quieten purify.  
78712   **
78713   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
78714   ** without this code, their parser segfaults.  I'm not sure what there
78715   ** parser is doing to make this happen.  This is the second bug report
78716   ** from wireshark this week.  Clearly they are stressing Lemon in ways
78717   ** that it has not been previously stressed...  (SQLite ticket #2172)
78718   */
78719   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
78720   yygotominor = yyzerominor;
78721
78722
78723   switch( yyruleno ){
78724   /* Beginning here are the reduction cases.  A typical example
78725   ** follows:
78726   **   case 0:
78727   **  #line <lineno> <grammarfile>
78728   **     { ... }           // User supplied code
78729   **  #line <lineno> <thisfile>
78730   **     break;
78731   */
78732       case 0: /* input ::= cmdlist */
78733       case 1: /* cmdlist ::= cmdlist ecmd */
78734       case 2: /* cmdlist ::= ecmd */
78735       case 4: /* ecmd ::= SEMI */
78736       case 5: /* ecmd ::= explain cmdx SEMI */
78737       case 10: /* trans_opt ::= */
78738       case 11: /* trans_opt ::= TRANSACTION */
78739       case 12: /* trans_opt ::= TRANSACTION nm */
78740       case 20: /* cmd ::= create_table create_table_args */
78741       case 28: /* columnlist ::= columnlist COMMA column */
78742       case 29: /* columnlist ::= column */
78743       case 37: /* type ::= */
78744       case 44: /* signed ::= plus_num */
78745       case 45: /* signed ::= minus_num */
78746       case 46: /* carglist ::= carglist carg */
78747       case 47: /* carglist ::= */
78748       case 48: /* carg ::= CONSTRAINT nm ccons */
78749       case 49: /* carg ::= ccons */
78750       case 55: /* ccons ::= NULL onconf */
78751       case 82: /* conslist ::= conslist COMMA tcons */
78752       case 83: /* conslist ::= conslist tcons */
78753       case 84: /* conslist ::= tcons */
78754       case 85: /* tcons ::= CONSTRAINT nm */
78755       case 258: /* plus_opt ::= PLUS */
78756       case 259: /* plus_opt ::= */
78757       case 269: /* foreach_clause ::= */
78758       case 270: /* foreach_clause ::= FOR EACH ROW */
78759       case 290: /* database_kw_opt ::= DATABASE */
78760       case 291: /* database_kw_opt ::= */
78761       case 299: /* kwcolumn_opt ::= */
78762       case 300: /* kwcolumn_opt ::= COLUMNKW */
78763       case 304: /* vtabarglist ::= vtabarg */
78764       case 305: /* vtabarglist ::= vtabarglist COMMA vtabarg */
78765       case 307: /* vtabarg ::= vtabarg vtabargtoken */
78766       case 311: /* anylist ::= */
78767 {
78768 }
78769         break;
78770       case 3: /* cmdx ::= cmd */
78771 { sqlite3FinishCoding(pParse); }
78772         break;
78773       case 6: /* explain ::= */
78774 { sqlite3BeginParse(pParse, 0); }
78775         break;
78776       case 7: /* explain ::= EXPLAIN */
78777 { sqlite3BeginParse(pParse, 1); }
78778         break;
78779       case 8: /* explain ::= EXPLAIN QUERY PLAN */
78780 { sqlite3BeginParse(pParse, 2); }
78781         break;
78782       case 9: /* cmd ::= BEGIN transtype trans_opt */
78783 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy46);}
78784         break;
78785       case 13: /* transtype ::= */
78786 {yygotominor.yy46 = TK_DEFERRED;}
78787         break;
78788       case 14: /* transtype ::= DEFERRED */
78789       case 15: /* transtype ::= IMMEDIATE */
78790       case 16: /* transtype ::= EXCLUSIVE */
78791       case 107: /* multiselect_op ::= UNION */
78792       case 109: /* multiselect_op ::= EXCEPT|INTERSECT */
78793 {yygotominor.yy46 = yymsp[0].major;}
78794         break;
78795       case 17: /* cmd ::= COMMIT trans_opt */
78796       case 18: /* cmd ::= END trans_opt */
78797 {sqlite3CommitTransaction(pParse);}
78798         break;
78799       case 19: /* cmd ::= ROLLBACK trans_opt */
78800 {sqlite3RollbackTransaction(pParse);}
78801         break;
78802       case 21: /* create_table ::= CREATE temp TABLE ifnotexists nm dbnm */
78803 {
78804    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy46,0,0,yymsp[-2].minor.yy46);
78805 }
78806         break;
78807       case 22: /* ifnotexists ::= */
78808       case 25: /* temp ::= */
78809       case 63: /* autoinc ::= */
78810       case 77: /* init_deferred_pred_opt ::= */
78811       case 79: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
78812       case 90: /* defer_subclause_opt ::= */
78813       case 101: /* ifexists ::= */
78814       case 112: /* distinct ::= ALL */
78815       case 113: /* distinct ::= */
78816       case 213: /* between_op ::= BETWEEN */
78817       case 216: /* in_op ::= IN */
78818 {yygotominor.yy46 = 0;}
78819         break;
78820       case 23: /* ifnotexists ::= IF NOT EXISTS */
78821       case 24: /* temp ::= TEMP */
78822       case 64: /* autoinc ::= AUTOINCR */
78823       case 78: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
78824       case 100: /* ifexists ::= IF EXISTS */
78825       case 111: /* distinct ::= DISTINCT */
78826       case 214: /* between_op ::= NOT BETWEEN */
78827       case 217: /* in_op ::= NOT IN */
78828 {yygotominor.yy46 = 1;}
78829         break;
78830       case 26: /* create_table_args ::= LP columnlist conslist_opt RP */
78831 {
78832   sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
78833 }
78834         break;
78835       case 27: /* create_table_args ::= AS select */
78836 {
78837   sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy219);
78838   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy219);
78839 }
78840         break;
78841       case 30: /* column ::= columnid type carglist */
78842 {
78843   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
78844   yygotominor.yy0.n = (pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
78845 }
78846         break;
78847       case 31: /* columnid ::= nm */
78848 {
78849   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
78850   yygotominor.yy0 = yymsp[0].minor.yy0;
78851 }
78852         break;
78853       case 32: /* id ::= ID */
78854       case 33: /* ids ::= ID|STRING */
78855       case 34: /* nm ::= ID */
78856       case 35: /* nm ::= STRING */
78857       case 36: /* nm ::= JOIN_KW */
78858       case 39: /* typetoken ::= typename */
78859       case 42: /* typename ::= ids */
78860       case 119: /* as ::= AS nm */
78861       case 120: /* as ::= ids */
78862       case 131: /* dbnm ::= DOT nm */
78863       case 241: /* idxitem ::= nm */
78864       case 243: /* collate ::= COLLATE ids */
78865       case 253: /* nmnum ::= plus_num */
78866       case 254: /* nmnum ::= nm */
78867       case 255: /* plus_num ::= plus_opt number */
78868       case 256: /* minus_num ::= MINUS number */
78869       case 257: /* number ::= INTEGER|FLOAT */
78870 {yygotominor.yy0 = yymsp[0].minor.yy0;}
78871         break;
78872       case 38: /* type ::= typetoken */
78873 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
78874         break;
78875       case 40: /* typetoken ::= typename LP signed RP */
78876 {
78877   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
78878   yygotominor.yy0.n = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z;
78879 }
78880         break;
78881       case 41: /* typetoken ::= typename LP signed COMMA signed RP */
78882 {
78883   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
78884   yygotominor.yy0.n = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z;
78885 }
78886         break;
78887       case 43: /* typename ::= typename ids */
78888 {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);}
78889         break;
78890       case 50: /* ccons ::= DEFAULT term */
78891       case 52: /* ccons ::= DEFAULT PLUS term */
78892 {sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy172);}
78893         break;
78894       case 51: /* ccons ::= DEFAULT LP expr RP */
78895 {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy172);}
78896         break;
78897       case 53: /* ccons ::= DEFAULT MINUS term */
78898 {
78899   Expr *p = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy172, 0, 0);
78900   sqlite3AddDefaultValue(pParse,p);
78901 }
78902         break;
78903       case 54: /* ccons ::= DEFAULT id */
78904 {
78905   Expr *p = sqlite3PExpr(pParse, TK_STRING, 0, 0, &yymsp[0].minor.yy0);
78906   sqlite3AddDefaultValue(pParse,p);
78907 }
78908         break;
78909       case 56: /* ccons ::= NOT NULL onconf */
78910 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy46);}
78911         break;
78912       case 57: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
78913 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy46,yymsp[0].minor.yy46,yymsp[-2].minor.yy46);}
78914         break;
78915       case 58: /* ccons ::= UNIQUE onconf */
78916 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy46,0,0,0,0);}
78917         break;
78918       case 59: /* ccons ::= CHECK LP expr RP */
78919 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy172);}
78920         break;
78921       case 60: /* ccons ::= REFERENCES nm idxlist_opt refargs */
78922 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy174,yymsp[0].minor.yy46);}
78923         break;
78924       case 61: /* ccons ::= defer_subclause */
78925 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy46);}
78926         break;
78927       case 62: /* ccons ::= COLLATE ids */
78928 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
78929         break;
78930       case 65: /* refargs ::= */
78931 { yygotominor.yy46 = OE_Restrict * 0x010101; }
78932         break;
78933       case 66: /* refargs ::= refargs refarg */
78934 { yygotominor.yy46 = (yymsp[-1].minor.yy46 & yymsp[0].minor.yy405.mask) | yymsp[0].minor.yy405.value; }
78935         break;
78936       case 67: /* refarg ::= MATCH nm */
78937 { yygotominor.yy405.value = 0;     yygotominor.yy405.mask = 0x000000; }
78938         break;
78939       case 68: /* refarg ::= ON DELETE refact */
78940 { yygotominor.yy405.value = yymsp[0].minor.yy46;     yygotominor.yy405.mask = 0x0000ff; }
78941         break;
78942       case 69: /* refarg ::= ON UPDATE refact */
78943 { yygotominor.yy405.value = yymsp[0].minor.yy46<<8;  yygotominor.yy405.mask = 0x00ff00; }
78944         break;
78945       case 70: /* refarg ::= ON INSERT refact */
78946 { yygotominor.yy405.value = yymsp[0].minor.yy46<<16; yygotominor.yy405.mask = 0xff0000; }
78947         break;
78948       case 71: /* refact ::= SET NULL */
78949 { yygotominor.yy46 = OE_SetNull; }
78950         break;
78951       case 72: /* refact ::= SET DEFAULT */
78952 { yygotominor.yy46 = OE_SetDflt; }
78953         break;
78954       case 73: /* refact ::= CASCADE */
78955 { yygotominor.yy46 = OE_Cascade; }
78956         break;
78957       case 74: /* refact ::= RESTRICT */
78958 { yygotominor.yy46 = OE_Restrict; }
78959         break;
78960       case 75: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
78961       case 76: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
78962       case 91: /* defer_subclause_opt ::= defer_subclause */
78963       case 93: /* onconf ::= ON CONFLICT resolvetype */
78964       case 95: /* orconf ::= OR resolvetype */
78965       case 96: /* resolvetype ::= raisetype */
78966       case 166: /* insert_cmd ::= INSERT orconf */
78967 {yygotominor.yy46 = yymsp[0].minor.yy46;}
78968         break;
78969       case 80: /* conslist_opt ::= */
78970 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
78971         break;
78972       case 81: /* conslist_opt ::= COMMA conslist */
78973 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
78974         break;
78975       case 86: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
78976 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy174,yymsp[0].minor.yy46,yymsp[-2].minor.yy46,0);}
78977         break;
78978       case 87: /* tcons ::= UNIQUE LP idxlist RP onconf */
78979 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy174,yymsp[0].minor.yy46,0,0,0,0);}
78980         break;
78981       case 88: /* tcons ::= CHECK LP expr RP onconf */
78982 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy172);}
78983         break;
78984       case 89: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
78985 {
78986     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy174, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy174, yymsp[-1].minor.yy46);
78987     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy46);
78988 }
78989         break;
78990       case 92: /* onconf ::= */
78991       case 94: /* orconf ::= */
78992 {yygotominor.yy46 = OE_Default;}
78993         break;
78994       case 97: /* resolvetype ::= IGNORE */
78995 {yygotominor.yy46 = OE_Ignore;}
78996         break;
78997       case 98: /* resolvetype ::= REPLACE */
78998       case 167: /* insert_cmd ::= REPLACE */
78999 {yygotominor.yy46 = OE_Replace;}
79000         break;
79001       case 99: /* cmd ::= DROP TABLE ifexists fullname */
79002 {
79003   sqlite3DropTable(pParse, yymsp[0].minor.yy373, 0, yymsp[-1].minor.yy46);
79004 }
79005         break;
79006       case 102: /* cmd ::= CREATE temp VIEW ifnotexists nm dbnm AS select */
79007 {
79008   sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy219, yymsp[-6].minor.yy46, yymsp[-4].minor.yy46);
79009 }
79010         break;
79011       case 103: /* cmd ::= DROP VIEW ifexists fullname */
79012 {
79013   sqlite3DropTable(pParse, yymsp[0].minor.yy373, 1, yymsp[-1].minor.yy46);
79014 }
79015         break;
79016       case 104: /* cmd ::= select */
79017 {
79018   SelectDest dest = {SRT_Callback, 0, 0, 0, 0};
79019   sqlite3Select(pParse, yymsp[0].minor.yy219, &dest, 0, 0, 0);
79020   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy219);
79021 }
79022         break;
79023       case 105: /* select ::= oneselect */
79024       case 128: /* seltablist_paren ::= select */
79025 {yygotominor.yy219 = yymsp[0].minor.yy219;}
79026         break;
79027       case 106: /* select ::= select multiselect_op oneselect */
79028 {
79029   if( yymsp[0].minor.yy219 ){
79030     yymsp[0].minor.yy219->op = yymsp[-1].minor.yy46;
79031     yymsp[0].minor.yy219->pPrior = yymsp[-2].minor.yy219;
79032   }else{
79033     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy219);
79034   }
79035   yygotominor.yy219 = yymsp[0].minor.yy219;
79036 }
79037         break;
79038       case 108: /* multiselect_op ::= UNION ALL */
79039 {yygotominor.yy46 = TK_ALL;}
79040         break;
79041       case 110: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
79042 {
79043   yygotominor.yy219 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy174,yymsp[-5].minor.yy373,yymsp[-4].minor.yy172,yymsp[-3].minor.yy174,yymsp[-2].minor.yy172,yymsp[-1].minor.yy174,yymsp[-7].minor.yy46,yymsp[0].minor.yy234.pLimit,yymsp[0].minor.yy234.pOffset);
79044 }
79045         break;
79046       case 114: /* sclp ::= selcollist COMMA */
79047       case 238: /* idxlist_opt ::= LP idxlist RP */
79048 {yygotominor.yy174 = yymsp[-1].minor.yy174;}
79049         break;
79050       case 115: /* sclp ::= */
79051       case 141: /* orderby_opt ::= */
79052       case 149: /* groupby_opt ::= */
79053       case 231: /* exprlist ::= */
79054       case 237: /* idxlist_opt ::= */
79055 {yygotominor.yy174 = 0;}
79056         break;
79057       case 116: /* selcollist ::= sclp expr as */
79058 {
79059    yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy174,yymsp[-1].minor.yy172,yymsp[0].minor.yy0.n?&yymsp[0].minor.yy0:0);
79060 }
79061         break;
79062       case 117: /* selcollist ::= sclp STAR */
79063 {
79064   Expr *p = sqlite3PExpr(pParse, TK_ALL, 0, 0, 0);
79065   yygotominor.yy174 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy174, p, 0);
79066 }
79067         break;
79068       case 118: /* selcollist ::= sclp nm DOT STAR */
79069 {
79070   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
79071   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
79072   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
79073   yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy174, pDot, 0);
79074 }
79075         break;
79076       case 121: /* as ::= */
79077 {yygotominor.yy0.n = 0;}
79078         break;
79079       case 122: /* from ::= */
79080 {yygotominor.yy373 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy373));}
79081         break;
79082       case 123: /* from ::= FROM seltablist */
79083 {
79084   yygotominor.yy373 = yymsp[0].minor.yy373;
79085   sqlite3SrcListShiftJoinType(yygotominor.yy373);
79086 }
79087         break;
79088       case 124: /* stl_prefix ::= seltablist joinop */
79089 {
79090    yygotominor.yy373 = yymsp[-1].minor.yy373;
79091    if( yygotominor.yy373 && yygotominor.yy373->nSrc>0 ) yygotominor.yy373->a[yygotominor.yy373->nSrc-1].jointype = yymsp[0].minor.yy46;
79092 }
79093         break;
79094       case 125: /* stl_prefix ::= */
79095 {yygotominor.yy373 = 0;}
79096         break;
79097       case 126: /* seltablist ::= stl_prefix nm dbnm as on_opt using_opt */
79098 {
79099   yygotominor.yy373 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-5].minor.yy373,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy172,yymsp[0].minor.yy432);
79100 }
79101         break;
79102       case 127: /* seltablist ::= stl_prefix LP seltablist_paren RP as on_opt using_opt */
79103 {
79104     yygotominor.yy373 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy373,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy219,yymsp[-1].minor.yy172,yymsp[0].minor.yy432);
79105   }
79106         break;
79107       case 129: /* seltablist_paren ::= seltablist */
79108 {
79109      sqlite3SrcListShiftJoinType(yymsp[0].minor.yy373);
79110      yygotominor.yy219 = sqlite3SelectNew(pParse,0,yymsp[0].minor.yy373,0,0,0,0,0,0,0);
79111   }
79112         break;
79113       case 130: /* dbnm ::= */
79114 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
79115         break;
79116       case 132: /* fullname ::= nm dbnm */
79117 {yygotominor.yy373 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
79118         break;
79119       case 133: /* joinop ::= COMMA|JOIN */
79120 { yygotominor.yy46 = JT_INNER; }
79121         break;
79122       case 134: /* joinop ::= JOIN_KW JOIN */
79123 { yygotominor.yy46 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
79124         break;
79125       case 135: /* joinop ::= JOIN_KW nm JOIN */
79126 { yygotominor.yy46 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
79127         break;
79128       case 136: /* joinop ::= JOIN_KW nm nm JOIN */
79129 { yygotominor.yy46 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
79130         break;
79131       case 137: /* on_opt ::= ON expr */
79132       case 145: /* sortitem ::= expr */
79133       case 152: /* having_opt ::= HAVING expr */
79134       case 159: /* where_opt ::= WHERE expr */
79135       case 174: /* expr ::= term */
79136       case 202: /* escape ::= ESCAPE expr */
79137       case 226: /* case_else ::= ELSE expr */
79138       case 228: /* case_operand ::= expr */
79139 {yygotominor.yy172 = yymsp[0].minor.yy172;}
79140         break;
79141       case 138: /* on_opt ::= */
79142       case 151: /* having_opt ::= */
79143       case 158: /* where_opt ::= */
79144       case 203: /* escape ::= */
79145       case 227: /* case_else ::= */
79146       case 229: /* case_operand ::= */
79147 {yygotominor.yy172 = 0;}
79148         break;
79149       case 139: /* using_opt ::= USING LP inscollist RP */
79150       case 171: /* inscollist_opt ::= LP inscollist RP */
79151 {yygotominor.yy432 = yymsp[-1].minor.yy432;}
79152         break;
79153       case 140: /* using_opt ::= */
79154       case 170: /* inscollist_opt ::= */
79155 {yygotominor.yy432 = 0;}
79156         break;
79157       case 142: /* orderby_opt ::= ORDER BY sortlist */
79158       case 150: /* groupby_opt ::= GROUP BY nexprlist */
79159       case 230: /* exprlist ::= nexprlist */
79160 {yygotominor.yy174 = yymsp[0].minor.yy174;}
79161         break;
79162       case 143: /* sortlist ::= sortlist COMMA sortitem sortorder */
79163 {
79164   yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy174,yymsp[-1].minor.yy172,0);
79165   if( yygotominor.yy174 ) yygotominor.yy174->a[yygotominor.yy174->nExpr-1].sortOrder = yymsp[0].minor.yy46;
79166 }
79167         break;
79168       case 144: /* sortlist ::= sortitem sortorder */
79169 {
79170   yygotominor.yy174 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy172,0);
79171   if( yygotominor.yy174 && yygotominor.yy174->a ) yygotominor.yy174->a[0].sortOrder = yymsp[0].minor.yy46;
79172 }
79173         break;
79174       case 146: /* sortorder ::= ASC */
79175       case 148: /* sortorder ::= */
79176 {yygotominor.yy46 = SQLITE_SO_ASC;}
79177         break;
79178       case 147: /* sortorder ::= DESC */
79179 {yygotominor.yy46 = SQLITE_SO_DESC;}
79180         break;
79181       case 153: /* limit_opt ::= */
79182 {yygotominor.yy234.pLimit = 0; yygotominor.yy234.pOffset = 0;}
79183         break;
79184       case 154: /* limit_opt ::= LIMIT expr */
79185 {yygotominor.yy234.pLimit = yymsp[0].minor.yy172; yygotominor.yy234.pOffset = 0;}
79186         break;
79187       case 155: /* limit_opt ::= LIMIT expr OFFSET expr */
79188 {yygotominor.yy234.pLimit = yymsp[-2].minor.yy172; yygotominor.yy234.pOffset = yymsp[0].minor.yy172;}
79189         break;
79190       case 156: /* limit_opt ::= LIMIT expr COMMA expr */
79191 {yygotominor.yy234.pOffset = yymsp[-2].minor.yy172; yygotominor.yy234.pLimit = yymsp[0].minor.yy172;}
79192         break;
79193       case 157: /* cmd ::= DELETE FROM fullname where_opt */
79194 {sqlite3DeleteFrom(pParse,yymsp[-1].minor.yy373,yymsp[0].minor.yy172);}
79195         break;
79196       case 160: /* cmd ::= UPDATE orconf fullname SET setlist where_opt */
79197 {
79198   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy174,"set list"); 
79199   sqlite3Update(pParse,yymsp[-3].minor.yy373,yymsp[-1].minor.yy174,yymsp[0].minor.yy172,yymsp[-4].minor.yy46);
79200 }
79201         break;
79202       case 161: /* setlist ::= setlist COMMA nm EQ expr */
79203 {yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy174,yymsp[0].minor.yy172,&yymsp[-2].minor.yy0);}
79204         break;
79205       case 162: /* setlist ::= nm EQ expr */
79206 {yygotominor.yy174 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy172,&yymsp[-2].minor.yy0);}
79207         break;
79208       case 163: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
79209 {sqlite3Insert(pParse, yymsp[-5].minor.yy373, yymsp[-1].minor.yy174, 0, yymsp[-4].minor.yy432, yymsp[-7].minor.yy46);}
79210         break;
79211       case 164: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
79212 {sqlite3Insert(pParse, yymsp[-2].minor.yy373, 0, yymsp[0].minor.yy219, yymsp[-1].minor.yy432, yymsp[-4].minor.yy46);}
79213         break;
79214       case 165: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
79215 {sqlite3Insert(pParse, yymsp[-3].minor.yy373, 0, 0, yymsp[-2].minor.yy432, yymsp[-5].minor.yy46);}
79216         break;
79217       case 168: /* itemlist ::= itemlist COMMA expr */
79218       case 232: /* nexprlist ::= nexprlist COMMA expr */
79219 {yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy174,yymsp[0].minor.yy172,0);}
79220         break;
79221       case 169: /* itemlist ::= expr */
79222       case 233: /* nexprlist ::= expr */
79223 {yygotominor.yy174 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy172,0);}
79224         break;
79225       case 172: /* inscollist ::= inscollist COMMA nm */
79226 {yygotominor.yy432 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy432,&yymsp[0].minor.yy0);}
79227         break;
79228       case 173: /* inscollist ::= nm */
79229 {yygotominor.yy432 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
79230         break;
79231       case 175: /* expr ::= LP expr RP */
79232 {yygotominor.yy172 = yymsp[-1].minor.yy172; sqlite3ExprSpan(yygotominor.yy172,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); }
79233         break;
79234       case 176: /* term ::= NULL */
79235       case 181: /* term ::= INTEGER|FLOAT|BLOB */
79236       case 182: /* term ::= STRING */
79237 {yygotominor.yy172 = sqlite3PExpr(pParse, yymsp[0].major, 0, 0, &yymsp[0].minor.yy0);}
79238         break;
79239       case 177: /* expr ::= ID */
79240       case 178: /* expr ::= JOIN_KW */
79241 {yygotominor.yy172 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);}
79242         break;
79243       case 179: /* expr ::= nm DOT nm */
79244 {
79245   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
79246   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
79247   yygotominor.yy172 = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
79248 }
79249         break;
79250       case 180: /* expr ::= nm DOT nm DOT nm */
79251 {
79252   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
79253   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
79254   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
79255   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
79256   yygotominor.yy172 = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
79257 }
79258         break;
79259       case 183: /* expr ::= REGISTER */
79260 {yygotominor.yy172 = sqlite3RegisterExpr(pParse, &yymsp[0].minor.yy0);}
79261         break;
79262       case 184: /* expr ::= VARIABLE */
79263 {
79264   Token *pToken = &yymsp[0].minor.yy0;
79265   Expr *pExpr = yygotominor.yy172 = sqlite3PExpr(pParse, TK_VARIABLE, 0, 0, pToken);
79266   sqlite3ExprAssignVarNumber(pParse, pExpr);
79267 }
79268         break;
79269       case 185: /* expr ::= expr COLLATE ids */
79270 {
79271   yygotominor.yy172 = sqlite3ExprSetColl(pParse, yymsp[-2].minor.yy172, &yymsp[0].minor.yy0);
79272 }
79273         break;
79274       case 186: /* expr ::= CAST LP expr AS typetoken RP */
79275 {
79276   yygotominor.yy172 = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy172, 0, &yymsp[-1].minor.yy0);
79277   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
79278 }
79279         break;
79280       case 187: /* expr ::= ID LP distinct exprlist RP */
79281 {
79282   if( yymsp[-1].minor.yy174 && yymsp[-1].minor.yy174->nExpr>SQLITE_MAX_FUNCTION_ARG ){
79283     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
79284   }
79285   yygotominor.yy172 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy174, &yymsp[-4].minor.yy0);
79286   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
79287   if( yymsp[-2].minor.yy46 && yygotominor.yy172 ){
79288     yygotominor.yy172->flags |= EP_Distinct;
79289   }
79290 }
79291         break;
79292       case 188: /* expr ::= ID LP STAR RP */
79293 {
79294   yygotominor.yy172 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
79295   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
79296 }
79297         break;
79298       case 189: /* term ::= CTIME_KW */
79299 {
79300   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
79301   ** treated as functions that return constants */
79302   yygotominor.yy172 = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
79303   if( yygotominor.yy172 ){
79304     yygotominor.yy172->op = TK_CONST_FUNC;  
79305     yygotominor.yy172->span = yymsp[0].minor.yy0;
79306   }
79307 }
79308         break;
79309       case 190: /* expr ::= expr AND expr */
79310       case 191: /* expr ::= expr OR expr */
79311       case 192: /* expr ::= expr LT|GT|GE|LE expr */
79312       case 193: /* expr ::= expr EQ|NE expr */
79313       case 194: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
79314       case 195: /* expr ::= expr PLUS|MINUS expr */
79315       case 196: /* expr ::= expr STAR|SLASH|REM expr */
79316       case 197: /* expr ::= expr CONCAT expr */
79317 {yygotominor.yy172 = sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy172,yymsp[0].minor.yy172,0);}
79318         break;
79319       case 198: /* likeop ::= LIKE_KW */
79320       case 200: /* likeop ::= MATCH */
79321 {yygotominor.yy72.eOperator = yymsp[0].minor.yy0; yygotominor.yy72.not = 0;}
79322         break;
79323       case 199: /* likeop ::= NOT LIKE_KW */
79324       case 201: /* likeop ::= NOT MATCH */
79325 {yygotominor.yy72.eOperator = yymsp[0].minor.yy0; yygotominor.yy72.not = 1;}
79326         break;
79327       case 204: /* expr ::= expr likeop expr escape */
79328 {
79329   ExprList *pList;
79330   pList = sqlite3ExprListAppend(pParse,0, yymsp[-1].minor.yy172, 0);
79331   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-3].minor.yy172, 0);
79332   if( yymsp[0].minor.yy172 ){
79333     pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy172, 0);
79334   }
79335   yygotominor.yy172 = sqlite3ExprFunction(pParse, pList, &yymsp[-2].minor.yy72.eOperator);
79336   if( yymsp[-2].minor.yy72.not ) yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy172, 0, 0);
79337   sqlite3ExprSpan(yygotominor.yy172, &yymsp[-3].minor.yy172->span, &yymsp[-1].minor.yy172->span);
79338   if( yygotominor.yy172 ) yygotominor.yy172->flags |= EP_InfixFunc;
79339 }
79340         break;
79341       case 205: /* expr ::= expr ISNULL|NOTNULL */
79342 {
79343   yygotominor.yy172 = sqlite3PExpr(pParse, yymsp[0].major, yymsp[-1].minor.yy172, 0, 0);
79344   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-1].minor.yy172->span,&yymsp[0].minor.yy0);
79345 }
79346         break;
79347       case 206: /* expr ::= expr IS NULL */
79348 {
79349   yygotominor.yy172 = sqlite3PExpr(pParse, TK_ISNULL, yymsp[-2].minor.yy172, 0, 0);
79350   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-2].minor.yy172->span,&yymsp[0].minor.yy0);
79351 }
79352         break;
79353       case 207: /* expr ::= expr NOT NULL */
79354 {
79355   yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOTNULL, yymsp[-2].minor.yy172, 0, 0);
79356   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-2].minor.yy172->span,&yymsp[0].minor.yy0);
79357 }
79358         break;
79359       case 208: /* expr ::= expr IS NOT NULL */
79360 {
79361   yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOTNULL, yymsp[-3].minor.yy172, 0, 0);
79362   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-3].minor.yy172->span,&yymsp[0].minor.yy0);
79363 }
79364         break;
79365       case 209: /* expr ::= NOT expr */
79366       case 210: /* expr ::= BITNOT expr */
79367 {
79368   yygotominor.yy172 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy172, 0, 0);
79369   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy172->span);
79370 }
79371         break;
79372       case 211: /* expr ::= MINUS expr */
79373 {
79374   yygotominor.yy172 = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy172, 0, 0);
79375   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy172->span);
79376 }
79377         break;
79378       case 212: /* expr ::= PLUS expr */
79379 {
79380   yygotominor.yy172 = sqlite3PExpr(pParse, TK_UPLUS, yymsp[0].minor.yy172, 0, 0);
79381   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy172->span);
79382 }
79383         break;
79384       case 215: /* expr ::= expr between_op expr AND expr */
79385 {
79386   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy172, 0);
79387   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy172, 0);
79388   yygotominor.yy172 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy172, 0, 0);
79389   if( yygotominor.yy172 ){
79390     yygotominor.yy172->pList = pList;
79391   }else{
79392     sqlite3ExprListDelete(pParse->db, pList);
79393   } 
79394   if( yymsp[-3].minor.yy46 ) yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy172, 0, 0);
79395   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-4].minor.yy172->span,&yymsp[0].minor.yy172->span);
79396 }
79397         break;
79398       case 218: /* expr ::= expr in_op LP exprlist RP */
79399 {
79400     yygotominor.yy172 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy172, 0, 0);
79401     if( yygotominor.yy172 ){
79402       yygotominor.yy172->pList = yymsp[-1].minor.yy174;
79403       sqlite3ExprSetHeight(pParse, yygotominor.yy172);
79404     }else{
79405       sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy174);
79406     }
79407     if( yymsp[-3].minor.yy46 ) yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy172, 0, 0);
79408     sqlite3ExprSpan(yygotominor.yy172,&yymsp[-4].minor.yy172->span,&yymsp[0].minor.yy0);
79409   }
79410         break;
79411       case 219: /* expr ::= LP select RP */
79412 {
79413     yygotominor.yy172 = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
79414     if( yygotominor.yy172 ){
79415       yygotominor.yy172->pSelect = yymsp[-1].minor.yy219;
79416       sqlite3ExprSetHeight(pParse, yygotominor.yy172);
79417     }else{
79418       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy219);
79419     }
79420     sqlite3ExprSpan(yygotominor.yy172,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
79421   }
79422         break;
79423       case 220: /* expr ::= expr in_op LP select RP */
79424 {
79425     yygotominor.yy172 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy172, 0, 0);
79426     if( yygotominor.yy172 ){
79427       yygotominor.yy172->pSelect = yymsp[-1].minor.yy219;
79428       sqlite3ExprSetHeight(pParse, yygotominor.yy172);
79429     }else{
79430       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy219);
79431     }
79432     if( yymsp[-3].minor.yy46 ) yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy172, 0, 0);
79433     sqlite3ExprSpan(yygotominor.yy172,&yymsp[-4].minor.yy172->span,&yymsp[0].minor.yy0);
79434   }
79435         break;
79436       case 221: /* expr ::= expr in_op nm dbnm */
79437 {
79438     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
79439     yygotominor.yy172 = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy172, 0, 0);
79440     if( yygotominor.yy172 ){
79441       yygotominor.yy172->pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
79442       sqlite3ExprSetHeight(pParse, yygotominor.yy172);
79443     }else{
79444       sqlite3SrcListDelete(pParse->db, pSrc);
79445     }
79446     if( yymsp[-2].minor.yy46 ) yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy172, 0, 0);
79447     sqlite3ExprSpan(yygotominor.yy172,&yymsp[-3].minor.yy172->span,yymsp[0].minor.yy0.z?&yymsp[0].minor.yy0:&yymsp[-1].minor.yy0);
79448   }
79449         break;
79450       case 222: /* expr ::= EXISTS LP select RP */
79451 {
79452     Expr *p = yygotominor.yy172 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
79453     if( p ){
79454       p->pSelect = yymsp[-1].minor.yy219;
79455       sqlite3ExprSpan(p,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
79456       sqlite3ExprSetHeight(pParse, yygotominor.yy172);
79457     }else{
79458       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy219);
79459     }
79460   }
79461         break;
79462       case 223: /* expr ::= CASE case_operand case_exprlist case_else END */
79463 {
79464   yygotominor.yy172 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy172, yymsp[-1].minor.yy172, 0);
79465   if( yygotominor.yy172 ){
79466     yygotominor.yy172->pList = yymsp[-2].minor.yy174;
79467     sqlite3ExprSetHeight(pParse, yygotominor.yy172);
79468   }else{
79469     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy174);
79470   }
79471   sqlite3ExprSpan(yygotominor.yy172, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0);
79472 }
79473         break;
79474       case 224: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
79475 {
79476   yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy174, yymsp[-2].minor.yy172, 0);
79477   yygotominor.yy174 = sqlite3ExprListAppend(pParse,yygotominor.yy174, yymsp[0].minor.yy172, 0);
79478 }
79479         break;
79480       case 225: /* case_exprlist ::= WHEN expr THEN expr */
79481 {
79482   yygotominor.yy174 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy172, 0);
79483   yygotominor.yy174 = sqlite3ExprListAppend(pParse,yygotominor.yy174, yymsp[0].minor.yy172, 0);
79484 }
79485         break;
79486       case 234: /* cmd ::= CREATE uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
79487 {
79488   sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0, 
79489                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy174, yymsp[-9].minor.yy46,
79490                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy46);
79491 }
79492         break;
79493       case 235: /* uniqueflag ::= UNIQUE */
79494       case 283: /* raisetype ::= ABORT */
79495 {yygotominor.yy46 = OE_Abort;}
79496         break;
79497       case 236: /* uniqueflag ::= */
79498 {yygotominor.yy46 = OE_None;}
79499         break;
79500       case 239: /* idxlist ::= idxlist COMMA idxitem collate sortorder */
79501 {
79502   Expr *p = 0;
79503   if( yymsp[-1].minor.yy0.n>0 ){
79504     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
79505     sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
79506   }
79507   yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy174, p, &yymsp[-2].minor.yy0);
79508   sqlite3ExprListCheckLength(pParse, yygotominor.yy174, "index");
79509   if( yygotominor.yy174 ) yygotominor.yy174->a[yygotominor.yy174->nExpr-1].sortOrder = yymsp[0].minor.yy46;
79510 }
79511         break;
79512       case 240: /* idxlist ::= idxitem collate sortorder */
79513 {
79514   Expr *p = 0;
79515   if( yymsp[-1].minor.yy0.n>0 ){
79516     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
79517     sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
79518   }
79519   yygotominor.yy174 = sqlite3ExprListAppend(pParse,0, p, &yymsp[-2].minor.yy0);
79520   sqlite3ExprListCheckLength(pParse, yygotominor.yy174, "index");
79521   if( yygotominor.yy174 ) yygotominor.yy174->a[yygotominor.yy174->nExpr-1].sortOrder = yymsp[0].minor.yy46;
79522 }
79523         break;
79524       case 242: /* collate ::= */
79525 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
79526         break;
79527       case 244: /* cmd ::= DROP INDEX ifexists fullname */
79528 {sqlite3DropIndex(pParse, yymsp[0].minor.yy373, yymsp[-1].minor.yy46);}
79529         break;
79530       case 245: /* cmd ::= VACUUM */
79531       case 246: /* cmd ::= VACUUM nm */
79532 {sqlite3Vacuum(pParse);}
79533         break;
79534       case 247: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
79535       case 248: /* cmd ::= PRAGMA nm dbnm EQ ON */
79536       case 249: /* cmd ::= PRAGMA nm dbnm EQ DELETE */
79537 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
79538         break;
79539       case 250: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
79540 {
79541   sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);
79542 }
79543         break;
79544       case 251: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
79545 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
79546         break;
79547       case 252: /* cmd ::= PRAGMA nm dbnm */
79548 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
79549         break;
79550       case 260: /* cmd ::= CREATE trigger_decl BEGIN trigger_cmd_list END */
79551 {
79552   Token all;
79553   all.z = yymsp[-3].minor.yy0.z;
79554   all.n = (yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
79555   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy243, &all);
79556 }
79557         break;
79558       case 261: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
79559 {
79560   sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy46, yymsp[-4].minor.yy370.a, yymsp[-4].minor.yy370.b, yymsp[-2].minor.yy373, yymsp[0].minor.yy172, yymsp[-10].minor.yy46, yymsp[-8].minor.yy46);
79561   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
79562 }
79563         break;
79564       case 262: /* trigger_time ::= BEFORE */
79565       case 265: /* trigger_time ::= */
79566 { yygotominor.yy46 = TK_BEFORE; }
79567         break;
79568       case 263: /* trigger_time ::= AFTER */
79569 { yygotominor.yy46 = TK_AFTER;  }
79570         break;
79571       case 264: /* trigger_time ::= INSTEAD OF */
79572 { yygotominor.yy46 = TK_INSTEAD;}
79573         break;
79574       case 266: /* trigger_event ::= DELETE|INSERT */
79575       case 267: /* trigger_event ::= UPDATE */
79576 {yygotominor.yy370.a = yymsp[0].major; yygotominor.yy370.b = 0;}
79577         break;
79578       case 268: /* trigger_event ::= UPDATE OF inscollist */
79579 {yygotominor.yy370.a = TK_UPDATE; yygotominor.yy370.b = yymsp[0].minor.yy432;}
79580         break;
79581       case 271: /* when_clause ::= */
79582       case 288: /* key_opt ::= */
79583 { yygotominor.yy172 = 0; }
79584         break;
79585       case 272: /* when_clause ::= WHEN expr */
79586       case 289: /* key_opt ::= KEY expr */
79587 { yygotominor.yy172 = yymsp[0].minor.yy172; }
79588         break;
79589       case 273: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
79590 {
79591   if( yymsp[-2].minor.yy243 ){
79592     yymsp[-2].minor.yy243->pLast->pNext = yymsp[-1].minor.yy243;
79593   }else{
79594     yymsp[-2].minor.yy243 = yymsp[-1].minor.yy243;
79595   }
79596   yymsp[-2].minor.yy243->pLast = yymsp[-1].minor.yy243;
79597   yygotominor.yy243 = yymsp[-2].minor.yy243;
79598 }
79599         break;
79600       case 274: /* trigger_cmd_list ::= */
79601 { yygotominor.yy243 = 0; }
79602         break;
79603       case 275: /* trigger_cmd ::= UPDATE orconf nm SET setlist where_opt */
79604 { yygotominor.yy243 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy174, yymsp[0].minor.yy172, yymsp[-4].minor.yy46); }
79605         break;
79606       case 276: /* trigger_cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP */
79607 {yygotominor.yy243 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy432, yymsp[-1].minor.yy174, 0, yymsp[-7].minor.yy46);}
79608         break;
79609       case 277: /* trigger_cmd ::= insert_cmd INTO nm inscollist_opt select */
79610 {yygotominor.yy243 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy432, 0, yymsp[0].minor.yy219, yymsp[-4].minor.yy46);}
79611         break;
79612       case 278: /* trigger_cmd ::= DELETE FROM nm where_opt */
79613 {yygotominor.yy243 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-1].minor.yy0, yymsp[0].minor.yy172);}
79614         break;
79615       case 279: /* trigger_cmd ::= select */
79616 {yygotominor.yy243 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy219); }
79617         break;
79618       case 280: /* expr ::= RAISE LP IGNORE RP */
79619 {
79620   yygotominor.yy172 = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); 
79621   if( yygotominor.yy172 ){
79622     yygotominor.yy172->iColumn = OE_Ignore;
79623     sqlite3ExprSpan(yygotominor.yy172, &yymsp[-3].minor.yy0, &yymsp[0].minor.yy0);
79624   }
79625 }
79626         break;
79627       case 281: /* expr ::= RAISE LP raisetype COMMA nm RP */
79628 {
79629   yygotominor.yy172 = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); 
79630   if( yygotominor.yy172 ) {
79631     yygotominor.yy172->iColumn = yymsp[-3].minor.yy46;
79632     sqlite3ExprSpan(yygotominor.yy172, &yymsp[-5].minor.yy0, &yymsp[0].minor.yy0);
79633   }
79634 }
79635         break;
79636       case 282: /* raisetype ::= ROLLBACK */
79637 {yygotominor.yy46 = OE_Rollback;}
79638         break;
79639       case 284: /* raisetype ::= FAIL */
79640 {yygotominor.yy46 = OE_Fail;}
79641         break;
79642       case 285: /* cmd ::= DROP TRIGGER ifexists fullname */
79643 {
79644   sqlite3DropTrigger(pParse,yymsp[0].minor.yy373,yymsp[-1].minor.yy46);
79645 }
79646         break;
79647       case 286: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
79648 {
79649   sqlite3Attach(pParse, yymsp[-3].minor.yy172, yymsp[-1].minor.yy172, yymsp[0].minor.yy172);
79650 }
79651         break;
79652       case 287: /* cmd ::= DETACH database_kw_opt expr */
79653 {
79654   sqlite3Detach(pParse, yymsp[0].minor.yy172);
79655 }
79656         break;
79657       case 292: /* cmd ::= REINDEX */
79658 {sqlite3Reindex(pParse, 0, 0);}
79659         break;
79660       case 293: /* cmd ::= REINDEX nm dbnm */
79661 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
79662         break;
79663       case 294: /* cmd ::= ANALYZE */
79664 {sqlite3Analyze(pParse, 0, 0);}
79665         break;
79666       case 295: /* cmd ::= ANALYZE nm dbnm */
79667 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
79668         break;
79669       case 296: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
79670 {
79671   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy373,&yymsp[0].minor.yy0);
79672 }
79673         break;
79674       case 297: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
79675 {
79676   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
79677 }
79678         break;
79679       case 298: /* add_column_fullname ::= fullname */
79680 {
79681   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy373);
79682 }
79683         break;
79684       case 301: /* cmd ::= create_vtab */
79685 {sqlite3VtabFinishParse(pParse,0);}
79686         break;
79687       case 302: /* cmd ::= create_vtab LP vtabarglist RP */
79688 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
79689         break;
79690       case 303: /* create_vtab ::= CREATE VIRTUAL TABLE nm dbnm USING nm */
79691 {
79692     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
79693 }
79694         break;
79695       case 306: /* vtabarg ::= */
79696 {sqlite3VtabArgInit(pParse);}
79697         break;
79698       case 308: /* vtabargtoken ::= ANY */
79699       case 309: /* vtabargtoken ::= lp anylist RP */
79700       case 310: /* lp ::= LP */
79701       case 312: /* anylist ::= anylist ANY */
79702 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
79703         break;
79704   };
79705   yygoto = yyRuleInfo[yyruleno].lhs;
79706   yysize = yyRuleInfo[yyruleno].nrhs;
79707   yypParser->yyidx -= yysize;
79708   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,yygoto);
79709   if( yyact < YYNSTATE ){
79710 #ifdef NDEBUG
79711     /* If we are not debugging and the reduce action popped at least
79712     ** one element off the stack, then we can push the new element back
79713     ** onto the stack here, and skip the stack overflow test in yy_shift().
79714     ** That gives a significant speed improvement. */
79715     if( yysize ){
79716       yypParser->yyidx++;
79717       yymsp -= yysize-1;
79718       yymsp->stateno = yyact;
79719       yymsp->major = yygoto;
79720       yymsp->minor = yygotominor;
79721     }else
79722 #endif
79723     {
79724       yy_shift(yypParser,yyact,yygoto,&yygotominor);
79725     }
79726   }else{
79727     assert( yyact == YYNSTATE + YYNRULE + 1 );
79728     yy_accept(yypParser);
79729   }
79730 }
79731
79732 /*
79733 ** The following code executes when the parse fails
79734 */
79735 static void yy_parse_failed(
79736   yyParser *yypParser           /* The parser */
79737 ){
79738   sqlite3ParserARG_FETCH;
79739 #ifndef NDEBUG
79740   if( yyTraceFILE ){
79741     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
79742   }
79743 #endif
79744   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
79745   /* Here code is inserted which will be executed whenever the
79746   ** parser fails */
79747   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
79748 }
79749
79750 /*
79751 ** The following code executes when a syntax error first occurs.
79752 */
79753 static void yy_syntax_error(
79754   yyParser *yypParser,           /* The parser */
79755   int yymajor,                   /* The major type of the error token */
79756   YYMINORTYPE yyminor            /* The minor type of the error token */
79757 ){
79758   sqlite3ParserARG_FETCH;
79759 #define TOKEN (yyminor.yy0)
79760
79761   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
79762   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
79763   pParse->parseError = 1;
79764   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
79765 }
79766
79767 /*
79768 ** The following is executed when the parser accepts
79769 */
79770 static void yy_accept(
79771   yyParser *yypParser           /* The parser */
79772 ){
79773   sqlite3ParserARG_FETCH;
79774 #ifndef NDEBUG
79775   if( yyTraceFILE ){
79776     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
79777   }
79778 #endif
79779   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
79780   /* Here code is inserted which will be executed whenever the
79781   ** parser accepts */
79782   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
79783 }
79784
79785 /* The main parser program.
79786 ** The first argument is a pointer to a structure obtained from
79787 ** "sqlite3ParserAlloc" which describes the current state of the parser.
79788 ** The second argument is the major token number.  The third is
79789 ** the minor token.  The fourth optional argument is whatever the
79790 ** user wants (and specified in the grammar) and is available for
79791 ** use by the action routines.
79792 **
79793 ** Inputs:
79794 ** <ul>
79795 ** <li> A pointer to the parser (an opaque structure.)
79796 ** <li> The major token number.
79797 ** <li> The minor token number.
79798 ** <li> An option argument of a grammar-specified type.
79799 ** </ul>
79800 **
79801 ** Outputs:
79802 ** None.
79803 */
79804 SQLITE_PRIVATE void sqlite3Parser(
79805   void *yyp,                   /* The parser */
79806   int yymajor,                 /* The major token code number */
79807   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
79808   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
79809 ){
79810   YYMINORTYPE yyminorunion;
79811   int yyact;            /* The parser action. */
79812   int yyendofinput;     /* True if we are at the end of input */
79813 #ifdef YYERRORSYMBOL
79814   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
79815 #endif
79816   yyParser *yypParser;  /* The parser */
79817
79818   /* (re)initialize the parser, if necessary */
79819   yypParser = (yyParser*)yyp;
79820   if( yypParser->yyidx<0 ){
79821 #if YYSTACKDEPTH<=0
79822     if( yypParser->yystksz <=0 ){
79823       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
79824       yyminorunion = yyzerominor;
79825       yyStackOverflow(yypParser, &yyminorunion);
79826       return;
79827     }
79828 #endif
79829     yypParser->yyidx = 0;
79830     yypParser->yyerrcnt = -1;
79831     yypParser->yystack[0].stateno = 0;
79832     yypParser->yystack[0].major = 0;
79833   }
79834   yyminorunion.yy0 = yyminor;
79835   yyendofinput = (yymajor==0);
79836   sqlite3ParserARG_STORE;
79837
79838 #ifndef NDEBUG
79839   if( yyTraceFILE ){
79840     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
79841   }
79842 #endif
79843
79844   do{
79845     yyact = yy_find_shift_action(yypParser,yymajor);
79846     if( yyact<YYNSTATE ){
79847       assert( !yyendofinput );  /* Impossible to shift the $ token */
79848       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
79849       yypParser->yyerrcnt--;
79850       yymajor = YYNOCODE;
79851     }else if( yyact < YYNSTATE + YYNRULE ){
79852       yy_reduce(yypParser,yyact-YYNSTATE);
79853     }else{
79854       assert( yyact == YY_ERROR_ACTION );
79855 #ifdef YYERRORSYMBOL
79856       int yymx;
79857 #endif
79858 #ifndef NDEBUG
79859       if( yyTraceFILE ){
79860         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
79861       }
79862 #endif
79863 #ifdef YYERRORSYMBOL
79864       /* A syntax error has occurred.
79865       ** The response to an error depends upon whether or not the
79866       ** grammar defines an error token "ERROR".  
79867       **
79868       ** This is what we do if the grammar does define ERROR:
79869       **
79870       **  * Call the %syntax_error function.
79871       **
79872       **  * Begin popping the stack until we enter a state where
79873       **    it is legal to shift the error symbol, then shift
79874       **    the error symbol.
79875       **
79876       **  * Set the error count to three.
79877       **
79878       **  * Begin accepting and shifting new tokens.  No new error
79879       **    processing will occur until three tokens have been
79880       **    shifted successfully.
79881       **
79882       */
79883       if( yypParser->yyerrcnt<0 ){
79884         yy_syntax_error(yypParser,yymajor,yyminorunion);
79885       }
79886       yymx = yypParser->yystack[yypParser->yyidx].major;
79887       if( yymx==YYERRORSYMBOL || yyerrorhit ){
79888 #ifndef NDEBUG
79889         if( yyTraceFILE ){
79890           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
79891              yyTracePrompt,yyTokenName[yymajor]);
79892         }
79893 #endif
79894         yy_destructor(yypParser, yymajor,&yyminorunion);
79895         yymajor = YYNOCODE;
79896       }else{
79897          while(
79898           yypParser->yyidx >= 0 &&
79899           yymx != YYERRORSYMBOL &&
79900           (yyact = yy_find_reduce_action(
79901                         yypParser->yystack[yypParser->yyidx].stateno,
79902                         YYERRORSYMBOL)) >= YYNSTATE
79903         ){
79904           yy_pop_parser_stack(yypParser);
79905         }
79906         if( yypParser->yyidx < 0 || yymajor==0 ){
79907           yy_destructor(yypParser,yymajor,&yyminorunion);
79908           yy_parse_failed(yypParser);
79909           yymajor = YYNOCODE;
79910         }else if( yymx!=YYERRORSYMBOL ){
79911           YYMINORTYPE u2;
79912           u2.YYERRSYMDT = 0;
79913           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
79914         }
79915       }
79916       yypParser->yyerrcnt = 3;
79917       yyerrorhit = 1;
79918 #else  /* YYERRORSYMBOL is not defined */
79919       /* This is what we do if the grammar does not define ERROR:
79920       **
79921       **  * Report an error message, and throw away the input token.
79922       **
79923       **  * If the input token is $, then fail the parse.
79924       **
79925       ** As before, subsequent error messages are suppressed until
79926       ** three input tokens have been successfully shifted.
79927       */
79928       if( yypParser->yyerrcnt<=0 ){
79929         yy_syntax_error(yypParser,yymajor,yyminorunion);
79930       }
79931       yypParser->yyerrcnt = 3;
79932       yy_destructor(yypParser,yymajor,&yyminorunion);
79933       if( yyendofinput ){
79934         yy_parse_failed(yypParser);
79935       }
79936       yymajor = YYNOCODE;
79937 #endif
79938     }
79939   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
79940   return;
79941 }
79942
79943 /************** End of parse.c ***********************************************/
79944 /************** Begin file tokenize.c ****************************************/
79945 /*
79946 ** 2001 September 15
79947 **
79948 ** The author disclaims copyright to this source code.  In place of
79949 ** a legal notice, here is a blessing:
79950 **
79951 **    May you do good and not evil.
79952 **    May you find forgiveness for yourself and forgive others.
79953 **    May you share freely, never taking more than you give.
79954 **
79955 *************************************************************************
79956 ** An tokenizer for SQL
79957 **
79958 ** This file contains C code that splits an SQL input string up into
79959 ** individual tokens and sends those tokens one-by-one over to the
79960 ** parser for analysis.
79961 **
79962 ** $Id: tokenize.c,v 1.148 2008/07/28 19:34:54 drh Exp $
79963 */
79964
79965 /*
79966 ** The charMap() macro maps alphabetic characters into their
79967 ** lower-case ASCII equivalent.  On ASCII machines, this is just
79968 ** an upper-to-lower case map.  On EBCDIC machines we also need
79969 ** to adjust the encoding.  Only alphabetic characters and underscores
79970 ** need to be translated.
79971 */
79972 #ifdef SQLITE_ASCII
79973 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
79974 #endif
79975 #ifdef SQLITE_EBCDIC
79976 # define charMap(X) ebcdicToAscii[(unsigned char)X]
79977 const unsigned char ebcdicToAscii[] = {
79978 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
79979    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
79980    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
79981    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
79982    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
79983    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
79984    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
79985    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
79986    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
79987    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
79988    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
79989    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
79990    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
79991    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
79992    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
79993    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
79994    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
79995 };
79996 #endif
79997
79998 /*
79999 ** The sqlite3KeywordCode function looks up an identifier to determine if
80000 ** it is a keyword.  If it is a keyword, the token code of that keyword is 
80001 ** returned.  If the input is not a keyword, TK_ID is returned.
80002 **
80003 ** The implementation of this routine was generated by a program,
80004 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
80005 ** The output of the mkkeywordhash.c program is written into a file
80006 ** named keywordhash.h and then included into this source file by
80007 ** the #include below.
80008 */
80009 /************** Include keywordhash.h in the middle of tokenize.c ************/
80010 /************** Begin file keywordhash.h *************************************/
80011 /***** This file contains automatically generated code ******
80012 **
80013 ** The code in this file has been automatically generated by
80014 **
80015 **     $Header: /sqlite/sqlite/tool/mkkeywordhash.c,v 1.31 2007/07/30 18:26:20 rse Exp $
80016 **
80017 ** The code in this file implements a function that determines whether
80018 ** or not a given identifier is really an SQL keyword.  The same thing
80019 ** might be implemented more directly using a hand-written hash table.
80020 ** But by using this automatically generated code, the size of the code
80021 ** is substantially reduced.  This is important for embedded applications
80022 ** on platforms with limited memory.
80023 */
80024 /* Hash score: 165 */
80025 static int keywordCode(const char *z, int n){
80026   /* zText[] encodes 775 bytes of keywords in 526 bytes */
80027   static const char zText[526] =
80028     "BEFOREIGNOREGEXPLAINSTEADDESCAPEACHECKEYCONSTRAINTERSECTABLEFT"
80029     "HENDATABASELECTRANSACTIONATURALTERAISELSEXCEPTRIGGEREFERENCES"
80030     "UNIQUERYATTACHAVINGROUPDATEMPORARYBEGINNEREINDEXCLUSIVEXISTSBETWEEN"
80031     "OTNULLIKECASCADEFERRABLECASECOLLATECREATECURRENT_DATEDELETEDETACH"
80032     "IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN"
80033     "WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICT"
80034     "CROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOB"
80035     "YIFINTOFFSETISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUM"
80036     "VIEWINITIALLY";
80037   static const unsigned char aHash[127] = {
80038       63,  92, 109,  61,   0,  38,   0,   0,  69,   0,  64,   0,   0,
80039      102,   4,  65,   7,   0, 108,  72, 103,  99,   0,  22,   0,   0,
80040      113,   0, 111, 106,   0,  18,  80,   0,   1,   0,   0,  56,  57,
80041        0,  55,  11,   0,  33,  77,  89,   0, 110,  88,   0,   0,  45,
80042        0,  90,  54,   0,  20,   0, 114,  34,  19,   0,  10,  97,  28,
80043       83,   0,   0, 116,  93,  47, 115,  41,  12,  44,   0,  78,   0,
80044       87,  29,   0,  86,   0,   0,   0,  82,  79,  84,  75,  96,   6,
80045       14,  95,   0,  68,   0,  21,  76,  98,  27,   0, 112,  67, 104,
80046       49,  40,  71,   0,   0,  81, 100,   0, 107,   0,  15,   0,   0,
80047       24,   0,  73,  42,  50,   0,  16,  48,   0,  37,
80048   };
80049   static const unsigned char aNext[116] = {
80050        0,   0,   0,   0,   0,   0,   0,   0,   0,   9,   0,   0,   0,
80051        0,   0,   0,   0,   5,   0,   0,   0,   0,   0,   0,   0,   0,
80052        0,   0,   0,   0,   0,   0,   0,   0,   0,   0,  32,   0,   0,
80053       17,   0,   0,   0,  36,  39,   0,   0,  25,   0,   0,  31,   0,
80054        0,   0,  43,  52,   0,   0,   0,  53,   0,   0,   0,   0,   0,
80055        0,   0,   0,   0,  51,   0,   0,   0,   0,  26,   0,   8,  46,
80056        2,   0,   0,   0,   0,   0,   0,   0,   3,  58,  66,   0,  13,
80057        0,  91,  85,   0,  94,   0,  74,   0,   0,  62,   0,  35, 101,
80058        0,   0, 105,  23,  30,  60,  70,   0,   0,  59,   0,   0,
80059   };
80060   static const unsigned char aLen[116] = {
80061        6,   7,   3,   6,   6,   7,   7,   3,   4,   6,   4,   5,   3,
80062       10,   9,   5,   4,   4,   3,   8,   2,   6,  11,   2,   7,   5,
80063        5,   4,   6,   7,  10,   6,   5,   6,   6,   5,   6,   4,   9,
80064        2,   5,   5,   7,   5,   9,   6,   7,   7,   3,   4,   4,   7,
80065        3,  10,   4,   7,   6,  12,   6,   6,   9,   4,   6,   5,   4,
80066        7,   6,   5,   6,   7,   5,   4,   5,   6,   5,   7,   3,   7,
80067       13,   2,   2,   4,   6,   6,   8,   5,  17,  12,   7,   8,   8,
80068        2,   4,   4,   4,   4,   4,   2,   2,   4,   6,   2,   3,   6,
80069        5,   8,   5,   5,   8,   3,   5,   5,   6,   4,   9,   3,
80070   };
80071   static const unsigned short int aOffset[116] = {
80072        0,   2,   2,   6,  10,  13,  18,  23,  25,  26,  31,  33,  37,
80073       40,  47,  55,  58,  61,  63,  65,  70,  71,  76,  85,  86,  91,
80074       95,  99, 102, 107, 113, 123, 126, 131, 136, 141, 144, 148, 148,
80075      152, 157, 160, 164, 166, 169, 177, 183, 189, 189, 192, 195, 199,
80076      200, 204, 214, 218, 225, 231, 243, 249, 255, 264, 266, 272, 277,
80077      279, 286, 291, 296, 302, 308, 313, 317, 320, 326, 330, 337, 339,
80078      346, 348, 350, 359, 363, 369, 375, 383, 388, 388, 404, 411, 418,
80079      419, 426, 430, 434, 438, 442, 445, 447, 449, 452, 452, 455, 458,
80080      464, 468, 476, 480, 485, 493, 496, 501, 506, 512, 516, 521,
80081   };
80082   static const unsigned char aCode[116] = {
80083     TK_BEFORE,     TK_FOREIGN,    TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    
80084     TK_EXPLAIN,    TK_INSTEAD,    TK_ADD,        TK_DESC,       TK_ESCAPE,     
80085     TK_EACH,       TK_CHECK,      TK_KEY,        TK_CONSTRAINT, TK_INTERSECT,  
80086     TK_TABLE,      TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DATABASE,   
80087     TK_AS,         TK_SELECT,     TK_TRANSACTION,TK_ON,         TK_JOIN_KW,    
80088     TK_ALTER,      TK_RAISE,      TK_ELSE,       TK_EXCEPT,     TK_TRIGGER,    
80089     TK_REFERENCES, TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,     
80090     TK_GROUP,      TK_UPDATE,     TK_TEMP,       TK_TEMP,       TK_OR,         
80091     TK_BEGIN,      TK_JOIN_KW,    TK_REINDEX,    TK_INDEX,      TK_EXCLUSIVE,  
80092     TK_EXISTS,     TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NULL,       
80093     TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DEFERRABLE, TK_CASE,       
80094     TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DELETE,     TK_DETACH,     
80095     TK_IMMEDIATE,  TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       
80096     TK_ANALYZE,    TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    
80097     TK_LIMIT,      TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      
80098     TK_REPLACE,    TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         
80099     TK_IN,         TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   
80100     TK_JOIN_KW,    TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   
80101     TK_DISTINCT,   TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       
80102     TK_JOIN_KW,    TK_LIKE_KW,    TK_BY,         TK_IF,         TK_INTO,       
80103     TK_OFFSET,     TK_OF,         TK_SET,        TK_ISNULL,     TK_ORDER,      
80104     TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        
80105     TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  
80106     TK_ALL,        
80107   };
80108   int h, i;
80109   if( n<2 ) return TK_ID;
80110   h = ((charMap(z[0])*4) ^
80111       (charMap(z[n-1])*3) ^
80112       n) % 127;
80113   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
80114     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
80115       return aCode[i];
80116     }
80117   }
80118   return TK_ID;
80119 }
80120 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
80121   return keywordCode((char*)z, n);
80122 }
80123
80124 /************** End of keywordhash.h *****************************************/
80125 /************** Continuing where we left off in tokenize.c *******************/
80126
80127
80128 /*
80129 ** If X is a character that can be used in an identifier then
80130 ** IdChar(X) will be true.  Otherwise it is false.
80131 **
80132 ** For ASCII, any character with the high-order bit set is
80133 ** allowed in an identifier.  For 7-bit characters, 
80134 ** sqlite3IsIdChar[X] must be 1.
80135 **
80136 ** For EBCDIC, the rules are more complex but have the same
80137 ** end result.
80138 **
80139 ** Ticket #1066.  the SQL standard does not allow '$' in the
80140 ** middle of identfiers.  But many SQL implementations do. 
80141 ** SQLite will allow '$' in identifiers for compatibility.
80142 ** But the feature is undocumented.
80143 */
80144 #ifdef SQLITE_ASCII
80145 SQLITE_PRIVATE const char sqlite3IsAsciiIdChar[] = {
80146 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
80147     0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
80148     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
80149     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
80150     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
80151     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
80152     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
80153 };
80154 #define IdChar(C)  (((c=C)&0x80)!=0 || (c>0x1f && sqlite3IsAsciiIdChar[c-0x20]))
80155 #endif
80156 #ifdef SQLITE_EBCDIC
80157 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
80158 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
80159     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
80160     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
80161     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
80162     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
80163     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
80164     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
80165     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
80166     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
80167     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
80168     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
80169     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
80170     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
80171 };
80172 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
80173 #endif
80174
80175
80176 /*
80177 ** Return the length of the token that begins at z[0]. 
80178 ** Store the token type in *tokenType before returning.
80179 */
80180 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
80181   int i, c;
80182   switch( *z ){
80183     case ' ': case '\t': case '\n': case '\f': case '\r': {
80184       for(i=1; isspace(z[i]); i++){}
80185       *tokenType = TK_SPACE;
80186       return i;
80187     }
80188     case '-': {
80189       if( z[1]=='-' ){
80190         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
80191         *tokenType = TK_COMMENT;
80192         return i;
80193       }
80194       *tokenType = TK_MINUS;
80195       return 1;
80196     }
80197     case '(': {
80198       *tokenType = TK_LP;
80199       return 1;
80200     }
80201     case ')': {
80202       *tokenType = TK_RP;
80203       return 1;
80204     }
80205     case ';': {
80206       *tokenType = TK_SEMI;
80207       return 1;
80208     }
80209     case '+': {
80210       *tokenType = TK_PLUS;
80211       return 1;
80212     }
80213     case '*': {
80214       *tokenType = TK_STAR;
80215       return 1;
80216     }
80217     case '/': {
80218       if( z[1]!='*' || z[2]==0 ){
80219         *tokenType = TK_SLASH;
80220         return 1;
80221       }
80222       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
80223       if( c ) i++;
80224       *tokenType = TK_COMMENT;
80225       return i;
80226     }
80227     case '%': {
80228       *tokenType = TK_REM;
80229       return 1;
80230     }
80231     case '=': {
80232       *tokenType = TK_EQ;
80233       return 1 + (z[1]=='=');
80234     }
80235     case '<': {
80236       if( (c=z[1])=='=' ){
80237         *tokenType = TK_LE;
80238         return 2;
80239       }else if( c=='>' ){
80240         *tokenType = TK_NE;
80241         return 2;
80242       }else if( c=='<' ){
80243         *tokenType = TK_LSHIFT;
80244         return 2;
80245       }else{
80246         *tokenType = TK_LT;
80247         return 1;
80248       }
80249     }
80250     case '>': {
80251       if( (c=z[1])=='=' ){
80252         *tokenType = TK_GE;
80253         return 2;
80254       }else if( c=='>' ){
80255         *tokenType = TK_RSHIFT;
80256         return 2;
80257       }else{
80258         *tokenType = TK_GT;
80259         return 1;
80260       }
80261     }
80262     case '!': {
80263       if( z[1]!='=' ){
80264         *tokenType = TK_ILLEGAL;
80265         return 2;
80266       }else{
80267         *tokenType = TK_NE;
80268         return 2;
80269       }
80270     }
80271     case '|': {
80272       if( z[1]!='|' ){
80273         *tokenType = TK_BITOR;
80274         return 1;
80275       }else{
80276         *tokenType = TK_CONCAT;
80277         return 2;
80278       }
80279     }
80280     case ',': {
80281       *tokenType = TK_COMMA;
80282       return 1;
80283     }
80284     case '&': {
80285       *tokenType = TK_BITAND;
80286       return 1;
80287     }
80288     case '~': {
80289       *tokenType = TK_BITNOT;
80290       return 1;
80291     }
80292     case '`':
80293     case '\'':
80294     case '"': {
80295       int delim = z[0];
80296       for(i=1; (c=z[i])!=0; i++){
80297         if( c==delim ){
80298           if( z[i+1]==delim ){
80299             i++;
80300           }else{
80301             break;
80302           }
80303         }
80304       }
80305       if( c ){
80306         *tokenType = TK_STRING;
80307         return i+1;
80308       }else{
80309         *tokenType = TK_ILLEGAL;
80310         return i;
80311       }
80312     }
80313     case '.': {
80314 #ifndef SQLITE_OMIT_FLOATING_POINT
80315       if( !isdigit(z[1]) )
80316 #endif
80317       {
80318         *tokenType = TK_DOT;
80319         return 1;
80320       }
80321       /* If the next character is a digit, this is a floating point
80322       ** number that begins with ".".  Fall thru into the next case */
80323     }
80324     case '0': case '1': case '2': case '3': case '4':
80325     case '5': case '6': case '7': case '8': case '9': {
80326       *tokenType = TK_INTEGER;
80327       for(i=0; isdigit(z[i]); i++){}
80328 #ifndef SQLITE_OMIT_FLOATING_POINT
80329       if( z[i]=='.' ){
80330         i++;
80331         while( isdigit(z[i]) ){ i++; }
80332         *tokenType = TK_FLOAT;
80333       }
80334       if( (z[i]=='e' || z[i]=='E') &&
80335            ( isdigit(z[i+1]) 
80336             || ((z[i+1]=='+' || z[i+1]=='-') && isdigit(z[i+2]))
80337            )
80338       ){
80339         i += 2;
80340         while( isdigit(z[i]) ){ i++; }
80341         *tokenType = TK_FLOAT;
80342       }
80343 #endif
80344       while( IdChar(z[i]) ){
80345         *tokenType = TK_ILLEGAL;
80346         i++;
80347       }
80348       return i;
80349     }
80350     case '[': {
80351       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
80352       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
80353       return i;
80354     }
80355     case '?': {
80356       *tokenType = TK_VARIABLE;
80357       for(i=1; isdigit(z[i]); i++){}
80358       return i;
80359     }
80360     case '#': {
80361       for(i=1; isdigit(z[i]); i++){}
80362       if( i>1 ){
80363         /* Parameters of the form #NNN (where NNN is a number) are used
80364         ** internally by sqlite3NestedParse.  */
80365         *tokenType = TK_REGISTER;
80366         return i;
80367       }
80368       /* Fall through into the next case if the '#' is not followed by
80369       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
80370     }
80371 #ifndef SQLITE_OMIT_TCL_VARIABLE
80372     case '$':
80373 #endif
80374     case '@':  /* For compatibility with MS SQL Server */
80375     case ':': {
80376       int n = 0;
80377       *tokenType = TK_VARIABLE;
80378       for(i=1; (c=z[i])!=0; i++){
80379         if( IdChar(c) ){
80380           n++;
80381 #ifndef SQLITE_OMIT_TCL_VARIABLE
80382         }else if( c=='(' && n>0 ){
80383           do{
80384             i++;
80385           }while( (c=z[i])!=0 && !isspace(c) && c!=')' );
80386           if( c==')' ){
80387             i++;
80388           }else{
80389             *tokenType = TK_ILLEGAL;
80390           }
80391           break;
80392         }else if( c==':' && z[i+1]==':' ){
80393           i++;
80394 #endif
80395         }else{
80396           break;
80397         }
80398       }
80399       if( n==0 ) *tokenType = TK_ILLEGAL;
80400       return i;
80401     }
80402 #ifndef SQLITE_OMIT_BLOB_LITERAL
80403     case 'x': case 'X': {
80404       if( z[1]=='\'' ){
80405         *tokenType = TK_BLOB;
80406         for(i=2; (c=z[i])!=0 && c!='\''; i++){
80407           if( !isxdigit(c) ){
80408             *tokenType = TK_ILLEGAL;
80409           }
80410         }
80411         if( i%2 || !c ) *tokenType = TK_ILLEGAL;
80412         if( c ) i++;
80413         return i;
80414       }
80415       /* Otherwise fall through to the next case */
80416     }
80417 #endif
80418     default: {
80419       if( !IdChar(*z) ){
80420         break;
80421       }
80422       for(i=1; IdChar(z[i]); i++){}
80423       *tokenType = keywordCode((char*)z, i);
80424       return i;
80425     }
80426   }
80427   *tokenType = TK_ILLEGAL;
80428   return 1;
80429 }
80430
80431 /*
80432 ** Run the parser on the given SQL string.  The parser structure is
80433 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
80434 ** then an and attempt is made to write an error message into 
80435 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
80436 ** error message.
80437 */
80438 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
80439   int nErr = 0;
80440   int i;
80441   void *pEngine;
80442   int tokenType;
80443   int lastTokenParsed = -1;
80444   sqlite3 *db = pParse->db;
80445   int mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
80446
80447   if( db->activeVdbeCnt==0 ){
80448     db->u1.isInterrupted = 0;
80449   }
80450   pParse->rc = SQLITE_OK;
80451   pParse->zTail = pParse->zSql = zSql;
80452   i = 0;
80453   assert( pzErrMsg!=0 );
80454   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
80455   if( pEngine==0 ){
80456     db->mallocFailed = 1;
80457     return SQLITE_NOMEM;
80458   }
80459   assert( pParse->sLastToken.dyn==0 );
80460   assert( pParse->pNewTable==0 );
80461   assert( pParse->pNewTrigger==0 );
80462   assert( pParse->nVar==0 );
80463   assert( pParse->nVarExpr==0 );
80464   assert( pParse->nVarExprAlloc==0 );
80465   assert( pParse->apVarExpr==0 );
80466   while( !db->mallocFailed && zSql[i]!=0 ){
80467     assert( i>=0 );
80468     pParse->sLastToken.z = (u8*)&zSql[i];
80469     assert( pParse->sLastToken.dyn==0 );
80470     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
80471     i += pParse->sLastToken.n;
80472     if( i>mxSqlLen ){
80473       pParse->rc = SQLITE_TOOBIG;
80474       break;
80475     }
80476     switch( tokenType ){
80477       case TK_SPACE:
80478       case TK_COMMENT: {
80479         if( db->u1.isInterrupted ){
80480           pParse->rc = SQLITE_INTERRUPT;
80481           sqlite3SetString(pzErrMsg, db, "interrupt");
80482           goto abort_parse;
80483         }
80484         break;
80485       }
80486       case TK_ILLEGAL: {
80487         sqlite3DbFree(db, *pzErrMsg);
80488         *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
80489                         &pParse->sLastToken);
80490         nErr++;
80491         goto abort_parse;
80492       }
80493       case TK_SEMI: {
80494         pParse->zTail = &zSql[i];
80495         /* Fall thru into the default case */
80496       }
80497       default: {
80498         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
80499         lastTokenParsed = tokenType;
80500         if( pParse->rc!=SQLITE_OK ){
80501           goto abort_parse;
80502         }
80503         break;
80504       }
80505     }
80506   }
80507 abort_parse:
80508   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
80509     if( lastTokenParsed!=TK_SEMI ){
80510       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
80511       pParse->zTail = &zSql[i];
80512     }
80513     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
80514   }
80515 #ifdef YYTRACKMAXSTACKDEPTH
80516   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
80517       sqlite3ParserStackPeak(pEngine)
80518   );
80519 #endif /* YYDEBUG */
80520   sqlite3ParserFree(pEngine, sqlite3_free);
80521   if( db->mallocFailed ){
80522     pParse->rc = SQLITE_NOMEM;
80523   }
80524   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
80525     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
80526   }
80527   if( pParse->zErrMsg ){
80528     if( *pzErrMsg==0 ){
80529       *pzErrMsg = pParse->zErrMsg;
80530     }else{
80531       sqlite3DbFree(db, pParse->zErrMsg);
80532     }
80533     pParse->zErrMsg = 0;
80534     nErr++;
80535   }
80536   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
80537     sqlite3VdbeDelete(pParse->pVdbe);
80538     pParse->pVdbe = 0;
80539   }
80540 #ifndef SQLITE_OMIT_SHARED_CACHE
80541   if( pParse->nested==0 ){
80542     sqlite3DbFree(db, pParse->aTableLock);
80543     pParse->aTableLock = 0;
80544     pParse->nTableLock = 0;
80545   }
80546 #endif
80547 #ifndef SQLITE_OMIT_VIRTUALTABLE
80548   sqlite3DbFree(db, pParse->apVtabLock);
80549 #endif
80550
80551   if( !IN_DECLARE_VTAB ){
80552     /* If the pParse->declareVtab flag is set, do not delete any table 
80553     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
80554     ** will take responsibility for freeing the Table structure.
80555     */
80556     sqlite3DeleteTable(pParse->pNewTable);
80557   }
80558
80559   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
80560   sqlite3DbFree(db, pParse->apVarExpr);
80561   if( nErr>0 && (pParse->rc==SQLITE_OK || pParse->rc==SQLITE_DONE) ){
80562     pParse->rc = SQLITE_ERROR;
80563   }
80564   return nErr;
80565 }
80566
80567 /************** End of tokenize.c ********************************************/
80568 /************** Begin file complete.c ****************************************/
80569 /*
80570 ** 2001 September 15
80571 **
80572 ** The author disclaims copyright to this source code.  In place of
80573 ** a legal notice, here is a blessing:
80574 **
80575 **    May you do good and not evil.
80576 **    May you find forgiveness for yourself and forgive others.
80577 **    May you share freely, never taking more than you give.
80578 **
80579 *************************************************************************
80580 ** An tokenizer for SQL
80581 **
80582 ** This file contains C code that implements the sqlite3_complete() API.
80583 ** This code used to be part of the tokenizer.c source file.  But by
80584 ** separating it out, the code will be automatically omitted from
80585 ** static links that do not use it.
80586 **
80587 ** $Id: complete.c,v 1.7 2008/06/13 18:24:27 drh Exp $
80588 */
80589 #ifndef SQLITE_OMIT_COMPLETE
80590
80591 /*
80592 ** This is defined in tokenize.c.  We just have to import the definition.
80593 */
80594 #ifndef SQLITE_AMALGAMATION
80595 #ifdef SQLITE_ASCII
80596 SQLITE_PRIVATE const char sqlite3IsAsciiIdChar[];
80597 #define IdChar(C)  (((c=C)&0x80)!=0 || (c>0x1f && sqlite3IsAsciiIdChar[c-0x20]))
80598 #endif
80599 #ifdef SQLITE_EBCDIC
80600 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
80601 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
80602 #endif
80603 #endif /* SQLITE_AMALGAMATION */
80604
80605
80606 /*
80607 ** Token types used by the sqlite3_complete() routine.  See the header
80608 ** comments on that procedure for additional information.
80609 */
80610 #define tkSEMI    0
80611 #define tkWS      1
80612 #define tkOTHER   2
80613 #define tkEXPLAIN 3
80614 #define tkCREATE  4
80615 #define tkTEMP    5
80616 #define tkTRIGGER 6
80617 #define tkEND     7
80618
80619 /*
80620 ** Return TRUE if the given SQL string ends in a semicolon.
80621 **
80622 ** Special handling is require for CREATE TRIGGER statements.
80623 ** Whenever the CREATE TRIGGER keywords are seen, the statement
80624 ** must end with ";END;".
80625 **
80626 ** This implementation uses a state machine with 7 states:
80627 **
80628 **   (0) START     At the beginning or end of an SQL statement.  This routine
80629 **                 returns 1 if it ends in the START state and 0 if it ends
80630 **                 in any other state.
80631 **
80632 **   (1) NORMAL    We are in the middle of statement which ends with a single
80633 **                 semicolon.
80634 **
80635 **   (2) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
80636 **                 a statement.
80637 **
80638 **   (3) CREATE    The keyword CREATE has been seen at the beginning of a
80639 **                 statement, possibly preceeded by EXPLAIN and/or followed by
80640 **                 TEMP or TEMPORARY
80641 **
80642 **   (4) TRIGGER   We are in the middle of a trigger definition that must be
80643 **                 ended by a semicolon, the keyword END, and another semicolon.
80644 **
80645 **   (5) SEMI      We've seen the first semicolon in the ";END;" that occurs at
80646 **                 the end of a trigger definition.
80647 **
80648 **   (6) END       We've seen the ";END" of the ";END;" that occurs at the end
80649 **                 of a trigger difinition.
80650 **
80651 ** Transitions between states above are determined by tokens extracted
80652 ** from the input.  The following tokens are significant:
80653 **
80654 **   (0) tkSEMI      A semicolon.
80655 **   (1) tkWS        Whitespace
80656 **   (2) tkOTHER     Any other SQL token.
80657 **   (3) tkEXPLAIN   The "explain" keyword.
80658 **   (4) tkCREATE    The "create" keyword.
80659 **   (5) tkTEMP      The "temp" or "temporary" keyword.
80660 **   (6) tkTRIGGER   The "trigger" keyword.
80661 **   (7) tkEND       The "end" keyword.
80662 **
80663 ** Whitespace never causes a state transition and is always ignored.
80664 **
80665 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
80666 ** to recognize the end of a trigger can be omitted.  All we have to do
80667 ** is look for a semicolon that is not part of an string or comment.
80668 */
80669 SQLITE_API int sqlite3_complete(const char *zSql){
80670   u8 state = 0;   /* Current state, using numbers defined in header comment */
80671   u8 token;       /* Value of the next token */
80672
80673 #ifndef SQLITE_OMIT_TRIGGER
80674   /* A complex statement machine used to detect the end of a CREATE TRIGGER
80675   ** statement.  This is the normal case.
80676   */
80677   static const u8 trans[7][8] = {
80678                      /* Token:                                                */
80679      /* State:       **  SEMI  WS  OTHER EXPLAIN  CREATE  TEMP  TRIGGER  END  */
80680      /* 0   START: */ {    0,  0,     1,      2,      3,    1,       1,   1,  },
80681      /* 1  NORMAL: */ {    0,  1,     1,      1,      1,    1,       1,   1,  },
80682      /* 2 EXPLAIN: */ {    0,  2,     1,      1,      3,    1,       1,   1,  },
80683      /* 3  CREATE: */ {    0,  3,     1,      1,      1,    3,       4,   1,  },
80684      /* 4 TRIGGER: */ {    5,  4,     4,      4,      4,    4,       4,   4,  },
80685      /* 5    SEMI: */ {    5,  5,     4,      4,      4,    4,       4,   6,  },
80686      /* 6     END: */ {    0,  6,     4,      4,      4,    4,       4,   4,  },
80687   };
80688 #else
80689   /* If triggers are not suppored by this compile then the statement machine
80690   ** used to detect the end of a statement is much simplier
80691   */
80692   static const u8 trans[2][3] = {
80693                      /* Token:           */
80694      /* State:       **  SEMI  WS  OTHER */
80695      /* 0   START: */ {    0,  0,     1, },
80696      /* 1  NORMAL: */ {    0,  1,     1, },
80697   };
80698 #endif /* SQLITE_OMIT_TRIGGER */
80699
80700   while( *zSql ){
80701     switch( *zSql ){
80702       case ';': {  /* A semicolon */
80703         token = tkSEMI;
80704         break;
80705       }
80706       case ' ':
80707       case '\r':
80708       case '\t':
80709       case '\n':
80710       case '\f': {  /* White space is ignored */
80711         token = tkWS;
80712         break;
80713       }
80714       case '/': {   /* C-style comments */
80715         if( zSql[1]!='*' ){
80716           token = tkOTHER;
80717           break;
80718         }
80719         zSql += 2;
80720         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
80721         if( zSql[0]==0 ) return 0;
80722         zSql++;
80723         token = tkWS;
80724         break;
80725       }
80726       case '-': {   /* SQL-style comments from "--" to end of line */
80727         if( zSql[1]!='-' ){
80728           token = tkOTHER;
80729           break;
80730         }
80731         while( *zSql && *zSql!='\n' ){ zSql++; }
80732         if( *zSql==0 ) return state==0;
80733         token = tkWS;
80734         break;
80735       }
80736       case '[': {   /* Microsoft-style identifiers in [...] */
80737         zSql++;
80738         while( *zSql && *zSql!=']' ){ zSql++; }
80739         if( *zSql==0 ) return 0;
80740         token = tkOTHER;
80741         break;
80742       }
80743       case '`':     /* Grave-accent quoted symbols used by MySQL */
80744       case '"':     /* single- and double-quoted strings */
80745       case '\'': {
80746         int c = *zSql;
80747         zSql++;
80748         while( *zSql && *zSql!=c ){ zSql++; }
80749         if( *zSql==0 ) return 0;
80750         token = tkOTHER;
80751         break;
80752       }
80753       default: {
80754         int c;
80755         if( IdChar((u8)*zSql) ){
80756           /* Keywords and unquoted identifiers */
80757           int nId;
80758           for(nId=1; IdChar(zSql[nId]); nId++){}
80759 #ifdef SQLITE_OMIT_TRIGGER
80760           token = tkOTHER;
80761 #else
80762           switch( *zSql ){
80763             case 'c': case 'C': {
80764               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
80765                 token = tkCREATE;
80766               }else{
80767                 token = tkOTHER;
80768               }
80769               break;
80770             }
80771             case 't': case 'T': {
80772               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
80773                 token = tkTRIGGER;
80774               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
80775                 token = tkTEMP;
80776               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
80777                 token = tkTEMP;
80778               }else{
80779                 token = tkOTHER;
80780               }
80781               break;
80782             }
80783             case 'e':  case 'E': {
80784               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
80785                 token = tkEND;
80786               }else
80787 #ifndef SQLITE_OMIT_EXPLAIN
80788               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
80789                 token = tkEXPLAIN;
80790               }else
80791 #endif
80792               {
80793                 token = tkOTHER;
80794               }
80795               break;
80796             }
80797             default: {
80798               token = tkOTHER;
80799               break;
80800             }
80801           }
80802 #endif /* SQLITE_OMIT_TRIGGER */
80803           zSql += nId-1;
80804         }else{
80805           /* Operators and special symbols */
80806           token = tkOTHER;
80807         }
80808         break;
80809       }
80810     }
80811     state = trans[state][token];
80812     zSql++;
80813   }
80814   return state==0;
80815 }
80816
80817 #ifndef SQLITE_OMIT_UTF16
80818 /*
80819 ** This routine is the same as the sqlite3_complete() routine described
80820 ** above, except that the parameter is required to be UTF-16 encoded, not
80821 ** UTF-8.
80822 */
80823 SQLITE_API int sqlite3_complete16(const void *zSql){
80824   sqlite3_value *pVal;
80825   char const *zSql8;
80826   int rc = SQLITE_NOMEM;
80827
80828 #ifndef SQLITE_OMIT_AUTOINIT
80829   rc = sqlite3_initialize();
80830   if( rc ) return rc;
80831 #endif
80832   pVal = sqlite3ValueNew(0);
80833   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
80834   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
80835   if( zSql8 ){
80836     rc = sqlite3_complete(zSql8);
80837   }else{
80838     rc = SQLITE_NOMEM;
80839   }
80840   sqlite3ValueFree(pVal);
80841   return sqlite3ApiExit(0, rc);
80842 }
80843 #endif /* SQLITE_OMIT_UTF16 */
80844 #endif /* SQLITE_OMIT_COMPLETE */
80845
80846 /************** End of complete.c ********************************************/
80847 /************** Begin file main.c ********************************************/
80848 /*
80849 ** 2001 September 15
80850 **
80851 ** The author disclaims copyright to this source code.  In place of
80852 ** a legal notice, here is a blessing:
80853 **
80854 **    May you do good and not evil.
80855 **    May you find forgiveness for yourself and forgive others.
80856 **    May you share freely, never taking more than you give.
80857 **
80858 *************************************************************************
80859 ** Main file for the SQLite library.  The routines in this file
80860 ** implement the programmer interface to the library.  Routines in
80861 ** other files are for internal use by SQLite and should not be
80862 ** accessed by users of the library.
80863 **
80864 ** $Id: main.c,v 1.486 2008/08/04 20:13:27 drh Exp $
80865 */
80866
80867 #ifdef SQLITE_ENABLE_FTS3
80868 /************** Include fts3.h in the middle of main.c ***********************/
80869 /************** Begin file fts3.h ********************************************/
80870 /*
80871 ** 2006 Oct 10
80872 **
80873 ** The author disclaims copyright to this source code.  In place of
80874 ** a legal notice, here is a blessing:
80875 **
80876 **    May you do good and not evil.
80877 **    May you find forgiveness for yourself and forgive others.
80878 **    May you share freely, never taking more than you give.
80879 **
80880 ******************************************************************************
80881 **
80882 ** This header file is used by programs that want to link against the
80883 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
80884 */
80885
80886 #if 0
80887 extern "C" {
80888 #endif  /* __cplusplus */
80889
80890 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
80891
80892 #if 0
80893 }  /* extern "C" */
80894 #endif  /* __cplusplus */
80895
80896 /************** End of fts3.h ************************************************/
80897 /************** Continuing where we left off in main.c ***********************/
80898 #endif
80899 #ifdef SQLITE_ENABLE_RTREE
80900 /************** Include rtree.h in the middle of main.c **********************/
80901 /************** Begin file rtree.h *******************************************/
80902 /*
80903 ** 2008 May 26
80904 **
80905 ** The author disclaims copyright to this source code.  In place of
80906 ** a legal notice, here is a blessing:
80907 **
80908 **    May you do good and not evil.
80909 **    May you find forgiveness for yourself and forgive others.
80910 **    May you share freely, never taking more than you give.
80911 **
80912 ******************************************************************************
80913 **
80914 ** This header file is used by programs that want to link against the
80915 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
80916 */
80917
80918 #if 0
80919 extern "C" {
80920 #endif  /* __cplusplus */
80921
80922 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
80923
80924 #if 0
80925 }  /* extern "C" */
80926 #endif  /* __cplusplus */
80927
80928 /************** End of rtree.h ***********************************************/
80929 /************** Continuing where we left off in main.c ***********************/
80930 #endif
80931
80932 /*
80933 ** The version of the library
80934 */
80935 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
80936 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
80937 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
80938 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
80939
80940 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
80941 /*
80942 ** If the following function pointer is not NULL and if
80943 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
80944 ** I/O active are written using this function.  These messages
80945 ** are intended for debugging activity only.
80946 */
80947 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
80948 #endif
80949
80950 /*
80951 ** If the following global variable points to a string which is the
80952 ** name of a directory, then that directory will be used to store
80953 ** temporary files.
80954 **
80955 ** See also the "PRAGMA temp_store_directory" SQL command.
80956 */
80957 SQLITE_API char *sqlite3_temp_directory = 0;
80958
80959 /*
80960 ** Initialize SQLite.  
80961 **
80962 ** This routine must be called to initialize the memory allocation,
80963 ** VFS, and mutex subsystesms prior to doing any serious work with
80964 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
80965 ** this routine will be called automatically by key routines such as
80966 ** sqlite3_open().  
80967 **
80968 ** This routine is a no-op except on its very first call for the process,
80969 ** or for the first call after a call to sqlite3_shutdown.
80970 */
80971 SQLITE_API int sqlite3_initialize(void){
80972   static int inProgress = 0;
80973   int rc;
80974
80975   /* If SQLite is already initialized, this call is a no-op. */
80976   if( sqlite3Config.isInit ) return SQLITE_OK;
80977
80978   /* Make sure the mutex system is initialized. */
80979   rc = sqlite3MutexInit();
80980
80981   if( rc==SQLITE_OK ){
80982
80983     /* Initialize the malloc() system and the recursive pInitMutex mutex.
80984     ** This operation is protected by the STATIC_MASTER mutex.
80985     */
80986     sqlite3_mutex *pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
80987     sqlite3_mutex_enter(pMaster);
80988     if( !sqlite3Config.isMallocInit ){
80989       rc = sqlite3MallocInit();
80990     }
80991     if( rc==SQLITE_OK ){
80992       sqlite3Config.isMallocInit = 1;
80993       if( !sqlite3Config.pInitMutex ){
80994         sqlite3Config.pInitMutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
80995         if( sqlite3Config.bCoreMutex && !sqlite3Config.pInitMutex ){
80996           rc = SQLITE_NOMEM;
80997         }
80998       }
80999     }
81000     sqlite3_mutex_leave(pMaster);
81001     if( rc!=SQLITE_OK ){
81002       return rc;
81003     }
81004
81005     /* Enter the recursive pInitMutex mutex. After doing so, if the
81006     ** sqlite3Config.isInit flag is true, then some other thread has
81007     ** finished doing the initialization. If the inProgress flag is
81008     ** true, then this function is being called recursively from within
81009     ** the sqlite3_os_init() call below. In either case, exit early.
81010     */
81011     sqlite3_mutex_enter(sqlite3Config.pInitMutex);
81012     if( sqlite3Config.isInit || inProgress ){
81013       sqlite3_mutex_leave(sqlite3Config.pInitMutex);
81014       return SQLITE_OK;
81015     }
81016     sqlite3StatusReset();
81017     inProgress = 1;
81018     rc = sqlite3_os_init();
81019     inProgress = 0;
81020     sqlite3Config.isInit = (rc==SQLITE_OK ? 1 : 0);
81021     sqlite3_mutex_leave(sqlite3Config.pInitMutex);
81022   }
81023
81024   /* Check NaN support. */
81025 #ifndef NDEBUG
81026   /* This section of code's only "output" is via assert() statements. */
81027   if ( rc==SQLITE_OK ){
81028     u64 x = (((u64)1)<<63)-1;
81029     double y;
81030     assert(sizeof(x)==8);
81031     assert(sizeof(x)==sizeof(y));
81032     memcpy(&y, &x, 8);
81033     assert( sqlite3IsNaN(y) );
81034   }
81035 #endif
81036
81037   return rc;
81038 }
81039
81040 /*
81041 ** Undo the effects of sqlite3_initialize().  Must not be called while
81042 ** there are outstanding database connections or memory allocations or
81043 ** while any part of SQLite is otherwise in use in any thread.  This
81044 ** routine is not threadsafe.  Not by a long shot.
81045 */
81046 SQLITE_API int sqlite3_shutdown(void){
81047   sqlite3_mutex_free(sqlite3Config.pInitMutex);
81048   sqlite3Config.pInitMutex = 0;
81049   sqlite3Config.isMallocInit = 0;
81050   if( sqlite3Config.isInit ){
81051     sqlite3_os_end();
81052   }
81053   if( sqlite3Config.m.xShutdown ){
81054     sqlite3MallocEnd();
81055   }
81056   if( sqlite3Config.mutex.xMutexEnd ){
81057     sqlite3MutexEnd();
81058   }
81059   sqlite3Config.isInit = 0;
81060   return SQLITE_OK;
81061 }
81062
81063 /*
81064 ** This API allows applications to modify the global configuration of
81065 ** the SQLite library at run-time.
81066 **
81067 ** This routine should only be called when there are no outstanding
81068 ** database connections or memory allocations.  This routine is not
81069 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
81070 ** behavior.
81071 */
81072 SQLITE_API int sqlite3_config(int op, ...){
81073   va_list ap;
81074   int rc = SQLITE_OK;
81075
81076   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
81077   ** the SQLite library is in use. */
81078   if( sqlite3Config.isInit ) return SQLITE_MISUSE;
81079
81080   va_start(ap, op);
81081   switch( op ){
81082     case SQLITE_CONFIG_SINGLETHREAD: {
81083       /* Disable all mutexing */
81084       sqlite3Config.bCoreMutex = 0;
81085       sqlite3Config.bFullMutex = 0;
81086       break;
81087     }
81088     case SQLITE_CONFIG_MULTITHREAD: {
81089       /* Disable mutexing of database connections */
81090       /* Enable mutexing of core data structures */
81091       sqlite3Config.bCoreMutex = 1;
81092       sqlite3Config.bFullMutex = 0;
81093       break;
81094     }
81095     case SQLITE_CONFIG_SERIALIZED: {
81096       /* Enable all mutexing */
81097       sqlite3Config.bCoreMutex = 1;
81098       sqlite3Config.bFullMutex = 1;
81099       break;
81100     }
81101     case SQLITE_CONFIG_MALLOC: {
81102       /* Specify an alternative malloc implementation */
81103       sqlite3Config.m = *va_arg(ap, sqlite3_mem_methods*);
81104       break;
81105     }
81106     case SQLITE_CONFIG_GETMALLOC: {
81107       /* Retrieve the current malloc() implementation */
81108       if( sqlite3Config.m.xMalloc==0 ) sqlite3MemSetDefault();
81109       *va_arg(ap, sqlite3_mem_methods*) = sqlite3Config.m;
81110       break;
81111     }
81112     case SQLITE_CONFIG_MUTEX: {
81113       /* Specify an alternative mutex implementation */
81114       sqlite3Config.mutex = *va_arg(ap, sqlite3_mutex_methods*);
81115       break;
81116     }
81117     case SQLITE_CONFIG_GETMUTEX: {
81118       /* Retrieve the current mutex implementation */
81119       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3Config.mutex;
81120       break;
81121     }
81122     case SQLITE_CONFIG_MEMSTATUS: {
81123       /* Enable or disable the malloc status collection */
81124       sqlite3Config.bMemstat = va_arg(ap, int);
81125       break;
81126     }
81127     case SQLITE_CONFIG_SCRATCH: {
81128       /* Designate a buffer for scratch memory space */
81129       sqlite3Config.pScratch = va_arg(ap, void*);
81130       sqlite3Config.szScratch = va_arg(ap, int);
81131       sqlite3Config.nScratch = va_arg(ap, int);
81132       break;
81133     }
81134     case SQLITE_CONFIG_PAGECACHE: {
81135       /* Designate a buffer for scratch memory space */
81136       sqlite3Config.pPage = va_arg(ap, void*);
81137       sqlite3Config.szPage = va_arg(ap, int);
81138       sqlite3Config.nPage = va_arg(ap, int);
81139       break;
81140     }
81141
81142 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
81143     case SQLITE_CONFIG_HEAP: {
81144       /* Designate a buffer for heap memory space */
81145       sqlite3Config.pHeap = va_arg(ap, void*);
81146       sqlite3Config.nHeap = va_arg(ap, int);
81147       sqlite3Config.mnReq = va_arg(ap, int);
81148
81149       if( sqlite3Config.pHeap==0 ){
81150         /* If the heap pointer is NULL, then restore the malloc implementation
81151         ** back to NULL pointers too.  This will cause the malloc to go
81152         ** back to its default implementation when sqlite3_initialize() is
81153         ** run.
81154         */
81155         memset(&sqlite3Config.m, 0, sizeof(sqlite3Config.m));
81156       }else{
81157         /* The heap pointer is not NULL, then install one of the
81158         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
81159         ** ENABLE_MEMSYS5 is defined, return an error.
81160         ** the default case and return an error.
81161         */
81162 #ifdef SQLITE_ENABLE_MEMSYS3
81163         sqlite3Config.m = *sqlite3MemGetMemsys3();
81164 #endif
81165 #ifdef SQLITE_ENABLE_MEMSYS5
81166         sqlite3Config.m = *sqlite3MemGetMemsys5();
81167 #endif
81168       }
81169       break;
81170     }
81171 #endif
81172
81173 #if defined(SQLITE_ENABLE_MEMSYS6)
81174     case SQLITE_CONFIG_CHUNKALLOC: {
81175       sqlite3Config.nSmall = va_arg(ap, int);
81176       sqlite3Config.m = *sqlite3MemGetMemsys6();
81177       break;
81178     }
81179 #endif
81180
81181     case SQLITE_CONFIG_LOOKASIDE: {
81182       sqlite3Config.szLookaside = va_arg(ap, int);
81183       sqlite3Config.nLookaside = va_arg(ap, int);
81184       break;
81185     }
81186
81187     default: {
81188       rc = SQLITE_ERROR;
81189       break;
81190     }
81191   }
81192   va_end(ap);
81193   return rc;
81194 }
81195
81196 /*
81197 ** Set up the lookaside buffers for a database connection.
81198 ** Return SQLITE_OK on success.  
81199 ** If lookaside is already active, return SQLITE_BUSY.
81200 **
81201 ** The sz parameter is the number of bytes in each lookaside slot.
81202 ** The cnt parameter is the number of slots.  If pStart is NULL the
81203 ** space for the lookaside memory is obtained from sqlite3_malloc().
81204 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
81205 ** the lookaside memory.
81206 */
81207 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
81208   void *pStart;
81209   if( db->lookaside.nOut ){
81210     return SQLITE_BUSY;
81211   }
81212   if( sz<0 ) sz = 0;
81213   if( cnt<0 ) cnt = 0;
81214   sz = (sz+7)&~7;
81215   if( pBuf==0 ){
81216     sqlite3BeginBenignMalloc();
81217     pStart = sqlite3Malloc( sz*cnt );
81218     sqlite3EndBenignMalloc();
81219   }else{
81220     pStart = pBuf;
81221   }
81222   if( db->lookaside.bMalloced ){
81223     sqlite3_free(db->lookaside.pStart);
81224   }
81225   db->lookaside.pStart = pStart;
81226   db->lookaside.pFree = 0;
81227   db->lookaside.sz = sz;
81228   db->lookaside.bMalloced = pBuf==0;
81229   if( pStart ){
81230     int i;
81231     LookasideSlot *p;
81232     p = (LookasideSlot*)pStart;
81233     for(i=cnt-1; i>=0; i--){
81234       p->pNext = db->lookaside.pFree;
81235       db->lookaside.pFree = p;
81236       p = (LookasideSlot*)&((u8*)p)[sz];
81237     }
81238     db->lookaside.pEnd = p;
81239     db->lookaside.bEnabled = 1;
81240   }else{
81241     db->lookaside.pEnd = 0;
81242     db->lookaside.bEnabled = 0;
81243   }
81244   return SQLITE_OK;
81245 }
81246
81247 /*
81248 ** Configuration settings for an individual database connection
81249 */
81250 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
81251   va_list ap;
81252   int rc;
81253   va_start(ap, op);
81254   switch( op ){
81255     case SQLITE_DBCONFIG_LOOKASIDE: {
81256       void *pBuf = va_arg(ap, void*);
81257       int sz = va_arg(ap, int);
81258       int cnt = va_arg(ap, int);
81259       rc = setupLookaside(db, pBuf, sz, cnt);
81260       break;
81261     }
81262     default: {
81263       rc = SQLITE_ERROR;
81264       break;
81265     }
81266   }
81267   va_end(ap);
81268   return rc;
81269 }
81270
81271 /*
81272 ** Routine needed to support the testcase() macro.
81273 */
81274 #ifdef SQLITE_COVERAGE_TEST
81275 SQLITE_PRIVATE void sqlite3Coverage(int x){
81276   static int dummy = 0;
81277   dummy += x;
81278 }
81279 #endif
81280
81281
81282 /*
81283 ** Return true if the buffer z[0..n-1] contains all spaces.
81284 */
81285 static int allSpaces(const char *z, int n){
81286   while( n>0 && z[n-1]==' ' ){ n--; }
81287   return n==0;
81288 }
81289
81290 /*
81291 ** This is the default collating function named "BINARY" which is always
81292 ** available.
81293 **
81294 ** If the padFlag argument is not NULL then space padding at the end
81295 ** of strings is ignored.  This implements the RTRIM collation.
81296 */
81297 static int binCollFunc(
81298   void *padFlag,
81299   int nKey1, const void *pKey1,
81300   int nKey2, const void *pKey2
81301 ){
81302   int rc, n;
81303   n = nKey1<nKey2 ? nKey1 : nKey2;
81304   rc = memcmp(pKey1, pKey2, n);
81305   if( rc==0 ){
81306     if( padFlag
81307      && allSpaces(((char*)pKey1)+n, nKey1-n)
81308      && allSpaces(((char*)pKey2)+n, nKey2-n)
81309     ){
81310       /* Leave rc unchanged at 0 */
81311     }else{
81312       rc = nKey1 - nKey2;
81313     }
81314   }
81315   return rc;
81316 }
81317
81318 /*
81319 ** Another built-in collating sequence: NOCASE. 
81320 **
81321 ** This collating sequence is intended to be used for "case independant
81322 ** comparison". SQLite's knowledge of upper and lower case equivalents
81323 ** extends only to the 26 characters used in the English language.
81324 **
81325 ** At the moment there is only a UTF-8 implementation.
81326 */
81327 static int nocaseCollatingFunc(
81328   void *NotUsed,
81329   int nKey1, const void *pKey1,
81330   int nKey2, const void *pKey2
81331 ){
81332   int r = sqlite3StrNICmp(
81333       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
81334   if( 0==r ){
81335     r = nKey1-nKey2;
81336   }
81337   return r;
81338 }
81339
81340 /*
81341 ** Return the ROWID of the most recent insert
81342 */
81343 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
81344   return db->lastRowid;
81345 }
81346
81347 /*
81348 ** Return the number of changes in the most recent call to sqlite3_exec().
81349 */
81350 SQLITE_API int sqlite3_changes(sqlite3 *db){
81351   return db->nChange;
81352 }
81353
81354 /*
81355 ** Return the number of changes since the database handle was opened.
81356 */
81357 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
81358   return db->nTotalChange;
81359 }
81360
81361 /*
81362 ** Close an existing SQLite database
81363 */
81364 SQLITE_API int sqlite3_close(sqlite3 *db){
81365   HashElem *i;
81366   int j;
81367
81368   if( !db ){
81369     return SQLITE_OK;
81370   }
81371   if( !sqlite3SafetyCheckSickOrOk(db) ){
81372     return SQLITE_MISUSE;
81373   }
81374   sqlite3_mutex_enter(db->mutex);
81375
81376 #ifdef SQLITE_SSE
81377   {
81378     extern void sqlite3SseCleanup(sqlite3*);
81379     sqlite3SseCleanup(db);
81380   }
81381 #endif 
81382
81383   sqlite3ResetInternalSchema(db, 0);
81384
81385   /* If a transaction is open, the ResetInternalSchema() call above
81386   ** will not have called the xDisconnect() method on any virtual
81387   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
81388   ** call will do so. We need to do this before the check for active
81389   ** SQL statements below, as the v-table implementation may be storing
81390   ** some prepared statements internally.
81391   */
81392   sqlite3VtabRollback(db);
81393
81394   /* If there are any outstanding VMs, return SQLITE_BUSY. */
81395   if( db->pVdbe ){
81396     sqlite3Error(db, SQLITE_BUSY, 
81397         "Unable to close due to unfinalised statements");
81398     sqlite3_mutex_leave(db->mutex);
81399     return SQLITE_BUSY;
81400   }
81401   assert( sqlite3SafetyCheckSickOrOk(db) );
81402
81403   for(j=0; j<db->nDb; j++){
81404     struct Db *pDb = &db->aDb[j];
81405     if( pDb->pBt ){
81406       sqlite3BtreeClose(pDb->pBt);
81407       pDb->pBt = 0;
81408       if( j!=1 ){
81409         pDb->pSchema = 0;
81410       }
81411     }
81412   }
81413   sqlite3ResetInternalSchema(db, 0);
81414   assert( db->nDb<=2 );
81415   assert( db->aDb==db->aDbStatic );
81416   for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
81417     FuncDef *pFunc, *pNext;
81418     for(pFunc = (FuncDef*)sqliteHashData(i); pFunc; pFunc=pNext){
81419       pNext = pFunc->pNext;
81420       sqlite3DbFree(db, pFunc);
81421     }
81422   }
81423
81424   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
81425     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
81426     /* Invoke any destructors registered for collation sequence user data. */
81427     for(j=0; j<3; j++){
81428       if( pColl[j].xDel ){
81429         pColl[j].xDel(pColl[j].pUser);
81430       }
81431     }
81432     sqlite3DbFree(db, pColl);
81433   }
81434   sqlite3HashClear(&db->aCollSeq);
81435 #ifndef SQLITE_OMIT_VIRTUALTABLE
81436   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
81437     Module *pMod = (Module *)sqliteHashData(i);
81438     if( pMod->xDestroy ){
81439       pMod->xDestroy(pMod->pAux);
81440     }
81441     sqlite3DbFree(db, pMod);
81442   }
81443   sqlite3HashClear(&db->aModule);
81444 #endif
81445
81446   sqlite3HashClear(&db->aFunc);
81447   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
81448   if( db->pErr ){
81449     sqlite3ValueFree(db->pErr);
81450   }
81451   sqlite3CloseExtensions(db);
81452
81453   db->magic = SQLITE_MAGIC_ERROR;
81454
81455   /* The temp-database schema is allocated differently from the other schema
81456   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
81457   ** So it needs to be freed here. Todo: Why not roll the temp schema into
81458   ** the same sqliteMalloc() as the one that allocates the database 
81459   ** structure?
81460   */
81461   sqlite3DbFree(db, db->aDb[1].pSchema);
81462   sqlite3_mutex_leave(db->mutex);
81463   db->magic = SQLITE_MAGIC_CLOSED;
81464   sqlite3_mutex_free(db->mutex);
81465   if( db->lookaside.bMalloced ){
81466     sqlite3_free(db->lookaside.pStart);
81467   }
81468   sqlite3_free(db);
81469   return SQLITE_OK;
81470 }
81471
81472 /*
81473 ** Rollback all database files.
81474 */
81475 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
81476   int i;
81477   int inTrans = 0;
81478   assert( sqlite3_mutex_held(db->mutex) );
81479   sqlite3BeginBenignMalloc();
81480   for(i=0; i<db->nDb; i++){
81481     if( db->aDb[i].pBt ){
81482       if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
81483         inTrans = 1;
81484       }
81485       sqlite3BtreeRollback(db->aDb[i].pBt);
81486       db->aDb[i].inTrans = 0;
81487     }
81488   }
81489   sqlite3VtabRollback(db);
81490   sqlite3EndBenignMalloc();
81491
81492   if( db->flags&SQLITE_InternChanges ){
81493     sqlite3ExpirePreparedStatements(db);
81494     sqlite3ResetInternalSchema(db, 0);
81495   }
81496
81497   /* If one has been configured, invoke the rollback-hook callback */
81498   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
81499     db->xRollbackCallback(db->pRollbackArg);
81500   }
81501 }
81502
81503 /*
81504 ** Return a static string that describes the kind of error specified in the
81505 ** argument.
81506 */
81507 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
81508   const char *z;
81509   switch( rc & 0xff ){
81510     case SQLITE_ROW:
81511     case SQLITE_DONE:
81512     case SQLITE_OK:         z = "not an error";                          break;
81513     case SQLITE_ERROR:      z = "SQL logic error or missing database";   break;
81514     case SQLITE_PERM:       z = "access permission denied";              break;
81515     case SQLITE_ABORT:      z = "callback requested query abort";        break;
81516     case SQLITE_BUSY:       z = "database is locked";                    break;
81517     case SQLITE_LOCKED:     z = "database table is locked";              break;
81518     case SQLITE_NOMEM:      z = "out of memory";                         break;
81519     case SQLITE_READONLY:   z = "attempt to write a readonly database";  break;
81520     case SQLITE_INTERRUPT:  z = "interrupted";                           break;
81521     case SQLITE_IOERR:      z = "disk I/O error";                        break;
81522     case SQLITE_CORRUPT:    z = "database disk image is malformed";      break;
81523     case SQLITE_FULL:       z = "database or disk is full";              break;
81524     case SQLITE_CANTOPEN:   z = "unable to open database file";          break;
81525     case SQLITE_EMPTY:      z = "table contains no data";                break;
81526     case SQLITE_SCHEMA:     z = "database schema has changed";           break;
81527     case SQLITE_TOOBIG:     z = "String or BLOB exceeded size limit";    break;
81528     case SQLITE_CONSTRAINT: z = "constraint failed";                     break;
81529     case SQLITE_MISMATCH:   z = "datatype mismatch";                     break;
81530     case SQLITE_MISUSE:     z = "library routine called out of sequence";break;
81531     case SQLITE_NOLFS:      z = "large file support is disabled";        break;
81532     case SQLITE_AUTH:       z = "authorization denied";                  break;
81533     case SQLITE_FORMAT:     z = "auxiliary database format error";       break;
81534     case SQLITE_RANGE:      z = "bind or column index out of range";     break;
81535     case SQLITE_NOTADB:     z = "file is encrypted or is not a database";break;
81536     default:                z = "unknown error";                         break;
81537   }
81538   return z;
81539 }
81540
81541 /*
81542 ** This routine implements a busy callback that sleeps and tries
81543 ** again until a timeout value is reached.  The timeout value is
81544 ** an integer number of milliseconds passed in as the first
81545 ** argument.
81546 */
81547 static int sqliteDefaultBusyCallback(
81548  void *ptr,               /* Database connection */
81549  int count                /* Number of times table has been busy */
81550 ){
81551 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
81552   static const u8 delays[] =
81553      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
81554   static const u8 totals[] =
81555      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
81556 # define NDELAY (sizeof(delays)/sizeof(delays[0]))
81557   sqlite3 *db = (sqlite3 *)ptr;
81558   int timeout = db->busyTimeout;
81559   int delay, prior;
81560
81561   assert( count>=0 );
81562   if( count < NDELAY ){
81563     delay = delays[count];
81564     prior = totals[count];
81565   }else{
81566     delay = delays[NDELAY-1];
81567     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
81568   }
81569   if( prior + delay > timeout ){
81570     delay = timeout - prior;
81571     if( delay<=0 ) return 0;
81572   }
81573   sqlite3OsSleep(db->pVfs, delay*1000);
81574   return 1;
81575 #else
81576   sqlite3 *db = (sqlite3 *)ptr;
81577   int timeout = ((sqlite3 *)ptr)->busyTimeout;
81578   if( (count+1)*1000 > timeout ){
81579     return 0;
81580   }
81581   sqlite3OsSleep(db->pVfs, 1000000);
81582   return 1;
81583 #endif
81584 }
81585
81586 /*
81587 ** Invoke the given busy handler.
81588 **
81589 ** This routine is called when an operation failed with a lock.
81590 ** If this routine returns non-zero, the lock is retried.  If it
81591 ** returns 0, the operation aborts with an SQLITE_BUSY error.
81592 */
81593 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
81594   int rc;
81595   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
81596   rc = p->xFunc(p->pArg, p->nBusy);
81597   if( rc==0 ){
81598     p->nBusy = -1;
81599   }else{
81600     p->nBusy++;
81601   }
81602   return rc; 
81603 }
81604
81605 /*
81606 ** This routine sets the busy callback for an Sqlite database to the
81607 ** given callback function with the given argument.
81608 */
81609 SQLITE_API int sqlite3_busy_handler(
81610   sqlite3 *db,
81611   int (*xBusy)(void*,int),
81612   void *pArg
81613 ){
81614   sqlite3_mutex_enter(db->mutex);
81615   db->busyHandler.xFunc = xBusy;
81616   db->busyHandler.pArg = pArg;
81617   db->busyHandler.nBusy = 0;
81618   sqlite3_mutex_leave(db->mutex);
81619   return SQLITE_OK;
81620 }
81621
81622 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
81623 /*
81624 ** This routine sets the progress callback for an Sqlite database to the
81625 ** given callback function with the given argument. The progress callback will
81626 ** be invoked every nOps opcodes.
81627 */
81628 SQLITE_API void sqlite3_progress_handler(
81629   sqlite3 *db, 
81630   int nOps,
81631   int (*xProgress)(void*), 
81632   void *pArg
81633 ){
81634   sqlite3_mutex_enter(db->mutex);
81635   if( nOps>0 ){
81636     db->xProgress = xProgress;
81637     db->nProgressOps = nOps;
81638     db->pProgressArg = pArg;
81639   }else{
81640     db->xProgress = 0;
81641     db->nProgressOps = 0;
81642     db->pProgressArg = 0;
81643   }
81644   sqlite3_mutex_leave(db->mutex);
81645 }
81646 #endif
81647
81648
81649 /*
81650 ** This routine installs a default busy handler that waits for the
81651 ** specified number of milliseconds before returning 0.
81652 */
81653 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
81654   if( ms>0 ){
81655     db->busyTimeout = ms;
81656     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
81657   }else{
81658     sqlite3_busy_handler(db, 0, 0);
81659   }
81660   return SQLITE_OK;
81661 }
81662
81663 /*
81664 ** Cause any pending operation to stop at its earliest opportunity.
81665 */
81666 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
81667   db->u1.isInterrupted = 1;
81668 }
81669
81670
81671 /*
81672 ** This function is exactly the same as sqlite3_create_function(), except
81673 ** that it is designed to be called by internal code. The difference is
81674 ** that if a malloc() fails in sqlite3_create_function(), an error code
81675 ** is returned and the mallocFailed flag cleared. 
81676 */
81677 SQLITE_PRIVATE int sqlite3CreateFunc(
81678   sqlite3 *db,
81679   const char *zFunctionName,
81680   int nArg,
81681   int enc,
81682   void *pUserData,
81683   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
81684   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
81685   void (*xFinal)(sqlite3_context*)
81686 ){
81687   FuncDef *p;
81688   int nName;
81689
81690   assert( sqlite3_mutex_held(db->mutex) );
81691   if( zFunctionName==0 ||
81692       (xFunc && (xFinal || xStep)) || 
81693       (!xFunc && (xFinal && !xStep)) ||
81694       (!xFunc && (!xFinal && xStep)) ||
81695       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
81696       (255<(nName = sqlite3Strlen(db, zFunctionName))) ){
81697     sqlite3Error(db, SQLITE_ERROR, "bad parameters");
81698     return SQLITE_ERROR;
81699   }
81700   
81701 #ifndef SQLITE_OMIT_UTF16
81702   /* If SQLITE_UTF16 is specified as the encoding type, transform this
81703   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
81704   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
81705   **
81706   ** If SQLITE_ANY is specified, add three versions of the function
81707   ** to the hash table.
81708   */
81709   if( enc==SQLITE_UTF16 ){
81710     enc = SQLITE_UTF16NATIVE;
81711   }else if( enc==SQLITE_ANY ){
81712     int rc;
81713     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
81714          pUserData, xFunc, xStep, xFinal);
81715     if( rc==SQLITE_OK ){
81716       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
81717           pUserData, xFunc, xStep, xFinal);
81718     }
81719     if( rc!=SQLITE_OK ){
81720       return rc;
81721     }
81722     enc = SQLITE_UTF16BE;
81723   }
81724 #else
81725   enc = SQLITE_UTF8;
81726 #endif
81727   
81728   /* Check if an existing function is being overridden or deleted. If so,
81729   ** and there are active VMs, then return SQLITE_BUSY. If a function
81730   ** is being overridden/deleted but there are no active VMs, allow the
81731   ** operation to continue but invalidate all precompiled statements.
81732   */
81733   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 0);
81734   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
81735     if( db->activeVdbeCnt ){
81736       sqlite3Error(db, SQLITE_BUSY, 
81737         "Unable to delete/modify user-function due to active statements");
81738       assert( !db->mallocFailed );
81739       return SQLITE_BUSY;
81740     }else{
81741       sqlite3ExpirePreparedStatements(db);
81742     }
81743   }
81744
81745   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 1);
81746   assert(p || db->mallocFailed);
81747   if( !p ){
81748     return SQLITE_NOMEM;
81749   }
81750   p->flags = 0;
81751   p->xFunc = xFunc;
81752   p->xStep = xStep;
81753   p->xFinalize = xFinal;
81754   p->pUserData = pUserData;
81755   p->nArg = nArg;
81756   return SQLITE_OK;
81757 }
81758
81759 /*
81760 ** Create new user functions.
81761 */
81762 SQLITE_API int sqlite3_create_function(
81763   sqlite3 *db,
81764   const char *zFunctionName,
81765   int nArg,
81766   int enc,
81767   void *p,
81768   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
81769   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
81770   void (*xFinal)(sqlite3_context*)
81771 ){
81772   int rc;
81773   sqlite3_mutex_enter(db->mutex);
81774   rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
81775   rc = sqlite3ApiExit(db, rc);
81776   sqlite3_mutex_leave(db->mutex);
81777   return rc;
81778 }
81779
81780 #ifndef SQLITE_OMIT_UTF16
81781 SQLITE_API int sqlite3_create_function16(
81782   sqlite3 *db,
81783   const void *zFunctionName,
81784   int nArg,
81785   int eTextRep,
81786   void *p,
81787   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
81788   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
81789   void (*xFinal)(sqlite3_context*)
81790 ){
81791   int rc;
81792   char *zFunc8;
81793   sqlite3_mutex_enter(db->mutex);
81794   assert( !db->mallocFailed );
81795   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1);
81796   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
81797   sqlite3DbFree(db, zFunc8);
81798   rc = sqlite3ApiExit(db, rc);
81799   sqlite3_mutex_leave(db->mutex);
81800   return rc;
81801 }
81802 #endif
81803
81804
81805 /*
81806 ** Declare that a function has been overloaded by a virtual table.
81807 **
81808 ** If the function already exists as a regular global function, then
81809 ** this routine is a no-op.  If the function does not exist, then create
81810 ** a new one that always throws a run-time error.  
81811 **
81812 ** When virtual tables intend to provide an overloaded function, they
81813 ** should call this routine to make sure the global function exists.
81814 ** A global function must exist in order for name resolution to work
81815 ** properly.
81816 */
81817 SQLITE_API int sqlite3_overload_function(
81818   sqlite3 *db,
81819   const char *zName,
81820   int nArg
81821 ){
81822   int nName = sqlite3Strlen(db, zName);
81823   int rc;
81824   sqlite3_mutex_enter(db->mutex);
81825   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
81826     sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
81827                       0, sqlite3InvalidFunction, 0, 0);
81828   }
81829   rc = sqlite3ApiExit(db, SQLITE_OK);
81830   sqlite3_mutex_leave(db->mutex);
81831   return rc;
81832 }
81833
81834 #ifndef SQLITE_OMIT_TRACE
81835 /*
81836 ** Register a trace function.  The pArg from the previously registered trace
81837 ** is returned.  
81838 **
81839 ** A NULL trace function means that no tracing is executes.  A non-NULL
81840 ** trace is a pointer to a function that is invoked at the start of each
81841 ** SQL statement.
81842 */
81843 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
81844   void *pOld;
81845   sqlite3_mutex_enter(db->mutex);
81846   pOld = db->pTraceArg;
81847   db->xTrace = xTrace;
81848   db->pTraceArg = pArg;
81849   sqlite3_mutex_leave(db->mutex);
81850   return pOld;
81851 }
81852 /*
81853 ** Register a profile function.  The pArg from the previously registered 
81854 ** profile function is returned.  
81855 **
81856 ** A NULL profile function means that no profiling is executes.  A non-NULL
81857 ** profile is a pointer to a function that is invoked at the conclusion of
81858 ** each SQL statement that is run.
81859 */
81860 SQLITE_API void *sqlite3_profile(
81861   sqlite3 *db,
81862   void (*xProfile)(void*,const char*,sqlite_uint64),
81863   void *pArg
81864 ){
81865   void *pOld;
81866   sqlite3_mutex_enter(db->mutex);
81867   pOld = db->pProfileArg;
81868   db->xProfile = xProfile;
81869   db->pProfileArg = pArg;
81870   sqlite3_mutex_leave(db->mutex);
81871   return pOld;
81872 }
81873 #endif /* SQLITE_OMIT_TRACE */
81874
81875 /*** EXPERIMENTAL ***
81876 **
81877 ** Register a function to be invoked when a transaction comments.
81878 ** If the invoked function returns non-zero, then the commit becomes a
81879 ** rollback.
81880 */
81881 SQLITE_API void *sqlite3_commit_hook(
81882   sqlite3 *db,              /* Attach the hook to this database */
81883   int (*xCallback)(void*),  /* Function to invoke on each commit */
81884   void *pArg                /* Argument to the function */
81885 ){
81886   void *pOld;
81887   sqlite3_mutex_enter(db->mutex);
81888   pOld = db->pCommitArg;
81889   db->xCommitCallback = xCallback;
81890   db->pCommitArg = pArg;
81891   sqlite3_mutex_leave(db->mutex);
81892   return pOld;
81893 }
81894
81895 /*
81896 ** Register a callback to be invoked each time a row is updated,
81897 ** inserted or deleted using this database connection.
81898 */
81899 SQLITE_API void *sqlite3_update_hook(
81900   sqlite3 *db,              /* Attach the hook to this database */
81901   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
81902   void *pArg                /* Argument to the function */
81903 ){
81904   void *pRet;
81905   sqlite3_mutex_enter(db->mutex);
81906   pRet = db->pUpdateArg;
81907   db->xUpdateCallback = xCallback;
81908   db->pUpdateArg = pArg;
81909   sqlite3_mutex_leave(db->mutex);
81910   return pRet;
81911 }
81912
81913 /*
81914 ** Register a callback to be invoked each time a transaction is rolled
81915 ** back by this database connection.
81916 */
81917 SQLITE_API void *sqlite3_rollback_hook(
81918   sqlite3 *db,              /* Attach the hook to this database */
81919   void (*xCallback)(void*), /* Callback function */
81920   void *pArg                /* Argument to the function */
81921 ){
81922   void *pRet;
81923   sqlite3_mutex_enter(db->mutex);
81924   pRet = db->pRollbackArg;
81925   db->xRollbackCallback = xCallback;
81926   db->pRollbackArg = pArg;
81927   sqlite3_mutex_leave(db->mutex);
81928   return pRet;
81929 }
81930
81931 /*
81932 ** This routine is called to create a connection to a database BTree
81933 ** driver.  If zFilename is the name of a file, then that file is
81934 ** opened and used.  If zFilename is the magic name ":memory:" then
81935 ** the database is stored in memory (and is thus forgotten as soon as
81936 ** the connection is closed.)  If zFilename is NULL then the database
81937 ** is a "virtual" database for transient use only and is deleted as
81938 ** soon as the connection is closed.
81939 **
81940 ** A virtual database can be either a disk file (that is automatically
81941 ** deleted when the file is closed) or it an be held entirely in memory,
81942 ** depending on the values of the SQLITE_TEMP_STORE compile-time macro and the
81943 ** db->temp_store variable, according to the following chart:
81944 **
81945 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
81946 **   -----------------     --------------     ------------------------------
81947 **   0                     any                file
81948 **   1                     1                  file
81949 **   1                     2                  memory
81950 **   1                     0                  file
81951 **   2                     1                  file
81952 **   2                     2                  memory
81953 **   2                     0                  memory
81954 **   3                     any                memory
81955 */
81956 SQLITE_PRIVATE int sqlite3BtreeFactory(
81957   const sqlite3 *db,        /* Main database when opening aux otherwise 0 */
81958   const char *zFilename,    /* Name of the file containing the BTree database */
81959   int omitJournal,          /* if TRUE then do not journal this file */
81960   int nCache,               /* How many pages in the page cache */
81961   int vfsFlags,             /* Flags passed through to vfsOpen */
81962   Btree **ppBtree           /* Pointer to new Btree object written here */
81963 ){
81964   int btFlags = 0;
81965   int rc;
81966   
81967   assert( sqlite3_mutex_held(db->mutex) );
81968   assert( ppBtree != 0);
81969   if( omitJournal ){
81970     btFlags |= BTREE_OMIT_JOURNAL;
81971   }
81972   if( db->flags & SQLITE_NoReadlock ){
81973     btFlags |= BTREE_NO_READLOCK;
81974   }
81975   if( zFilename==0 ){
81976 #if SQLITE_TEMP_STORE==0
81977     /* Do nothing */
81978 #endif
81979 #ifndef SQLITE_OMIT_MEMORYDB
81980 #if SQLITE_TEMP_STORE==1
81981     if( db->temp_store==2 ) zFilename = ":memory:";
81982 #endif
81983 #if SQLITE_TEMP_STORE==2
81984     if( db->temp_store!=1 ) zFilename = ":memory:";
81985 #endif
81986 #if SQLITE_TEMP_STORE==3
81987     zFilename = ":memory:";
81988 #endif
81989 #endif /* SQLITE_OMIT_MEMORYDB */
81990   }
81991
81992   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
81993     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
81994   }
81995   rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
81996
81997   /* If the B-Tree was successfully opened, set the pager-cache size to the
81998   ** default value. Except, if the call to BtreeOpen() returned a handle
81999   ** open on an existing shared pager-cache, do not change the pager-cache 
82000   ** size.
82001   */
82002   if( rc==SQLITE_OK && 0==sqlite3BtreeSchema(*ppBtree, 0, 0) ){
82003     sqlite3BtreeSetCacheSize(*ppBtree, nCache);
82004   }
82005   return rc;
82006 }
82007
82008 /*
82009 ** Return UTF-8 encoded English language explanation of the most recent
82010 ** error.
82011 */
82012 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
82013   const char *z;
82014   if( !db ){
82015     return sqlite3ErrStr(SQLITE_NOMEM);
82016   }
82017   if( !sqlite3SafetyCheckSickOrOk(db) ){
82018     return sqlite3ErrStr(SQLITE_MISUSE);
82019   }
82020   sqlite3_mutex_enter(db->mutex);
82021   assert( !db->mallocFailed );
82022   z = (char*)sqlite3_value_text(db->pErr);
82023   assert( !db->mallocFailed );
82024   if( z==0 ){
82025     z = sqlite3ErrStr(db->errCode);
82026   }
82027   sqlite3_mutex_leave(db->mutex);
82028   return z;
82029 }
82030
82031 #ifndef SQLITE_OMIT_UTF16
82032 /*
82033 ** Return UTF-16 encoded English language explanation of the most recent
82034 ** error.
82035 */
82036 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
82037   /* Because all the characters in the string are in the unicode
82038   ** range 0x00-0xFF, if we pad the big-endian string with a 
82039   ** zero byte, we can obtain the little-endian string with
82040   ** &big_endian[1].
82041   */
82042   static const char outOfMemBe[] = {
82043     0, 'o', 0, 'u', 0, 't', 0, ' ', 
82044     0, 'o', 0, 'f', 0, ' ', 
82045     0, 'm', 0, 'e', 0, 'm', 0, 'o', 0, 'r', 0, 'y', 0, 0, 0
82046   };
82047   static const char misuseBe [] = {
82048     0, 'l', 0, 'i', 0, 'b', 0, 'r', 0, 'a', 0, 'r', 0, 'y', 0, ' ', 
82049     0, 'r', 0, 'o', 0, 'u', 0, 't', 0, 'i', 0, 'n', 0, 'e', 0, ' ', 
82050     0, 'c', 0, 'a', 0, 'l', 0, 'l', 0, 'e', 0, 'd', 0, ' ', 
82051     0, 'o', 0, 'u', 0, 't', 0, ' ', 
82052     0, 'o', 0, 'f', 0, ' ', 
82053     0, 's', 0, 'e', 0, 'q', 0, 'u', 0, 'e', 0, 'n', 0, 'c', 0, 'e', 0, 0, 0
82054   };
82055
82056   const void *z;
82057   if( !db ){
82058     return (void *)(&outOfMemBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
82059   }
82060   if( !sqlite3SafetyCheckSickOrOk(db) ){
82061     return (void *)(&misuseBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
82062   }
82063   sqlite3_mutex_enter(db->mutex);
82064   assert( !db->mallocFailed );
82065   z = sqlite3_value_text16(db->pErr);
82066   if( z==0 ){
82067     sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
82068          SQLITE_UTF8, SQLITE_STATIC);
82069     z = sqlite3_value_text16(db->pErr);
82070   }
82071   /* A malloc() may have failed within the call to sqlite3_value_text16()
82072   ** above. If this is the case, then the db->mallocFailed flag needs to
82073   ** be cleared before returning. Do this directly, instead of via
82074   ** sqlite3ApiExit(), to avoid setting the database handle error message.
82075   */
82076   db->mallocFailed = 0;
82077   sqlite3_mutex_leave(db->mutex);
82078   return z;
82079 }
82080 #endif /* SQLITE_OMIT_UTF16 */
82081
82082 /*
82083 ** Return the most recent error code generated by an SQLite routine. If NULL is
82084 ** passed to this function, we assume a malloc() failed during sqlite3_open().
82085 */
82086 SQLITE_API int sqlite3_errcode(sqlite3 *db){
82087   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
82088     return SQLITE_MISUSE;
82089   }
82090   if( !db || db->mallocFailed ){
82091     return SQLITE_NOMEM;
82092   }
82093   return db->errCode & db->errMask;
82094 }
82095
82096 /*
82097 ** Create a new collating function for database "db".  The name is zName
82098 ** and the encoding is enc.
82099 */
82100 static int createCollation(
82101   sqlite3* db, 
82102   const char *zName, 
82103   int enc, 
82104   void* pCtx,
82105   int(*xCompare)(void*,int,const void*,int,const void*),
82106   void(*xDel)(void*)
82107 ){
82108   CollSeq *pColl;
82109   int enc2;
82110   int nName;
82111   
82112   assert( sqlite3_mutex_held(db->mutex) );
82113
82114   /* If SQLITE_UTF16 is specified as the encoding type, transform this
82115   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
82116   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
82117   */
82118   enc2 = enc & ~SQLITE_UTF16_ALIGNED;
82119   if( enc2==SQLITE_UTF16 ){
82120     enc2 = SQLITE_UTF16NATIVE;
82121   }
82122   if( (enc2&~3)!=0 ){
82123     return SQLITE_MISUSE;
82124   }
82125
82126   /* Check if this call is removing or replacing an existing collation 
82127   ** sequence. If so, and there are active VMs, return busy. If there
82128   ** are no active VMs, invalidate any pre-compiled statements.
82129   */
82130   nName = sqlite3Strlen(db, zName);
82131   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, nName, 0);
82132   if( pColl && pColl->xCmp ){
82133     if( db->activeVdbeCnt ){
82134       sqlite3Error(db, SQLITE_BUSY, 
82135         "Unable to delete/modify collation sequence due to active statements");
82136       return SQLITE_BUSY;
82137     }
82138     sqlite3ExpirePreparedStatements(db);
82139
82140     /* If collation sequence pColl was created directly by a call to
82141     ** sqlite3_create_collation, and not generated by synthCollSeq(),
82142     ** then any copies made by synthCollSeq() need to be invalidated.
82143     ** Also, collation destructor - CollSeq.xDel() - function may need
82144     ** to be called.
82145     */ 
82146     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
82147       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
82148       int j;
82149       for(j=0; j<3; j++){
82150         CollSeq *p = &aColl[j];
82151         if( p->enc==pColl->enc ){
82152           if( p->xDel ){
82153             p->xDel(p->pUser);
82154           }
82155           p->xCmp = 0;
82156         }
82157       }
82158     }
82159   }
82160
82161   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, nName, 1);
82162   if( pColl ){
82163     pColl->xCmp = xCompare;
82164     pColl->pUser = pCtx;
82165     pColl->xDel = xDel;
82166     pColl->enc = enc2 | (enc & SQLITE_UTF16_ALIGNED);
82167   }
82168   sqlite3Error(db, SQLITE_OK, 0);
82169   return SQLITE_OK;
82170 }
82171
82172
82173 /*
82174 ** This array defines hard upper bounds on limit values.  The
82175 ** initializer must be kept in sync with the SQLITE_LIMIT_*
82176 ** #defines in sqlite3.h.
82177 */
82178 static const int aHardLimit[] = {
82179   SQLITE_MAX_LENGTH,
82180   SQLITE_MAX_SQL_LENGTH,
82181   SQLITE_MAX_COLUMN,
82182   SQLITE_MAX_EXPR_DEPTH,
82183   SQLITE_MAX_COMPOUND_SELECT,
82184   SQLITE_MAX_VDBE_OP,
82185   SQLITE_MAX_FUNCTION_ARG,
82186   SQLITE_MAX_ATTACHED,
82187   SQLITE_MAX_LIKE_PATTERN_LENGTH,
82188   SQLITE_MAX_VARIABLE_NUMBER,
82189 };
82190
82191 /*
82192 ** Make sure the hard limits are set to reasonable values
82193 */
82194 #if SQLITE_MAX_LENGTH<100
82195 # error SQLITE_MAX_LENGTH must be at least 100
82196 #endif
82197 #if SQLITE_MAX_SQL_LENGTH<100
82198 # error SQLITE_MAX_SQL_LENGTH must be at least 100
82199 #endif
82200 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
82201 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
82202 #endif
82203 #if SQLITE_MAX_COMPOUND_SELECT<2
82204 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
82205 #endif
82206 #if SQLITE_MAX_VDBE_OP<40
82207 # error SQLITE_MAX_VDBE_OP must be at least 40
82208 #endif
82209 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
82210 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
82211 #endif
82212 #if SQLITE_MAX_ATTACH<0 || SQLITE_MAX_ATTACH>30
82213 # error SQLITE_MAX_ATTACH must be between 0 and 30
82214 #endif
82215 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
82216 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
82217 #endif
82218 #if SQLITE_MAX_VARIABLE_NUMBER<1
82219 # error SQLITE_MAX_VARIABLE_NUMBER must be at least 1
82220 #endif
82221
82222
82223 /*
82224 ** Change the value of a limit.  Report the old value.
82225 ** If an invalid limit index is supplied, report -1.
82226 ** Make no changes but still report the old value if the
82227 ** new limit is negative.
82228 **
82229 ** A new lower limit does not shrink existing constructs.
82230 ** It merely prevents new constructs that exceed the limit
82231 ** from forming.
82232 */
82233 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
82234   int oldLimit;
82235   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
82236     return -1;
82237   }
82238   oldLimit = db->aLimit[limitId];
82239   if( newLimit>=0 ){
82240     if( newLimit>aHardLimit[limitId] ){
82241       newLimit = aHardLimit[limitId];
82242     }
82243     db->aLimit[limitId] = newLimit;
82244   }
82245   return oldLimit;
82246 }
82247
82248 /*
82249 ** This routine does the work of opening a database on behalf of
82250 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
82251 ** is UTF-8 encoded.
82252 */
82253 static int openDatabase(
82254   const char *zFilename, /* Database filename UTF-8 encoded */
82255   sqlite3 **ppDb,        /* OUT: Returned database handle */
82256   unsigned flags,        /* Operational flags */
82257   const char *zVfs       /* Name of the VFS to use */
82258 ){
82259   sqlite3 *db;
82260   int rc;
82261   CollSeq *pColl;
82262   int isThreadsafe = 1;
82263
82264 #ifndef SQLITE_OMIT_AUTOINIT
82265   rc = sqlite3_initialize();
82266   if( rc ) return rc;
82267 #endif
82268
82269   if( flags&SQLITE_OPEN_NOMUTEX ){
82270     isThreadsafe = 0;
82271   }
82272
82273   /* Remove harmful bits from the flags parameter */
82274   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
82275                SQLITE_OPEN_MAIN_DB |
82276                SQLITE_OPEN_TEMP_DB | 
82277                SQLITE_OPEN_TRANSIENT_DB | 
82278                SQLITE_OPEN_MAIN_JOURNAL | 
82279                SQLITE_OPEN_TEMP_JOURNAL | 
82280                SQLITE_OPEN_SUBJOURNAL | 
82281                SQLITE_OPEN_MASTER_JOURNAL |
82282                SQLITE_OPEN_NOMUTEX
82283              );
82284
82285   /* Allocate the sqlite data structure */
82286   db = sqlite3MallocZero( sizeof(sqlite3) );
82287   if( db==0 ) goto opendb_out;
82288   if( sqlite3Config.bFullMutex && isThreadsafe ){
82289     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
82290     if( db->mutex==0 ){
82291       sqlite3_free(db);
82292       db = 0;
82293       goto opendb_out;
82294     }
82295   }
82296   sqlite3_mutex_enter(db->mutex);
82297   db->errMask = 0xff;
82298   db->priorNewRowid = 0;
82299   db->nDb = 2;
82300   db->magic = SQLITE_MAGIC_BUSY;
82301   db->aDb = db->aDbStatic;
82302
82303   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
82304   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
82305   db->autoCommit = 1;
82306   db->nextAutovac = -1;
82307   db->nextPagesize = 0;
82308   db->flags |= SQLITE_ShortColNames
82309 #if SQLITE_DEFAULT_FILE_FORMAT<4
82310                  | SQLITE_LegacyFileFmt
82311 #endif
82312 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
82313                  | SQLITE_LoadExtension
82314 #endif
82315       ;
82316   sqlite3HashInit(&db->aFunc, SQLITE_HASH_STRING, 0);
82317   sqlite3HashInit(&db->aCollSeq, SQLITE_HASH_STRING, 0);
82318 #ifndef SQLITE_OMIT_VIRTUALTABLE
82319   sqlite3HashInit(&db->aModule, SQLITE_HASH_STRING, 0);
82320 #endif
82321
82322   db->pVfs = sqlite3_vfs_find(zVfs);
82323   if( !db->pVfs ){
82324     rc = SQLITE_ERROR;
82325     db->magic = SQLITE_MAGIC_SICK;
82326     sqlite3Error(db, rc, "no such vfs: %s", zVfs);
82327     goto opendb_out;
82328   }
82329
82330   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
82331   ** and UTF-16, so add a version for each to avoid any unnecessary
82332   ** conversions. The only error that can occur here is a malloc() failure.
82333   */
82334   createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
82335   createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
82336   createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
82337   createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
82338   if( db->mallocFailed ){
82339     db->magic = SQLITE_MAGIC_SICK;
82340     goto opendb_out;
82341   }
82342   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0);
82343   assert( db->pDfltColl!=0 );
82344
82345   /* Also add a UTF-8 case-insensitive collation sequence. */
82346   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
82347
82348   /* Set flags on the built-in collating sequences */
82349   db->pDfltColl->type = SQLITE_COLL_BINARY;
82350   pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "NOCASE", 6, 0);
82351   if( pColl ){
82352     pColl->type = SQLITE_COLL_NOCASE;
82353   }
82354
82355   /* Open the backend database driver */
82356   db->openFlags = flags;
82357   rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE, 
82358                            flags | SQLITE_OPEN_MAIN_DB,
82359                            &db->aDb[0].pBt);
82360   if( rc!=SQLITE_OK ){
82361     sqlite3Error(db, rc, 0);
82362     db->magic = SQLITE_MAGIC_SICK;
82363     goto opendb_out;
82364   }
82365   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
82366   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
82367
82368
82369   /* The default safety_level for the main database is 'full'; for the temp
82370   ** database it is 'NONE'. This matches the pager layer defaults.  
82371   */
82372   db->aDb[0].zName = "main";
82373   db->aDb[0].safety_level = 3;
82374 #ifndef SQLITE_OMIT_TEMPDB
82375   db->aDb[1].zName = "temp";
82376   db->aDb[1].safety_level = 1;
82377 #endif
82378
82379   db->magic = SQLITE_MAGIC_OPEN;
82380   if( db->mallocFailed ){
82381     goto opendb_out;
82382   }
82383
82384   /* Register all built-in functions, but do not attempt to read the
82385   ** database schema yet. This is delayed until the first time the database
82386   ** is accessed.
82387   */
82388   sqlite3Error(db, SQLITE_OK, 0);
82389   sqlite3RegisterBuiltinFunctions(db);
82390
82391   /* Load automatic extensions - extensions that have been registered
82392   ** using the sqlite3_automatic_extension() API.
82393   */
82394   (void)sqlite3AutoLoadExtensions(db);
82395   if( sqlite3_errcode(db)!=SQLITE_OK ){
82396     goto opendb_out;
82397   }
82398
82399 #ifdef SQLITE_ENABLE_FTS1
82400   if( !db->mallocFailed ){
82401     extern int sqlite3Fts1Init(sqlite3*);
82402     rc = sqlite3Fts1Init(db);
82403   }
82404 #endif
82405
82406 #ifdef SQLITE_ENABLE_FTS2
82407   if( !db->mallocFailed && rc==SQLITE_OK ){
82408     extern int sqlite3Fts2Init(sqlite3*);
82409     rc = sqlite3Fts2Init(db);
82410   }
82411 #endif
82412
82413 #ifdef SQLITE_ENABLE_FTS3
82414   if( !db->mallocFailed && rc==SQLITE_OK ){
82415     rc = sqlite3Fts3Init(db);
82416   }
82417 #endif
82418
82419 #ifdef SQLITE_ENABLE_ICU
82420   if( !db->mallocFailed && rc==SQLITE_OK ){
82421     extern int sqlite3IcuInit(sqlite3*);
82422     rc = sqlite3IcuInit(db);
82423   }
82424 #endif
82425
82426 #ifdef SQLITE_ENABLE_RTREE
82427   if( !db->mallocFailed && rc==SQLITE_OK){
82428     rc = sqlite3RtreeInit(db);
82429   }
82430 #endif
82431
82432   sqlite3Error(db, rc, 0);
82433
82434   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
82435   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
82436   ** mode.  Doing nothing at all also makes NORMAL the default.
82437   */
82438 #ifdef SQLITE_DEFAULT_LOCKING_MODE
82439   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
82440   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
82441                           SQLITE_DEFAULT_LOCKING_MODE);
82442 #endif
82443
82444   /* Enable the lookaside-malloc subsystem */
82445   setupLookaside(db, 0, sqlite3Config.szLookaside, sqlite3Config.nLookaside);
82446
82447 opendb_out:
82448   if( db ){
82449     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3Config.bFullMutex==0 );
82450     sqlite3_mutex_leave(db->mutex);
82451   }
82452   if( SQLITE_NOMEM==(rc = sqlite3_errcode(db)) ){
82453     sqlite3_close(db);
82454     db = 0;
82455   }
82456   *ppDb = db;
82457   return sqlite3ApiExit(0, rc);
82458 }
82459
82460 /*
82461 ** Open a new database handle.
82462 */
82463 SQLITE_API int sqlite3_open(
82464   const char *zFilename, 
82465   sqlite3 **ppDb 
82466 ){
82467   return openDatabase(zFilename, ppDb,
82468                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
82469 }
82470 SQLITE_API int sqlite3_open_v2(
82471   const char *filename,   /* Database filename (UTF-8) */
82472   sqlite3 **ppDb,         /* OUT: SQLite db handle */
82473   int flags,              /* Flags */
82474   const char *zVfs        /* Name of VFS module to use */
82475 ){
82476   return openDatabase(filename, ppDb, flags, zVfs);
82477 }
82478
82479 #ifndef SQLITE_OMIT_UTF16
82480 /*
82481 ** Open a new database handle.
82482 */
82483 SQLITE_API int sqlite3_open16(
82484   const void *zFilename, 
82485   sqlite3 **ppDb
82486 ){
82487   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
82488   sqlite3_value *pVal;
82489   int rc;
82490
82491   assert( zFilename );
82492   assert( ppDb );
82493   *ppDb = 0;
82494 #ifndef SQLITE_OMIT_AUTOINIT
82495   rc = sqlite3_initialize();
82496   if( rc ) return rc;
82497 #endif
82498   pVal = sqlite3ValueNew(0);
82499   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
82500   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
82501   if( zFilename8 ){
82502     rc = openDatabase(zFilename8, ppDb,
82503                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
82504     assert( *ppDb || rc==SQLITE_NOMEM );
82505     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
82506       ENC(*ppDb) = SQLITE_UTF16NATIVE;
82507     }
82508   }else{
82509     rc = SQLITE_NOMEM;
82510   }
82511   sqlite3ValueFree(pVal);
82512
82513   return sqlite3ApiExit(0, rc);
82514 }
82515 #endif /* SQLITE_OMIT_UTF16 */
82516
82517 /*
82518 ** Register a new collation sequence with the database handle db.
82519 */
82520 SQLITE_API int sqlite3_create_collation(
82521   sqlite3* db, 
82522   const char *zName, 
82523   int enc, 
82524   void* pCtx,
82525   int(*xCompare)(void*,int,const void*,int,const void*)
82526 ){
82527   int rc;
82528   sqlite3_mutex_enter(db->mutex);
82529   assert( !db->mallocFailed );
82530   rc = createCollation(db, zName, enc, pCtx, xCompare, 0);
82531   rc = sqlite3ApiExit(db, rc);
82532   sqlite3_mutex_leave(db->mutex);
82533   return rc;
82534 }
82535
82536 /*
82537 ** Register a new collation sequence with the database handle db.
82538 */
82539 SQLITE_API int sqlite3_create_collation_v2(
82540   sqlite3* db, 
82541   const char *zName, 
82542   int enc, 
82543   void* pCtx,
82544   int(*xCompare)(void*,int,const void*,int,const void*),
82545   void(*xDel)(void*)
82546 ){
82547   int rc;
82548   sqlite3_mutex_enter(db->mutex);
82549   assert( !db->mallocFailed );
82550   rc = createCollation(db, zName, enc, pCtx, xCompare, xDel);
82551   rc = sqlite3ApiExit(db, rc);
82552   sqlite3_mutex_leave(db->mutex);
82553   return rc;
82554 }
82555
82556 #ifndef SQLITE_OMIT_UTF16
82557 /*
82558 ** Register a new collation sequence with the database handle db.
82559 */
82560 SQLITE_API int sqlite3_create_collation16(
82561   sqlite3* db, 
82562   const void *zName,
82563   int enc, 
82564   void* pCtx,
82565   int(*xCompare)(void*,int,const void*,int,const void*)
82566 ){
82567   int rc = SQLITE_OK;
82568   char *zName8;
82569   sqlite3_mutex_enter(db->mutex);
82570   assert( !db->mallocFailed );
82571   zName8 = sqlite3Utf16to8(db, zName, -1);
82572   if( zName8 ){
82573     rc = createCollation(db, zName8, enc, pCtx, xCompare, 0);
82574     sqlite3DbFree(db, zName8);
82575   }
82576   rc = sqlite3ApiExit(db, rc);
82577   sqlite3_mutex_leave(db->mutex);
82578   return rc;
82579 }
82580 #endif /* SQLITE_OMIT_UTF16 */
82581
82582 /*
82583 ** Register a collation sequence factory callback with the database handle
82584 ** db. Replace any previously installed collation sequence factory.
82585 */
82586 SQLITE_API int sqlite3_collation_needed(
82587   sqlite3 *db, 
82588   void *pCollNeededArg, 
82589   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
82590 ){
82591   sqlite3_mutex_enter(db->mutex);
82592   db->xCollNeeded = xCollNeeded;
82593   db->xCollNeeded16 = 0;
82594   db->pCollNeededArg = pCollNeededArg;
82595   sqlite3_mutex_leave(db->mutex);
82596   return SQLITE_OK;
82597 }
82598
82599 #ifndef SQLITE_OMIT_UTF16
82600 /*
82601 ** Register a collation sequence factory callback with the database handle
82602 ** db. Replace any previously installed collation sequence factory.
82603 */
82604 SQLITE_API int sqlite3_collation_needed16(
82605   sqlite3 *db, 
82606   void *pCollNeededArg, 
82607   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
82608 ){
82609   sqlite3_mutex_enter(db->mutex);
82610   db->xCollNeeded = 0;
82611   db->xCollNeeded16 = xCollNeeded16;
82612   db->pCollNeededArg = pCollNeededArg;
82613   sqlite3_mutex_leave(db->mutex);
82614   return SQLITE_OK;
82615 }
82616 #endif /* SQLITE_OMIT_UTF16 */
82617
82618 #ifndef SQLITE_OMIT_GLOBALRECOVER
82619 /*
82620 ** This function is now an anachronism. It used to be used to recover from a
82621 ** malloc() failure, but SQLite now does this automatically.
82622 */
82623 SQLITE_API int sqlite3_global_recover(void){
82624   return SQLITE_OK;
82625 }
82626 #endif
82627
82628 /*
82629 ** Test to see whether or not the database connection is in autocommit
82630 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
82631 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
82632 ** by the next COMMIT or ROLLBACK.
82633 **
82634 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
82635 */
82636 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
82637   return db->autoCommit;
82638 }
82639
82640 #ifdef SQLITE_DEBUG
82641 /*
82642 ** The following routine is subtituted for constant SQLITE_CORRUPT in
82643 ** debugging builds.  This provides a way to set a breakpoint for when
82644 ** corruption is first detected.
82645 */
82646 SQLITE_PRIVATE int sqlite3Corrupt(void){
82647   return SQLITE_CORRUPT;
82648 }
82649 #endif
82650
82651 /*
82652 ** This is a convenience routine that makes sure that all thread-specific
82653 ** data for this thread has been deallocated.
82654 **
82655 ** SQLite no longer uses thread-specific data so this routine is now a
82656 ** no-op.  It is retained for historical compatibility.
82657 */
82658 SQLITE_API void sqlite3_thread_cleanup(void){
82659 }
82660
82661 /*
82662 ** Return meta information about a specific column of a database table.
82663 ** See comment in sqlite3.h (sqlite.h.in) for details.
82664 */
82665 #ifdef SQLITE_ENABLE_COLUMN_METADATA
82666 SQLITE_API int sqlite3_table_column_metadata(
82667   sqlite3 *db,                /* Connection handle */
82668   const char *zDbName,        /* Database name or NULL */
82669   const char *zTableName,     /* Table name */
82670   const char *zColumnName,    /* Column name */
82671   char const **pzDataType,    /* OUTPUT: Declared data type */
82672   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
82673   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
82674   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
82675   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
82676 ){
82677   int rc;
82678   char *zErrMsg = 0;
82679   Table *pTab = 0;
82680   Column *pCol = 0;
82681   int iCol;
82682
82683   char const *zDataType = 0;
82684   char const *zCollSeq = 0;
82685   int notnull = 0;
82686   int primarykey = 0;
82687   int autoinc = 0;
82688
82689   /* Ensure the database schema has been loaded */
82690   sqlite3_mutex_enter(db->mutex);
82691   (void)sqlite3SafetyOn(db);
82692   sqlite3BtreeEnterAll(db);
82693   rc = sqlite3Init(db, &zErrMsg);
82694   sqlite3BtreeLeaveAll(db);
82695   if( SQLITE_OK!=rc ){
82696     goto error_out;
82697   }
82698
82699   /* Locate the table in question */
82700   pTab = sqlite3FindTable(db, zTableName, zDbName);
82701   if( !pTab || pTab->pSelect ){
82702     pTab = 0;
82703     goto error_out;
82704   }
82705
82706   /* Find the column for which info is requested */
82707   if( sqlite3IsRowid(zColumnName) ){
82708     iCol = pTab->iPKey;
82709     if( iCol>=0 ){
82710       pCol = &pTab->aCol[iCol];
82711     }
82712   }else{
82713     for(iCol=0; iCol<pTab->nCol; iCol++){
82714       pCol = &pTab->aCol[iCol];
82715       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
82716         break;
82717       }
82718     }
82719     if( iCol==pTab->nCol ){
82720       pTab = 0;
82721       goto error_out;
82722     }
82723   }
82724
82725   /* The following block stores the meta information that will be returned
82726   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
82727   ** and autoinc. At this point there are two possibilities:
82728   ** 
82729   **     1. The specified column name was rowid", "oid" or "_rowid_" 
82730   **        and there is no explicitly declared IPK column. 
82731   **
82732   **     2. The table is not a view and the column name identified an 
82733   **        explicitly declared column. Copy meta information from *pCol.
82734   */ 
82735   if( pCol ){
82736     zDataType = pCol->zType;
82737     zCollSeq = pCol->zColl;
82738     notnull = pCol->notNull!=0;
82739     primarykey  = pCol->isPrimKey!=0;
82740     autoinc = pTab->iPKey==iCol && pTab->autoInc;
82741   }else{
82742     zDataType = "INTEGER";
82743     primarykey = 1;
82744   }
82745   if( !zCollSeq ){
82746     zCollSeq = "BINARY";
82747   }
82748
82749 error_out:
82750   (void)sqlite3SafetyOff(db);
82751
82752   /* Whether the function call succeeded or failed, set the output parameters
82753   ** to whatever their local counterparts contain. If an error did occur,
82754   ** this has the effect of zeroing all output parameters.
82755   */
82756   if( pzDataType ) *pzDataType = zDataType;
82757   if( pzCollSeq ) *pzCollSeq = zCollSeq;
82758   if( pNotNull ) *pNotNull = notnull;
82759   if( pPrimaryKey ) *pPrimaryKey = primarykey;
82760   if( pAutoinc ) *pAutoinc = autoinc;
82761
82762   if( SQLITE_OK==rc && !pTab ){
82763     sqlite3DbFree(db, zErrMsg);
82764     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
82765         zColumnName);
82766     rc = SQLITE_ERROR;
82767   }
82768   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
82769   sqlite3DbFree(db, zErrMsg);
82770   rc = sqlite3ApiExit(db, rc);
82771   sqlite3_mutex_leave(db->mutex);
82772   return rc;
82773 }
82774 #endif
82775
82776 /*
82777 ** Sleep for a little while.  Return the amount of time slept.
82778 */
82779 SQLITE_API int sqlite3_sleep(int ms){
82780   sqlite3_vfs *pVfs;
82781   int rc;
82782   pVfs = sqlite3_vfs_find(0);
82783   if( pVfs==0 ) return 0;
82784
82785   /* This function works in milliseconds, but the underlying OsSleep() 
82786   ** API uses microseconds. Hence the 1000's.
82787   */
82788   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
82789   return rc;
82790 }
82791
82792 /*
82793 ** Enable or disable the extended result codes.
82794 */
82795 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
82796   sqlite3_mutex_enter(db->mutex);
82797   db->errMask = onoff ? 0xffffffff : 0xff;
82798   sqlite3_mutex_leave(db->mutex);
82799   return SQLITE_OK;
82800 }
82801
82802 /*
82803 ** Invoke the xFileControl method on a particular database.
82804 */
82805 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
82806   int rc = SQLITE_ERROR;
82807   int iDb;
82808   sqlite3_mutex_enter(db->mutex);
82809   if( zDbName==0 ){
82810     iDb = 0;
82811   }else{
82812     for(iDb=0; iDb<db->nDb; iDb++){
82813       if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
82814     }
82815   }
82816   if( iDb<db->nDb ){
82817     Btree *pBtree = db->aDb[iDb].pBt;
82818     if( pBtree ){
82819       Pager *pPager;
82820       sqlite3_file *fd;
82821       sqlite3BtreeEnter(pBtree);
82822       pPager = sqlite3BtreePager(pBtree);
82823       assert( pPager!=0 );
82824       fd = sqlite3PagerFile(pPager);
82825       assert( fd!=0 );
82826       if( fd->pMethods ){
82827         rc = sqlite3OsFileControl(fd, op, pArg);
82828       }
82829       sqlite3BtreeLeave(pBtree);
82830     }
82831   }
82832   sqlite3_mutex_leave(db->mutex);
82833   return rc;   
82834 }
82835
82836 /*
82837 ** Interface to the testing logic.
82838 */
82839 SQLITE_API int sqlite3_test_control(int op, ...){
82840   int rc = 0;
82841 #ifndef SQLITE_OMIT_BUILTIN_TEST
82842   va_list ap;
82843   va_start(ap, op);
82844   switch( op ){
82845
82846     /*
82847     ** Save the current state of the PRNG.
82848     */
82849     case SQLITE_TESTCTRL_PRNG_SAVE: {
82850       sqlite3PrngSaveState();
82851       break;
82852     }
82853
82854     /*
82855     ** Restore the state of the PRNG to the last state saved using
82856     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
82857     ** this verb acts like PRNG_RESET.
82858     */
82859     case SQLITE_TESTCTRL_PRNG_RESTORE: {
82860       sqlite3PrngRestoreState();
82861       break;
82862     }
82863
82864     /*
82865     ** Reset the PRNG back to its uninitialized state.  The next call
82866     ** to sqlite3_randomness() will reseed the PRNG using a single call
82867     ** to the xRandomness method of the default VFS.
82868     */
82869     case SQLITE_TESTCTRL_PRNG_RESET: {
82870       sqlite3PrngResetState();
82871       break;
82872     }
82873
82874     /*
82875     **  sqlite3_test_control(BITVEC_TEST, size, program)
82876     **
82877     ** Run a test against a Bitvec object of size.  The program argument
82878     ** is an array of integers that defines the test.  Return -1 on a
82879     ** memory allocation error, 0 on success, or non-zero for an error.
82880     ** See the sqlite3BitvecBuiltinTest() for additional information.
82881     */
82882     case SQLITE_TESTCTRL_BITVEC_TEST: {
82883       int sz = va_arg(ap, int);
82884       int *aProg = va_arg(ap, int*);
82885       rc = sqlite3BitvecBuiltinTest(sz, aProg);
82886       break;
82887     }
82888
82889     /*
82890     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
82891     **
82892     ** Register hooks to call to indicate which malloc() failures 
82893     ** are benign.
82894     */
82895     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
82896       typedef void (*void_function)(void);
82897       void_function xBenignBegin;
82898       void_function xBenignEnd;
82899       xBenignBegin = va_arg(ap, void_function);
82900       xBenignEnd = va_arg(ap, void_function);
82901       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
82902       break;
82903     }
82904   }
82905   va_end(ap);
82906 #endif /* SQLITE_OMIT_BUILTIN_TEST */
82907   return rc;
82908 }
82909
82910 /************** End of main.c ************************************************/
82911 /************** Begin file fts3.c ********************************************/
82912 /*
82913 ** 2006 Oct 10
82914 **
82915 ** The author disclaims copyright to this source code.  In place of
82916 ** a legal notice, here is a blessing:
82917 **
82918 **    May you do good and not evil.
82919 **    May you find forgiveness for yourself and forgive others.
82920 **    May you share freely, never taking more than you give.
82921 **
82922 ******************************************************************************
82923 **
82924 ** This is an SQLite module implementing full-text search.
82925 */
82926
82927 /*
82928 ** The code in this file is only compiled if:
82929 **
82930 **     * The FTS3 module is being built as an extension
82931 **       (in which case SQLITE_CORE is not defined), or
82932 **
82933 **     * The FTS3 module is being built into the core of
82934 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
82935 */
82936
82937 /* TODO(shess) Consider exporting this comment to an HTML file or the
82938 ** wiki.
82939 */
82940 /* The full-text index is stored in a series of b+tree (-like)
82941 ** structures called segments which map terms to doclists.  The
82942 ** structures are like b+trees in layout, but are constructed from the
82943 ** bottom up in optimal fashion and are not updatable.  Since trees
82944 ** are built from the bottom up, things will be described from the
82945 ** bottom up.
82946 **
82947 **
82948 **** Varints ****
82949 ** The basic unit of encoding is a variable-length integer called a
82950 ** varint.  We encode variable-length integers in little-endian order
82951 ** using seven bits * per byte as follows:
82952 **
82953 ** KEY:
82954 **         A = 0xxxxxxx    7 bits of data and one flag bit
82955 **         B = 1xxxxxxx    7 bits of data and one flag bit
82956 **
82957 **  7 bits - A
82958 ** 14 bits - BA
82959 ** 21 bits - BBA
82960 ** and so on.
82961 **
82962 ** This is identical to how sqlite encodes varints (see util.c).
82963 **
82964 **
82965 **** Document lists ****
82966 ** A doclist (document list) holds a docid-sorted list of hits for a
82967 ** given term.  Doclists hold docids, and can optionally associate
82968 ** token positions and offsets with docids.
82969 **
82970 ** A DL_POSITIONS_OFFSETS doclist is stored like this:
82971 **
82972 ** array {
82973 **   varint docid;
82974 **   array {                (position list for column 0)
82975 **     varint position;     (delta from previous position plus POS_BASE)
82976 **     varint startOffset;  (delta from previous startOffset)
82977 **     varint endOffset;    (delta from startOffset)
82978 **   }
82979 **   array {
82980 **     varint POS_COLUMN;   (marks start of position list for new column)
82981 **     varint column;       (index of new column)
82982 **     array {
82983 **       varint position;   (delta from previous position plus POS_BASE)
82984 **       varint startOffset;(delta from previous startOffset)
82985 **       varint endOffset;  (delta from startOffset)
82986 **     }
82987 **   }
82988 **   varint POS_END;        (marks end of positions for this document.
82989 ** }
82990 **
82991 ** Here, array { X } means zero or more occurrences of X, adjacent in
82992 ** memory.  A "position" is an index of a token in the token stream
82993 ** generated by the tokenizer, while an "offset" is a byte offset,
82994 ** both based at 0.  Note that POS_END and POS_COLUMN occur in the
82995 ** same logical place as the position element, and act as sentinals
82996 ** ending a position list array.
82997 **
82998 ** A DL_POSITIONS doclist omits the startOffset and endOffset
82999 ** information.  A DL_DOCIDS doclist omits both the position and
83000 ** offset information, becoming an array of varint-encoded docids.
83001 **
83002 ** On-disk data is stored as type DL_DEFAULT, so we don't serialize
83003 ** the type.  Due to how deletion is implemented in the segmentation
83004 ** system, on-disk doclists MUST store at least positions.
83005 **
83006 **
83007 **** Segment leaf nodes ****
83008 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
83009 ** nodes are written using LeafWriter, and read using LeafReader (to
83010 ** iterate through a single leaf node's data) and LeavesReader (to
83011 ** iterate through a segment's entire leaf layer).  Leaf nodes have
83012 ** the format:
83013 **
83014 ** varint iHeight;             (height from leaf level, always 0)
83015 ** varint nTerm;               (length of first term)
83016 ** char pTerm[nTerm];          (content of first term)
83017 ** varint nDoclist;            (length of term's associated doclist)
83018 ** char pDoclist[nDoclist];    (content of doclist)
83019 ** array {
83020 **                             (further terms are delta-encoded)
83021 **   varint nPrefix;           (length of prefix shared with previous term)
83022 **   varint nSuffix;           (length of unshared suffix)
83023 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
83024 **   varint nDoclist;          (length of term's associated doclist)
83025 **   char pDoclist[nDoclist];  (content of doclist)
83026 ** }
83027 **
83028 ** Here, array { X } means zero or more occurrences of X, adjacent in
83029 ** memory.
83030 **
83031 ** Leaf nodes are broken into blocks which are stored contiguously in
83032 ** the %_segments table in sorted order.  This means that when the end
83033 ** of a node is reached, the next term is in the node with the next
83034 ** greater node id.
83035 **
83036 ** New data is spilled to a new leaf node when the current node
83037 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
83038 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
83039 ** node (a leaf node with a single term and doclist).  The goal of
83040 ** these settings is to pack together groups of small doclists while
83041 ** making it efficient to directly access large doclists.  The
83042 ** assumption is that large doclists represent terms which are more
83043 ** likely to be query targets.
83044 **
83045 ** TODO(shess) It may be useful for blocking decisions to be more
83046 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
83047 ** node rather than splitting into 2k and .5k nodes.  My intuition is
83048 ** that this might extend through 2x or 4x the pagesize.
83049 **
83050 **
83051 **** Segment interior nodes ****
83052 ** Segment interior nodes store blockids for subtree nodes and terms
83053 ** to describe what data is stored by the each subtree.  Interior
83054 ** nodes are written using InteriorWriter, and read using
83055 ** InteriorReader.  InteriorWriters are created as needed when
83056 ** SegmentWriter creates new leaf nodes, or when an interior node
83057 ** itself grows too big and must be split.  The format of interior
83058 ** nodes:
83059 **
83060 ** varint iHeight;           (height from leaf level, always >0)
83061 ** varint iBlockid;          (block id of node's leftmost subtree)
83062 ** optional {
83063 **   varint nTerm;           (length of first term)
83064 **   char pTerm[nTerm];      (content of first term)
83065 **   array {
83066 **                                (further terms are delta-encoded)
83067 **     varint nPrefix;            (length of shared prefix with previous term)
83068 **     varint nSuffix;            (length of unshared suffix)
83069 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
83070 **   }
83071 ** }
83072 **
83073 ** Here, optional { X } means an optional element, while array { X }
83074 ** means zero or more occurrences of X, adjacent in memory.
83075 **
83076 ** An interior node encodes n terms separating n+1 subtrees.  The
83077 ** subtree blocks are contiguous, so only the first subtree's blockid
83078 ** is encoded.  The subtree at iBlockid will contain all terms less
83079 ** than the first term encoded (or all terms if no term is encoded).
83080 ** Otherwise, for terms greater than or equal to pTerm[i] but less
83081 ** than pTerm[i+1], the subtree for that term will be rooted at
83082 ** iBlockid+i.  Interior nodes only store enough term data to
83083 ** distinguish adjacent children (if the rightmost term of the left
83084 ** child is "something", and the leftmost term of the right child is
83085 ** "wicked", only "w" is stored).
83086 **
83087 ** New data is spilled to a new interior node at the same height when
83088 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
83089 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
83090 ** interior nodes and making the tree too skinny.  The interior nodes
83091 ** at a given height are naturally tracked by interior nodes at
83092 ** height+1, and so on.
83093 **
83094 **
83095 **** Segment directory ****
83096 ** The segment directory in table %_segdir stores meta-information for
83097 ** merging and deleting segments, and also the root node of the
83098 ** segment's tree.
83099 **
83100 ** The root node is the top node of the segment's tree after encoding
83101 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
83102 ** This could be either a leaf node or an interior node.  If the top
83103 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
83104 ** and a new root interior node is generated (which should always fit
83105 ** within ROOT_MAX because it only needs space for 2 varints, the
83106 ** height and the blockid of the previous root).
83107 **
83108 ** The meta-information in the segment directory is:
83109 **   level               - segment level (see below)
83110 **   idx                 - index within level
83111 **                       - (level,idx uniquely identify a segment)
83112 **   start_block         - first leaf node
83113 **   leaves_end_block    - last leaf node
83114 **   end_block           - last block (including interior nodes)
83115 **   root                - contents of root node
83116 **
83117 ** If the root node is a leaf node, then start_block,
83118 ** leaves_end_block, and end_block are all 0.
83119 **
83120 **
83121 **** Segment merging ****
83122 ** To amortize update costs, segments are groups into levels and
83123 ** merged in matches.  Each increase in level represents exponentially
83124 ** more documents.
83125 **
83126 ** New documents (actually, document updates) are tokenized and
83127 ** written individually (using LeafWriter) to a level 0 segment, with
83128 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
83129 ** level 0 segments are merged into a single level 1 segment.  Level 1
83130 ** is populated like level 0, and eventually MERGE_COUNT level 1
83131 ** segments are merged to a single level 2 segment (representing
83132 ** MERGE_COUNT^2 updates), and so on.
83133 **
83134 ** A segment merge traverses all segments at a given level in
83135 ** parallel, performing a straightforward sorted merge.  Since segment
83136 ** leaf nodes are written in to the %_segments table in order, this
83137 ** merge traverses the underlying sqlite disk structures efficiently.
83138 ** After the merge, all segment blocks from the merged level are
83139 ** deleted.
83140 **
83141 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
83142 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
83143 ** very similar performance numbers to 16 on insertion, though they're
83144 ** a tiny bit slower (perhaps due to more overhead in merge-time
83145 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
83146 ** 16, 2 about 66% slower than 16.
83147 **
83148 ** At query time, high MERGE_COUNT increases the number of segments
83149 ** which need to be scanned and merged.  For instance, with 100k docs
83150 ** inserted:
83151 **
83152 **    MERGE_COUNT   segments
83153 **       16           25
83154 **        8           12
83155 **        4           10
83156 **        2            6
83157 **
83158 ** This appears to have only a moderate impact on queries for very
83159 ** frequent terms (which are somewhat dominated by segment merge
83160 ** costs), and infrequent and non-existent terms still seem to be fast
83161 ** even with many segments.
83162 **
83163 ** TODO(shess) That said, it would be nice to have a better query-side
83164 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
83165 ** optimizations to things like doclist merging will swing the sweet
83166 ** spot around.
83167 **
83168 **
83169 **
83170 **** Handling of deletions and updates ****
83171 ** Since we're using a segmented structure, with no docid-oriented
83172 ** index into the term index, we clearly cannot simply update the term
83173 ** index when a document is deleted or updated.  For deletions, we
83174 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
83175 ** we simply write the new doclist.  Segment merges overwrite older
83176 ** data for a particular docid with newer data, so deletes or updates
83177 ** will eventually overtake the earlier data and knock it out.  The
83178 ** query logic likewise merges doclists so that newer data knocks out
83179 ** older data.
83180 **
83181 ** TODO(shess) Provide a VACUUM type operation to clear out all
83182 ** deletions and duplications.  This would basically be a forced merge
83183 ** into a single segment.
83184 */
83185
83186 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
83187
83188 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
83189 # define SQLITE_CORE 1
83190 #endif
83191
83192
83193 /************** Include fts3_hash.h in the middle of fts3.c ******************/
83194 /************** Begin file fts3_hash.h ***************************************/
83195 /*
83196 ** 2001 September 22
83197 **
83198 ** The author disclaims copyright to this source code.  In place of
83199 ** a legal notice, here is a blessing:
83200 **
83201 **    May you do good and not evil.
83202 **    May you find forgiveness for yourself and forgive others.
83203 **    May you share freely, never taking more than you give.
83204 **
83205 *************************************************************************
83206 ** This is the header file for the generic hash-table implemenation
83207 ** used in SQLite.  We've modified it slightly to serve as a standalone
83208 ** hash table implementation for the full-text indexing module.
83209 **
83210 */
83211 #ifndef _FTS3_HASH_H_
83212 #define _FTS3_HASH_H_
83213
83214 /* Forward declarations of structures. */
83215 typedef struct fts3Hash fts3Hash;
83216 typedef struct fts3HashElem fts3HashElem;
83217
83218 /* A complete hash table is an instance of the following structure.
83219 ** The internals of this structure are intended to be opaque -- client
83220 ** code should not attempt to access or modify the fields of this structure
83221 ** directly.  Change this structure only by using the routines below.
83222 ** However, many of the "procedures" and "functions" for modifying and
83223 ** accessing this structure are really macros, so we can't really make
83224 ** this structure opaque.
83225 */
83226 struct fts3Hash {
83227   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
83228   char copyKey;           /* True if copy of key made on insert */
83229   int count;              /* Number of entries in this table */
83230   fts3HashElem *first;    /* The first element of the array */
83231   int htsize;             /* Number of buckets in the hash table */
83232   struct _fts3ht {        /* the hash table */
83233     int count;               /* Number of entries with this hash */
83234     fts3HashElem *chain;     /* Pointer to first entry with this hash */
83235   } *ht;
83236 };
83237
83238 /* Each element in the hash table is an instance of the following 
83239 ** structure.  All elements are stored on a single doubly-linked list.
83240 **
83241 ** Again, this structure is intended to be opaque, but it can't really
83242 ** be opaque because it is used by macros.
83243 */
83244 struct fts3HashElem {
83245   fts3HashElem *next, *prev; /* Next and previous elements in the table */
83246   void *data;                /* Data associated with this element */
83247   void *pKey; int nKey;      /* Key associated with this element */
83248 };
83249
83250 /*
83251 ** There are 2 different modes of operation for a hash table:
83252 **
83253 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
83254 **                           (including the null-terminator, if any).  Case
83255 **                           is respected in comparisons.
83256 **
83257 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
83258 **                           memcmp() is used to compare keys.
83259 **
83260 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
83261 */
83262 #define FTS3_HASH_STRING    1
83263 #define FTS3_HASH_BINARY    2
83264
83265 /*
83266 ** Access routines.  To delete, insert a NULL pointer.
83267 */
83268 SQLITE_PRIVATE void sqlite3Fts3HashInit(fts3Hash*, int keytype, int copyKey);
83269 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(fts3Hash*, const void *pKey, int nKey, void *pData);
83270 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const fts3Hash*, const void *pKey, int nKey);
83271 SQLITE_PRIVATE void sqlite3Fts3HashClear(fts3Hash*);
83272
83273 /*
83274 ** Shorthand for the functions above
83275 */
83276 #define fts3HashInit   sqlite3Fts3HashInit
83277 #define fts3HashInsert sqlite3Fts3HashInsert
83278 #define fts3HashFind   sqlite3Fts3HashFind
83279 #define fts3HashClear  sqlite3Fts3HashClear
83280
83281 /*
83282 ** Macros for looping over all elements of a hash table.  The idiom is
83283 ** like this:
83284 **
83285 **   fts3Hash h;
83286 **   fts3HashElem *p;
83287 **   ...
83288 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
83289 **     SomeStructure *pData = fts3HashData(p);
83290 **     // do something with pData
83291 **   }
83292 */
83293 #define fts3HashFirst(H)  ((H)->first)
83294 #define fts3HashNext(E)   ((E)->next)
83295 #define fts3HashData(E)   ((E)->data)
83296 #define fts3HashKey(E)    ((E)->pKey)
83297 #define fts3HashKeysize(E) ((E)->nKey)
83298
83299 /*
83300 ** Number of entries in a hash table
83301 */
83302 #define fts3HashCount(H)  ((H)->count)
83303
83304 #endif /* _FTS3_HASH_H_ */
83305
83306 /************** End of fts3_hash.h *******************************************/
83307 /************** Continuing where we left off in fts3.c ***********************/
83308 /************** Include fts3_tokenizer.h in the middle of fts3.c *************/
83309 /************** Begin file fts3_tokenizer.h **********************************/
83310 /*
83311 ** 2006 July 10
83312 **
83313 ** The author disclaims copyright to this source code.
83314 **
83315 *************************************************************************
83316 ** Defines the interface to tokenizers used by fulltext-search.  There
83317 ** are three basic components:
83318 **
83319 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
83320 ** interface functions.  This is essentially the class structure for
83321 ** tokenizers.
83322 **
83323 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
83324 ** including customization information defined at creation time.
83325 **
83326 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
83327 ** tokens from a particular input.
83328 */
83329 #ifndef _FTS3_TOKENIZER_H_
83330 #define _FTS3_TOKENIZER_H_
83331
83332 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
83333 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
83334 ** we will need a way to register the API consistently.
83335 */
83336
83337 /*
83338 ** Structures used by the tokenizer interface. When a new tokenizer
83339 ** implementation is registered, the caller provides a pointer to
83340 ** an sqlite3_tokenizer_module containing pointers to the callback
83341 ** functions that make up an implementation.
83342 **
83343 ** When an fts3 table is created, it passes any arguments passed to
83344 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
83345 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
83346 ** implementation. The xCreate() function in turn returns an 
83347 ** sqlite3_tokenizer structure representing the specific tokenizer to
83348 ** be used for the fts3 table (customized by the tokenizer clause arguments).
83349 **
83350 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
83351 ** method is called. It returns an sqlite3_tokenizer_cursor object
83352 ** that may be used to tokenize a specific input buffer based on
83353 ** the tokenization rules supplied by a specific sqlite3_tokenizer
83354 ** object.
83355 */
83356 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
83357 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
83358 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
83359
83360 struct sqlite3_tokenizer_module {
83361
83362   /*
83363   ** Structure version. Should always be set to 0.
83364   */
83365   int iVersion;
83366
83367   /*
83368   ** Create a new tokenizer. The values in the argv[] array are the
83369   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
83370   ** TABLE statement that created the fts3 table. For example, if
83371   ** the following SQL is executed:
83372   **
83373   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
83374   **
83375   ** then argc is set to 2, and the argv[] array contains pointers
83376   ** to the strings "arg1" and "arg2".
83377   **
83378   ** This method should return either SQLITE_OK (0), or an SQLite error 
83379   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
83380   ** to point at the newly created tokenizer structure. The generic
83381   ** sqlite3_tokenizer.pModule variable should not be initialised by
83382   ** this callback. The caller will do so.
83383   */
83384   int (*xCreate)(
83385     int argc,                           /* Size of argv array */
83386     const char *const*argv,             /* Tokenizer argument strings */
83387     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
83388   );
83389
83390   /*
83391   ** Destroy an existing tokenizer. The fts3 module calls this method
83392   ** exactly once for each successful call to xCreate().
83393   */
83394   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
83395
83396   /*
83397   ** Create a tokenizer cursor to tokenize an input buffer. The caller
83398   ** is responsible for ensuring that the input buffer remains valid
83399   ** until the cursor is closed (using the xClose() method). 
83400   */
83401   int (*xOpen)(
83402     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
83403     const char *pInput, int nBytes,      /* Input buffer */
83404     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
83405   );
83406
83407   /*
83408   ** Destroy an existing tokenizer cursor. The fts3 module calls this 
83409   ** method exactly once for each successful call to xOpen().
83410   */
83411   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
83412
83413   /*
83414   ** Retrieve the next token from the tokenizer cursor pCursor. This
83415   ** method should either return SQLITE_OK and set the values of the
83416   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
83417   ** the end of the buffer has been reached, or an SQLite error code.
83418   **
83419   ** *ppToken should be set to point at a buffer containing the 
83420   ** normalized version of the token (i.e. after any case-folding and/or
83421   ** stemming has been performed). *pnBytes should be set to the length
83422   ** of this buffer in bytes. The input text that generated the token is
83423   ** identified by the byte offsets returned in *piStartOffset and
83424   ** *piEndOffset.
83425   **
83426   ** The buffer *ppToken is set to point at is managed by the tokenizer
83427   ** implementation. It is only required to be valid until the next call
83428   ** to xNext() or xClose(). 
83429   */
83430   /* TODO(shess) current implementation requires pInput to be
83431   ** nul-terminated.  This should either be fixed, or pInput/nBytes
83432   ** should be converted to zInput.
83433   */
83434   int (*xNext)(
83435     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
83436     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
83437     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
83438     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
83439     int *piPosition      /* OUT: Number of tokens returned before this one */
83440   );
83441 };
83442
83443 struct sqlite3_tokenizer {
83444   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
83445   /* Tokenizer implementations will typically add additional fields */
83446 };
83447
83448 struct sqlite3_tokenizer_cursor {
83449   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
83450   /* Tokenizer implementations will typically add additional fields */
83451 };
83452
83453 #endif /* _FTS3_TOKENIZER_H_ */
83454
83455 /************** End of fts3_tokenizer.h **************************************/
83456 /************** Continuing where we left off in fts3.c ***********************/
83457 #ifndef SQLITE_CORE 
83458   SQLITE_EXTENSION_INIT1
83459 #endif
83460
83461
83462 /* TODO(shess) MAN, this thing needs some refactoring.  At minimum, it
83463 ** would be nice to order the file better, perhaps something along the
83464 ** lines of:
83465 **
83466 **  - utility functions
83467 **  - table setup functions
83468 **  - table update functions
83469 **  - table query functions
83470 **
83471 ** Put the query functions last because they're likely to reference
83472 ** typedefs or functions from the table update section.
83473 */
83474
83475 #if 0
83476 # define FTSTRACE(A)  printf A; fflush(stdout)
83477 #else
83478 # define FTSTRACE(A)
83479 #endif
83480
83481 /*
83482 ** Default span for NEAR operators.
83483 */
83484 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
83485
83486 /* It is not safe to call isspace(), tolower(), or isalnum() on
83487 ** hi-bit-set characters.  This is the same solution used in the
83488 ** tokenizer.
83489 */
83490 /* TODO(shess) The snippet-generation code should be using the
83491 ** tokenizer-generated tokens rather than doing its own local
83492 ** tokenization.
83493 */
83494 /* TODO(shess) Is __isascii() a portable version of (c&0x80)==0? */
83495 static int safe_isspace(char c){
83496   return (c&0x80)==0 ? isspace(c) : 0;
83497 }
83498 static int safe_tolower(char c){
83499   return (c&0x80)==0 ? tolower(c) : c;
83500 }
83501 static int safe_isalnum(char c){
83502   return (c&0x80)==0 ? isalnum(c) : 0;
83503 }
83504
83505 typedef enum DocListType {
83506   DL_DOCIDS,              /* docids only */
83507   DL_POSITIONS,           /* docids + positions */
83508   DL_POSITIONS_OFFSETS    /* docids + positions + offsets */
83509 } DocListType;
83510
83511 /*
83512 ** By default, only positions and not offsets are stored in the doclists.
83513 ** To change this so that offsets are stored too, compile with
83514 **
83515 **          -DDL_DEFAULT=DL_POSITIONS_OFFSETS
83516 **
83517 ** If DL_DEFAULT is set to DL_DOCIDS, your table can only be inserted
83518 ** into (no deletes or updates).
83519 */
83520 #ifndef DL_DEFAULT
83521 # define DL_DEFAULT DL_POSITIONS
83522 #endif
83523
83524 enum {
83525   POS_END = 0,        /* end of this position list */
83526   POS_COLUMN,         /* followed by new column number */
83527   POS_BASE
83528 };
83529
83530 /* MERGE_COUNT controls how often we merge segments (see comment at
83531 ** top of file).
83532 */
83533 #define MERGE_COUNT 16
83534
83535 /* utility functions */
83536
83537 /* CLEAR() and SCRAMBLE() abstract memset() on a pointer to a single
83538 ** record to prevent errors of the form:
83539 **
83540 ** my_function(SomeType *b){
83541 **   memset(b, '\0', sizeof(b));  // sizeof(b)!=sizeof(*b)
83542 ** }
83543 */
83544 /* TODO(shess) Obvious candidates for a header file. */
83545 #define CLEAR(b) memset(b, '\0', sizeof(*(b)))
83546
83547 #ifndef NDEBUG
83548 #  define SCRAMBLE(b) memset(b, 0x55, sizeof(*(b)))
83549 #else
83550 #  define SCRAMBLE(b)
83551 #endif
83552
83553 /* We may need up to VARINT_MAX bytes to store an encoded 64-bit integer. */
83554 #define VARINT_MAX 10
83555
83556 /* Write a 64-bit variable-length integer to memory starting at p[0].
83557  * The length of data written will be between 1 and VARINT_MAX bytes.
83558  * The number of bytes written is returned. */
83559 static int fts3PutVarint(char *p, sqlite_int64 v){
83560   unsigned char *q = (unsigned char *) p;
83561   sqlite_uint64 vu = v;
83562   do{
83563     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
83564     vu >>= 7;
83565   }while( vu!=0 );
83566   q[-1] &= 0x7f;  /* turn off high bit in final byte */
83567   assert( q - (unsigned char *)p <= VARINT_MAX );
83568   return (int) (q - (unsigned char *)p);
83569 }
83570
83571 /* Read a 64-bit variable-length integer from memory starting at p[0].
83572  * Return the number of bytes read, or 0 on error.
83573  * The value is stored in *v. */
83574 static int fts3GetVarint(const char *p, sqlite_int64 *v){
83575   const unsigned char *q = (const unsigned char *) p;
83576   sqlite_uint64 x = 0, y = 1;
83577   while( (*q & 0x80) == 0x80 ){
83578     x += y * (*q++ & 0x7f);
83579     y <<= 7;
83580     if( q - (unsigned char *)p >= VARINT_MAX ){  /* bad data */
83581       assert( 0 );
83582       return 0;
83583     }
83584   }
83585   x += y * (*q++);
83586   *v = (sqlite_int64) x;
83587   return (int) (q - (unsigned char *)p);
83588 }
83589
83590 static int fts3GetVarint32(const char *p, int *pi){
83591  sqlite_int64 i;
83592  int ret = fts3GetVarint(p, &i);
83593  *pi = (int) i;
83594  assert( *pi==i );
83595  return ret;
83596 }
83597
83598 /*******************************************************************/
83599 /* DataBuffer is used to collect data into a buffer in piecemeal
83600 ** fashion.  It implements the usual distinction between amount of
83601 ** data currently stored (nData) and buffer capacity (nCapacity).
83602 **
83603 ** dataBufferInit - create a buffer with given initial capacity.
83604 ** dataBufferReset - forget buffer's data, retaining capacity.
83605 ** dataBufferDestroy - free buffer's data.
83606 ** dataBufferSwap - swap contents of two buffers.
83607 ** dataBufferExpand - expand capacity without adding data.
83608 ** dataBufferAppend - append data.
83609 ** dataBufferAppend2 - append two pieces of data at once.
83610 ** dataBufferReplace - replace buffer's data.
83611 */
83612 typedef struct DataBuffer {
83613   char *pData;          /* Pointer to malloc'ed buffer. */
83614   int nCapacity;        /* Size of pData buffer. */
83615   int nData;            /* End of data loaded into pData. */
83616 } DataBuffer;
83617
83618 static void dataBufferInit(DataBuffer *pBuffer, int nCapacity){
83619   assert( nCapacity>=0 );
83620   pBuffer->nData = 0;
83621   pBuffer->nCapacity = nCapacity;
83622   pBuffer->pData = nCapacity==0 ? NULL : sqlite3_malloc(nCapacity);
83623 }
83624 static void dataBufferReset(DataBuffer *pBuffer){
83625   pBuffer->nData = 0;
83626 }
83627 static void dataBufferDestroy(DataBuffer *pBuffer){
83628   if( pBuffer->pData!=NULL ) sqlite3_free(pBuffer->pData);
83629   SCRAMBLE(pBuffer);
83630 }
83631 static void dataBufferSwap(DataBuffer *pBuffer1, DataBuffer *pBuffer2){
83632   DataBuffer tmp = *pBuffer1;
83633   *pBuffer1 = *pBuffer2;
83634   *pBuffer2 = tmp;
83635 }
83636 static void dataBufferExpand(DataBuffer *pBuffer, int nAddCapacity){
83637   assert( nAddCapacity>0 );
83638   /* TODO(shess) Consider expanding more aggressively.  Note that the
83639   ** underlying malloc implementation may take care of such things for
83640   ** us already.
83641   */
83642   if( pBuffer->nData+nAddCapacity>pBuffer->nCapacity ){
83643     pBuffer->nCapacity = pBuffer->nData+nAddCapacity;
83644     pBuffer->pData = sqlite3_realloc(pBuffer->pData, pBuffer->nCapacity);
83645   }
83646 }
83647 static void dataBufferAppend(DataBuffer *pBuffer,
83648                              const char *pSource, int nSource){
83649   assert( nSource>0 && pSource!=NULL );
83650   dataBufferExpand(pBuffer, nSource);
83651   memcpy(pBuffer->pData+pBuffer->nData, pSource, nSource);
83652   pBuffer->nData += nSource;
83653 }
83654 static void dataBufferAppend2(DataBuffer *pBuffer,
83655                               const char *pSource1, int nSource1,
83656                               const char *pSource2, int nSource2){
83657   assert( nSource1>0 && pSource1!=NULL );
83658   assert( nSource2>0 && pSource2!=NULL );
83659   dataBufferExpand(pBuffer, nSource1+nSource2);
83660   memcpy(pBuffer->pData+pBuffer->nData, pSource1, nSource1);
83661   memcpy(pBuffer->pData+pBuffer->nData+nSource1, pSource2, nSource2);
83662   pBuffer->nData += nSource1+nSource2;
83663 }
83664 static void dataBufferReplace(DataBuffer *pBuffer,
83665                               const char *pSource, int nSource){
83666   dataBufferReset(pBuffer);
83667   dataBufferAppend(pBuffer, pSource, nSource);
83668 }
83669
83670 /* StringBuffer is a null-terminated version of DataBuffer. */
83671 typedef struct StringBuffer {
83672   DataBuffer b;            /* Includes null terminator. */
83673 } StringBuffer;
83674
83675 static void initStringBuffer(StringBuffer *sb){
83676   dataBufferInit(&sb->b, 100);
83677   dataBufferReplace(&sb->b, "", 1);
83678 }
83679 static int stringBufferLength(StringBuffer *sb){
83680   return sb->b.nData-1;
83681 }
83682 static char *stringBufferData(StringBuffer *sb){
83683   return sb->b.pData;
83684 }
83685 static void stringBufferDestroy(StringBuffer *sb){
83686   dataBufferDestroy(&sb->b);
83687 }
83688
83689 static void nappend(StringBuffer *sb, const char *zFrom, int nFrom){
83690   assert( sb->b.nData>0 );
83691   if( nFrom>0 ){
83692     sb->b.nData--;
83693     dataBufferAppend2(&sb->b, zFrom, nFrom, "", 1);
83694   }
83695 }
83696 static void append(StringBuffer *sb, const char *zFrom){
83697   nappend(sb, zFrom, strlen(zFrom));
83698 }
83699
83700 /* Append a list of strings separated by commas. */
83701 static void appendList(StringBuffer *sb, int nString, char **azString){
83702   int i;
83703   for(i=0; i<nString; ++i){
83704     if( i>0 ) append(sb, ", ");
83705     append(sb, azString[i]);
83706   }
83707 }
83708
83709 static int endsInWhiteSpace(StringBuffer *p){
83710   return stringBufferLength(p)>0 &&
83711     safe_isspace(stringBufferData(p)[stringBufferLength(p)-1]);
83712 }
83713
83714 /* If the StringBuffer ends in something other than white space, add a
83715 ** single space character to the end.
83716 */
83717 static void appendWhiteSpace(StringBuffer *p){
83718   if( stringBufferLength(p)==0 ) return;
83719   if( !endsInWhiteSpace(p) ) append(p, " ");
83720 }
83721
83722 /* Remove white space from the end of the StringBuffer */
83723 static void trimWhiteSpace(StringBuffer *p){
83724   while( endsInWhiteSpace(p) ){
83725     p->b.pData[--p->b.nData-1] = '\0';
83726   }
83727 }
83728
83729 /*******************************************************************/
83730 /* DLReader is used to read document elements from a doclist.  The
83731 ** current docid is cached, so dlrDocid() is fast.  DLReader does not
83732 ** own the doclist buffer.
83733 **
83734 ** dlrAtEnd - true if there's no more data to read.
83735 ** dlrDocid - docid of current document.
83736 ** dlrDocData - doclist data for current document (including docid).
83737 ** dlrDocDataBytes - length of same.
83738 ** dlrAllDataBytes - length of all remaining data.
83739 ** dlrPosData - position data for current document.
83740 ** dlrPosDataLen - length of pos data for current document (incl POS_END).
83741 ** dlrStep - step to current document.
83742 ** dlrInit - initial for doclist of given type against given data.
83743 ** dlrDestroy - clean up.
83744 **
83745 ** Expected usage is something like:
83746 **
83747 **   DLReader reader;
83748 **   dlrInit(&reader, pData, nData);
83749 **   while( !dlrAtEnd(&reader) ){
83750 **     // calls to dlrDocid() and kin.
83751 **     dlrStep(&reader);
83752 **   }
83753 **   dlrDestroy(&reader);
83754 */
83755 typedef struct DLReader {
83756   DocListType iType;
83757   const char *pData;
83758   int nData;
83759
83760   sqlite_int64 iDocid;
83761   int nElement;
83762 } DLReader;
83763
83764 static int dlrAtEnd(DLReader *pReader){
83765   assert( pReader->nData>=0 );
83766   return pReader->nData==0;
83767 }
83768 static sqlite_int64 dlrDocid(DLReader *pReader){
83769   assert( !dlrAtEnd(pReader) );
83770   return pReader->iDocid;
83771 }
83772 static const char *dlrDocData(DLReader *pReader){
83773   assert( !dlrAtEnd(pReader) );
83774   return pReader->pData;
83775 }
83776 static int dlrDocDataBytes(DLReader *pReader){
83777   assert( !dlrAtEnd(pReader) );
83778   return pReader->nElement;
83779 }
83780 static int dlrAllDataBytes(DLReader *pReader){
83781   assert( !dlrAtEnd(pReader) );
83782   return pReader->nData;
83783 }
83784 /* TODO(shess) Consider adding a field to track iDocid varint length
83785 ** to make these two functions faster.  This might matter (a tiny bit)
83786 ** for queries.
83787 */
83788 static const char *dlrPosData(DLReader *pReader){
83789   sqlite_int64 iDummy;
83790   int n = fts3GetVarint(pReader->pData, &iDummy);
83791   assert( !dlrAtEnd(pReader) );
83792   return pReader->pData+n;
83793 }
83794 static int dlrPosDataLen(DLReader *pReader){
83795   sqlite_int64 iDummy;
83796   int n = fts3GetVarint(pReader->pData, &iDummy);
83797   assert( !dlrAtEnd(pReader) );
83798   return pReader->nElement-n;
83799 }
83800 static void dlrStep(DLReader *pReader){
83801   assert( !dlrAtEnd(pReader) );
83802
83803   /* Skip past current doclist element. */
83804   assert( pReader->nElement<=pReader->nData );
83805   pReader->pData += pReader->nElement;
83806   pReader->nData -= pReader->nElement;
83807
83808   /* If there is more data, read the next doclist element. */
83809   if( pReader->nData!=0 ){
83810     sqlite_int64 iDocidDelta;
83811     int iDummy, n = fts3GetVarint(pReader->pData, &iDocidDelta);
83812     pReader->iDocid += iDocidDelta;
83813     if( pReader->iType>=DL_POSITIONS ){
83814       assert( n<pReader->nData );
83815       while( 1 ){
83816         n += fts3GetVarint32(pReader->pData+n, &iDummy);
83817         assert( n<=pReader->nData );
83818         if( iDummy==POS_END ) break;
83819         if( iDummy==POS_COLUMN ){
83820           n += fts3GetVarint32(pReader->pData+n, &iDummy);
83821           assert( n<pReader->nData );
83822         }else if( pReader->iType==DL_POSITIONS_OFFSETS ){
83823           n += fts3GetVarint32(pReader->pData+n, &iDummy);
83824           n += fts3GetVarint32(pReader->pData+n, &iDummy);
83825           assert( n<pReader->nData );
83826         }
83827       }
83828     }
83829     pReader->nElement = n;
83830     assert( pReader->nElement<=pReader->nData );
83831   }
83832 }
83833 static void dlrInit(DLReader *pReader, DocListType iType,
83834                     const char *pData, int nData){
83835   assert( pData!=NULL && nData!=0 );
83836   pReader->iType = iType;
83837   pReader->pData = pData;
83838   pReader->nData = nData;
83839   pReader->nElement = 0;
83840   pReader->iDocid = 0;
83841
83842   /* Load the first element's data.  There must be a first element. */
83843   dlrStep(pReader);
83844 }
83845 static void dlrDestroy(DLReader *pReader){
83846   SCRAMBLE(pReader);
83847 }
83848
83849 #ifndef NDEBUG
83850 /* Verify that the doclist can be validly decoded.  Also returns the
83851 ** last docid found because it is convenient in other assertions for
83852 ** DLWriter.
83853 */
83854 static void docListValidate(DocListType iType, const char *pData, int nData,
83855                             sqlite_int64 *pLastDocid){
83856   sqlite_int64 iPrevDocid = 0;
83857   assert( nData>0 );
83858   assert( pData!=0 );
83859   assert( pData+nData>pData );
83860   while( nData!=0 ){
83861     sqlite_int64 iDocidDelta;
83862     int n = fts3GetVarint(pData, &iDocidDelta);
83863     iPrevDocid += iDocidDelta;
83864     if( iType>DL_DOCIDS ){
83865       int iDummy;
83866       while( 1 ){
83867         n += fts3GetVarint32(pData+n, &iDummy);
83868         if( iDummy==POS_END ) break;
83869         if( iDummy==POS_COLUMN ){
83870           n += fts3GetVarint32(pData+n, &iDummy);
83871         }else if( iType>DL_POSITIONS ){
83872           n += fts3GetVarint32(pData+n, &iDummy);
83873           n += fts3GetVarint32(pData+n, &iDummy);
83874         }
83875         assert( n<=nData );
83876       }
83877     }
83878     assert( n<=nData );
83879     pData += n;
83880     nData -= n;
83881   }
83882   if( pLastDocid ) *pLastDocid = iPrevDocid;
83883 }
83884 #define ASSERT_VALID_DOCLIST(i, p, n, o) docListValidate(i, p, n, o)
83885 #else
83886 #define ASSERT_VALID_DOCLIST(i, p, n, o) assert( 1 )
83887 #endif
83888
83889 /*******************************************************************/
83890 /* DLWriter is used to write doclist data to a DataBuffer.  DLWriter
83891 ** always appends to the buffer and does not own it.
83892 **
83893 ** dlwInit - initialize to write a given type doclistto a buffer.
83894 ** dlwDestroy - clear the writer's memory.  Does not free buffer.
83895 ** dlwAppend - append raw doclist data to buffer.
83896 ** dlwCopy - copy next doclist from reader to writer.
83897 ** dlwAdd - construct doclist element and append to buffer.
83898 **    Only apply dlwAdd() to DL_DOCIDS doclists (else use PLWriter).
83899 */
83900 typedef struct DLWriter {
83901   DocListType iType;
83902   DataBuffer *b;
83903   sqlite_int64 iPrevDocid;
83904 #ifndef NDEBUG
83905   int has_iPrevDocid;
83906 #endif
83907 } DLWriter;
83908
83909 static void dlwInit(DLWriter *pWriter, DocListType iType, DataBuffer *b){
83910   pWriter->b = b;
83911   pWriter->iType = iType;
83912   pWriter->iPrevDocid = 0;
83913 #ifndef NDEBUG
83914   pWriter->has_iPrevDocid = 0;
83915 #endif
83916 }
83917 static void dlwDestroy(DLWriter *pWriter){
83918   SCRAMBLE(pWriter);
83919 }
83920 /* iFirstDocid is the first docid in the doclist in pData.  It is
83921 ** needed because pData may point within a larger doclist, in which
83922 ** case the first item would be delta-encoded.
83923 **
83924 ** iLastDocid is the final docid in the doclist in pData.  It is
83925 ** needed to create the new iPrevDocid for future delta-encoding.  The
83926 ** code could decode the passed doclist to recreate iLastDocid, but
83927 ** the only current user (docListMerge) already has decoded this
83928 ** information.
83929 */
83930 /* TODO(shess) This has become just a helper for docListMerge.
83931 ** Consider a refactor to make this cleaner.
83932 */
83933 static void dlwAppend(DLWriter *pWriter,
83934                       const char *pData, int nData,
83935                       sqlite_int64 iFirstDocid, sqlite_int64 iLastDocid){
83936   sqlite_int64 iDocid = 0;
83937   char c[VARINT_MAX];
83938   int nFirstOld, nFirstNew;     /* Old and new varint len of first docid. */
83939 #ifndef NDEBUG
83940   sqlite_int64 iLastDocidDelta;
83941 #endif
83942
83943   /* Recode the initial docid as delta from iPrevDocid. */
83944   nFirstOld = fts3GetVarint(pData, &iDocid);
83945   assert( nFirstOld<nData || (nFirstOld==nData && pWriter->iType==DL_DOCIDS) );
83946   nFirstNew = fts3PutVarint(c, iFirstDocid-pWriter->iPrevDocid);
83947
83948   /* Verify that the incoming doclist is valid AND that it ends with
83949   ** the expected docid.  This is essential because we'll trust this
83950   ** docid in future delta-encoding.
83951   */
83952   ASSERT_VALID_DOCLIST(pWriter->iType, pData, nData, &iLastDocidDelta);
83953   assert( iLastDocid==iFirstDocid-iDocid+iLastDocidDelta );
83954
83955   /* Append recoded initial docid and everything else.  Rest of docids
83956   ** should have been delta-encoded from previous initial docid.
83957   */
83958   if( nFirstOld<nData ){
83959     dataBufferAppend2(pWriter->b, c, nFirstNew,
83960                       pData+nFirstOld, nData-nFirstOld);
83961   }else{
83962     dataBufferAppend(pWriter->b, c, nFirstNew);
83963   }
83964   pWriter->iPrevDocid = iLastDocid;
83965 }
83966 static void dlwCopy(DLWriter *pWriter, DLReader *pReader){
83967   dlwAppend(pWriter, dlrDocData(pReader), dlrDocDataBytes(pReader),
83968             dlrDocid(pReader), dlrDocid(pReader));
83969 }
83970 static void dlwAdd(DLWriter *pWriter, sqlite_int64 iDocid){
83971   char c[VARINT_MAX];
83972   int n = fts3PutVarint(c, iDocid-pWriter->iPrevDocid);
83973
83974   /* Docids must ascend. */
83975   assert( !pWriter->has_iPrevDocid || iDocid>pWriter->iPrevDocid );
83976   assert( pWriter->iType==DL_DOCIDS );
83977
83978   dataBufferAppend(pWriter->b, c, n);
83979   pWriter->iPrevDocid = iDocid;
83980 #ifndef NDEBUG
83981   pWriter->has_iPrevDocid = 1;
83982 #endif
83983 }
83984
83985 /*******************************************************************/
83986 /* PLReader is used to read data from a document's position list.  As
83987 ** the caller steps through the list, data is cached so that varints
83988 ** only need to be decoded once.
83989 **
83990 ** plrInit, plrDestroy - create/destroy a reader.
83991 ** plrColumn, plrPosition, plrStartOffset, plrEndOffset - accessors
83992 ** plrAtEnd - at end of stream, only call plrDestroy once true.
83993 ** plrStep - step to the next element.
83994 */
83995 typedef struct PLReader {
83996   /* These refer to the next position's data.  nData will reach 0 when
83997   ** reading the last position, so plrStep() signals EOF by setting
83998   ** pData to NULL.
83999   */
84000   const char *pData;
84001   int nData;
84002
84003   DocListType iType;
84004   int iColumn;         /* the last column read */
84005   int iPosition;       /* the last position read */
84006   int iStartOffset;    /* the last start offset read */
84007   int iEndOffset;      /* the last end offset read */
84008 } PLReader;
84009
84010 static int plrAtEnd(PLReader *pReader){
84011   return pReader->pData==NULL;
84012 }
84013 static int plrColumn(PLReader *pReader){
84014   assert( !plrAtEnd(pReader) );
84015   return pReader->iColumn;
84016 }
84017 static int plrPosition(PLReader *pReader){
84018   assert( !plrAtEnd(pReader) );
84019   return pReader->iPosition;
84020 }
84021 static int plrStartOffset(PLReader *pReader){
84022   assert( !plrAtEnd(pReader) );
84023   return pReader->iStartOffset;
84024 }
84025 static int plrEndOffset(PLReader *pReader){
84026   assert( !plrAtEnd(pReader) );
84027   return pReader->iEndOffset;
84028 }
84029 static void plrStep(PLReader *pReader){
84030   int i, n;
84031
84032   assert( !plrAtEnd(pReader) );
84033
84034   if( pReader->nData==0 ){
84035     pReader->pData = NULL;
84036     return;
84037   }
84038
84039   n = fts3GetVarint32(pReader->pData, &i);
84040   if( i==POS_COLUMN ){
84041     n += fts3GetVarint32(pReader->pData+n, &pReader->iColumn);
84042     pReader->iPosition = 0;
84043     pReader->iStartOffset = 0;
84044     n += fts3GetVarint32(pReader->pData+n, &i);
84045   }
84046   /* Should never see adjacent column changes. */
84047   assert( i!=POS_COLUMN );
84048
84049   if( i==POS_END ){
84050     pReader->nData = 0;
84051     pReader->pData = NULL;
84052     return;
84053   }
84054
84055   pReader->iPosition += i-POS_BASE;
84056   if( pReader->iType==DL_POSITIONS_OFFSETS ){
84057     n += fts3GetVarint32(pReader->pData+n, &i);
84058     pReader->iStartOffset += i;
84059     n += fts3GetVarint32(pReader->pData+n, &i);
84060     pReader->iEndOffset = pReader->iStartOffset+i;
84061   }
84062   assert( n<=pReader->nData );
84063   pReader->pData += n;
84064   pReader->nData -= n;
84065 }
84066
84067 static void plrInit(PLReader *pReader, DLReader *pDLReader){
84068   pReader->pData = dlrPosData(pDLReader);
84069   pReader->nData = dlrPosDataLen(pDLReader);
84070   pReader->iType = pDLReader->iType;
84071   pReader->iColumn = 0;
84072   pReader->iPosition = 0;
84073   pReader->iStartOffset = 0;
84074   pReader->iEndOffset = 0;
84075   plrStep(pReader);
84076 }
84077 static void plrDestroy(PLReader *pReader){
84078   SCRAMBLE(pReader);
84079 }
84080
84081 /*******************************************************************/
84082 /* PLWriter is used in constructing a document's position list.  As a
84083 ** convenience, if iType is DL_DOCIDS, PLWriter becomes a no-op.
84084 ** PLWriter writes to the associated DLWriter's buffer.
84085 **
84086 ** plwInit - init for writing a document's poslist.
84087 ** plwDestroy - clear a writer.
84088 ** plwAdd - append position and offset information.
84089 ** plwCopy - copy next position's data from reader to writer.
84090 ** plwTerminate - add any necessary doclist terminator.
84091 **
84092 ** Calling plwAdd() after plwTerminate() may result in a corrupt
84093 ** doclist.
84094 */
84095 /* TODO(shess) Until we've written the second item, we can cache the
84096 ** first item's information.  Then we'd have three states:
84097 **
84098 ** - initialized with docid, no positions.
84099 ** - docid and one position.
84100 ** - docid and multiple positions.
84101 **
84102 ** Only the last state needs to actually write to dlw->b, which would
84103 ** be an improvement in the DLCollector case.
84104 */
84105 typedef struct PLWriter {
84106   DLWriter *dlw;
84107
84108   int iColumn;    /* the last column written */
84109   int iPos;       /* the last position written */
84110   int iOffset;    /* the last start offset written */
84111 } PLWriter;
84112
84113 /* TODO(shess) In the case where the parent is reading these values
84114 ** from a PLReader, we could optimize to a copy if that PLReader has
84115 ** the same type as pWriter.
84116 */
84117 static void plwAdd(PLWriter *pWriter, int iColumn, int iPos,
84118                    int iStartOffset, int iEndOffset){
84119   /* Worst-case space for POS_COLUMN, iColumn, iPosDelta,
84120   ** iStartOffsetDelta, and iEndOffsetDelta.
84121   */
84122   char c[5*VARINT_MAX];
84123   int n = 0;
84124
84125   /* Ban plwAdd() after plwTerminate(). */
84126   assert( pWriter->iPos!=-1 );
84127
84128   if( pWriter->dlw->iType==DL_DOCIDS ) return;
84129
84130   if( iColumn!=pWriter->iColumn ){
84131     n += fts3PutVarint(c+n, POS_COLUMN);
84132     n += fts3PutVarint(c+n, iColumn);
84133     pWriter->iColumn = iColumn;
84134     pWriter->iPos = 0;
84135     pWriter->iOffset = 0;
84136   }
84137   assert( iPos>=pWriter->iPos );
84138   n += fts3PutVarint(c+n, POS_BASE+(iPos-pWriter->iPos));
84139   pWriter->iPos = iPos;
84140   if( pWriter->dlw->iType==DL_POSITIONS_OFFSETS ){
84141     assert( iStartOffset>=pWriter->iOffset );
84142     n += fts3PutVarint(c+n, iStartOffset-pWriter->iOffset);
84143     pWriter->iOffset = iStartOffset;
84144     assert( iEndOffset>=iStartOffset );
84145     n += fts3PutVarint(c+n, iEndOffset-iStartOffset);
84146   }
84147   dataBufferAppend(pWriter->dlw->b, c, n);
84148 }
84149 static void plwCopy(PLWriter *pWriter, PLReader *pReader){
84150   plwAdd(pWriter, plrColumn(pReader), plrPosition(pReader),
84151          plrStartOffset(pReader), plrEndOffset(pReader));
84152 }
84153 static void plwInit(PLWriter *pWriter, DLWriter *dlw, sqlite_int64 iDocid){
84154   char c[VARINT_MAX];
84155   int n;
84156
84157   pWriter->dlw = dlw;
84158
84159   /* Docids must ascend. */
84160   assert( !pWriter->dlw->has_iPrevDocid || iDocid>pWriter->dlw->iPrevDocid );
84161   n = fts3PutVarint(c, iDocid-pWriter->dlw->iPrevDocid);
84162   dataBufferAppend(pWriter->dlw->b, c, n);
84163   pWriter->dlw->iPrevDocid = iDocid;
84164 #ifndef NDEBUG
84165   pWriter->dlw->has_iPrevDocid = 1;
84166 #endif
84167
84168   pWriter->iColumn = 0;
84169   pWriter->iPos = 0;
84170   pWriter->iOffset = 0;
84171 }
84172 /* TODO(shess) Should plwDestroy() also terminate the doclist?  But
84173 ** then plwDestroy() would no longer be just a destructor, it would
84174 ** also be doing work, which isn't consistent with the overall idiom.
84175 ** Another option would be for plwAdd() to always append any necessary
84176 ** terminator, so that the output is always correct.  But that would
84177 ** add incremental work to the common case with the only benefit being
84178 ** API elegance.  Punt for now.
84179 */
84180 static void plwTerminate(PLWriter *pWriter){
84181   if( pWriter->dlw->iType>DL_DOCIDS ){
84182     char c[VARINT_MAX];
84183     int n = fts3PutVarint(c, POS_END);
84184     dataBufferAppend(pWriter->dlw->b, c, n);
84185   }
84186 #ifndef NDEBUG
84187   /* Mark as terminated for assert in plwAdd(). */
84188   pWriter->iPos = -1;
84189 #endif
84190 }
84191 static void plwDestroy(PLWriter *pWriter){
84192   SCRAMBLE(pWriter);
84193 }
84194
84195 /*******************************************************************/
84196 /* DLCollector wraps PLWriter and DLWriter to provide a
84197 ** dynamically-allocated doclist area to use during tokenization.
84198 **
84199 ** dlcNew - malloc up and initialize a collector.
84200 ** dlcDelete - destroy a collector and all contained items.
84201 ** dlcAddPos - append position and offset information.
84202 ** dlcAddDoclist - add the collected doclist to the given buffer.
84203 ** dlcNext - terminate the current document and open another.
84204 */
84205 typedef struct DLCollector {
84206   DataBuffer b;
84207   DLWriter dlw;
84208   PLWriter plw;
84209 } DLCollector;
84210
84211 /* TODO(shess) This could also be done by calling plwTerminate() and
84212 ** dataBufferAppend().  I tried that, expecting nominal performance
84213 ** differences, but it seemed to pretty reliably be worth 1% to code
84214 ** it this way.  I suspect it is the incremental malloc overhead (some
84215 ** percentage of the plwTerminate() calls will cause a realloc), so
84216 ** this might be worth revisiting if the DataBuffer implementation
84217 ** changes.
84218 */
84219 static void dlcAddDoclist(DLCollector *pCollector, DataBuffer *b){
84220   if( pCollector->dlw.iType>DL_DOCIDS ){
84221     char c[VARINT_MAX];
84222     int n = fts3PutVarint(c, POS_END);
84223     dataBufferAppend2(b, pCollector->b.pData, pCollector->b.nData, c, n);
84224   }else{
84225     dataBufferAppend(b, pCollector->b.pData, pCollector->b.nData);
84226   }
84227 }
84228 static void dlcNext(DLCollector *pCollector, sqlite_int64 iDocid){
84229   plwTerminate(&pCollector->plw);
84230   plwDestroy(&pCollector->plw);
84231   plwInit(&pCollector->plw, &pCollector->dlw, iDocid);
84232 }
84233 static void dlcAddPos(DLCollector *pCollector, int iColumn, int iPos,
84234                       int iStartOffset, int iEndOffset){
84235   plwAdd(&pCollector->plw, iColumn, iPos, iStartOffset, iEndOffset);
84236 }
84237
84238 static DLCollector *dlcNew(sqlite_int64 iDocid, DocListType iType){
84239   DLCollector *pCollector = sqlite3_malloc(sizeof(DLCollector));
84240   dataBufferInit(&pCollector->b, 0);
84241   dlwInit(&pCollector->dlw, iType, &pCollector->b);
84242   plwInit(&pCollector->plw, &pCollector->dlw, iDocid);
84243   return pCollector;
84244 }
84245 static void dlcDelete(DLCollector *pCollector){
84246   plwDestroy(&pCollector->plw);
84247   dlwDestroy(&pCollector->dlw);
84248   dataBufferDestroy(&pCollector->b);
84249   SCRAMBLE(pCollector);
84250   sqlite3_free(pCollector);
84251 }
84252
84253
84254 /* Copy the doclist data of iType in pData/nData into *out, trimming
84255 ** unnecessary data as we go.  Only columns matching iColumn are
84256 ** copied, all columns copied if iColumn is -1.  Elements with no
84257 ** matching columns are dropped.  The output is an iOutType doclist.
84258 */
84259 /* NOTE(shess) This code is only valid after all doclists are merged.
84260 ** If this is run before merges, then doclist items which represent
84261 ** deletion will be trimmed, and will thus not effect a deletion
84262 ** during the merge.
84263 */
84264 static void docListTrim(DocListType iType, const char *pData, int nData,
84265                         int iColumn, DocListType iOutType, DataBuffer *out){
84266   DLReader dlReader;
84267   DLWriter dlWriter;
84268
84269   assert( iOutType<=iType );
84270
84271   dlrInit(&dlReader, iType, pData, nData);
84272   dlwInit(&dlWriter, iOutType, out);
84273
84274   while( !dlrAtEnd(&dlReader) ){
84275     PLReader plReader;
84276     PLWriter plWriter;
84277     int match = 0;
84278
84279     plrInit(&plReader, &dlReader);
84280
84281     while( !plrAtEnd(&plReader) ){
84282       if( iColumn==-1 || plrColumn(&plReader)==iColumn ){
84283         if( !match ){
84284           plwInit(&plWriter, &dlWriter, dlrDocid(&dlReader));
84285           match = 1;
84286         }
84287         plwAdd(&plWriter, plrColumn(&plReader), plrPosition(&plReader),
84288                plrStartOffset(&plReader), plrEndOffset(&plReader));
84289       }
84290       plrStep(&plReader);
84291     }
84292     if( match ){
84293       plwTerminate(&plWriter);
84294       plwDestroy(&plWriter);
84295     }
84296
84297     plrDestroy(&plReader);
84298     dlrStep(&dlReader);
84299   }
84300   dlwDestroy(&dlWriter);
84301   dlrDestroy(&dlReader);
84302 }
84303
84304 /* Used by docListMerge() to keep doclists in the ascending order by
84305 ** docid, then ascending order by age (so the newest comes first).
84306 */
84307 typedef struct OrderedDLReader {
84308   DLReader *pReader;
84309
84310   /* TODO(shess) If we assume that docListMerge pReaders is ordered by
84311   ** age (which we do), then we could use pReader comparisons to break
84312   ** ties.
84313   */
84314   int idx;
84315 } OrderedDLReader;
84316
84317 /* Order eof to end, then by docid asc, idx desc. */
84318 static int orderedDLReaderCmp(OrderedDLReader *r1, OrderedDLReader *r2){
84319   if( dlrAtEnd(r1->pReader) ){
84320     if( dlrAtEnd(r2->pReader) ) return 0;  /* Both atEnd(). */
84321     return 1;                              /* Only r1 atEnd(). */
84322   }
84323   if( dlrAtEnd(r2->pReader) ) return -1;   /* Only r2 atEnd(). */
84324
84325   if( dlrDocid(r1->pReader)<dlrDocid(r2->pReader) ) return -1;
84326   if( dlrDocid(r1->pReader)>dlrDocid(r2->pReader) ) return 1;
84327
84328   /* Descending on idx. */
84329   return r2->idx-r1->idx;
84330 }
84331
84332 /* Bubble p[0] to appropriate place in p[1..n-1].  Assumes that
84333 ** p[1..n-1] is already sorted.
84334 */
84335 /* TODO(shess) Is this frequent enough to warrant a binary search?
84336 ** Before implementing that, instrument the code to check.  In most
84337 ** current usage, I expect that p[0] will be less than p[1] a very
84338 ** high proportion of the time.
84339 */
84340 static void orderedDLReaderReorder(OrderedDLReader *p, int n){
84341   while( n>1 && orderedDLReaderCmp(p, p+1)>0 ){
84342     OrderedDLReader tmp = p[0];
84343     p[0] = p[1];
84344     p[1] = tmp;
84345     n--;
84346     p++;
84347   }
84348 }
84349
84350 /* Given an array of doclist readers, merge their doclist elements
84351 ** into out in sorted order (by docid), dropping elements from older
84352 ** readers when there is a duplicate docid.  pReaders is assumed to be
84353 ** ordered by age, oldest first.
84354 */
84355 /* TODO(shess) nReaders must be <= MERGE_COUNT.  This should probably
84356 ** be fixed.
84357 */
84358 static void docListMerge(DataBuffer *out,
84359                          DLReader *pReaders, int nReaders){
84360   OrderedDLReader readers[MERGE_COUNT];
84361   DLWriter writer;
84362   int i, n;
84363   const char *pStart = 0;
84364   int nStart = 0;
84365   sqlite_int64 iFirstDocid = 0, iLastDocid = 0;
84366
84367   assert( nReaders>0 );
84368   if( nReaders==1 ){
84369     dataBufferAppend(out, dlrDocData(pReaders), dlrAllDataBytes(pReaders));
84370     return;
84371   }
84372
84373   assert( nReaders<=MERGE_COUNT );
84374   n = 0;
84375   for(i=0; i<nReaders; i++){
84376     assert( pReaders[i].iType==pReaders[0].iType );
84377     readers[i].pReader = pReaders+i;
84378     readers[i].idx = i;
84379     n += dlrAllDataBytes(&pReaders[i]);
84380   }
84381   /* Conservatively size output to sum of inputs.  Output should end
84382   ** up strictly smaller than input.
84383   */
84384   dataBufferExpand(out, n);
84385
84386   /* Get the readers into sorted order. */
84387   while( i-->0 ){
84388     orderedDLReaderReorder(readers+i, nReaders-i);
84389   }
84390
84391   dlwInit(&writer, pReaders[0].iType, out);
84392   while( !dlrAtEnd(readers[0].pReader) ){
84393     sqlite_int64 iDocid = dlrDocid(readers[0].pReader);
84394
84395     /* If this is a continuation of the current buffer to copy, extend
84396     ** that buffer.  memcpy() seems to be more efficient if it has a
84397     ** lots of data to copy.
84398     */
84399     if( dlrDocData(readers[0].pReader)==pStart+nStart ){
84400       nStart += dlrDocDataBytes(readers[0].pReader);
84401     }else{
84402       if( pStart!=0 ){
84403         dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid);
84404       }
84405       pStart = dlrDocData(readers[0].pReader);
84406       nStart = dlrDocDataBytes(readers[0].pReader);
84407       iFirstDocid = iDocid;
84408     }
84409     iLastDocid = iDocid;
84410     dlrStep(readers[0].pReader);
84411
84412     /* Drop all of the older elements with the same docid. */
84413     for(i=1; i<nReaders &&
84414              !dlrAtEnd(readers[i].pReader) &&
84415              dlrDocid(readers[i].pReader)==iDocid; i++){
84416       dlrStep(readers[i].pReader);
84417     }
84418
84419     /* Get the readers back into order. */
84420     while( i-->0 ){
84421       orderedDLReaderReorder(readers+i, nReaders-i);
84422     }
84423   }
84424
84425   /* Copy over any remaining elements. */
84426   if( nStart>0 ) dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid);
84427   dlwDestroy(&writer);
84428 }
84429
84430 /* Helper function for posListUnion().  Compares the current position
84431 ** between left and right, returning as standard C idiom of <0 if
84432 ** left<right, >0 if left>right, and 0 if left==right.  "End" always
84433 ** compares greater.
84434 */
84435 static int posListCmp(PLReader *pLeft, PLReader *pRight){
84436   assert( pLeft->iType==pRight->iType );
84437   if( pLeft->iType==DL_DOCIDS ) return 0;
84438
84439   if( plrAtEnd(pLeft) ) return plrAtEnd(pRight) ? 0 : 1;
84440   if( plrAtEnd(pRight) ) return -1;
84441
84442   if( plrColumn(pLeft)<plrColumn(pRight) ) return -1;
84443   if( plrColumn(pLeft)>plrColumn(pRight) ) return 1;
84444
84445   if( plrPosition(pLeft)<plrPosition(pRight) ) return -1;
84446   if( plrPosition(pLeft)>plrPosition(pRight) ) return 1;
84447   if( pLeft->iType==DL_POSITIONS ) return 0;
84448
84449   if( plrStartOffset(pLeft)<plrStartOffset(pRight) ) return -1;
84450   if( plrStartOffset(pLeft)>plrStartOffset(pRight) ) return 1;
84451
84452   if( plrEndOffset(pLeft)<plrEndOffset(pRight) ) return -1;
84453   if( plrEndOffset(pLeft)>plrEndOffset(pRight) ) return 1;
84454
84455   return 0;
84456 }
84457
84458 /* Write the union of position lists in pLeft and pRight to pOut.
84459 ** "Union" in this case meaning "All unique position tuples".  Should
84460 ** work with any doclist type, though both inputs and the output
84461 ** should be the same type.
84462 */
84463 static void posListUnion(DLReader *pLeft, DLReader *pRight, DLWriter *pOut){
84464   PLReader left, right;
84465   PLWriter writer;
84466
84467   assert( dlrDocid(pLeft)==dlrDocid(pRight) );
84468   assert( pLeft->iType==pRight->iType );
84469   assert( pLeft->iType==pOut->iType );
84470
84471   plrInit(&left, pLeft);
84472   plrInit(&right, pRight);
84473   plwInit(&writer, pOut, dlrDocid(pLeft));
84474
84475   while( !plrAtEnd(&left) || !plrAtEnd(&right) ){
84476     int c = posListCmp(&left, &right);
84477     if( c<0 ){
84478       plwCopy(&writer, &left);
84479       plrStep(&left);
84480     }else if( c>0 ){
84481       plwCopy(&writer, &right);
84482       plrStep(&right);
84483     }else{
84484       plwCopy(&writer, &left);
84485       plrStep(&left);
84486       plrStep(&right);
84487     }
84488   }
84489
84490   plwTerminate(&writer);
84491   plwDestroy(&writer);
84492   plrDestroy(&left);
84493   plrDestroy(&right);
84494 }
84495
84496 /* Write the union of doclists in pLeft and pRight to pOut.  For
84497 ** docids in common between the inputs, the union of the position
84498 ** lists is written.  Inputs and outputs are always type DL_DEFAULT.
84499 */
84500 static void docListUnion(
84501   const char *pLeft, int nLeft,
84502   const char *pRight, int nRight,
84503   DataBuffer *pOut      /* Write the combined doclist here */
84504 ){
84505   DLReader left, right;
84506   DLWriter writer;
84507
84508   if( nLeft==0 ){
84509     if( nRight!=0) dataBufferAppend(pOut, pRight, nRight);
84510     return;
84511   }
84512   if( nRight==0 ){
84513     dataBufferAppend(pOut, pLeft, nLeft);
84514     return;
84515   }
84516
84517   dlrInit(&left, DL_DEFAULT, pLeft, nLeft);
84518   dlrInit(&right, DL_DEFAULT, pRight, nRight);
84519   dlwInit(&writer, DL_DEFAULT, pOut);
84520
84521   while( !dlrAtEnd(&left) || !dlrAtEnd(&right) ){
84522     if( dlrAtEnd(&right) ){
84523       dlwCopy(&writer, &left);
84524       dlrStep(&left);
84525     }else if( dlrAtEnd(&left) ){
84526       dlwCopy(&writer, &right);
84527       dlrStep(&right);
84528     }else if( dlrDocid(&left)<dlrDocid(&right) ){
84529       dlwCopy(&writer, &left);
84530       dlrStep(&left);
84531     }else if( dlrDocid(&left)>dlrDocid(&right) ){
84532       dlwCopy(&writer, &right);
84533       dlrStep(&right);
84534     }else{
84535       posListUnion(&left, &right, &writer);
84536       dlrStep(&left);
84537       dlrStep(&right);
84538     }
84539   }
84540
84541   dlrDestroy(&left);
84542   dlrDestroy(&right);
84543   dlwDestroy(&writer);
84544 }
84545
84546 /* 
84547 ** This function is used as part of the implementation of phrase and
84548 ** NEAR matching.
84549 **
84550 ** pLeft and pRight are DLReaders positioned to the same docid in
84551 ** lists of type DL_POSITION. This function writes an entry to the
84552 ** DLWriter pOut for each position in pRight that is less than
84553 ** (nNear+1) greater (but not equal to or smaller) than a position 
84554 ** in pLeft. For example, if nNear is 0, and the positions contained
84555 ** by pLeft and pRight are:
84556 **
84557 **    pLeft:  5 10 15 20
84558 **    pRight: 6  9 17 21
84559 **
84560 ** then the docid is added to pOut. If pOut is of type DL_POSITIONS,
84561 ** then a positionids "6" and "21" are also added to pOut.
84562 **
84563 ** If boolean argument isSaveLeft is true, then positionids are copied
84564 ** from pLeft instead of pRight. In the example above, the positions "5"
84565 ** and "20" would be added instead of "6" and "21".
84566 */
84567 static void posListPhraseMerge(
84568   DLReader *pLeft, 
84569   DLReader *pRight,
84570   int nNear,
84571   int isSaveLeft,
84572   DLWriter *pOut
84573 ){
84574   PLReader left, right;
84575   PLWriter writer;
84576   int match = 0;
84577
84578   assert( dlrDocid(pLeft)==dlrDocid(pRight) );
84579   assert( pOut->iType!=DL_POSITIONS_OFFSETS );
84580
84581   plrInit(&left, pLeft);
84582   plrInit(&right, pRight);
84583
84584   while( !plrAtEnd(&left) && !plrAtEnd(&right) ){
84585     if( plrColumn(&left)<plrColumn(&right) ){
84586       plrStep(&left);
84587     }else if( plrColumn(&left)>plrColumn(&right) ){
84588       plrStep(&right);
84589     }else if( plrPosition(&left)>=plrPosition(&right) ){
84590       plrStep(&right);
84591     }else{
84592       if( (plrPosition(&right)-plrPosition(&left))<=(nNear+1) ){
84593         if( !match ){
84594           plwInit(&writer, pOut, dlrDocid(pLeft));
84595           match = 1;
84596         }
84597         if( !isSaveLeft ){
84598           plwAdd(&writer, plrColumn(&right), plrPosition(&right), 0, 0);
84599         }else{
84600           plwAdd(&writer, plrColumn(&left), plrPosition(&left), 0, 0);
84601         }
84602         plrStep(&right);
84603       }else{
84604         plrStep(&left);
84605       }
84606     }
84607   }
84608
84609   if( match ){
84610     plwTerminate(&writer);
84611     plwDestroy(&writer);
84612   }
84613
84614   plrDestroy(&left);
84615   plrDestroy(&right);
84616 }
84617
84618 /*
84619 ** Compare the values pointed to by the PLReaders passed as arguments. 
84620 ** Return -1 if the value pointed to by pLeft is considered less than
84621 ** the value pointed to by pRight, +1 if it is considered greater
84622 ** than it, or 0 if it is equal. i.e.
84623 **
84624 **     (*pLeft - *pRight)
84625 **
84626 ** A PLReader that is in the EOF condition is considered greater than
84627 ** any other. If neither argument is in EOF state, the return value of
84628 ** plrColumn() is used. If the plrColumn() values are equal, the
84629 ** comparison is on the basis of plrPosition().
84630 */
84631 static int plrCompare(PLReader *pLeft, PLReader *pRight){
84632   assert(!plrAtEnd(pLeft) || !plrAtEnd(pRight));
84633
84634   if( plrAtEnd(pRight) || plrAtEnd(pLeft) ){
84635     return (plrAtEnd(pRight) ? -1 : 1);
84636   }
84637   if( plrColumn(pLeft)!=plrColumn(pRight) ){
84638     return ((plrColumn(pLeft)<plrColumn(pRight)) ? -1 : 1);
84639   }
84640   if( plrPosition(pLeft)!=plrPosition(pRight) ){
84641     return ((plrPosition(pLeft)<plrPosition(pRight)) ? -1 : 1);
84642   }
84643   return 0;
84644 }
84645
84646 /* We have two doclists with positions:  pLeft and pRight. Depending
84647 ** on the value of the nNear parameter, perform either a phrase
84648 ** intersection (if nNear==0) or a NEAR intersection (if nNear>0)
84649 ** and write the results into pOut.
84650 **
84651 ** A phrase intersection means that two documents only match
84652 ** if pLeft.iPos+1==pRight.iPos.
84653 **
84654 ** A NEAR intersection means that two documents only match if 
84655 ** (abs(pLeft.iPos-pRight.iPos)<nNear).
84656 **
84657 ** If a NEAR intersection is requested, then the nPhrase argument should
84658 ** be passed the number of tokens in the two operands to the NEAR operator
84659 ** combined. For example:
84660 **
84661 **       Query syntax               nPhrase
84662 **      ------------------------------------
84663 **       "A B C" NEAR "D E"         5
84664 **       A NEAR B                   2
84665 **
84666 ** iType controls the type of data written to pOut.  If iType is
84667 ** DL_POSITIONS, the positions are those from pRight.
84668 */
84669 static void docListPhraseMerge(
84670   const char *pLeft, int nLeft,
84671   const char *pRight, int nRight,
84672   int nNear,            /* 0 for a phrase merge, non-zero for a NEAR merge */
84673   int nPhrase,          /* Number of tokens in left+right operands to NEAR */
84674   DocListType iType,    /* Type of doclist to write to pOut */
84675   DataBuffer *pOut      /* Write the combined doclist here */
84676 ){
84677   DLReader left, right;
84678   DLWriter writer;
84679
84680   if( nLeft==0 || nRight==0 ) return;
84681
84682   assert( iType!=DL_POSITIONS_OFFSETS );
84683
84684   dlrInit(&left, DL_POSITIONS, pLeft, nLeft);
84685   dlrInit(&right, DL_POSITIONS, pRight, nRight);
84686   dlwInit(&writer, iType, pOut);
84687
84688   while( !dlrAtEnd(&left) && !dlrAtEnd(&right) ){
84689     if( dlrDocid(&left)<dlrDocid(&right) ){
84690       dlrStep(&left);
84691     }else if( dlrDocid(&right)<dlrDocid(&left) ){
84692       dlrStep(&right);
84693     }else{
84694       if( nNear==0 ){
84695         posListPhraseMerge(&left, &right, 0, 0, &writer);
84696       }else{
84697         /* This case occurs when two terms (simple terms or phrases) are
84698          * connected by a NEAR operator, span (nNear+1). i.e.
84699          *
84700          *     '"terrible company" NEAR widget'
84701          */
84702         DataBuffer one = {0, 0, 0};
84703         DataBuffer two = {0, 0, 0};
84704
84705         DLWriter dlwriter2;
84706         DLReader dr1 = {0, 0, 0, 0, 0}; 
84707         DLReader dr2 = {0, 0, 0, 0, 0};
84708
84709         dlwInit(&dlwriter2, iType, &one);
84710         posListPhraseMerge(&right, &left, nNear-3+nPhrase, 1, &dlwriter2);
84711         dlwInit(&dlwriter2, iType, &two);
84712         posListPhraseMerge(&left, &right, nNear-1, 0, &dlwriter2);
84713
84714         if( one.nData) dlrInit(&dr1, iType, one.pData, one.nData);
84715         if( two.nData) dlrInit(&dr2, iType, two.pData, two.nData);
84716
84717         if( !dlrAtEnd(&dr1) || !dlrAtEnd(&dr2) ){
84718           PLReader pr1 = {0};
84719           PLReader pr2 = {0};
84720
84721           PLWriter plwriter;
84722           plwInit(&plwriter, &writer, dlrDocid(dlrAtEnd(&dr1)?&dr2:&dr1));
84723
84724           if( one.nData ) plrInit(&pr1, &dr1);
84725           if( two.nData ) plrInit(&pr2, &dr2);
84726           while( !plrAtEnd(&pr1) || !plrAtEnd(&pr2) ){
84727             int iCompare = plrCompare(&pr1, &pr2);
84728             switch( iCompare ){
84729               case -1:
84730                 plwCopy(&plwriter, &pr1);
84731                 plrStep(&pr1);
84732                 break;
84733               case 1:
84734                 plwCopy(&plwriter, &pr2);
84735                 plrStep(&pr2);
84736                 break;
84737               case 0:
84738                 plwCopy(&plwriter, &pr1);
84739                 plrStep(&pr1);
84740                 plrStep(&pr2);
84741                 break;
84742             }
84743           }
84744           plwTerminate(&plwriter);
84745         }
84746         dataBufferDestroy(&one);
84747         dataBufferDestroy(&two);
84748       }
84749       dlrStep(&left);
84750       dlrStep(&right);
84751     }
84752   }
84753
84754   dlrDestroy(&left);
84755   dlrDestroy(&right);
84756   dlwDestroy(&writer);
84757 }
84758
84759 /* We have two DL_DOCIDS doclists:  pLeft and pRight.
84760 ** Write the intersection of these two doclists into pOut as a
84761 ** DL_DOCIDS doclist.
84762 */
84763 static void docListAndMerge(
84764   const char *pLeft, int nLeft,
84765   const char *pRight, int nRight,
84766   DataBuffer *pOut      /* Write the combined doclist here */
84767 ){
84768   DLReader left, right;
84769   DLWriter writer;
84770
84771   if( nLeft==0 || nRight==0 ) return;
84772
84773   dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
84774   dlrInit(&right, DL_DOCIDS, pRight, nRight);
84775   dlwInit(&writer, DL_DOCIDS, pOut);
84776
84777   while( !dlrAtEnd(&left) && !dlrAtEnd(&right) ){
84778     if( dlrDocid(&left)<dlrDocid(&right) ){
84779       dlrStep(&left);
84780     }else if( dlrDocid(&right)<dlrDocid(&left) ){
84781       dlrStep(&right);
84782     }else{
84783       dlwAdd(&writer, dlrDocid(&left));
84784       dlrStep(&left);
84785       dlrStep(&right);
84786     }
84787   }
84788
84789   dlrDestroy(&left);
84790   dlrDestroy(&right);
84791   dlwDestroy(&writer);
84792 }
84793
84794 /* We have two DL_DOCIDS doclists:  pLeft and pRight.
84795 ** Write the union of these two doclists into pOut as a
84796 ** DL_DOCIDS doclist.
84797 */
84798 static void docListOrMerge(
84799   const char *pLeft, int nLeft,
84800   const char *pRight, int nRight,
84801   DataBuffer *pOut      /* Write the combined doclist here */
84802 ){
84803   DLReader left, right;
84804   DLWriter writer;
84805
84806   if( nLeft==0 ){
84807     if( nRight!=0 ) dataBufferAppend(pOut, pRight, nRight);
84808     return;
84809   }
84810   if( nRight==0 ){
84811     dataBufferAppend(pOut, pLeft, nLeft);
84812     return;
84813   }
84814
84815   dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
84816   dlrInit(&right, DL_DOCIDS, pRight, nRight);
84817   dlwInit(&writer, DL_DOCIDS, pOut);
84818
84819   while( !dlrAtEnd(&left) || !dlrAtEnd(&right) ){
84820     if( dlrAtEnd(&right) ){
84821       dlwAdd(&writer, dlrDocid(&left));
84822       dlrStep(&left);
84823     }else if( dlrAtEnd(&left) ){
84824       dlwAdd(&writer, dlrDocid(&right));
84825       dlrStep(&right);
84826     }else if( dlrDocid(&left)<dlrDocid(&right) ){
84827       dlwAdd(&writer, dlrDocid(&left));
84828       dlrStep(&left);
84829     }else if( dlrDocid(&right)<dlrDocid(&left) ){
84830       dlwAdd(&writer, dlrDocid(&right));
84831       dlrStep(&right);
84832     }else{
84833       dlwAdd(&writer, dlrDocid(&left));
84834       dlrStep(&left);
84835       dlrStep(&right);
84836     }
84837   }
84838
84839   dlrDestroy(&left);
84840   dlrDestroy(&right);
84841   dlwDestroy(&writer);
84842 }
84843
84844 /* We have two DL_DOCIDS doclists:  pLeft and pRight.
84845 ** Write into pOut as DL_DOCIDS doclist containing all documents that
84846 ** occur in pLeft but not in pRight.
84847 */
84848 static void docListExceptMerge(
84849   const char *pLeft, int nLeft,
84850   const char *pRight, int nRight,
84851   DataBuffer *pOut      /* Write the combined doclist here */
84852 ){
84853   DLReader left, right;
84854   DLWriter writer;
84855
84856   if( nLeft==0 ) return;
84857   if( nRight==0 ){
84858     dataBufferAppend(pOut, pLeft, nLeft);
84859     return;
84860   }
84861
84862   dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
84863   dlrInit(&right, DL_DOCIDS, pRight, nRight);
84864   dlwInit(&writer, DL_DOCIDS, pOut);
84865
84866   while( !dlrAtEnd(&left) ){
84867     while( !dlrAtEnd(&right) && dlrDocid(&right)<dlrDocid(&left) ){
84868       dlrStep(&right);
84869     }
84870     if( dlrAtEnd(&right) || dlrDocid(&left)<dlrDocid(&right) ){
84871       dlwAdd(&writer, dlrDocid(&left));
84872     }
84873     dlrStep(&left);
84874   }
84875
84876   dlrDestroy(&left);
84877   dlrDestroy(&right);
84878   dlwDestroy(&writer);
84879 }
84880
84881 static char *string_dup_n(const char *s, int n){
84882   char *str = sqlite3_malloc(n + 1);
84883   memcpy(str, s, n);
84884   str[n] = '\0';
84885   return str;
84886 }
84887
84888 /* Duplicate a string; the caller must free() the returned string.
84889  * (We don't use strdup() since it is not part of the standard C library and
84890  * may not be available everywhere.) */
84891 static char *string_dup(const char *s){
84892   return string_dup_n(s, strlen(s));
84893 }
84894
84895 /* Format a string, replacing each occurrence of the % character with
84896  * zDb.zName.  This may be more convenient than sqlite_mprintf()
84897  * when one string is used repeatedly in a format string.
84898  * The caller must free() the returned string. */
84899 static char *string_format(const char *zFormat,
84900                            const char *zDb, const char *zName){
84901   const char *p;
84902   size_t len = 0;
84903   size_t nDb = strlen(zDb);
84904   size_t nName = strlen(zName);
84905   size_t nFullTableName = nDb+1+nName;
84906   char *result;
84907   char *r;
84908
84909   /* first compute length needed */
84910   for(p = zFormat ; *p ; ++p){
84911     len += (*p=='%' ? nFullTableName : 1);
84912   }
84913   len += 1;  /* for null terminator */
84914
84915   r = result = sqlite3_malloc(len);
84916   for(p = zFormat; *p; ++p){
84917     if( *p=='%' ){
84918       memcpy(r, zDb, nDb);
84919       r += nDb;
84920       *r++ = '.';
84921       memcpy(r, zName, nName);
84922       r += nName;
84923     } else {
84924       *r++ = *p;
84925     }
84926   }
84927   *r++ = '\0';
84928   assert( r == result + len );
84929   return result;
84930 }
84931
84932 static int sql_exec(sqlite3 *db, const char *zDb, const char *zName,
84933                     const char *zFormat){
84934   char *zCommand = string_format(zFormat, zDb, zName);
84935   int rc;
84936   FTSTRACE(("FTS3 sql: %s\n", zCommand));
84937   rc = sqlite3_exec(db, zCommand, NULL, 0, NULL);
84938   sqlite3_free(zCommand);
84939   return rc;
84940 }
84941
84942 static int sql_prepare(sqlite3 *db, const char *zDb, const char *zName,
84943                        sqlite3_stmt **ppStmt, const char *zFormat){
84944   char *zCommand = string_format(zFormat, zDb, zName);
84945   int rc;
84946   FTSTRACE(("FTS3 prepare: %s\n", zCommand));
84947   rc = sqlite3_prepare_v2(db, zCommand, -1, ppStmt, NULL);
84948   sqlite3_free(zCommand);
84949   return rc;
84950 }
84951
84952 /* end utility functions */
84953
84954 /* Forward reference */
84955 typedef struct fulltext_vtab fulltext_vtab;
84956
84957 /* A single term in a query is represented by an instances of
84958 ** the following structure. Each word which may match against
84959 ** document content is a term. Operators, like NEAR or OR, are
84960 ** not terms. Query terms are organized as a flat list stored
84961 ** in the Query.pTerms array.
84962 **
84963 ** If the QueryTerm.nPhrase variable is non-zero, then the QueryTerm
84964 ** is the first in a contiguous string of terms that are either part
84965 ** of the same phrase, or connected by the NEAR operator.
84966 **
84967 ** If the QueryTerm.nNear variable is non-zero, then the token is followed 
84968 ** by a NEAR operator with span set to (nNear-1). For example, the 
84969 ** following query:
84970 **
84971 ** The QueryTerm.iPhrase variable stores the index of the token within
84972 ** its phrase, indexed starting at 1, or 1 if the token is not part 
84973 ** of any phrase.
84974 **
84975 ** For example, the data structure used to represent the following query:
84976 **
84977 **     ... MATCH 'sqlite NEAR/5 google NEAR/2 "search engine"'
84978 **
84979 ** is:
84980 **
84981 **     {nPhrase=4, iPhrase=1, nNear=6, pTerm="sqlite"},
84982 **     {nPhrase=0, iPhrase=1, nNear=3, pTerm="google"},
84983 **     {nPhrase=0, iPhrase=1, nNear=0, pTerm="search"},
84984 **     {nPhrase=0, iPhrase=2, nNear=0, pTerm="engine"},
84985 **
84986 ** compiling the FTS3 syntax to Query structures is done by the parseQuery()
84987 ** function.
84988 */
84989 typedef struct QueryTerm {
84990   short int nPhrase; /* How many following terms are part of the same phrase */
84991   short int iPhrase; /* This is the i-th term of a phrase. */
84992   short int iColumn; /* Column of the index that must match this term */
84993   signed char nNear; /* term followed by a NEAR operator with span=(nNear-1) */
84994   signed char isOr;  /* this term is preceded by "OR" */
84995   signed char isNot; /* this term is preceded by "-" */
84996   signed char isPrefix; /* this term is followed by "*" */
84997   char *pTerm;       /* text of the term.  '\000' terminated.  malloced */
84998   int nTerm;         /* Number of bytes in pTerm[] */
84999 } QueryTerm;
85000
85001
85002 /* A query string is parsed into a Query structure.
85003  *
85004  * We could, in theory, allow query strings to be complicated
85005  * nested expressions with precedence determined by parentheses.
85006  * But none of the major search engines do this.  (Perhaps the
85007  * feeling is that an parenthesized expression is two complex of
85008  * an idea for the average user to grasp.)  Taking our lead from
85009  * the major search engines, we will allow queries to be a list
85010  * of terms (with an implied AND operator) or phrases in double-quotes,
85011  * with a single optional "-" before each non-phrase term to designate
85012  * negation and an optional OR connector.
85013  *
85014  * OR binds more tightly than the implied AND, which is what the
85015  * major search engines seem to do.  So, for example:
85016  * 
85017  *    [one two OR three]     ==>    one AND (two OR three)
85018  *    [one OR two three]     ==>    (one OR two) AND three
85019  *
85020  * A "-" before a term matches all entries that lack that term.
85021  * The "-" must occur immediately before the term with in intervening
85022  * space.  This is how the search engines do it.
85023  *
85024  * A NOT term cannot be the right-hand operand of an OR.  If this
85025  * occurs in the query string, the NOT is ignored:
85026  *
85027  *    [one OR -two]          ==>    one OR two
85028  *
85029  */
85030 typedef struct Query {
85031   fulltext_vtab *pFts;  /* The full text index */
85032   int nTerms;           /* Number of terms in the query */
85033   QueryTerm *pTerms;    /* Array of terms.  Space obtained from malloc() */
85034   int nextIsOr;         /* Set the isOr flag on the next inserted term */
85035   int nextIsNear;       /* Set the isOr flag on the next inserted term */
85036   int nextColumn;       /* Next word parsed must be in this column */
85037   int dfltColumn;       /* The default column */
85038 } Query;
85039
85040
85041 /*
85042 ** An instance of the following structure keeps track of generated
85043 ** matching-word offset information and snippets.
85044 */
85045 typedef struct Snippet {
85046   int nMatch;     /* Total number of matches */
85047   int nAlloc;     /* Space allocated for aMatch[] */
85048   struct snippetMatch { /* One entry for each matching term */
85049     char snStatus;       /* Status flag for use while constructing snippets */
85050     short int iCol;      /* The column that contains the match */
85051     short int iTerm;     /* The index in Query.pTerms[] of the matching term */
85052     int iToken;          /* The index of the matching document token */
85053     short int nByte;     /* Number of bytes in the term */
85054     int iStart;          /* The offset to the first character of the term */
85055   } *aMatch;      /* Points to space obtained from malloc */
85056   char *zOffset;  /* Text rendering of aMatch[] */
85057   int nOffset;    /* strlen(zOffset) */
85058   char *zSnippet; /* Snippet text */
85059   int nSnippet;   /* strlen(zSnippet) */
85060 } Snippet;
85061
85062
85063 typedef enum QueryType {
85064   QUERY_GENERIC,   /* table scan */
85065   QUERY_DOCID,     /* lookup by docid */
85066   QUERY_FULLTEXT   /* QUERY_FULLTEXT + [i] is a full-text search for column i*/
85067 } QueryType;
85068
85069 typedef enum fulltext_statement {
85070   CONTENT_INSERT_STMT,
85071   CONTENT_SELECT_STMT,
85072   CONTENT_UPDATE_STMT,
85073   CONTENT_DELETE_STMT,
85074   CONTENT_EXISTS_STMT,
85075
85076   BLOCK_INSERT_STMT,
85077   BLOCK_SELECT_STMT,
85078   BLOCK_DELETE_STMT,
85079   BLOCK_DELETE_ALL_STMT,
85080
85081   SEGDIR_MAX_INDEX_STMT,
85082   SEGDIR_SET_STMT,
85083   SEGDIR_SELECT_LEVEL_STMT,
85084   SEGDIR_SPAN_STMT,
85085   SEGDIR_DELETE_STMT,
85086   SEGDIR_SELECT_SEGMENT_STMT,
85087   SEGDIR_SELECT_ALL_STMT,
85088   SEGDIR_DELETE_ALL_STMT,
85089   SEGDIR_COUNT_STMT,
85090
85091   MAX_STMT                     /* Always at end! */
85092 } fulltext_statement;
85093
85094 /* These must exactly match the enum above. */
85095 /* TODO(shess): Is there some risk that a statement will be used in two
85096 ** cursors at once, e.g.  if a query joins a virtual table to itself?
85097 ** If so perhaps we should move some of these to the cursor object.
85098 */
85099 static const char *const fulltext_zStatement[MAX_STMT] = {
85100   /* CONTENT_INSERT */ NULL,  /* generated in contentInsertStatement() */
85101   /* CONTENT_SELECT */ NULL,  /* generated in contentSelectStatement() */
85102   /* CONTENT_UPDATE */ NULL,  /* generated in contentUpdateStatement() */
85103   /* CONTENT_DELETE */ "delete from %_content where docid = ?",
85104   /* CONTENT_EXISTS */ "select docid from %_content limit 1",
85105
85106   /* BLOCK_INSERT */
85107   "insert into %_segments (blockid, block) values (null, ?)",
85108   /* BLOCK_SELECT */ "select block from %_segments where blockid = ?",
85109   /* BLOCK_DELETE */ "delete from %_segments where blockid between ? and ?",
85110   /* BLOCK_DELETE_ALL */ "delete from %_segments",
85111
85112   /* SEGDIR_MAX_INDEX */ "select max(idx) from %_segdir where level = ?",
85113   /* SEGDIR_SET */ "insert into %_segdir values (?, ?, ?, ?, ?, ?)",
85114   /* SEGDIR_SELECT_LEVEL */
85115   "select start_block, leaves_end_block, root from %_segdir "
85116   " where level = ? order by idx",
85117   /* SEGDIR_SPAN */
85118   "select min(start_block), max(end_block) from %_segdir "
85119   " where level = ? and start_block <> 0",
85120   /* SEGDIR_DELETE */ "delete from %_segdir where level = ?",
85121
85122   /* NOTE(shess): The first three results of the following two
85123   ** statements must match.
85124   */
85125   /* SEGDIR_SELECT_SEGMENT */
85126   "select start_block, leaves_end_block, root from %_segdir "
85127   " where level = ? and idx = ?",
85128   /* SEGDIR_SELECT_ALL */
85129   "select start_block, leaves_end_block, root from %_segdir "
85130   " order by level desc, idx asc",
85131   /* SEGDIR_DELETE_ALL */ "delete from %_segdir",
85132   /* SEGDIR_COUNT */ "select count(*), ifnull(max(level),0) from %_segdir",
85133 };
85134
85135 /*
85136 ** A connection to a fulltext index is an instance of the following
85137 ** structure.  The xCreate and xConnect methods create an instance
85138 ** of this structure and xDestroy and xDisconnect free that instance.
85139 ** All other methods receive a pointer to the structure as one of their
85140 ** arguments.
85141 */
85142 struct fulltext_vtab {
85143   sqlite3_vtab base;               /* Base class used by SQLite core */
85144   sqlite3 *db;                     /* The database connection */
85145   const char *zDb;                 /* logical database name */
85146   const char *zName;               /* virtual table name */
85147   int nColumn;                     /* number of columns in virtual table */
85148   char **azColumn;                 /* column names.  malloced */
85149   char **azContentColumn;          /* column names in content table; malloced */
85150   sqlite3_tokenizer *pTokenizer;   /* tokenizer for inserts and queries */
85151
85152   /* Precompiled statements which we keep as long as the table is
85153   ** open.
85154   */
85155   sqlite3_stmt *pFulltextStatements[MAX_STMT];
85156
85157   /* Precompiled statements used for segment merges.  We run a
85158   ** separate select across the leaf level of each tree being merged.
85159   */
85160   sqlite3_stmt *pLeafSelectStmts[MERGE_COUNT];
85161   /* The statement used to prepare pLeafSelectStmts. */
85162 #define LEAF_SELECT \
85163   "select block from %_segments where blockid between ? and ? order by blockid"
85164
85165   /* These buffer pending index updates during transactions.
85166   ** nPendingData estimates the memory size of the pending data.  It
85167   ** doesn't include the hash-bucket overhead, nor any malloc
85168   ** overhead.  When nPendingData exceeds kPendingThreshold, the
85169   ** buffer is flushed even before the transaction closes.
85170   ** pendingTerms stores the data, and is only valid when nPendingData
85171   ** is >=0 (nPendingData<0 means pendingTerms has not been
85172   ** initialized).  iPrevDocid is the last docid written, used to make
85173   ** certain we're inserting in sorted order.
85174   */
85175   int nPendingData;
85176 #define kPendingThreshold (1*1024*1024)
85177   sqlite_int64 iPrevDocid;
85178   fts3Hash pendingTerms;
85179 };
85180
85181 /*
85182 ** When the core wants to do a query, it create a cursor using a
85183 ** call to xOpen.  This structure is an instance of a cursor.  It
85184 ** is destroyed by xClose.
85185 */
85186 typedef struct fulltext_cursor {
85187   sqlite3_vtab_cursor base;        /* Base class used by SQLite core */
85188   QueryType iCursorType;           /* Copy of sqlite3_index_info.idxNum */
85189   sqlite3_stmt *pStmt;             /* Prepared statement in use by the cursor */
85190   int eof;                         /* True if at End Of Results */
85191   Query q;                         /* Parsed query string */
85192   Snippet snippet;                 /* Cached snippet for the current row */
85193   int iColumn;                     /* Column being searched */
85194   DataBuffer result;               /* Doclist results from fulltextQuery */
85195   DLReader reader;                 /* Result reader if result not empty */
85196 } fulltext_cursor;
85197
85198 static struct fulltext_vtab *cursor_vtab(fulltext_cursor *c){
85199   return (fulltext_vtab *) c->base.pVtab;
85200 }
85201
85202 static const sqlite3_module fts3Module;   /* forward declaration */
85203
85204 /* Return a dynamically generated statement of the form
85205  *   insert into %_content (docid, ...) values (?, ...)
85206  */
85207 static const char *contentInsertStatement(fulltext_vtab *v){
85208   StringBuffer sb;
85209   int i;
85210
85211   initStringBuffer(&sb);
85212   append(&sb, "insert into %_content (docid, ");
85213   appendList(&sb, v->nColumn, v->azContentColumn);
85214   append(&sb, ") values (?");
85215   for(i=0; i<v->nColumn; ++i)
85216     append(&sb, ", ?");
85217   append(&sb, ")");
85218   return stringBufferData(&sb);
85219 }
85220
85221 /* Return a dynamically generated statement of the form
85222  *   select <content columns> from %_content where docid = ?
85223  */
85224 static const char *contentSelectStatement(fulltext_vtab *v){
85225   StringBuffer sb;
85226   initStringBuffer(&sb);
85227   append(&sb, "SELECT ");
85228   appendList(&sb, v->nColumn, v->azContentColumn);
85229   append(&sb, " FROM %_content WHERE docid = ?");
85230   return stringBufferData(&sb);
85231 }
85232
85233 /* Return a dynamically generated statement of the form
85234  *   update %_content set [col_0] = ?, [col_1] = ?, ...
85235  *                    where docid = ?
85236  */
85237 static const char *contentUpdateStatement(fulltext_vtab *v){
85238   StringBuffer sb;
85239   int i;
85240
85241   initStringBuffer(&sb);
85242   append(&sb, "update %_content set ");
85243   for(i=0; i<v->nColumn; ++i) {
85244     if( i>0 ){
85245       append(&sb, ", ");
85246     }
85247     append(&sb, v->azContentColumn[i]);
85248     append(&sb, " = ?");
85249   }
85250   append(&sb, " where docid = ?");
85251   return stringBufferData(&sb);
85252 }
85253
85254 /* Puts a freshly-prepared statement determined by iStmt in *ppStmt.
85255 ** If the indicated statement has never been prepared, it is prepared
85256 ** and cached, otherwise the cached version is reset.
85257 */
85258 static int sql_get_statement(fulltext_vtab *v, fulltext_statement iStmt,
85259                              sqlite3_stmt **ppStmt){
85260   assert( iStmt<MAX_STMT );
85261   if( v->pFulltextStatements[iStmt]==NULL ){
85262     const char *zStmt;
85263     int rc;
85264     switch( iStmt ){
85265       case CONTENT_INSERT_STMT:
85266         zStmt = contentInsertStatement(v); break;
85267       case CONTENT_SELECT_STMT:
85268         zStmt = contentSelectStatement(v); break;
85269       case CONTENT_UPDATE_STMT:
85270         zStmt = contentUpdateStatement(v); break;
85271       default:
85272         zStmt = fulltext_zStatement[iStmt];
85273     }
85274     rc = sql_prepare(v->db, v->zDb, v->zName, &v->pFulltextStatements[iStmt],
85275                          zStmt);
85276     if( zStmt != fulltext_zStatement[iStmt]) sqlite3_free((void *) zStmt);
85277     if( rc!=SQLITE_OK ) return rc;
85278   } else {
85279     int rc = sqlite3_reset(v->pFulltextStatements[iStmt]);
85280     if( rc!=SQLITE_OK ) return rc;
85281   }
85282
85283   *ppStmt = v->pFulltextStatements[iStmt];
85284   return SQLITE_OK;
85285 }
85286
85287 /* Like sqlite3_step(), but convert SQLITE_DONE to SQLITE_OK and
85288 ** SQLITE_ROW to SQLITE_ERROR.  Useful for statements like UPDATE,
85289 ** where we expect no results.
85290 */
85291 static int sql_single_step(sqlite3_stmt *s){
85292   int rc = sqlite3_step(s);
85293   return (rc==SQLITE_DONE) ? SQLITE_OK : rc;
85294 }
85295
85296 /* Like sql_get_statement(), but for special replicated LEAF_SELECT
85297 ** statements.  idx -1 is a special case for an uncached version of
85298 ** the statement (used in the optimize implementation).
85299 */
85300 /* TODO(shess) Write version for generic statements and then share
85301 ** that between the cached-statement functions.
85302 */
85303 static int sql_get_leaf_statement(fulltext_vtab *v, int idx,
85304                                   sqlite3_stmt **ppStmt){
85305   assert( idx>=-1 && idx<MERGE_COUNT );
85306   if( idx==-1 ){
85307     return sql_prepare(v->db, v->zDb, v->zName, ppStmt, LEAF_SELECT);
85308   }else if( v->pLeafSelectStmts[idx]==NULL ){
85309     int rc = sql_prepare(v->db, v->zDb, v->zName, &v->pLeafSelectStmts[idx],
85310                          LEAF_SELECT);
85311     if( rc!=SQLITE_OK ) return rc;
85312   }else{
85313     int rc = sqlite3_reset(v->pLeafSelectStmts[idx]);
85314     if( rc!=SQLITE_OK ) return rc;
85315   }
85316
85317   *ppStmt = v->pLeafSelectStmts[idx];
85318   return SQLITE_OK;
85319 }
85320
85321 /* insert into %_content (docid, ...) values ([docid], [pValues])
85322 ** If the docid contains SQL NULL, then a unique docid will be
85323 ** generated.
85324 */
85325 static int content_insert(fulltext_vtab *v, sqlite3_value *docid,
85326                           sqlite3_value **pValues){
85327   sqlite3_stmt *s;
85328   int i;
85329   int rc = sql_get_statement(v, CONTENT_INSERT_STMT, &s);
85330   if( rc!=SQLITE_OK ) return rc;
85331
85332   rc = sqlite3_bind_value(s, 1, docid);
85333   if( rc!=SQLITE_OK ) return rc;
85334
85335   for(i=0; i<v->nColumn; ++i){
85336     rc = sqlite3_bind_value(s, 2+i, pValues[i]);
85337     if( rc!=SQLITE_OK ) return rc;
85338   }
85339
85340   return sql_single_step(s);
85341 }
85342
85343 /* update %_content set col0 = pValues[0], col1 = pValues[1], ...
85344  *                  where docid = [iDocid] */
85345 static int content_update(fulltext_vtab *v, sqlite3_value **pValues,
85346                           sqlite_int64 iDocid){
85347   sqlite3_stmt *s;
85348   int i;
85349   int rc = sql_get_statement(v, CONTENT_UPDATE_STMT, &s);
85350   if( rc!=SQLITE_OK ) return rc;
85351
85352   for(i=0; i<v->nColumn; ++i){
85353     rc = sqlite3_bind_value(s, 1+i, pValues[i]);
85354     if( rc!=SQLITE_OK ) return rc;
85355   }
85356
85357   rc = sqlite3_bind_int64(s, 1+v->nColumn, iDocid);
85358   if( rc!=SQLITE_OK ) return rc;
85359
85360   return sql_single_step(s);
85361 }
85362
85363 static void freeStringArray(int nString, const char **pString){
85364   int i;
85365
85366   for (i=0 ; i < nString ; ++i) {
85367     if( pString[i]!=NULL ) sqlite3_free((void *) pString[i]);
85368   }
85369   sqlite3_free((void *) pString);
85370 }
85371
85372 /* select * from %_content where docid = [iDocid]
85373  * The caller must delete the returned array and all strings in it.
85374  * null fields will be NULL in the returned array.
85375  *
85376  * TODO: Perhaps we should return pointer/length strings here for consistency
85377  * with other code which uses pointer/length. */
85378 static int content_select(fulltext_vtab *v, sqlite_int64 iDocid,
85379                           const char ***pValues){
85380   sqlite3_stmt *s;
85381   const char **values;
85382   int i;
85383   int rc;
85384
85385   *pValues = NULL;
85386
85387   rc = sql_get_statement(v, CONTENT_SELECT_STMT, &s);
85388   if( rc!=SQLITE_OK ) return rc;
85389
85390   rc = sqlite3_bind_int64(s, 1, iDocid);
85391   if( rc!=SQLITE_OK ) return rc;
85392
85393   rc = sqlite3_step(s);
85394   if( rc!=SQLITE_ROW ) return rc;
85395
85396   values = (const char **) sqlite3_malloc(v->nColumn * sizeof(const char *));
85397   for(i=0; i<v->nColumn; ++i){
85398     if( sqlite3_column_type(s, i)==SQLITE_NULL ){
85399       values[i] = NULL;
85400     }else{
85401       values[i] = string_dup((char*)sqlite3_column_text(s, i));
85402     }
85403   }
85404
85405   /* We expect only one row.  We must execute another sqlite3_step()
85406    * to complete the iteration; otherwise the table will remain locked. */
85407   rc = sqlite3_step(s);
85408   if( rc==SQLITE_DONE ){
85409     *pValues = values;
85410     return SQLITE_OK;
85411   }
85412
85413   freeStringArray(v->nColumn, values);
85414   return rc;
85415 }
85416
85417 /* delete from %_content where docid = [iDocid ] */
85418 static int content_delete(fulltext_vtab *v, sqlite_int64 iDocid){
85419   sqlite3_stmt *s;
85420   int rc = sql_get_statement(v, CONTENT_DELETE_STMT, &s);
85421   if( rc!=SQLITE_OK ) return rc;
85422
85423   rc = sqlite3_bind_int64(s, 1, iDocid);
85424   if( rc!=SQLITE_OK ) return rc;
85425
85426   return sql_single_step(s);
85427 }
85428
85429 /* Returns SQLITE_ROW if any rows exist in %_content, SQLITE_DONE if
85430 ** no rows exist, and any error in case of failure.
85431 */
85432 static int content_exists(fulltext_vtab *v){
85433   sqlite3_stmt *s;
85434   int rc = sql_get_statement(v, CONTENT_EXISTS_STMT, &s);
85435   if( rc!=SQLITE_OK ) return rc;
85436
85437   rc = sqlite3_step(s);
85438   if( rc!=SQLITE_ROW ) return rc;
85439
85440   /* We expect only one row.  We must execute another sqlite3_step()
85441    * to complete the iteration; otherwise the table will remain locked. */
85442   rc = sqlite3_step(s);
85443   if( rc==SQLITE_DONE ) return SQLITE_ROW;
85444   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
85445   return rc;
85446 }
85447
85448 /* insert into %_segments values ([pData])
85449 **   returns assigned blockid in *piBlockid
85450 */
85451 static int block_insert(fulltext_vtab *v, const char *pData, int nData,
85452                         sqlite_int64 *piBlockid){
85453   sqlite3_stmt *s;
85454   int rc = sql_get_statement(v, BLOCK_INSERT_STMT, &s);
85455   if( rc!=SQLITE_OK ) return rc;
85456
85457   rc = sqlite3_bind_blob(s, 1, pData, nData, SQLITE_STATIC);
85458   if( rc!=SQLITE_OK ) return rc;
85459
85460   rc = sqlite3_step(s);
85461   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
85462   if( rc!=SQLITE_DONE ) return rc;
85463
85464   /* blockid column is an alias for rowid. */
85465   *piBlockid = sqlite3_last_insert_rowid(v->db);
85466   return SQLITE_OK;
85467 }
85468
85469 /* delete from %_segments
85470 **   where blockid between [iStartBlockid] and [iEndBlockid]
85471 **
85472 ** Deletes the range of blocks, inclusive, used to delete the blocks
85473 ** which form a segment.
85474 */
85475 static int block_delete(fulltext_vtab *v,
85476                         sqlite_int64 iStartBlockid, sqlite_int64 iEndBlockid){
85477   sqlite3_stmt *s;
85478   int rc = sql_get_statement(v, BLOCK_DELETE_STMT, &s);
85479   if( rc!=SQLITE_OK ) return rc;
85480
85481   rc = sqlite3_bind_int64(s, 1, iStartBlockid);
85482   if( rc!=SQLITE_OK ) return rc;
85483
85484   rc = sqlite3_bind_int64(s, 2, iEndBlockid);
85485   if( rc!=SQLITE_OK ) return rc;
85486
85487   return sql_single_step(s);
85488 }
85489
85490 /* Returns SQLITE_ROW with *pidx set to the maximum segment idx found
85491 ** at iLevel.  Returns SQLITE_DONE if there are no segments at
85492 ** iLevel.  Otherwise returns an error.
85493 */
85494 static int segdir_max_index(fulltext_vtab *v, int iLevel, int *pidx){
85495   sqlite3_stmt *s;
85496   int rc = sql_get_statement(v, SEGDIR_MAX_INDEX_STMT, &s);
85497   if( rc!=SQLITE_OK ) return rc;
85498
85499   rc = sqlite3_bind_int(s, 1, iLevel);
85500   if( rc!=SQLITE_OK ) return rc;
85501
85502   rc = sqlite3_step(s);
85503   /* Should always get at least one row due to how max() works. */
85504   if( rc==SQLITE_DONE ) return SQLITE_DONE;
85505   if( rc!=SQLITE_ROW ) return rc;
85506
85507   /* NULL means that there were no inputs to max(). */
85508   if( SQLITE_NULL==sqlite3_column_type(s, 0) ){
85509     rc = sqlite3_step(s);
85510     if( rc==SQLITE_ROW ) return SQLITE_ERROR;
85511     return rc;
85512   }
85513
85514   *pidx = sqlite3_column_int(s, 0);
85515
85516   /* We expect only one row.  We must execute another sqlite3_step()
85517    * to complete the iteration; otherwise the table will remain locked. */
85518   rc = sqlite3_step(s);
85519   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
85520   if( rc!=SQLITE_DONE ) return rc;
85521   return SQLITE_ROW;
85522 }
85523
85524 /* insert into %_segdir values (
85525 **   [iLevel], [idx],
85526 **   [iStartBlockid], [iLeavesEndBlockid], [iEndBlockid],
85527 **   [pRootData]
85528 ** )
85529 */
85530 static int segdir_set(fulltext_vtab *v, int iLevel, int idx,
85531                       sqlite_int64 iStartBlockid,
85532                       sqlite_int64 iLeavesEndBlockid,
85533                       sqlite_int64 iEndBlockid,
85534                       const char *pRootData, int nRootData){
85535   sqlite3_stmt *s;
85536   int rc = sql_get_statement(v, SEGDIR_SET_STMT, &s);
85537   if( rc!=SQLITE_OK ) return rc;
85538
85539   rc = sqlite3_bind_int(s, 1, iLevel);
85540   if( rc!=SQLITE_OK ) return rc;
85541
85542   rc = sqlite3_bind_int(s, 2, idx);
85543   if( rc!=SQLITE_OK ) return rc;
85544
85545   rc = sqlite3_bind_int64(s, 3, iStartBlockid);
85546   if( rc!=SQLITE_OK ) return rc;
85547
85548   rc = sqlite3_bind_int64(s, 4, iLeavesEndBlockid);
85549   if( rc!=SQLITE_OK ) return rc;
85550
85551   rc = sqlite3_bind_int64(s, 5, iEndBlockid);
85552   if( rc!=SQLITE_OK ) return rc;
85553
85554   rc = sqlite3_bind_blob(s, 6, pRootData, nRootData, SQLITE_STATIC);
85555   if( rc!=SQLITE_OK ) return rc;
85556
85557   return sql_single_step(s);
85558 }
85559
85560 /* Queries %_segdir for the block span of the segments in level
85561 ** iLevel.  Returns SQLITE_DONE if there are no blocks for iLevel,
85562 ** SQLITE_ROW if there are blocks, else an error.
85563 */
85564 static int segdir_span(fulltext_vtab *v, int iLevel,
85565                        sqlite_int64 *piStartBlockid,
85566                        sqlite_int64 *piEndBlockid){
85567   sqlite3_stmt *s;
85568   int rc = sql_get_statement(v, SEGDIR_SPAN_STMT, &s);
85569   if( rc!=SQLITE_OK ) return rc;
85570
85571   rc = sqlite3_bind_int(s, 1, iLevel);
85572   if( rc!=SQLITE_OK ) return rc;
85573
85574   rc = sqlite3_step(s);
85575   if( rc==SQLITE_DONE ) return SQLITE_DONE;  /* Should never happen */
85576   if( rc!=SQLITE_ROW ) return rc;
85577
85578   /* This happens if all segments at this level are entirely inline. */
85579   if( SQLITE_NULL==sqlite3_column_type(s, 0) ){
85580     /* We expect only one row.  We must execute another sqlite3_step()
85581      * to complete the iteration; otherwise the table will remain locked. */
85582     int rc2 = sqlite3_step(s);
85583     if( rc2==SQLITE_ROW ) return SQLITE_ERROR;
85584     return rc2;
85585   }
85586
85587   *piStartBlockid = sqlite3_column_int64(s, 0);
85588   *piEndBlockid = sqlite3_column_int64(s, 1);
85589
85590   /* We expect only one row.  We must execute another sqlite3_step()
85591    * to complete the iteration; otherwise the table will remain locked. */
85592   rc = sqlite3_step(s);
85593   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
85594   if( rc!=SQLITE_DONE ) return rc;
85595   return SQLITE_ROW;
85596 }
85597
85598 /* Delete the segment blocks and segment directory records for all
85599 ** segments at iLevel.
85600 */
85601 static int segdir_delete(fulltext_vtab *v, int iLevel){
85602   sqlite3_stmt *s;
85603   sqlite_int64 iStartBlockid, iEndBlockid;
85604   int rc = segdir_span(v, iLevel, &iStartBlockid, &iEndBlockid);
85605   if( rc!=SQLITE_ROW && rc!=SQLITE_DONE ) return rc;
85606
85607   if( rc==SQLITE_ROW ){
85608     rc = block_delete(v, iStartBlockid, iEndBlockid);
85609     if( rc!=SQLITE_OK ) return rc;
85610   }
85611
85612   /* Delete the segment directory itself. */
85613   rc = sql_get_statement(v, SEGDIR_DELETE_STMT, &s);
85614   if( rc!=SQLITE_OK ) return rc;
85615
85616   rc = sqlite3_bind_int64(s, 1, iLevel);
85617   if( rc!=SQLITE_OK ) return rc;
85618
85619   return sql_single_step(s);
85620 }
85621
85622 /* Delete entire fts index, SQLITE_OK on success, relevant error on
85623 ** failure.
85624 */
85625 static int segdir_delete_all(fulltext_vtab *v){
85626   sqlite3_stmt *s;
85627   int rc = sql_get_statement(v, SEGDIR_DELETE_ALL_STMT, &s);
85628   if( rc!=SQLITE_OK ) return rc;
85629
85630   rc = sql_single_step(s);
85631   if( rc!=SQLITE_OK ) return rc;
85632
85633   rc = sql_get_statement(v, BLOCK_DELETE_ALL_STMT, &s);
85634   if( rc!=SQLITE_OK ) return rc;
85635
85636   return sql_single_step(s);
85637 }
85638
85639 /* Returns SQLITE_OK with *pnSegments set to the number of entries in
85640 ** %_segdir and *piMaxLevel set to the highest level which has a
85641 ** segment.  Otherwise returns the SQLite error which caused failure.
85642 */
85643 static int segdir_count(fulltext_vtab *v, int *pnSegments, int *piMaxLevel){
85644   sqlite3_stmt *s;
85645   int rc = sql_get_statement(v, SEGDIR_COUNT_STMT, &s);
85646   if( rc!=SQLITE_OK ) return rc;
85647
85648   rc = sqlite3_step(s);
85649   /* TODO(shess): This case should not be possible?  Should stronger
85650   ** measures be taken if it happens?
85651   */
85652   if( rc==SQLITE_DONE ){
85653     *pnSegments = 0;
85654     *piMaxLevel = 0;
85655     return SQLITE_OK;
85656   }
85657   if( rc!=SQLITE_ROW ) return rc;
85658
85659   *pnSegments = sqlite3_column_int(s, 0);
85660   *piMaxLevel = sqlite3_column_int(s, 1);
85661
85662   /* We expect only one row.  We must execute another sqlite3_step()
85663    * to complete the iteration; otherwise the table will remain locked. */
85664   rc = sqlite3_step(s);
85665   if( rc==SQLITE_DONE ) return SQLITE_OK;
85666   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
85667   return rc;
85668 }
85669
85670 /* TODO(shess) clearPendingTerms() is far down the file because
85671 ** writeZeroSegment() is far down the file because LeafWriter is far
85672 ** down the file.  Consider refactoring the code to move the non-vtab
85673 ** code above the vtab code so that we don't need this forward
85674 ** reference.
85675 */
85676 static int clearPendingTerms(fulltext_vtab *v);
85677
85678 /*
85679 ** Free the memory used to contain a fulltext_vtab structure.
85680 */
85681 static void fulltext_vtab_destroy(fulltext_vtab *v){
85682   int iStmt, i;
85683
85684   FTSTRACE(("FTS3 Destroy %p\n", v));
85685   for( iStmt=0; iStmt<MAX_STMT; iStmt++ ){
85686     if( v->pFulltextStatements[iStmt]!=NULL ){
85687       sqlite3_finalize(v->pFulltextStatements[iStmt]);
85688       v->pFulltextStatements[iStmt] = NULL;
85689     }
85690   }
85691
85692   for( i=0; i<MERGE_COUNT; i++ ){
85693     if( v->pLeafSelectStmts[i]!=NULL ){
85694       sqlite3_finalize(v->pLeafSelectStmts[i]);
85695       v->pLeafSelectStmts[i] = NULL;
85696     }
85697   }
85698
85699   if( v->pTokenizer!=NULL ){
85700     v->pTokenizer->pModule->xDestroy(v->pTokenizer);
85701     v->pTokenizer = NULL;
85702   }
85703
85704   clearPendingTerms(v);
85705
85706   sqlite3_free(v->azColumn);
85707   for(i = 0; i < v->nColumn; ++i) {
85708     sqlite3_free(v->azContentColumn[i]);
85709   }
85710   sqlite3_free(v->azContentColumn);
85711   sqlite3_free(v);
85712 }
85713
85714 /*
85715 ** Token types for parsing the arguments to xConnect or xCreate.
85716 */
85717 #define TOKEN_EOF         0    /* End of file */
85718 #define TOKEN_SPACE       1    /* Any kind of whitespace */
85719 #define TOKEN_ID          2    /* An identifier */
85720 #define TOKEN_STRING      3    /* A string literal */
85721 #define TOKEN_PUNCT       4    /* A single punctuation character */
85722
85723 /*
85724 ** If X is a character that can be used in an identifier then
85725 ** ftsIdChar(X) will be true.  Otherwise it is false.
85726 **
85727 ** For ASCII, any character with the high-order bit set is
85728 ** allowed in an identifier.  For 7-bit characters, 
85729 ** isFtsIdChar[X] must be 1.
85730 **
85731 ** Ticket #1066.  the SQL standard does not allow '$' in the
85732 ** middle of identfiers.  But many SQL implementations do. 
85733 ** SQLite will allow '$' in identifiers for compatibility.
85734 ** But the feature is undocumented.
85735 */
85736 static const char isFtsIdChar[] = {
85737 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
85738     0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
85739     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
85740     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
85741     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
85742     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
85743     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
85744 };
85745 #define ftsIdChar(C)  (((c=C)&0x80)!=0 || (c>0x1f && isFtsIdChar[c-0x20]))
85746
85747
85748 /*
85749 ** Return the length of the token that begins at z[0]. 
85750 ** Store the token type in *tokenType before returning.
85751 */
85752 static int ftsGetToken(const char *z, int *tokenType){
85753   int i, c;
85754   switch( *z ){
85755     case 0: {
85756       *tokenType = TOKEN_EOF;
85757       return 0;
85758     }
85759     case ' ': case '\t': case '\n': case '\f': case '\r': {
85760       for(i=1; safe_isspace(z[i]); i++){}
85761       *tokenType = TOKEN_SPACE;
85762       return i;
85763     }
85764     case '`':
85765     case '\'':
85766     case '"': {
85767       int delim = z[0];
85768       for(i=1; (c=z[i])!=0; i++){
85769         if( c==delim ){
85770           if( z[i+1]==delim ){
85771             i++;
85772           }else{
85773             break;
85774           }
85775         }
85776       }
85777       *tokenType = TOKEN_STRING;
85778       return i + (c!=0);
85779     }
85780     case '[': {
85781       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
85782       *tokenType = TOKEN_ID;
85783       return i;
85784     }
85785     default: {
85786       if( !ftsIdChar(*z) ){
85787         break;
85788       }
85789       for(i=1; ftsIdChar(z[i]); i++){}
85790       *tokenType = TOKEN_ID;
85791       return i;
85792     }
85793   }
85794   *tokenType = TOKEN_PUNCT;
85795   return 1;
85796 }
85797
85798 /*
85799 ** A token extracted from a string is an instance of the following
85800 ** structure.
85801 */
85802 typedef struct FtsToken {
85803   const char *z;       /* Pointer to token text.  Not '\000' terminated */
85804   short int n;         /* Length of the token text in bytes. */
85805 } FtsToken;
85806
85807 /*
85808 ** Given a input string (which is really one of the argv[] parameters
85809 ** passed into xConnect or xCreate) split the string up into tokens.
85810 ** Return an array of pointers to '\000' terminated strings, one string
85811 ** for each non-whitespace token.
85812 **
85813 ** The returned array is terminated by a single NULL pointer.
85814 **
85815 ** Space to hold the returned array is obtained from a single
85816 ** malloc and should be freed by passing the return value to free().
85817 ** The individual strings within the token list are all a part of
85818 ** the single memory allocation and will all be freed at once.
85819 */
85820 static char **tokenizeString(const char *z, int *pnToken){
85821   int nToken = 0;
85822   FtsToken *aToken = sqlite3_malloc( strlen(z) * sizeof(aToken[0]) );
85823   int n = 1;
85824   int e, i;
85825   int totalSize = 0;
85826   char **azToken;
85827   char *zCopy;
85828   while( n>0 ){
85829     n = ftsGetToken(z, &e);
85830     if( e!=TOKEN_SPACE ){
85831       aToken[nToken].z = z;
85832       aToken[nToken].n = n;
85833       nToken++;
85834       totalSize += n+1;
85835     }
85836     z += n;
85837   }
85838   azToken = (char**)sqlite3_malloc( nToken*sizeof(char*) + totalSize );
85839   zCopy = (char*)&azToken[nToken];
85840   nToken--;
85841   for(i=0; i<nToken; i++){
85842     azToken[i] = zCopy;
85843     n = aToken[i].n;
85844     memcpy(zCopy, aToken[i].z, n);
85845     zCopy[n] = 0;
85846     zCopy += n+1;
85847   }
85848   azToken[nToken] = 0;
85849   sqlite3_free(aToken);
85850   *pnToken = nToken;
85851   return azToken;
85852 }
85853
85854 /*
85855 ** Convert an SQL-style quoted string into a normal string by removing
85856 ** the quote characters.  The conversion is done in-place.  If the
85857 ** input does not begin with a quote character, then this routine
85858 ** is a no-op.
85859 **
85860 ** Examples:
85861 **
85862 **     "abc"   becomes   abc
85863 **     'xyz'   becomes   xyz
85864 **     [pqr]   becomes   pqr
85865 **     `mno`   becomes   mno
85866 */
85867 static void dequoteString(char *z){
85868   int quote;
85869   int i, j;
85870   if( z==0 ) return;
85871   quote = z[0];
85872   switch( quote ){
85873     case '\'':  break;
85874     case '"':   break;
85875     case '`':   break;                /* For MySQL compatibility */
85876     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
85877     default:    return;
85878   }
85879   for(i=1, j=0; z[i]; i++){
85880     if( z[i]==quote ){
85881       if( z[i+1]==quote ){
85882         z[j++] = quote;
85883         i++;
85884       }else{
85885         z[j++] = 0;
85886         break;
85887       }
85888     }else{
85889       z[j++] = z[i];
85890     }
85891   }
85892 }
85893
85894 /*
85895 ** The input azIn is a NULL-terminated list of tokens.  Remove the first
85896 ** token and all punctuation tokens.  Remove the quotes from
85897 ** around string literal tokens.
85898 **
85899 ** Example:
85900 **
85901 **     input:      tokenize chinese ( 'simplifed' , 'mixed' )
85902 **     output:     chinese simplifed mixed
85903 **
85904 ** Another example:
85905 **
85906 **     input:      delimiters ( '[' , ']' , '...' )
85907 **     output:     [ ] ...
85908 */
85909 static void tokenListToIdList(char **azIn){
85910   int i, j;
85911   if( azIn ){
85912     for(i=0, j=-1; azIn[i]; i++){
85913       if( safe_isalnum(azIn[i][0]) || azIn[i][1] ){
85914         dequoteString(azIn[i]);
85915         if( j>=0 ){
85916           azIn[j] = azIn[i];
85917         }
85918         j++;
85919       }
85920     }
85921     azIn[j] = 0;
85922   }
85923 }
85924
85925
85926 /*
85927 ** Find the first alphanumeric token in the string zIn.  Null-terminate
85928 ** this token.  Remove any quotation marks.  And return a pointer to
85929 ** the result.
85930 */
85931 static char *firstToken(char *zIn, char **pzTail){
85932   int n, ttype;
85933   while(1){
85934     n = ftsGetToken(zIn, &ttype);
85935     if( ttype==TOKEN_SPACE ){
85936       zIn += n;
85937     }else if( ttype==TOKEN_EOF ){
85938       *pzTail = zIn;
85939       return 0;
85940     }else{
85941       zIn[n] = 0;
85942       *pzTail = &zIn[1];
85943       dequoteString(zIn);
85944       return zIn;
85945     }
85946   }
85947   /*NOTREACHED*/
85948 }
85949
85950 /* Return true if...
85951 **
85952 **   *  s begins with the string t, ignoring case
85953 **   *  s is longer than t
85954 **   *  The first character of s beyond t is not a alphanumeric
85955 ** 
85956 ** Ignore leading space in *s.
85957 **
85958 ** To put it another way, return true if the first token of
85959 ** s[] is t[].
85960 */
85961 static int startsWith(const char *s, const char *t){
85962   while( safe_isspace(*s) ){ s++; }
85963   while( *t ){
85964     if( safe_tolower(*s++)!=safe_tolower(*t++) ) return 0;
85965   }
85966   return *s!='_' && !safe_isalnum(*s);
85967 }
85968
85969 /*
85970 ** An instance of this structure defines the "spec" of a
85971 ** full text index.  This structure is populated by parseSpec
85972 ** and use by fulltextConnect and fulltextCreate.
85973 */
85974 typedef struct TableSpec {
85975   const char *zDb;         /* Logical database name */
85976   const char *zName;       /* Name of the full-text index */
85977   int nColumn;             /* Number of columns to be indexed */
85978   char **azColumn;         /* Original names of columns to be indexed */
85979   char **azContentColumn;  /* Column names for %_content */
85980   char **azTokenizer;      /* Name of tokenizer and its arguments */
85981 } TableSpec;
85982
85983 /*
85984 ** Reclaim all of the memory used by a TableSpec
85985 */
85986 static void clearTableSpec(TableSpec *p) {
85987   sqlite3_free(p->azColumn);
85988   sqlite3_free(p->azContentColumn);
85989   sqlite3_free(p->azTokenizer);
85990 }
85991
85992 /* Parse a CREATE VIRTUAL TABLE statement, which looks like this:
85993  *
85994  * CREATE VIRTUAL TABLE email
85995  *        USING fts3(subject, body, tokenize mytokenizer(myarg))
85996  *
85997  * We return parsed information in a TableSpec structure.
85998  * 
85999  */
86000 static int parseSpec(TableSpec *pSpec, int argc, const char *const*argv,
86001                      char**pzErr){
86002   int i, n;
86003   char *z, *zDummy;
86004   char **azArg;
86005   const char *zTokenizer = 0;    /* argv[] entry describing the tokenizer */
86006
86007   assert( argc>=3 );
86008   /* Current interface:
86009   ** argv[0] - module name
86010   ** argv[1] - database name
86011   ** argv[2] - table name
86012   ** argv[3..] - columns, optionally followed by tokenizer specification
86013   **             and snippet delimiters specification.
86014   */
86015
86016   /* Make a copy of the complete argv[][] array in a single allocation.
86017   ** The argv[][] array is read-only and transient.  We can write to the
86018   ** copy in order to modify things and the copy is persistent.
86019   */
86020   CLEAR(pSpec);
86021   for(i=n=0; i<argc; i++){
86022     n += strlen(argv[i]) + 1;
86023   }
86024   azArg = sqlite3_malloc( sizeof(char*)*argc + n );
86025   if( azArg==0 ){
86026     return SQLITE_NOMEM;
86027   }
86028   z = (char*)&azArg[argc];
86029   for(i=0; i<argc; i++){
86030     azArg[i] = z;
86031     strcpy(z, argv[i]);
86032     z += strlen(z)+1;
86033   }
86034
86035   /* Identify the column names and the tokenizer and delimiter arguments
86036   ** in the argv[][] array.
86037   */
86038   pSpec->zDb = azArg[1];
86039   pSpec->zName = azArg[2];
86040   pSpec->nColumn = 0;
86041   pSpec->azColumn = azArg;
86042   zTokenizer = "tokenize simple";
86043   for(i=3; i<argc; ++i){
86044     if( startsWith(azArg[i],"tokenize") ){
86045       zTokenizer = azArg[i];
86046     }else{
86047       z = azArg[pSpec->nColumn] = firstToken(azArg[i], &zDummy);
86048       pSpec->nColumn++;
86049     }
86050   }
86051   if( pSpec->nColumn==0 ){
86052     azArg[0] = "content";
86053     pSpec->nColumn = 1;
86054   }
86055
86056   /*
86057   ** Construct the list of content column names.
86058   **
86059   ** Each content column name will be of the form cNNAAAA
86060   ** where NN is the column number and AAAA is the sanitized
86061   ** column name.  "sanitized" means that special characters are
86062   ** converted to "_".  The cNN prefix guarantees that all column
86063   ** names are unique.
86064   **
86065   ** The AAAA suffix is not strictly necessary.  It is included
86066   ** for the convenience of people who might examine the generated
86067   ** %_content table and wonder what the columns are used for.
86068   */
86069   pSpec->azContentColumn = sqlite3_malloc( pSpec->nColumn * sizeof(char *) );
86070   if( pSpec->azContentColumn==0 ){
86071     clearTableSpec(pSpec);
86072     return SQLITE_NOMEM;
86073   }
86074   for(i=0; i<pSpec->nColumn; i++){
86075     char *p;
86076     pSpec->azContentColumn[i] = sqlite3_mprintf("c%d%s", i, azArg[i]);
86077     for (p = pSpec->azContentColumn[i]; *p ; ++p) {
86078       if( !safe_isalnum(*p) ) *p = '_';
86079     }
86080   }
86081
86082   /*
86083   ** Parse the tokenizer specification string.
86084   */
86085   pSpec->azTokenizer = tokenizeString(zTokenizer, &n);
86086   tokenListToIdList(pSpec->azTokenizer);
86087
86088   return SQLITE_OK;
86089 }
86090
86091 /*
86092 ** Generate a CREATE TABLE statement that describes the schema of
86093 ** the virtual table.  Return a pointer to this schema string.
86094 **
86095 ** Space is obtained from sqlite3_mprintf() and should be freed
86096 ** using sqlite3_free().
86097 */
86098 static char *fulltextSchema(
86099   int nColumn,                  /* Number of columns */
86100   const char *const* azColumn,  /* List of columns */
86101   const char *zTableName        /* Name of the table */
86102 ){
86103   int i;
86104   char *zSchema, *zNext;
86105   const char *zSep = "(";
86106   zSchema = sqlite3_mprintf("CREATE TABLE x");
86107   for(i=0; i<nColumn; i++){
86108     zNext = sqlite3_mprintf("%s%s%Q", zSchema, zSep, azColumn[i]);
86109     sqlite3_free(zSchema);
86110     zSchema = zNext;
86111     zSep = ",";
86112   }
86113   zNext = sqlite3_mprintf("%s,%Q HIDDEN", zSchema, zTableName);
86114   sqlite3_free(zSchema);
86115   zSchema = zNext;
86116   zNext = sqlite3_mprintf("%s,docid HIDDEN)", zSchema);
86117   sqlite3_free(zSchema);
86118   return zNext;
86119 }
86120
86121 /*
86122 ** Build a new sqlite3_vtab structure that will describe the
86123 ** fulltext index defined by spec.
86124 */
86125 static int constructVtab(
86126   sqlite3 *db,              /* The SQLite database connection */
86127   fts3Hash *pHash,          /* Hash table containing tokenizers */
86128   TableSpec *spec,          /* Parsed spec information from parseSpec() */
86129   sqlite3_vtab **ppVTab,    /* Write the resulting vtab structure here */
86130   char **pzErr              /* Write any error message here */
86131 ){
86132   int rc;
86133   int n;
86134   fulltext_vtab *v = 0;
86135   const sqlite3_tokenizer_module *m = NULL;
86136   char *schema;
86137
86138   char const *zTok;         /* Name of tokenizer to use for this fts table */
86139   int nTok;                 /* Length of zTok, including nul terminator */
86140
86141   v = (fulltext_vtab *) sqlite3_malloc(sizeof(fulltext_vtab));
86142   if( v==0 ) return SQLITE_NOMEM;
86143   CLEAR(v);
86144   /* sqlite will initialize v->base */
86145   v->db = db;
86146   v->zDb = spec->zDb;       /* Freed when azColumn is freed */
86147   v->zName = spec->zName;   /* Freed when azColumn is freed */
86148   v->nColumn = spec->nColumn;
86149   v->azContentColumn = spec->azContentColumn;
86150   spec->azContentColumn = 0;
86151   v->azColumn = spec->azColumn;
86152   spec->azColumn = 0;
86153
86154   if( spec->azTokenizer==0 ){
86155     return SQLITE_NOMEM;
86156   }
86157
86158   zTok = spec->azTokenizer[0]; 
86159   if( !zTok ){
86160     zTok = "simple";
86161   }
86162   nTok = strlen(zTok)+1;
86163
86164   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zTok, nTok);
86165   if( !m ){
86166     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", spec->azTokenizer[0]);
86167     rc = SQLITE_ERROR;
86168     goto err;
86169   }
86170
86171   for(n=0; spec->azTokenizer[n]; n++){}
86172   if( n ){
86173     rc = m->xCreate(n-1, (const char*const*)&spec->azTokenizer[1],
86174                     &v->pTokenizer);
86175   }else{
86176     rc = m->xCreate(0, 0, &v->pTokenizer);
86177   }
86178   if( rc!=SQLITE_OK ) goto err;
86179   v->pTokenizer->pModule = m;
86180
86181   /* TODO: verify the existence of backing tables foo_content, foo_term */
86182
86183   schema = fulltextSchema(v->nColumn, (const char*const*)v->azColumn,
86184                           spec->zName);
86185   rc = sqlite3_declare_vtab(db, schema);
86186   sqlite3_free(schema);
86187   if( rc!=SQLITE_OK ) goto err;
86188
86189   memset(v->pFulltextStatements, 0, sizeof(v->pFulltextStatements));
86190
86191   /* Indicate that the buffer is not live. */
86192   v->nPendingData = -1;
86193
86194   *ppVTab = &v->base;
86195   FTSTRACE(("FTS3 Connect %p\n", v));
86196
86197   return rc;
86198
86199 err:
86200   fulltext_vtab_destroy(v);
86201   return rc;
86202 }
86203
86204 static int fulltextConnect(
86205   sqlite3 *db,
86206   void *pAux,
86207   int argc, const char *const*argv,
86208   sqlite3_vtab **ppVTab,
86209   char **pzErr
86210 ){
86211   TableSpec spec;
86212   int rc = parseSpec(&spec, argc, argv, pzErr);
86213   if( rc!=SQLITE_OK ) return rc;
86214
86215   rc = constructVtab(db, (fts3Hash *)pAux, &spec, ppVTab, pzErr);
86216   clearTableSpec(&spec);
86217   return rc;
86218 }
86219
86220 /* The %_content table holds the text of each document, with
86221 ** the docid column exposed as the SQLite rowid for the table.
86222 */
86223 /* TODO(shess) This comment needs elaboration to match the updated
86224 ** code.  Work it into the top-of-file comment at that time.
86225 */
86226 static int fulltextCreate(sqlite3 *db, void *pAux,
86227                           int argc, const char * const *argv,
86228                           sqlite3_vtab **ppVTab, char **pzErr){
86229   int rc;
86230   TableSpec spec;
86231   StringBuffer schema;
86232   FTSTRACE(("FTS3 Create\n"));
86233
86234   rc = parseSpec(&spec, argc, argv, pzErr);
86235   if( rc!=SQLITE_OK ) return rc;
86236
86237   initStringBuffer(&schema);
86238   append(&schema, "CREATE TABLE %_content(");
86239   append(&schema, "  docid INTEGER PRIMARY KEY,");
86240   appendList(&schema, spec.nColumn, spec.azContentColumn);
86241   append(&schema, ")");
86242   rc = sql_exec(db, spec.zDb, spec.zName, stringBufferData(&schema));
86243   stringBufferDestroy(&schema);
86244   if( rc!=SQLITE_OK ) goto out;
86245
86246   rc = sql_exec(db, spec.zDb, spec.zName,
86247                 "create table %_segments("
86248                 "  blockid INTEGER PRIMARY KEY,"
86249                 "  block blob"
86250                 ");"
86251                 );
86252   if( rc!=SQLITE_OK ) goto out;
86253
86254   rc = sql_exec(db, spec.zDb, spec.zName,
86255                 "create table %_segdir("
86256                 "  level integer,"
86257                 "  idx integer,"
86258                 "  start_block integer,"
86259                 "  leaves_end_block integer,"
86260                 "  end_block integer,"
86261                 "  root blob,"
86262                 "  primary key(level, idx)"
86263                 ");");
86264   if( rc!=SQLITE_OK ) goto out;
86265
86266   rc = constructVtab(db, (fts3Hash *)pAux, &spec, ppVTab, pzErr);
86267
86268 out:
86269   clearTableSpec(&spec);
86270   return rc;
86271 }
86272
86273 /* Decide how to handle an SQL query. */
86274 static int fulltextBestIndex(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
86275   fulltext_vtab *v = (fulltext_vtab *)pVTab;
86276   int i;
86277   FTSTRACE(("FTS3 BestIndex\n"));
86278
86279   for(i=0; i<pInfo->nConstraint; ++i){
86280     const struct sqlite3_index_constraint *pConstraint;
86281     pConstraint = &pInfo->aConstraint[i];
86282     if( pConstraint->usable ) {
86283       if( (pConstraint->iColumn==-1 || pConstraint->iColumn==v->nColumn+1) &&
86284           pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
86285         pInfo->idxNum = QUERY_DOCID;      /* lookup by docid */
86286         FTSTRACE(("FTS3 QUERY_DOCID\n"));
86287       } else if( pConstraint->iColumn>=0 && pConstraint->iColumn<=v->nColumn &&
86288                  pConstraint->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
86289         /* full-text search */
86290         pInfo->idxNum = QUERY_FULLTEXT + pConstraint->iColumn;
86291         FTSTRACE(("FTS3 QUERY_FULLTEXT %d\n", pConstraint->iColumn));
86292       } else continue;
86293
86294       pInfo->aConstraintUsage[i].argvIndex = 1;
86295       pInfo->aConstraintUsage[i].omit = 1;
86296
86297       /* An arbitrary value for now.
86298        * TODO: Perhaps docid matches should be considered cheaper than
86299        * full-text searches. */
86300       pInfo->estimatedCost = 1.0;   
86301
86302       return SQLITE_OK;
86303     }
86304   }
86305   pInfo->idxNum = QUERY_GENERIC;
86306   return SQLITE_OK;
86307 }
86308
86309 static int fulltextDisconnect(sqlite3_vtab *pVTab){
86310   FTSTRACE(("FTS3 Disconnect %p\n", pVTab));
86311   fulltext_vtab_destroy((fulltext_vtab *)pVTab);
86312   return SQLITE_OK;
86313 }
86314
86315 static int fulltextDestroy(sqlite3_vtab *pVTab){
86316   fulltext_vtab *v = (fulltext_vtab *)pVTab;
86317   int rc;
86318
86319   FTSTRACE(("FTS3 Destroy %p\n", pVTab));
86320   rc = sql_exec(v->db, v->zDb, v->zName,
86321                 "drop table if exists %_content;"
86322                 "drop table if exists %_segments;"
86323                 "drop table if exists %_segdir;"
86324                 );
86325   if( rc!=SQLITE_OK ) return rc;
86326
86327   fulltext_vtab_destroy((fulltext_vtab *)pVTab);
86328   return SQLITE_OK;
86329 }
86330
86331 static int fulltextOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
86332   fulltext_cursor *c;
86333
86334   c = (fulltext_cursor *) sqlite3_malloc(sizeof(fulltext_cursor));
86335   if( c ){
86336     memset(c, 0, sizeof(fulltext_cursor));
86337     /* sqlite will initialize c->base */
86338     *ppCursor = &c->base;
86339     FTSTRACE(("FTS3 Open %p: %p\n", pVTab, c));
86340     return SQLITE_OK;
86341   }else{
86342     return SQLITE_NOMEM;
86343   }
86344 }
86345
86346
86347 /* Free all of the dynamically allocated memory held by *q
86348 */
86349 static void queryClear(Query *q){
86350   int i;
86351   for(i = 0; i < q->nTerms; ++i){
86352     sqlite3_free(q->pTerms[i].pTerm);
86353   }
86354   sqlite3_free(q->pTerms);
86355   CLEAR(q);
86356 }
86357
86358 /* Free all of the dynamically allocated memory held by the
86359 ** Snippet
86360 */
86361 static void snippetClear(Snippet *p){
86362   sqlite3_free(p->aMatch);
86363   sqlite3_free(p->zOffset);
86364   sqlite3_free(p->zSnippet);
86365   CLEAR(p);
86366 }
86367 /*
86368 ** Append a single entry to the p->aMatch[] log.
86369 */
86370 static void snippetAppendMatch(
86371   Snippet *p,               /* Append the entry to this snippet */
86372   int iCol, int iTerm,      /* The column and query term */
86373   int iToken,               /* Matching token in document */
86374   int iStart, int nByte     /* Offset and size of the match */
86375 ){
86376   int i;
86377   struct snippetMatch *pMatch;
86378   if( p->nMatch+1>=p->nAlloc ){
86379     p->nAlloc = p->nAlloc*2 + 10;
86380     p->aMatch = sqlite3_realloc(p->aMatch, p->nAlloc*sizeof(p->aMatch[0]) );
86381     if( p->aMatch==0 ){
86382       p->nMatch = 0;
86383       p->nAlloc = 0;
86384       return;
86385     }
86386   }
86387   i = p->nMatch++;
86388   pMatch = &p->aMatch[i];
86389   pMatch->iCol = iCol;
86390   pMatch->iTerm = iTerm;
86391   pMatch->iToken = iToken;
86392   pMatch->iStart = iStart;
86393   pMatch->nByte = nByte;
86394 }
86395
86396 /*
86397 ** Sizing information for the circular buffer used in snippetOffsetsOfColumn()
86398 */
86399 #define FTS3_ROTOR_SZ   (32)
86400 #define FTS3_ROTOR_MASK (FTS3_ROTOR_SZ-1)
86401
86402 /*
86403 ** Add entries to pSnippet->aMatch[] for every match that occurs against
86404 ** document zDoc[0..nDoc-1] which is stored in column iColumn.
86405 */
86406 static void snippetOffsetsOfColumn(
86407   Query *pQuery,
86408   Snippet *pSnippet,
86409   int iColumn,
86410   const char *zDoc,
86411   int nDoc
86412 ){
86413   const sqlite3_tokenizer_module *pTModule;  /* The tokenizer module */
86414   sqlite3_tokenizer *pTokenizer;             /* The specific tokenizer */
86415   sqlite3_tokenizer_cursor *pTCursor;        /* Tokenizer cursor */
86416   fulltext_vtab *pVtab;                /* The full text index */
86417   int nColumn;                         /* Number of columns in the index */
86418   const QueryTerm *aTerm;              /* Query string terms */
86419   int nTerm;                           /* Number of query string terms */  
86420   int i, j;                            /* Loop counters */
86421   int rc;                              /* Return code */
86422   unsigned int match, prevMatch;       /* Phrase search bitmasks */
86423   const char *zToken;                  /* Next token from the tokenizer */
86424   int nToken;                          /* Size of zToken */
86425   int iBegin, iEnd, iPos;              /* Offsets of beginning and end */
86426
86427   /* The following variables keep a circular buffer of the last
86428   ** few tokens */
86429   unsigned int iRotor = 0;             /* Index of current token */
86430   int iRotorBegin[FTS3_ROTOR_SZ];      /* Beginning offset of token */
86431   int iRotorLen[FTS3_ROTOR_SZ];        /* Length of token */
86432
86433   pVtab = pQuery->pFts;
86434   nColumn = pVtab->nColumn;
86435   pTokenizer = pVtab->pTokenizer;
86436   pTModule = pTokenizer->pModule;
86437   rc = pTModule->xOpen(pTokenizer, zDoc, nDoc, &pTCursor);
86438   if( rc ) return;
86439   pTCursor->pTokenizer = pTokenizer;
86440   aTerm = pQuery->pTerms;
86441   nTerm = pQuery->nTerms;
86442   if( nTerm>=FTS3_ROTOR_SZ ){
86443     nTerm = FTS3_ROTOR_SZ - 1;
86444   }
86445   prevMatch = 0;
86446   while(1){
86447     rc = pTModule->xNext(pTCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
86448     if( rc ) break;
86449     iRotorBegin[iRotor&FTS3_ROTOR_MASK] = iBegin;
86450     iRotorLen[iRotor&FTS3_ROTOR_MASK] = iEnd-iBegin;
86451     match = 0;
86452     for(i=0; i<nTerm; i++){
86453       int iCol;
86454       iCol = aTerm[i].iColumn;
86455       if( iCol>=0 && iCol<nColumn && iCol!=iColumn ) continue;
86456       if( aTerm[i].nTerm>nToken ) continue;
86457       if( !aTerm[i].isPrefix && aTerm[i].nTerm<nToken ) continue;
86458       assert( aTerm[i].nTerm<=nToken );
86459       if( memcmp(aTerm[i].pTerm, zToken, aTerm[i].nTerm) ) continue;
86460       if( aTerm[i].iPhrase>1 && (prevMatch & (1<<i))==0 ) continue;
86461       match |= 1<<i;
86462       if( i==nTerm-1 || aTerm[i+1].iPhrase==1 ){
86463         for(j=aTerm[i].iPhrase-1; j>=0; j--){
86464           int k = (iRotor-j) & FTS3_ROTOR_MASK;
86465           snippetAppendMatch(pSnippet, iColumn, i-j, iPos-j,
86466                 iRotorBegin[k], iRotorLen[k]);
86467         }
86468       }
86469     }
86470     prevMatch = match<<1;
86471     iRotor++;
86472   }
86473   pTModule->xClose(pTCursor);  
86474 }
86475
86476 /*
86477 ** Remove entries from the pSnippet structure to account for the NEAR
86478 ** operator. When this is called, pSnippet contains the list of token 
86479 ** offsets produced by treating all NEAR operators as AND operators.
86480 ** This function removes any entries that should not be present after
86481 ** accounting for the NEAR restriction. For example, if the queried
86482 ** document is:
86483 **
86484 **     "A B C D E A"
86485 **
86486 ** and the query is:
86487 ** 
86488 **     A NEAR/0 E
86489 **
86490 ** then when this function is called the Snippet contains token offsets
86491 ** 0, 4 and 5. This function removes the "0" entry (because the first A
86492 ** is not near enough to an E).
86493 */
86494 static void trimSnippetOffsetsForNear(Query *pQuery, Snippet *pSnippet){
86495   int ii;
86496   int iDir = 1;
86497
86498   while(iDir>-2) {
86499     assert( iDir==1 || iDir==-1 );
86500     for(ii=0; ii<pSnippet->nMatch; ii++){
86501       int jj;
86502       int nNear;
86503       struct snippetMatch *pMatch = &pSnippet->aMatch[ii];
86504       QueryTerm *pQueryTerm = &pQuery->pTerms[pMatch->iTerm];
86505
86506       if( (pMatch->iTerm+iDir)<0 
86507        || (pMatch->iTerm+iDir)>=pQuery->nTerms
86508       ){
86509         continue;
86510       }
86511      
86512       nNear = pQueryTerm->nNear;
86513       if( iDir<0 ){
86514         nNear = pQueryTerm[-1].nNear;
86515       }
86516   
86517       if( pMatch->iTerm>=0 && nNear ){
86518         int isOk = 0;
86519         int iNextTerm = pMatch->iTerm+iDir;
86520         int iPrevTerm = iNextTerm;
86521
86522         int iEndToken;
86523         int iStartToken;
86524
86525         if( iDir<0 ){
86526           int nPhrase = 1;
86527           iStartToken = pMatch->iToken;
86528           while( (pMatch->iTerm+nPhrase)<pQuery->nTerms 
86529               && pQuery->pTerms[pMatch->iTerm+nPhrase].iPhrase>1 
86530           ){
86531             nPhrase++;
86532           }
86533           iEndToken = iStartToken + nPhrase - 1;
86534         }else{
86535           iEndToken   = pMatch->iToken;
86536           iStartToken = pMatch->iToken+1-pQueryTerm->iPhrase;
86537         }
86538
86539         while( pQuery->pTerms[iNextTerm].iPhrase>1 ){
86540           iNextTerm--;
86541         }
86542         while( (iPrevTerm+1)<pQuery->nTerms && 
86543                pQuery->pTerms[iPrevTerm+1].iPhrase>1 
86544         ){
86545           iPrevTerm++;
86546         }
86547   
86548         for(jj=0; isOk==0 && jj<pSnippet->nMatch; jj++){
86549           struct snippetMatch *p = &pSnippet->aMatch[jj];
86550           if( p->iCol==pMatch->iCol && ((
86551                p->iTerm==iNextTerm && 
86552                p->iToken>iEndToken && 
86553                p->iToken<=iEndToken+nNear
86554           ) || (
86555                p->iTerm==iPrevTerm && 
86556                p->iToken<iStartToken && 
86557                p->iToken>=iStartToken-nNear
86558           ))){
86559             isOk = 1;
86560           }
86561         }
86562         if( !isOk ){
86563           for(jj=1-pQueryTerm->iPhrase; jj<=0; jj++){
86564             pMatch[jj].iTerm = -1;
86565           }
86566           ii = -1;
86567           iDir = 1;
86568         }
86569       }
86570     }
86571     iDir -= 2;
86572   }
86573 }
86574
86575 /*
86576 ** Compute all offsets for the current row of the query.  
86577 ** If the offsets have already been computed, this routine is a no-op.
86578 */
86579 static void snippetAllOffsets(fulltext_cursor *p){
86580   int nColumn;
86581   int iColumn, i;
86582   int iFirst, iLast;
86583   fulltext_vtab *pFts;
86584
86585   if( p->snippet.nMatch ) return;
86586   if( p->q.nTerms==0 ) return;
86587   pFts = p->q.pFts;
86588   nColumn = pFts->nColumn;
86589   iColumn = (p->iCursorType - QUERY_FULLTEXT);
86590   if( iColumn<0 || iColumn>=nColumn ){
86591     iFirst = 0;
86592     iLast = nColumn-1;
86593   }else{
86594     iFirst = iColumn;
86595     iLast = iColumn;
86596   }
86597   for(i=iFirst; i<=iLast; i++){
86598     const char *zDoc;
86599     int nDoc;
86600     zDoc = (const char*)sqlite3_column_text(p->pStmt, i+1);
86601     nDoc = sqlite3_column_bytes(p->pStmt, i+1);
86602     snippetOffsetsOfColumn(&p->q, &p->snippet, i, zDoc, nDoc);
86603   }
86604
86605   trimSnippetOffsetsForNear(&p->q, &p->snippet);
86606 }
86607
86608 /*
86609 ** Convert the information in the aMatch[] array of the snippet
86610 ** into the string zOffset[0..nOffset-1].
86611 */
86612 static void snippetOffsetText(Snippet *p){
86613   int i;
86614   int cnt = 0;
86615   StringBuffer sb;
86616   char zBuf[200];
86617   if( p->zOffset ) return;
86618   initStringBuffer(&sb);
86619   for(i=0; i<p->nMatch; i++){
86620     struct snippetMatch *pMatch = &p->aMatch[i];
86621     if( pMatch->iTerm>=0 ){
86622       /* If snippetMatch.iTerm is less than 0, then the match was 
86623       ** discarded as part of processing the NEAR operator (see the 
86624       ** trimSnippetOffsetsForNear() function for details). Ignore 
86625       ** it in this case
86626       */
86627       zBuf[0] = ' ';
86628       sqlite3_snprintf(sizeof(zBuf)-1, &zBuf[cnt>0], "%d %d %d %d",
86629           pMatch->iCol, pMatch->iTerm, pMatch->iStart, pMatch->nByte);
86630       append(&sb, zBuf);
86631       cnt++;
86632     }
86633   }
86634   p->zOffset = stringBufferData(&sb);
86635   p->nOffset = stringBufferLength(&sb);
86636 }
86637
86638 /*
86639 ** zDoc[0..nDoc-1] is phrase of text.  aMatch[0..nMatch-1] are a set
86640 ** of matching words some of which might be in zDoc.  zDoc is column
86641 ** number iCol.
86642 **
86643 ** iBreak is suggested spot in zDoc where we could begin or end an
86644 ** excerpt.  Return a value similar to iBreak but possibly adjusted
86645 ** to be a little left or right so that the break point is better.
86646 */
86647 static int wordBoundary(
86648   int iBreak,                   /* The suggested break point */
86649   const char *zDoc,             /* Document text */
86650   int nDoc,                     /* Number of bytes in zDoc[] */
86651   struct snippetMatch *aMatch,  /* Matching words */
86652   int nMatch,                   /* Number of entries in aMatch[] */
86653   int iCol                      /* The column number for zDoc[] */
86654 ){
86655   int i;
86656   if( iBreak<=10 ){
86657     return 0;
86658   }
86659   if( iBreak>=nDoc-10 ){
86660     return nDoc;
86661   }
86662   for(i=0; i<nMatch && aMatch[i].iCol<iCol; i++){}
86663   while( i<nMatch && aMatch[i].iStart+aMatch[i].nByte<iBreak ){ i++; }
86664   if( i<nMatch ){
86665     if( aMatch[i].iStart<iBreak+10 ){
86666       return aMatch[i].iStart;
86667     }
86668     if( i>0 && aMatch[i-1].iStart+aMatch[i-1].nByte>=iBreak ){
86669       return aMatch[i-1].iStart;
86670     }
86671   }
86672   for(i=1; i<=10; i++){
86673     if( safe_isspace(zDoc[iBreak-i]) ){
86674       return iBreak - i + 1;
86675     }
86676     if( safe_isspace(zDoc[iBreak+i]) ){
86677       return iBreak + i + 1;
86678     }
86679   }
86680   return iBreak;
86681 }
86682
86683
86684
86685 /*
86686 ** Allowed values for Snippet.aMatch[].snStatus
86687 */
86688 #define SNIPPET_IGNORE  0   /* It is ok to omit this match from the snippet */
86689 #define SNIPPET_DESIRED 1   /* We want to include this match in the snippet */
86690
86691 /*
86692 ** Generate the text of a snippet.
86693 */
86694 static void snippetText(
86695   fulltext_cursor *pCursor,   /* The cursor we need the snippet for */
86696   const char *zStartMark,     /* Markup to appear before each match */
86697   const char *zEndMark,       /* Markup to appear after each match */
86698   const char *zEllipsis       /* Ellipsis mark */
86699 ){
86700   int i, j;
86701   struct snippetMatch *aMatch;
86702   int nMatch;
86703   int nDesired;
86704   StringBuffer sb;
86705   int tailCol;
86706   int tailOffset;
86707   int iCol;
86708   int nDoc;
86709   const char *zDoc;
86710   int iStart, iEnd;
86711   int tailEllipsis = 0;
86712   int iMatch;
86713   
86714
86715   sqlite3_free(pCursor->snippet.zSnippet);
86716   pCursor->snippet.zSnippet = 0;
86717   aMatch = pCursor->snippet.aMatch;
86718   nMatch = pCursor->snippet.nMatch;
86719   initStringBuffer(&sb);
86720
86721   for(i=0; i<nMatch; i++){
86722     aMatch[i].snStatus = SNIPPET_IGNORE;
86723   }
86724   nDesired = 0;
86725   for(i=0; i<pCursor->q.nTerms; i++){
86726     for(j=0; j<nMatch; j++){
86727       if( aMatch[j].iTerm==i ){
86728         aMatch[j].snStatus = SNIPPET_DESIRED;
86729         nDesired++;
86730         break;
86731       }
86732     }
86733   }
86734
86735   iMatch = 0;
86736   tailCol = -1;
86737   tailOffset = 0;
86738   for(i=0; i<nMatch && nDesired>0; i++){
86739     if( aMatch[i].snStatus!=SNIPPET_DESIRED ) continue;
86740     nDesired--;
86741     iCol = aMatch[i].iCol;
86742     zDoc = (const char*)sqlite3_column_text(pCursor->pStmt, iCol+1);
86743     nDoc = sqlite3_column_bytes(pCursor->pStmt, iCol+1);
86744     iStart = aMatch[i].iStart - 40;
86745     iStart = wordBoundary(iStart, zDoc, nDoc, aMatch, nMatch, iCol);
86746     if( iStart<=10 ){
86747       iStart = 0;
86748     }
86749     if( iCol==tailCol && iStart<=tailOffset+20 ){
86750       iStart = tailOffset;
86751     }
86752     if( (iCol!=tailCol && tailCol>=0) || iStart!=tailOffset ){
86753       trimWhiteSpace(&sb);
86754       appendWhiteSpace(&sb);
86755       append(&sb, zEllipsis);
86756       appendWhiteSpace(&sb);
86757     }
86758     iEnd = aMatch[i].iStart + aMatch[i].nByte + 40;
86759     iEnd = wordBoundary(iEnd, zDoc, nDoc, aMatch, nMatch, iCol);
86760     if( iEnd>=nDoc-10 ){
86761       iEnd = nDoc;
86762       tailEllipsis = 0;
86763     }else{
86764       tailEllipsis = 1;
86765     }
86766     while( iMatch<nMatch && aMatch[iMatch].iCol<iCol ){ iMatch++; }
86767     while( iStart<iEnd ){
86768       while( iMatch<nMatch && aMatch[iMatch].iStart<iStart
86769              && aMatch[iMatch].iCol<=iCol ){
86770         iMatch++;
86771       }
86772       if( iMatch<nMatch && aMatch[iMatch].iStart<iEnd
86773              && aMatch[iMatch].iCol==iCol ){
86774         nappend(&sb, &zDoc[iStart], aMatch[iMatch].iStart - iStart);
86775         iStart = aMatch[iMatch].iStart;
86776         append(&sb, zStartMark);
86777         nappend(&sb, &zDoc[iStart], aMatch[iMatch].nByte);
86778         append(&sb, zEndMark);
86779         iStart += aMatch[iMatch].nByte;
86780         for(j=iMatch+1; j<nMatch; j++){
86781           if( aMatch[j].iTerm==aMatch[iMatch].iTerm
86782               && aMatch[j].snStatus==SNIPPET_DESIRED ){
86783             nDesired--;
86784             aMatch[j].snStatus = SNIPPET_IGNORE;
86785           }
86786         }
86787       }else{
86788         nappend(&sb, &zDoc[iStart], iEnd - iStart);
86789         iStart = iEnd;
86790       }
86791     }
86792     tailCol = iCol;
86793     tailOffset = iEnd;
86794   }
86795   trimWhiteSpace(&sb);
86796   if( tailEllipsis ){
86797     appendWhiteSpace(&sb);
86798     append(&sb, zEllipsis);
86799   }
86800   pCursor->snippet.zSnippet = stringBufferData(&sb);
86801   pCursor->snippet.nSnippet = stringBufferLength(&sb);
86802 }
86803
86804
86805 /*
86806 ** Close the cursor.  For additional information see the documentation
86807 ** on the xClose method of the virtual table interface.
86808 */
86809 static int fulltextClose(sqlite3_vtab_cursor *pCursor){
86810   fulltext_cursor *c = (fulltext_cursor *) pCursor;
86811   FTSTRACE(("FTS3 Close %p\n", c));
86812   sqlite3_finalize(c->pStmt);
86813   queryClear(&c->q);
86814   snippetClear(&c->snippet);
86815   if( c->result.nData!=0 ) dlrDestroy(&c->reader);
86816   dataBufferDestroy(&c->result);
86817   sqlite3_free(c);
86818   return SQLITE_OK;
86819 }
86820
86821 static int fulltextNext(sqlite3_vtab_cursor *pCursor){
86822   fulltext_cursor *c = (fulltext_cursor *) pCursor;
86823   int rc;
86824
86825   FTSTRACE(("FTS3 Next %p\n", pCursor));
86826   snippetClear(&c->snippet);
86827   if( c->iCursorType < QUERY_FULLTEXT ){
86828     /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
86829     rc = sqlite3_step(c->pStmt);
86830     switch( rc ){
86831       case SQLITE_ROW:
86832         c->eof = 0;
86833         return SQLITE_OK;
86834       case SQLITE_DONE:
86835         c->eof = 1;
86836         return SQLITE_OK;
86837       default:
86838         c->eof = 1;
86839         return rc;
86840     }
86841   } else {  /* full-text query */
86842     rc = sqlite3_reset(c->pStmt);
86843     if( rc!=SQLITE_OK ) return rc;
86844
86845     if( c->result.nData==0 || dlrAtEnd(&c->reader) ){
86846       c->eof = 1;
86847       return SQLITE_OK;
86848     }
86849     rc = sqlite3_bind_int64(c->pStmt, 1, dlrDocid(&c->reader));
86850     dlrStep(&c->reader);
86851     if( rc!=SQLITE_OK ) return rc;
86852     /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
86853     rc = sqlite3_step(c->pStmt);
86854     if( rc==SQLITE_ROW ){   /* the case we expect */
86855       c->eof = 0;
86856       return SQLITE_OK;
86857     }
86858     /* an error occurred; abort */
86859     return rc==SQLITE_DONE ? SQLITE_ERROR : rc;
86860   }
86861 }
86862
86863
86864 /* TODO(shess) If we pushed LeafReader to the top of the file, or to
86865 ** another file, term_select() could be pushed above
86866 ** docListOfTerm().
86867 */
86868 static int termSelect(fulltext_vtab *v, int iColumn,
86869                       const char *pTerm, int nTerm, int isPrefix,
86870                       DocListType iType, DataBuffer *out);
86871
86872 /* Return a DocList corresponding to the query term *pTerm.  If *pTerm
86873 ** is the first term of a phrase query, go ahead and evaluate the phrase
86874 ** query and return the doclist for the entire phrase query.
86875 **
86876 ** The resulting DL_DOCIDS doclist is stored in pResult, which is
86877 ** overwritten.
86878 */
86879 static int docListOfTerm(
86880   fulltext_vtab *v,    /* The full text index */
86881   int iColumn,         /* column to restrict to.  No restriction if >=nColumn */
86882   QueryTerm *pQTerm,   /* Term we are looking for, or 1st term of a phrase */
86883   DataBuffer *pResult  /* Write the result here */
86884 ){
86885   DataBuffer left, right, new;
86886   int i, rc;
86887
86888   /* No phrase search if no position info. */
86889   assert( pQTerm->nPhrase==0 || DL_DEFAULT!=DL_DOCIDS );
86890
86891   /* This code should never be called with buffered updates. */
86892   assert( v->nPendingData<0 );
86893
86894   dataBufferInit(&left, 0);
86895   rc = termSelect(v, iColumn, pQTerm->pTerm, pQTerm->nTerm, pQTerm->isPrefix,
86896                   (0<pQTerm->nPhrase ? DL_POSITIONS : DL_DOCIDS), &left);
86897   if( rc ) return rc;
86898   for(i=1; i<=pQTerm->nPhrase && left.nData>0; i++){
86899     /* If this token is connected to the next by a NEAR operator, and
86900     ** the next token is the start of a phrase, then set nPhraseRight
86901     ** to the number of tokens in the phrase. Otherwise leave it at 1.
86902     */
86903     int nPhraseRight = 1;
86904     while( (i+nPhraseRight)<=pQTerm->nPhrase 
86905         && pQTerm[i+nPhraseRight].nNear==0 
86906     ){
86907       nPhraseRight++;
86908     }
86909
86910     dataBufferInit(&right, 0);
86911     rc = termSelect(v, iColumn, pQTerm[i].pTerm, pQTerm[i].nTerm,
86912                     pQTerm[i].isPrefix, DL_POSITIONS, &right);
86913     if( rc ){
86914       dataBufferDestroy(&left);
86915       return rc;
86916     }
86917     dataBufferInit(&new, 0);
86918     docListPhraseMerge(left.pData, left.nData, right.pData, right.nData,
86919                        pQTerm[i-1].nNear, pQTerm[i-1].iPhrase + nPhraseRight,
86920                        ((i<pQTerm->nPhrase) ? DL_POSITIONS : DL_DOCIDS),
86921                        &new);
86922     dataBufferDestroy(&left);
86923     dataBufferDestroy(&right);
86924     left = new;
86925   }
86926   *pResult = left;
86927   return SQLITE_OK;
86928 }
86929
86930 /* Add a new term pTerm[0..nTerm-1] to the query *q.
86931 */
86932 static void queryAdd(Query *q, const char *pTerm, int nTerm){
86933   QueryTerm *t;
86934   ++q->nTerms;
86935   q->pTerms = sqlite3_realloc(q->pTerms, q->nTerms * sizeof(q->pTerms[0]));
86936   if( q->pTerms==0 ){
86937     q->nTerms = 0;
86938     return;
86939   }
86940   t = &q->pTerms[q->nTerms - 1];
86941   CLEAR(t);
86942   t->pTerm = sqlite3_malloc(nTerm+1);
86943   memcpy(t->pTerm, pTerm, nTerm);
86944   t->pTerm[nTerm] = 0;
86945   t->nTerm = nTerm;
86946   t->isOr = q->nextIsOr;
86947   t->isPrefix = 0;
86948   q->nextIsOr = 0;
86949   t->iColumn = q->nextColumn;
86950   q->nextColumn = q->dfltColumn;
86951 }
86952
86953 /*
86954 ** Check to see if the string zToken[0...nToken-1] matches any
86955 ** column name in the virtual table.   If it does,
86956 ** return the zero-indexed column number.  If not, return -1.
86957 */
86958 static int checkColumnSpecifier(
86959   fulltext_vtab *pVtab,    /* The virtual table */
86960   const char *zToken,      /* Text of the token */
86961   int nToken               /* Number of characters in the token */
86962 ){
86963   int i;
86964   for(i=0; i<pVtab->nColumn; i++){
86965     if( memcmp(pVtab->azColumn[i], zToken, nToken)==0
86966         && pVtab->azColumn[i][nToken]==0 ){
86967       return i;
86968     }
86969   }
86970   return -1;
86971 }
86972
86973 /*
86974 ** Parse the text at pSegment[0..nSegment-1].  Add additional terms
86975 ** to the query being assemblied in pQuery.
86976 **
86977 ** inPhrase is true if pSegment[0..nSegement-1] is contained within
86978 ** double-quotes.  If inPhrase is true, then the first term
86979 ** is marked with the number of terms in the phrase less one and
86980 ** OR and "-" syntax is ignored.  If inPhrase is false, then every
86981 ** term found is marked with nPhrase=0 and OR and "-" syntax is significant.
86982 */
86983 static int tokenizeSegment(
86984   sqlite3_tokenizer *pTokenizer,          /* The tokenizer to use */
86985   const char *pSegment, int nSegment,     /* Query expression being parsed */
86986   int inPhrase,                           /* True if within "..." */
86987   Query *pQuery                           /* Append results here */
86988 ){
86989   const sqlite3_tokenizer_module *pModule = pTokenizer->pModule;
86990   sqlite3_tokenizer_cursor *pCursor;
86991   int firstIndex = pQuery->nTerms;
86992   int iCol;
86993   int nTerm = 1;
86994   
86995   int rc = pModule->xOpen(pTokenizer, pSegment, nSegment, &pCursor);
86996   if( rc!=SQLITE_OK ) return rc;
86997   pCursor->pTokenizer = pTokenizer;
86998
86999   while( 1 ){
87000     const char *pToken;
87001     int nToken, iBegin, iEnd, iPos;
87002
87003     rc = pModule->xNext(pCursor,
87004                         &pToken, &nToken,
87005                         &iBegin, &iEnd, &iPos);
87006     if( rc!=SQLITE_OK ) break;
87007     if( !inPhrase &&
87008         pSegment[iEnd]==':' &&
87009          (iCol = checkColumnSpecifier(pQuery->pFts, pToken, nToken))>=0 ){
87010       pQuery->nextColumn = iCol;
87011       continue;
87012     }
87013     if( !inPhrase && pQuery->nTerms>0 && nToken==2 
87014      && pSegment[iBegin+0]=='O'
87015      && pSegment[iBegin+1]=='R' 
87016     ){
87017       pQuery->nextIsOr = 1;
87018       continue;
87019     }
87020     if( !inPhrase && pQuery->nTerms>0 && !pQuery->nextIsOr && nToken==4 
87021       && pSegment[iBegin+0]=='N' 
87022       && pSegment[iBegin+1]=='E' 
87023       && pSegment[iBegin+2]=='A' 
87024       && pSegment[iBegin+3]=='R' 
87025     ){
87026       QueryTerm *pTerm = &pQuery->pTerms[pQuery->nTerms-1];
87027       if( (iBegin+6)<nSegment 
87028        && pSegment[iBegin+4] == '/'
87029        && pSegment[iBegin+5]>='0' && pSegment[iBegin+5]<='9'
87030       ){
87031         pTerm->nNear = (pSegment[iBegin+5] - '0');
87032         nToken += 2;
87033         if( pSegment[iBegin+6]>='0' && pSegment[iBegin+6]<=9 ){
87034           pTerm->nNear = pTerm->nNear * 10 + (pSegment[iBegin+6] - '0');
87035           iEnd++;
87036         }
87037         pModule->xNext(pCursor, &pToken, &nToken, &iBegin, &iEnd, &iPos);
87038       } else {
87039         pTerm->nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
87040       }
87041       pTerm->nNear++;
87042       continue;
87043     }
87044
87045     queryAdd(pQuery, pToken, nToken);
87046     if( !inPhrase && iBegin>0 && pSegment[iBegin-1]=='-' ){
87047       pQuery->pTerms[pQuery->nTerms-1].isNot = 1;
87048     }
87049     if( iEnd<nSegment && pSegment[iEnd]=='*' ){
87050       pQuery->pTerms[pQuery->nTerms-1].isPrefix = 1;
87051     }
87052     pQuery->pTerms[pQuery->nTerms-1].iPhrase = nTerm;
87053     if( inPhrase ){
87054       nTerm++;
87055     }
87056   }
87057
87058   if( inPhrase && pQuery->nTerms>firstIndex ){
87059     pQuery->pTerms[firstIndex].nPhrase = pQuery->nTerms - firstIndex - 1;
87060   }
87061
87062   return pModule->xClose(pCursor);
87063 }
87064
87065 /* Parse a query string, yielding a Query object pQuery.
87066 **
87067 ** The calling function will need to queryClear() to clean up
87068 ** the dynamically allocated memory held by pQuery.
87069 */
87070 static int parseQuery(
87071   fulltext_vtab *v,        /* The fulltext index */
87072   const char *zInput,      /* Input text of the query string */
87073   int nInput,              /* Size of the input text */
87074   int dfltColumn,          /* Default column of the index to match against */
87075   Query *pQuery            /* Write the parse results here. */
87076 ){
87077   int iInput, inPhrase = 0;
87078   int ii;
87079   QueryTerm *aTerm;
87080
87081   if( zInput==0 ) nInput = 0;
87082   if( nInput<0 ) nInput = strlen(zInput);
87083   pQuery->nTerms = 0;
87084   pQuery->pTerms = NULL;
87085   pQuery->nextIsOr = 0;
87086   pQuery->nextColumn = dfltColumn;
87087   pQuery->dfltColumn = dfltColumn;
87088   pQuery->pFts = v;
87089
87090   for(iInput=0; iInput<nInput; ++iInput){
87091     int i;
87092     for(i=iInput; i<nInput && zInput[i]!='"'; ++i){}
87093     if( i>iInput ){
87094       tokenizeSegment(v->pTokenizer, zInput+iInput, i-iInput, inPhrase,
87095                        pQuery);
87096     }
87097     iInput = i;
87098     if( i<nInput ){
87099       assert( zInput[i]=='"' );
87100       inPhrase = !inPhrase;
87101     }
87102   }
87103
87104   if( inPhrase ){
87105     /* unmatched quote */
87106     queryClear(pQuery);
87107     return SQLITE_ERROR;
87108   }
87109
87110   /* Modify the values of the QueryTerm.nPhrase variables to account for
87111   ** the NEAR operator. For the purposes of QueryTerm.nPhrase, phrases
87112   ** and tokens connected by the NEAR operator are handled as a single
87113   ** phrase. See comments above the QueryTerm structure for details.
87114   */
87115   aTerm = pQuery->pTerms;
87116   for(ii=0; ii<pQuery->nTerms; ii++){
87117     if( aTerm[ii].nNear || aTerm[ii].nPhrase ){
87118       while (aTerm[ii+aTerm[ii].nPhrase].nNear) {
87119         aTerm[ii].nPhrase += (1 + aTerm[ii+aTerm[ii].nPhrase+1].nPhrase);
87120       }
87121     }
87122   }
87123
87124   return SQLITE_OK;
87125 }
87126
87127 /* TODO(shess) Refactor the code to remove this forward decl. */
87128 static int flushPendingTerms(fulltext_vtab *v);
87129
87130 /* Perform a full-text query using the search expression in
87131 ** zInput[0..nInput-1].  Return a list of matching documents
87132 ** in pResult.
87133 **
87134 ** Queries must match column iColumn.  Or if iColumn>=nColumn
87135 ** they are allowed to match against any column.
87136 */
87137 static int fulltextQuery(
87138   fulltext_vtab *v,      /* The full text index */
87139   int iColumn,           /* Match against this column by default */
87140   const char *zInput,    /* The query string */
87141   int nInput,            /* Number of bytes in zInput[] */
87142   DataBuffer *pResult,   /* Write the result doclist here */
87143   Query *pQuery          /* Put parsed query string here */
87144 ){
87145   int i, iNext, rc;
87146   DataBuffer left, right, or, new;
87147   int nNot = 0;
87148   QueryTerm *aTerm;
87149
87150   /* TODO(shess) Instead of flushing pendingTerms, we could query for
87151   ** the relevant term and merge the doclist into what we receive from
87152   ** the database.  Wait and see if this is a common issue, first.
87153   **
87154   ** A good reason not to flush is to not generate update-related
87155   ** error codes from here.
87156   */
87157
87158   /* Flush any buffered updates before executing the query. */
87159   rc = flushPendingTerms(v);
87160   if( rc!=SQLITE_OK ) return rc;
87161
87162   /* TODO(shess) I think that the queryClear() calls below are not
87163   ** necessary, because fulltextClose() already clears the query.
87164   */
87165   rc = parseQuery(v, zInput, nInput, iColumn, pQuery);
87166   if( rc!=SQLITE_OK ) return rc;
87167
87168   /* Empty or NULL queries return no results. */
87169   if( pQuery->nTerms==0 ){
87170     dataBufferInit(pResult, 0);
87171     return SQLITE_OK;
87172   }
87173
87174   /* Merge AND terms. */
87175   /* TODO(shess) I think we can early-exit if( i>nNot && left.nData==0 ). */
87176   aTerm = pQuery->pTerms;
87177   for(i = 0; i<pQuery->nTerms; i=iNext){
87178     if( aTerm[i].isNot ){
87179       /* Handle all NOT terms in a separate pass */
87180       nNot++;
87181       iNext = i + aTerm[i].nPhrase+1;
87182       continue;
87183     }
87184     iNext = i + aTerm[i].nPhrase + 1;
87185     rc = docListOfTerm(v, aTerm[i].iColumn, &aTerm[i], &right);
87186     if( rc ){
87187       if( i!=nNot ) dataBufferDestroy(&left);
87188       queryClear(pQuery);
87189       return rc;
87190     }
87191     while( iNext<pQuery->nTerms && aTerm[iNext].isOr ){
87192       rc = docListOfTerm(v, aTerm[iNext].iColumn, &aTerm[iNext], &or);
87193       iNext += aTerm[iNext].nPhrase + 1;
87194       if( rc ){
87195         if( i!=nNot ) dataBufferDestroy(&left);
87196         dataBufferDestroy(&right);
87197         queryClear(pQuery);
87198         return rc;
87199       }
87200       dataBufferInit(&new, 0);
87201       docListOrMerge(right.pData, right.nData, or.pData, or.nData, &new);
87202       dataBufferDestroy(&right);
87203       dataBufferDestroy(&or);
87204       right = new;
87205     }
87206     if( i==nNot ){           /* first term processed. */
87207       left = right;
87208     }else{
87209       dataBufferInit(&new, 0);
87210       docListAndMerge(left.pData, left.nData, right.pData, right.nData, &new);
87211       dataBufferDestroy(&right);
87212       dataBufferDestroy(&left);
87213       left = new;
87214     }
87215   }
87216
87217   if( nNot==pQuery->nTerms ){
87218     /* We do not yet know how to handle a query of only NOT terms */
87219     return SQLITE_ERROR;
87220   }
87221
87222   /* Do the EXCEPT terms */
87223   for(i=0; i<pQuery->nTerms;  i += aTerm[i].nPhrase + 1){
87224     if( !aTerm[i].isNot ) continue;
87225     rc = docListOfTerm(v, aTerm[i].iColumn, &aTerm[i], &right);
87226     if( rc ){
87227       queryClear(pQuery);
87228       dataBufferDestroy(&left);
87229       return rc;
87230     }
87231     dataBufferInit(&new, 0);
87232     docListExceptMerge(left.pData, left.nData, right.pData, right.nData, &new);
87233     dataBufferDestroy(&right);
87234     dataBufferDestroy(&left);
87235     left = new;
87236   }
87237
87238   *pResult = left;
87239   return rc;
87240 }
87241
87242 /*
87243 ** This is the xFilter interface for the virtual table.  See
87244 ** the virtual table xFilter method documentation for additional
87245 ** information.
87246 **
87247 ** If idxNum==QUERY_GENERIC then do a full table scan against
87248 ** the %_content table.
87249 **
87250 ** If idxNum==QUERY_DOCID then do a docid lookup for a single entry
87251 ** in the %_content table.
87252 **
87253 ** If idxNum>=QUERY_FULLTEXT then use the full text index.  The
87254 ** column on the left-hand side of the MATCH operator is column
87255 ** number idxNum-QUERY_FULLTEXT, 0 indexed.  argv[0] is the right-hand
87256 ** side of the MATCH operator.
87257 */
87258 /* TODO(shess) Upgrade the cursor initialization and destruction to
87259 ** account for fulltextFilter() being called multiple times on the
87260 ** same cursor.  The current solution is very fragile.  Apply fix to
87261 ** fts3 as appropriate.
87262 */
87263 static int fulltextFilter(
87264   sqlite3_vtab_cursor *pCursor,     /* The cursor used for this query */
87265   int idxNum, const char *idxStr,   /* Which indexing scheme to use */
87266   int argc, sqlite3_value **argv    /* Arguments for the indexing scheme */
87267 ){
87268   fulltext_cursor *c = (fulltext_cursor *) pCursor;
87269   fulltext_vtab *v = cursor_vtab(c);
87270   int rc;
87271
87272   FTSTRACE(("FTS3 Filter %p\n",pCursor));
87273
87274   /* If the cursor has a statement that was not prepared according to
87275   ** idxNum, clear it.  I believe all calls to fulltextFilter with a
87276   ** given cursor will have the same idxNum , but in this case it's
87277   ** easy to be safe.
87278   */
87279   if( c->pStmt && c->iCursorType!=idxNum ){
87280     sqlite3_finalize(c->pStmt);
87281     c->pStmt = NULL;
87282   }
87283
87284   /* Get a fresh statement appropriate to idxNum. */
87285   /* TODO(shess): Add a prepared-statement cache in the vt structure.
87286   ** The cache must handle multiple open cursors.  Easier to cache the
87287   ** statement variants at the vt to reduce malloc/realloc/free here.
87288   ** Or we could have a StringBuffer variant which allowed stack
87289   ** construction for small values.
87290   */
87291   if( !c->pStmt ){
87292     StringBuffer sb;
87293     initStringBuffer(&sb);
87294     append(&sb, "SELECT docid, ");
87295     appendList(&sb, v->nColumn, v->azContentColumn);
87296     append(&sb, " FROM %_content");
87297     if( idxNum!=QUERY_GENERIC ) append(&sb, " WHERE docid = ?");
87298     rc = sql_prepare(v->db, v->zDb, v->zName, &c->pStmt,
87299                      stringBufferData(&sb));
87300     stringBufferDestroy(&sb);
87301     if( rc!=SQLITE_OK ) return rc;
87302     c->iCursorType = idxNum;
87303   }else{
87304     sqlite3_reset(c->pStmt);
87305     assert( c->iCursorType==idxNum );
87306   }
87307
87308   switch( idxNum ){
87309     case QUERY_GENERIC:
87310       break;
87311
87312     case QUERY_DOCID:
87313       rc = sqlite3_bind_int64(c->pStmt, 1, sqlite3_value_int64(argv[0]));
87314       if( rc!=SQLITE_OK ) return rc;
87315       break;
87316
87317     default:   /* full-text search */
87318     {
87319       const char *zQuery = (const char *)sqlite3_value_text(argv[0]);
87320       assert( idxNum<=QUERY_FULLTEXT+v->nColumn);
87321       assert( argc==1 );
87322       queryClear(&c->q);
87323       if( c->result.nData!=0 ){
87324         /* This case happens if the same cursor is used repeatedly. */
87325         dlrDestroy(&c->reader);
87326         dataBufferReset(&c->result);
87327       }else{
87328         dataBufferInit(&c->result, 0);
87329       }
87330       rc = fulltextQuery(v, idxNum-QUERY_FULLTEXT, zQuery, -1, &c->result, &c->q);
87331       if( rc!=SQLITE_OK ) return rc;
87332       if( c->result.nData!=0 ){
87333         dlrInit(&c->reader, DL_DOCIDS, c->result.pData, c->result.nData);
87334       }
87335       break;
87336     }
87337   }
87338
87339   return fulltextNext(pCursor);
87340 }
87341
87342 /* This is the xEof method of the virtual table.  The SQLite core
87343 ** calls this routine to find out if it has reached the end of
87344 ** a query's results set.
87345 */
87346 static int fulltextEof(sqlite3_vtab_cursor *pCursor){
87347   fulltext_cursor *c = (fulltext_cursor *) pCursor;
87348   return c->eof;
87349 }
87350
87351 /* This is the xColumn method of the virtual table.  The SQLite
87352 ** core calls this method during a query when it needs the value
87353 ** of a column from the virtual table.  This method needs to use
87354 ** one of the sqlite3_result_*() routines to store the requested
87355 ** value back in the pContext.
87356 */
87357 static int fulltextColumn(sqlite3_vtab_cursor *pCursor,
87358                           sqlite3_context *pContext, int idxCol){
87359   fulltext_cursor *c = (fulltext_cursor *) pCursor;
87360   fulltext_vtab *v = cursor_vtab(c);
87361
87362   if( idxCol<v->nColumn ){
87363     sqlite3_value *pVal = sqlite3_column_value(c->pStmt, idxCol+1);
87364     sqlite3_result_value(pContext, pVal);
87365   }else if( idxCol==v->nColumn ){
87366     /* The extra column whose name is the same as the table.
87367     ** Return a blob which is a pointer to the cursor
87368     */
87369     sqlite3_result_blob(pContext, &c, sizeof(c), SQLITE_TRANSIENT);
87370   }else if( idxCol==v->nColumn+1 ){
87371     /* The docid column, which is an alias for rowid. */
87372     sqlite3_value *pVal = sqlite3_column_value(c->pStmt, 0);
87373     sqlite3_result_value(pContext, pVal);
87374   }
87375   return SQLITE_OK;
87376 }
87377
87378 /* This is the xRowid method.  The SQLite core calls this routine to
87379 ** retrieve the rowid for the current row of the result set.  fts3
87380 ** exposes %_content.docid as the rowid for the virtual table.  The
87381 ** rowid should be written to *pRowid.
87382 */
87383 static int fulltextRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
87384   fulltext_cursor *c = (fulltext_cursor *) pCursor;
87385
87386   *pRowid = sqlite3_column_int64(c->pStmt, 0);
87387   return SQLITE_OK;
87388 }
87389
87390 /* Add all terms in [zText] to pendingTerms table.  If [iColumn] > 0,
87391 ** we also store positions and offsets in the hash table using that
87392 ** column number.
87393 */
87394 static int buildTerms(fulltext_vtab *v, sqlite_int64 iDocid,
87395                       const char *zText, int iColumn){
87396   sqlite3_tokenizer *pTokenizer = v->pTokenizer;
87397   sqlite3_tokenizer_cursor *pCursor;
87398   const char *pToken;
87399   int nTokenBytes;
87400   int iStartOffset, iEndOffset, iPosition;
87401   int rc;
87402
87403   rc = pTokenizer->pModule->xOpen(pTokenizer, zText, -1, &pCursor);
87404   if( rc!=SQLITE_OK ) return rc;
87405
87406   pCursor->pTokenizer = pTokenizer;
87407   while( SQLITE_OK==(rc=pTokenizer->pModule->xNext(pCursor,
87408                                                    &pToken, &nTokenBytes,
87409                                                    &iStartOffset, &iEndOffset,
87410                                                    &iPosition)) ){
87411     DLCollector *p;
87412     int nData;                   /* Size of doclist before our update. */
87413
87414     /* Positions can't be negative; we use -1 as a terminator
87415      * internally.  Token can't be NULL or empty. */
87416     if( iPosition<0 || pToken == NULL || nTokenBytes == 0 ){
87417       rc = SQLITE_ERROR;
87418       break;
87419     }
87420
87421     p = fts3HashFind(&v->pendingTerms, pToken, nTokenBytes);
87422     if( p==NULL ){
87423       nData = 0;
87424       p = dlcNew(iDocid, DL_DEFAULT);
87425       fts3HashInsert(&v->pendingTerms, pToken, nTokenBytes, p);
87426
87427       /* Overhead for our hash table entry, the key, and the value. */
87428       v->nPendingData += sizeof(struct fts3HashElem)+sizeof(*p)+nTokenBytes;
87429     }else{
87430       nData = p->b.nData;
87431       if( p->dlw.iPrevDocid!=iDocid ) dlcNext(p, iDocid);
87432     }
87433     if( iColumn>=0 ){
87434       dlcAddPos(p, iColumn, iPosition, iStartOffset, iEndOffset);
87435     }
87436
87437     /* Accumulate data added by dlcNew or dlcNext, and dlcAddPos. */
87438     v->nPendingData += p->b.nData-nData;
87439   }
87440
87441   /* TODO(shess) Check return?  Should this be able to cause errors at
87442   ** this point?  Actually, same question about sqlite3_finalize(),
87443   ** though one could argue that failure there means that the data is
87444   ** not durable.  *ponder*
87445   */
87446   pTokenizer->pModule->xClose(pCursor);
87447   if( SQLITE_DONE == rc ) return SQLITE_OK;
87448   return rc;
87449 }
87450
87451 /* Add doclists for all terms in [pValues] to pendingTerms table. */
87452 static int insertTerms(fulltext_vtab *v, sqlite_int64 iDocid,
87453                        sqlite3_value **pValues){
87454   int i;
87455   for(i = 0; i < v->nColumn ; ++i){
87456     char *zText = (char*)sqlite3_value_text(pValues[i]);
87457     int rc = buildTerms(v, iDocid, zText, i);
87458     if( rc!=SQLITE_OK ) return rc;
87459   }
87460   return SQLITE_OK;
87461 }
87462
87463 /* Add empty doclists for all terms in the given row's content to
87464 ** pendingTerms.
87465 */
87466 static int deleteTerms(fulltext_vtab *v, sqlite_int64 iDocid){
87467   const char **pValues;
87468   int i, rc;
87469
87470   /* TODO(shess) Should we allow such tables at all? */
87471   if( DL_DEFAULT==DL_DOCIDS ) return SQLITE_ERROR;
87472
87473   rc = content_select(v, iDocid, &pValues);
87474   if( rc!=SQLITE_OK ) return rc;
87475
87476   for(i = 0 ; i < v->nColumn; ++i) {
87477     rc = buildTerms(v, iDocid, pValues[i], -1);
87478     if( rc!=SQLITE_OK ) break;
87479   }
87480
87481   freeStringArray(v->nColumn, pValues);
87482   return SQLITE_OK;
87483 }
87484
87485 /* TODO(shess) Refactor the code to remove this forward decl. */
87486 static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid);
87487
87488 /* Insert a row into the %_content table; set *piDocid to be the ID of the
87489 ** new row.  Add doclists for terms to pendingTerms.
87490 */
87491 static int index_insert(fulltext_vtab *v, sqlite3_value *pRequestDocid,
87492                         sqlite3_value **pValues, sqlite_int64 *piDocid){
87493   int rc;
87494
87495   rc = content_insert(v, pRequestDocid, pValues);  /* execute an SQL INSERT */
87496   if( rc!=SQLITE_OK ) return rc;
87497
87498   /* docid column is an alias for rowid. */
87499   *piDocid = sqlite3_last_insert_rowid(v->db);
87500   rc = initPendingTerms(v, *piDocid);
87501   if( rc!=SQLITE_OK ) return rc;
87502
87503   return insertTerms(v, *piDocid, pValues);
87504 }
87505
87506 /* Delete a row from the %_content table; add empty doclists for terms
87507 ** to pendingTerms.
87508 */
87509 static int index_delete(fulltext_vtab *v, sqlite_int64 iRow){
87510   int rc = initPendingTerms(v, iRow);
87511   if( rc!=SQLITE_OK ) return rc;
87512
87513   rc = deleteTerms(v, iRow);
87514   if( rc!=SQLITE_OK ) return rc;
87515
87516   return content_delete(v, iRow);  /* execute an SQL DELETE */
87517 }
87518
87519 /* Update a row in the %_content table; add delete doclists to
87520 ** pendingTerms for old terms not in the new data, add insert doclists
87521 ** to pendingTerms for terms in the new data.
87522 */
87523 static int index_update(fulltext_vtab *v, sqlite_int64 iRow,
87524                         sqlite3_value **pValues){
87525   int rc = initPendingTerms(v, iRow);
87526   if( rc!=SQLITE_OK ) return rc;
87527
87528   /* Generate an empty doclist for each term that previously appeared in this
87529    * row. */
87530   rc = deleteTerms(v, iRow);
87531   if( rc!=SQLITE_OK ) return rc;
87532
87533   rc = content_update(v, pValues, iRow);  /* execute an SQL UPDATE */
87534   if( rc!=SQLITE_OK ) return rc;
87535
87536   /* Now add positions for terms which appear in the updated row. */
87537   return insertTerms(v, iRow, pValues);
87538 }
87539
87540 /*******************************************************************/
87541 /* InteriorWriter is used to collect terms and block references into
87542 ** interior nodes in %_segments.  See commentary at top of file for
87543 ** format.
87544 */
87545
87546 /* How large interior nodes can grow. */
87547 #define INTERIOR_MAX 2048
87548
87549 /* Minimum number of terms per interior node (except the root). This
87550 ** prevents large terms from making the tree too skinny - must be >0
87551 ** so that the tree always makes progress.  Note that the min tree
87552 ** fanout will be INTERIOR_MIN_TERMS+1.
87553 */
87554 #define INTERIOR_MIN_TERMS 7
87555 #if INTERIOR_MIN_TERMS<1
87556 # error INTERIOR_MIN_TERMS must be greater than 0.
87557 #endif
87558
87559 /* ROOT_MAX controls how much data is stored inline in the segment
87560 ** directory.
87561 */
87562 /* TODO(shess) Push ROOT_MAX down to whoever is writing things.  It's
87563 ** only here so that interiorWriterRootInfo() and leafWriterRootInfo()
87564 ** can both see it, but if the caller passed it in, we wouldn't even
87565 ** need a define.
87566 */
87567 #define ROOT_MAX 1024
87568 #if ROOT_MAX<VARINT_MAX*2
87569 # error ROOT_MAX must have enough space for a header.
87570 #endif
87571
87572 /* InteriorBlock stores a linked-list of interior blocks while a lower
87573 ** layer is being constructed.
87574 */
87575 typedef struct InteriorBlock {
87576   DataBuffer term;           /* Leftmost term in block's subtree. */
87577   DataBuffer data;           /* Accumulated data for the block. */
87578   struct InteriorBlock *next;
87579 } InteriorBlock;
87580
87581 static InteriorBlock *interiorBlockNew(int iHeight, sqlite_int64 iChildBlock,
87582                                        const char *pTerm, int nTerm){
87583   InteriorBlock *block = sqlite3_malloc(sizeof(InteriorBlock));
87584   char c[VARINT_MAX+VARINT_MAX];
87585   int n;
87586
87587   if( block ){
87588     memset(block, 0, sizeof(*block));
87589     dataBufferInit(&block->term, 0);
87590     dataBufferReplace(&block->term, pTerm, nTerm);
87591
87592     n = fts3PutVarint(c, iHeight);
87593     n += fts3PutVarint(c+n, iChildBlock);
87594     dataBufferInit(&block->data, INTERIOR_MAX);
87595     dataBufferReplace(&block->data, c, n);
87596   }
87597   return block;
87598 }
87599
87600 #ifndef NDEBUG
87601 /* Verify that the data is readable as an interior node. */
87602 static void interiorBlockValidate(InteriorBlock *pBlock){
87603   const char *pData = pBlock->data.pData;
87604   int nData = pBlock->data.nData;
87605   int n, iDummy;
87606   sqlite_int64 iBlockid;
87607
87608   assert( nData>0 );
87609   assert( pData!=0 );
87610   assert( pData+nData>pData );
87611
87612   /* Must lead with height of node as a varint(n), n>0 */
87613   n = fts3GetVarint32(pData, &iDummy);
87614   assert( n>0 );
87615   assert( iDummy>0 );
87616   assert( n<nData );
87617   pData += n;
87618   nData -= n;
87619
87620   /* Must contain iBlockid. */
87621   n = fts3GetVarint(pData, &iBlockid);
87622   assert( n>0 );
87623   assert( n<=nData );
87624   pData += n;
87625   nData -= n;
87626
87627   /* Zero or more terms of positive length */
87628   if( nData!=0 ){
87629     /* First term is not delta-encoded. */
87630     n = fts3GetVarint32(pData, &iDummy);
87631     assert( n>0 );
87632     assert( iDummy>0 );
87633     assert( n+iDummy>0);
87634     assert( n+iDummy<=nData );
87635     pData += n+iDummy;
87636     nData -= n+iDummy;
87637
87638     /* Following terms delta-encoded. */
87639     while( nData!=0 ){
87640       /* Length of shared prefix. */
87641       n = fts3GetVarint32(pData, &iDummy);
87642       assert( n>0 );
87643       assert( iDummy>=0 );
87644       assert( n<nData );
87645       pData += n;
87646       nData -= n;
87647
87648       /* Length and data of distinct suffix. */
87649       n = fts3GetVarint32(pData, &iDummy);
87650       assert( n>0 );
87651       assert( iDummy>0 );
87652       assert( n+iDummy>0);
87653       assert( n+iDummy<=nData );
87654       pData += n+iDummy;
87655       nData -= n+iDummy;
87656     }
87657   }
87658 }
87659 #define ASSERT_VALID_INTERIOR_BLOCK(x) interiorBlockValidate(x)
87660 #else
87661 #define ASSERT_VALID_INTERIOR_BLOCK(x) assert( 1 )
87662 #endif
87663
87664 typedef struct InteriorWriter {
87665   int iHeight;                   /* from 0 at leaves. */
87666   InteriorBlock *first, *last;
87667   struct InteriorWriter *parentWriter;
87668
87669   DataBuffer term;               /* Last term written to block "last". */
87670   sqlite_int64 iOpeningChildBlock; /* First child block in block "last". */
87671 #ifndef NDEBUG
87672   sqlite_int64 iLastChildBlock;  /* for consistency checks. */
87673 #endif
87674 } InteriorWriter;
87675
87676 /* Initialize an interior node where pTerm[nTerm] marks the leftmost
87677 ** term in the tree.  iChildBlock is the leftmost child block at the
87678 ** next level down the tree.
87679 */
87680 static void interiorWriterInit(int iHeight, const char *pTerm, int nTerm,
87681                                sqlite_int64 iChildBlock,
87682                                InteriorWriter *pWriter){
87683   InteriorBlock *block;
87684   assert( iHeight>0 );
87685   CLEAR(pWriter);
87686
87687   pWriter->iHeight = iHeight;
87688   pWriter->iOpeningChildBlock = iChildBlock;
87689 #ifndef NDEBUG
87690   pWriter->iLastChildBlock = iChildBlock;
87691 #endif
87692   block = interiorBlockNew(iHeight, iChildBlock, pTerm, nTerm);
87693   pWriter->last = pWriter->first = block;
87694   ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
87695   dataBufferInit(&pWriter->term, 0);
87696 }
87697
87698 /* Append the child node rooted at iChildBlock to the interior node,
87699 ** with pTerm[nTerm] as the leftmost term in iChildBlock's subtree.
87700 */
87701 static void interiorWriterAppend(InteriorWriter *pWriter,
87702                                  const char *pTerm, int nTerm,
87703                                  sqlite_int64 iChildBlock){
87704   char c[VARINT_MAX+VARINT_MAX];
87705   int n, nPrefix = 0;
87706
87707   ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
87708
87709   /* The first term written into an interior node is actually
87710   ** associated with the second child added (the first child was added
87711   ** in interiorWriterInit, or in the if clause at the bottom of this
87712   ** function).  That term gets encoded straight up, with nPrefix left
87713   ** at 0.
87714   */
87715   if( pWriter->term.nData==0 ){
87716     n = fts3PutVarint(c, nTerm);
87717   }else{
87718     while( nPrefix<pWriter->term.nData &&
87719            pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){
87720       nPrefix++;
87721     }
87722
87723     n = fts3PutVarint(c, nPrefix);
87724     n += fts3PutVarint(c+n, nTerm-nPrefix);
87725   }
87726
87727 #ifndef NDEBUG
87728   pWriter->iLastChildBlock++;
87729 #endif
87730   assert( pWriter->iLastChildBlock==iChildBlock );
87731
87732   /* Overflow to a new block if the new term makes the current block
87733   ** too big, and the current block already has enough terms.
87734   */
87735   if( pWriter->last->data.nData+n+nTerm-nPrefix>INTERIOR_MAX &&
87736       iChildBlock-pWriter->iOpeningChildBlock>INTERIOR_MIN_TERMS ){
87737     pWriter->last->next = interiorBlockNew(pWriter->iHeight, iChildBlock,
87738                                            pTerm, nTerm);
87739     pWriter->last = pWriter->last->next;
87740     pWriter->iOpeningChildBlock = iChildBlock;
87741     dataBufferReset(&pWriter->term);
87742   }else{
87743     dataBufferAppend2(&pWriter->last->data, c, n,
87744                       pTerm+nPrefix, nTerm-nPrefix);
87745     dataBufferReplace(&pWriter->term, pTerm, nTerm);
87746   }
87747   ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
87748 }
87749
87750 /* Free the space used by pWriter, including the linked-list of
87751 ** InteriorBlocks, and parentWriter, if present.
87752 */
87753 static int interiorWriterDestroy(InteriorWriter *pWriter){
87754   InteriorBlock *block = pWriter->first;
87755
87756   while( block!=NULL ){
87757     InteriorBlock *b = block;
87758     block = block->next;
87759     dataBufferDestroy(&b->term);
87760     dataBufferDestroy(&b->data);
87761     sqlite3_free(b);
87762   }
87763   if( pWriter->parentWriter!=NULL ){
87764     interiorWriterDestroy(pWriter->parentWriter);
87765     sqlite3_free(pWriter->parentWriter);
87766   }
87767   dataBufferDestroy(&pWriter->term);
87768   SCRAMBLE(pWriter);
87769   return SQLITE_OK;
87770 }
87771
87772 /* If pWriter can fit entirely in ROOT_MAX, return it as the root info
87773 ** directly, leaving *piEndBlockid unchanged.  Otherwise, flush
87774 ** pWriter to %_segments, building a new layer of interior nodes, and
87775 ** recursively ask for their root into.
87776 */
87777 static int interiorWriterRootInfo(fulltext_vtab *v, InteriorWriter *pWriter,
87778                                   char **ppRootInfo, int *pnRootInfo,
87779                                   sqlite_int64 *piEndBlockid){
87780   InteriorBlock *block = pWriter->first;
87781   sqlite_int64 iBlockid = 0;
87782   int rc;
87783
87784   /* If we can fit the segment inline */
87785   if( block==pWriter->last && block->data.nData<ROOT_MAX ){
87786     *ppRootInfo = block->data.pData;
87787     *pnRootInfo = block->data.nData;
87788     return SQLITE_OK;
87789   }
87790
87791   /* Flush the first block to %_segments, and create a new level of
87792   ** interior node.
87793   */
87794   ASSERT_VALID_INTERIOR_BLOCK(block);
87795   rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid);
87796   if( rc!=SQLITE_OK ) return rc;
87797   *piEndBlockid = iBlockid;
87798
87799   pWriter->parentWriter = sqlite3_malloc(sizeof(*pWriter->parentWriter));
87800   interiorWriterInit(pWriter->iHeight+1,
87801                      block->term.pData, block->term.nData,
87802                      iBlockid, pWriter->parentWriter);
87803
87804   /* Flush additional blocks and append to the higher interior
87805   ** node.
87806   */
87807   for(block=block->next; block!=NULL; block=block->next){
87808     ASSERT_VALID_INTERIOR_BLOCK(block);
87809     rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid);
87810     if( rc!=SQLITE_OK ) return rc;
87811     *piEndBlockid = iBlockid;
87812
87813     interiorWriterAppend(pWriter->parentWriter,
87814                          block->term.pData, block->term.nData, iBlockid);
87815   }
87816
87817   /* Parent node gets the chance to be the root. */
87818   return interiorWriterRootInfo(v, pWriter->parentWriter,
87819                                 ppRootInfo, pnRootInfo, piEndBlockid);
87820 }
87821
87822 /****************************************************************/
87823 /* InteriorReader is used to read off the data from an interior node
87824 ** (see comment at top of file for the format).
87825 */
87826 typedef struct InteriorReader {
87827   const char *pData;
87828   int nData;
87829
87830   DataBuffer term;          /* previous term, for decoding term delta. */
87831
87832   sqlite_int64 iBlockid;
87833 } InteriorReader;
87834
87835 static void interiorReaderDestroy(InteriorReader *pReader){
87836   dataBufferDestroy(&pReader->term);
87837   SCRAMBLE(pReader);
87838 }
87839
87840 /* TODO(shess) The assertions are great, but what if we're in NDEBUG
87841 ** and the blob is empty or otherwise contains suspect data?
87842 */
87843 static void interiorReaderInit(const char *pData, int nData,
87844                                InteriorReader *pReader){
87845   int n, nTerm;
87846
87847   /* Require at least the leading flag byte */
87848   assert( nData>0 );
87849   assert( pData[0]!='\0' );
87850
87851   CLEAR(pReader);
87852
87853   /* Decode the base blockid, and set the cursor to the first term. */
87854   n = fts3GetVarint(pData+1, &pReader->iBlockid);
87855   assert( 1+n<=nData );
87856   pReader->pData = pData+1+n;
87857   pReader->nData = nData-(1+n);
87858
87859   /* A single-child interior node (such as when a leaf node was too
87860   ** large for the segment directory) won't have any terms.
87861   ** Otherwise, decode the first term.
87862   */
87863   if( pReader->nData==0 ){
87864     dataBufferInit(&pReader->term, 0);
87865   }else{
87866     n = fts3GetVarint32(pReader->pData, &nTerm);
87867     dataBufferInit(&pReader->term, nTerm);
87868     dataBufferReplace(&pReader->term, pReader->pData+n, nTerm);
87869     assert( n+nTerm<=pReader->nData );
87870     pReader->pData += n+nTerm;
87871     pReader->nData -= n+nTerm;
87872   }
87873 }
87874
87875 static int interiorReaderAtEnd(InteriorReader *pReader){
87876   return pReader->term.nData==0;
87877 }
87878
87879 static sqlite_int64 interiorReaderCurrentBlockid(InteriorReader *pReader){
87880   return pReader->iBlockid;
87881 }
87882
87883 static int interiorReaderTermBytes(InteriorReader *pReader){
87884   assert( !interiorReaderAtEnd(pReader) );
87885   return pReader->term.nData;
87886 }
87887 static const char *interiorReaderTerm(InteriorReader *pReader){
87888   assert( !interiorReaderAtEnd(pReader) );
87889   return pReader->term.pData;
87890 }
87891
87892 /* Step forward to the next term in the node. */
87893 static void interiorReaderStep(InteriorReader *pReader){
87894   assert( !interiorReaderAtEnd(pReader) );
87895
87896   /* If the last term has been read, signal eof, else construct the
87897   ** next term.
87898   */
87899   if( pReader->nData==0 ){
87900     dataBufferReset(&pReader->term);
87901   }else{
87902     int n, nPrefix, nSuffix;
87903
87904     n = fts3GetVarint32(pReader->pData, &nPrefix);
87905     n += fts3GetVarint32(pReader->pData+n, &nSuffix);
87906
87907     /* Truncate the current term and append suffix data. */
87908     pReader->term.nData = nPrefix;
87909     dataBufferAppend(&pReader->term, pReader->pData+n, nSuffix);
87910
87911     assert( n+nSuffix<=pReader->nData );
87912     pReader->pData += n+nSuffix;
87913     pReader->nData -= n+nSuffix;
87914   }
87915   pReader->iBlockid++;
87916 }
87917
87918 /* Compare the current term to pTerm[nTerm], returning strcmp-style
87919 ** results.  If isPrefix, equality means equal through nTerm bytes.
87920 */
87921 static int interiorReaderTermCmp(InteriorReader *pReader,
87922                                  const char *pTerm, int nTerm, int isPrefix){
87923   const char *pReaderTerm = interiorReaderTerm(pReader);
87924   int nReaderTerm = interiorReaderTermBytes(pReader);
87925   int c, n = nReaderTerm<nTerm ? nReaderTerm : nTerm;
87926
87927   if( n==0 ){
87928     if( nReaderTerm>0 ) return -1;
87929     if( nTerm>0 ) return 1;
87930     return 0;
87931   }
87932
87933   c = memcmp(pReaderTerm, pTerm, n);
87934   if( c!=0 ) return c;
87935   if( isPrefix && n==nTerm ) return 0;
87936   return nReaderTerm - nTerm;
87937 }
87938
87939 /****************************************************************/
87940 /* LeafWriter is used to collect terms and associated doclist data
87941 ** into leaf blocks in %_segments (see top of file for format info).
87942 ** Expected usage is:
87943 **
87944 ** LeafWriter writer;
87945 ** leafWriterInit(0, 0, &writer);
87946 ** while( sorted_terms_left_to_process ){
87947 **   // data is doclist data for that term.
87948 **   rc = leafWriterStep(v, &writer, pTerm, nTerm, pData, nData);
87949 **   if( rc!=SQLITE_OK ) goto err;
87950 ** }
87951 ** rc = leafWriterFinalize(v, &writer);
87952 **err:
87953 ** leafWriterDestroy(&writer);
87954 ** return rc;
87955 **
87956 ** leafWriterStep() may write a collected leaf out to %_segments.
87957 ** leafWriterFinalize() finishes writing any buffered data and stores
87958 ** a root node in %_segdir.  leafWriterDestroy() frees all buffers and
87959 ** InteriorWriters allocated as part of writing this segment.
87960 **
87961 ** TODO(shess) Document leafWriterStepMerge().
87962 */
87963
87964 /* Put terms with data this big in their own block. */
87965 #define STANDALONE_MIN 1024
87966
87967 /* Keep leaf blocks below this size. */
87968 #define LEAF_MAX 2048
87969
87970 typedef struct LeafWriter {
87971   int iLevel;
87972   int idx;
87973   sqlite_int64 iStartBlockid;     /* needed to create the root info */
87974   sqlite_int64 iEndBlockid;       /* when we're done writing. */
87975
87976   DataBuffer term;                /* previous encoded term */
87977   DataBuffer data;                /* encoding buffer */
87978
87979   /* bytes of first term in the current node which distinguishes that
87980   ** term from the last term of the previous node.
87981   */
87982   int nTermDistinct;
87983
87984   InteriorWriter parentWriter;    /* if we overflow */
87985   int has_parent;
87986 } LeafWriter;
87987
87988 static void leafWriterInit(int iLevel, int idx, LeafWriter *pWriter){
87989   CLEAR(pWriter);
87990   pWriter->iLevel = iLevel;
87991   pWriter->idx = idx;
87992
87993   dataBufferInit(&pWriter->term, 32);
87994
87995   /* Start out with a reasonably sized block, though it can grow. */
87996   dataBufferInit(&pWriter->data, LEAF_MAX);
87997 }
87998
87999 #ifndef NDEBUG
88000 /* Verify that the data is readable as a leaf node. */
88001 static void leafNodeValidate(const char *pData, int nData){
88002   int n, iDummy;
88003
88004   if( nData==0 ) return;
88005   assert( nData>0 );
88006   assert( pData!=0 );
88007   assert( pData+nData>pData );
88008
88009   /* Must lead with a varint(0) */
88010   n = fts3GetVarint32(pData, &iDummy);
88011   assert( iDummy==0 );
88012   assert( n>0 );
88013   assert( n<nData );
88014   pData += n;
88015   nData -= n;
88016
88017   /* Leading term length and data must fit in buffer. */
88018   n = fts3GetVarint32(pData, &iDummy);
88019   assert( n>0 );
88020   assert( iDummy>0 );
88021   assert( n+iDummy>0 );
88022   assert( n+iDummy<nData );
88023   pData += n+iDummy;
88024   nData -= n+iDummy;
88025
88026   /* Leading term's doclist length and data must fit. */
88027   n = fts3GetVarint32(pData, &iDummy);
88028   assert( n>0 );
88029   assert( iDummy>0 );
88030   assert( n+iDummy>0 );
88031   assert( n+iDummy<=nData );
88032   ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL);
88033   pData += n+iDummy;
88034   nData -= n+iDummy;
88035
88036   /* Verify that trailing terms and doclists also are readable. */
88037   while( nData!=0 ){
88038     n = fts3GetVarint32(pData, &iDummy);
88039     assert( n>0 );
88040     assert( iDummy>=0 );
88041     assert( n<nData );
88042     pData += n;
88043     nData -= n;
88044     n = fts3GetVarint32(pData, &iDummy);
88045     assert( n>0 );
88046     assert( iDummy>0 );
88047     assert( n+iDummy>0 );
88048     assert( n+iDummy<nData );
88049     pData += n+iDummy;
88050     nData -= n+iDummy;
88051
88052     n = fts3GetVarint32(pData, &iDummy);
88053     assert( n>0 );
88054     assert( iDummy>0 );
88055     assert( n+iDummy>0 );
88056     assert( n+iDummy<=nData );
88057     ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL);
88058     pData += n+iDummy;
88059     nData -= n+iDummy;
88060   }
88061 }
88062 #define ASSERT_VALID_LEAF_NODE(p, n) leafNodeValidate(p, n)
88063 #else
88064 #define ASSERT_VALID_LEAF_NODE(p, n) assert( 1 )
88065 #endif
88066
88067 /* Flush the current leaf node to %_segments, and adding the resulting
88068 ** blockid and the starting term to the interior node which will
88069 ** contain it.
88070 */
88071 static int leafWriterInternalFlush(fulltext_vtab *v, LeafWriter *pWriter,
88072                                    int iData, int nData){
88073   sqlite_int64 iBlockid = 0;
88074   const char *pStartingTerm;
88075   int nStartingTerm, rc, n;
88076
88077   /* Must have the leading varint(0) flag, plus at least some
88078   ** valid-looking data.
88079   */
88080   assert( nData>2 );
88081   assert( iData>=0 );
88082   assert( iData+nData<=pWriter->data.nData );
88083   ASSERT_VALID_LEAF_NODE(pWriter->data.pData+iData, nData);
88084
88085   rc = block_insert(v, pWriter->data.pData+iData, nData, &iBlockid);
88086   if( rc!=SQLITE_OK ) return rc;
88087   assert( iBlockid!=0 );
88088
88089   /* Reconstruct the first term in the leaf for purposes of building
88090   ** the interior node.
88091   */
88092   n = fts3GetVarint32(pWriter->data.pData+iData+1, &nStartingTerm);
88093   pStartingTerm = pWriter->data.pData+iData+1+n;
88094   assert( pWriter->data.nData>iData+1+n+nStartingTerm );
88095   assert( pWriter->nTermDistinct>0 );
88096   assert( pWriter->nTermDistinct<=nStartingTerm );
88097   nStartingTerm = pWriter->nTermDistinct;
88098
88099   if( pWriter->has_parent ){
88100     interiorWriterAppend(&pWriter->parentWriter,
88101                          pStartingTerm, nStartingTerm, iBlockid);
88102   }else{
88103     interiorWriterInit(1, pStartingTerm, nStartingTerm, iBlockid,
88104                        &pWriter->parentWriter);
88105     pWriter->has_parent = 1;
88106   }
88107
88108   /* Track the span of this segment's leaf nodes. */
88109   if( pWriter->iEndBlockid==0 ){
88110     pWriter->iEndBlockid = pWriter->iStartBlockid = iBlockid;
88111   }else{
88112     pWriter->iEndBlockid++;
88113     assert( iBlockid==pWriter->iEndBlockid );
88114   }
88115
88116   return SQLITE_OK;
88117 }
88118 static int leafWriterFlush(fulltext_vtab *v, LeafWriter *pWriter){
88119   int rc = leafWriterInternalFlush(v, pWriter, 0, pWriter->data.nData);
88120   if( rc!=SQLITE_OK ) return rc;
88121
88122   /* Re-initialize the output buffer. */
88123   dataBufferReset(&pWriter->data);
88124
88125   return SQLITE_OK;
88126 }
88127
88128 /* Fetch the root info for the segment.  If the entire leaf fits
88129 ** within ROOT_MAX, then it will be returned directly, otherwise it
88130 ** will be flushed and the root info will be returned from the
88131 ** interior node.  *piEndBlockid is set to the blockid of the last
88132 ** interior or leaf node written to disk (0 if none are written at
88133 ** all).
88134 */
88135 static int leafWriterRootInfo(fulltext_vtab *v, LeafWriter *pWriter,
88136                               char **ppRootInfo, int *pnRootInfo,
88137                               sqlite_int64 *piEndBlockid){
88138   /* we can fit the segment entirely inline */
88139   if( !pWriter->has_parent && pWriter->data.nData<ROOT_MAX ){
88140     *ppRootInfo = pWriter->data.pData;
88141     *pnRootInfo = pWriter->data.nData;
88142     *piEndBlockid = 0;
88143     return SQLITE_OK;
88144   }
88145
88146   /* Flush remaining leaf data. */
88147   if( pWriter->data.nData>0 ){
88148     int rc = leafWriterFlush(v, pWriter);
88149     if( rc!=SQLITE_OK ) return rc;
88150   }
88151
88152   /* We must have flushed a leaf at some point. */
88153   assert( pWriter->has_parent );
88154
88155   /* Tenatively set the end leaf blockid as the end blockid.  If the
88156   ** interior node can be returned inline, this will be the final
88157   ** blockid, otherwise it will be overwritten by
88158   ** interiorWriterRootInfo().
88159   */
88160   *piEndBlockid = pWriter->iEndBlockid;
88161
88162   return interiorWriterRootInfo(v, &pWriter->parentWriter,
88163                                 ppRootInfo, pnRootInfo, piEndBlockid);
88164 }
88165
88166 /* Collect the rootInfo data and store it into the segment directory.
88167 ** This has the effect of flushing the segment's leaf data to
88168 ** %_segments, and also flushing any interior nodes to %_segments.
88169 */
88170 static int leafWriterFinalize(fulltext_vtab *v, LeafWriter *pWriter){
88171   sqlite_int64 iEndBlockid;
88172   char *pRootInfo;
88173   int rc, nRootInfo;
88174
88175   rc = leafWriterRootInfo(v, pWriter, &pRootInfo, &nRootInfo, &iEndBlockid);
88176   if( rc!=SQLITE_OK ) return rc;
88177
88178   /* Don't bother storing an entirely empty segment. */
88179   if( iEndBlockid==0 && nRootInfo==0 ) return SQLITE_OK;
88180
88181   return segdir_set(v, pWriter->iLevel, pWriter->idx,
88182                     pWriter->iStartBlockid, pWriter->iEndBlockid,
88183                     iEndBlockid, pRootInfo, nRootInfo);
88184 }
88185
88186 static void leafWriterDestroy(LeafWriter *pWriter){
88187   if( pWriter->has_parent ) interiorWriterDestroy(&pWriter->parentWriter);
88188   dataBufferDestroy(&pWriter->term);
88189   dataBufferDestroy(&pWriter->data);
88190 }
88191
88192 /* Encode a term into the leafWriter, delta-encoding as appropriate.
88193 ** Returns the length of the new term which distinguishes it from the
88194 ** previous term, which can be used to set nTermDistinct when a node
88195 ** boundary is crossed.
88196 */
88197 static int leafWriterEncodeTerm(LeafWriter *pWriter,
88198                                 const char *pTerm, int nTerm){
88199   char c[VARINT_MAX+VARINT_MAX];
88200   int n, nPrefix = 0;
88201
88202   assert( nTerm>0 );
88203   while( nPrefix<pWriter->term.nData &&
88204          pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){
88205     nPrefix++;
88206     /* Failing this implies that the terms weren't in order. */
88207     assert( nPrefix<nTerm );
88208   }
88209
88210   if( pWriter->data.nData==0 ){
88211     /* Encode the node header and leading term as:
88212     **  varint(0)
88213     **  varint(nTerm)
88214     **  char pTerm[nTerm]
88215     */
88216     n = fts3PutVarint(c, '\0');
88217     n += fts3PutVarint(c+n, nTerm);
88218     dataBufferAppend2(&pWriter->data, c, n, pTerm, nTerm);
88219   }else{
88220     /* Delta-encode the term as:
88221     **  varint(nPrefix)
88222     **  varint(nSuffix)
88223     **  char pTermSuffix[nSuffix]
88224     */
88225     n = fts3PutVarint(c, nPrefix);
88226     n += fts3PutVarint(c+n, nTerm-nPrefix);
88227     dataBufferAppend2(&pWriter->data, c, n, pTerm+nPrefix, nTerm-nPrefix);
88228   }
88229   dataBufferReplace(&pWriter->term, pTerm, nTerm);
88230
88231   return nPrefix+1;
88232 }
88233
88234 /* Used to avoid a memmove when a large amount of doclist data is in
88235 ** the buffer.  This constructs a node and term header before
88236 ** iDoclistData and flushes the resulting complete node using
88237 ** leafWriterInternalFlush().
88238 */
88239 static int leafWriterInlineFlush(fulltext_vtab *v, LeafWriter *pWriter,
88240                                  const char *pTerm, int nTerm,
88241                                  int iDoclistData){
88242   char c[VARINT_MAX+VARINT_MAX];
88243   int iData, n = fts3PutVarint(c, 0);
88244   n += fts3PutVarint(c+n, nTerm);
88245
88246   /* There should always be room for the header.  Even if pTerm shared
88247   ** a substantial prefix with the previous term, the entire prefix
88248   ** could be constructed from earlier data in the doclist, so there
88249   ** should be room.
88250   */
88251   assert( iDoclistData>=n+nTerm );
88252
88253   iData = iDoclistData-(n+nTerm);
88254   memcpy(pWriter->data.pData+iData, c, n);
88255   memcpy(pWriter->data.pData+iData+n, pTerm, nTerm);
88256
88257   return leafWriterInternalFlush(v, pWriter, iData, pWriter->data.nData-iData);
88258 }
88259
88260 /* Push pTerm[nTerm] along with the doclist data to the leaf layer of
88261 ** %_segments.
88262 */
88263 static int leafWriterStepMerge(fulltext_vtab *v, LeafWriter *pWriter,
88264                                const char *pTerm, int nTerm,
88265                                DLReader *pReaders, int nReaders){
88266   char c[VARINT_MAX+VARINT_MAX];
88267   int iTermData = pWriter->data.nData, iDoclistData;
88268   int i, nData, n, nActualData, nActual, rc, nTermDistinct;
88269
88270   ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData);
88271   nTermDistinct = leafWriterEncodeTerm(pWriter, pTerm, nTerm);
88272
88273   /* Remember nTermDistinct if opening a new node. */
88274   if( iTermData==0 ) pWriter->nTermDistinct = nTermDistinct;
88275
88276   iDoclistData = pWriter->data.nData;
88277
88278   /* Estimate the length of the merged doclist so we can leave space
88279   ** to encode it.
88280   */
88281   for(i=0, nData=0; i<nReaders; i++){
88282     nData += dlrAllDataBytes(&pReaders[i]);
88283   }
88284   n = fts3PutVarint(c, nData);
88285   dataBufferAppend(&pWriter->data, c, n);
88286
88287   docListMerge(&pWriter->data, pReaders, nReaders);
88288   ASSERT_VALID_DOCLIST(DL_DEFAULT,
88289                        pWriter->data.pData+iDoclistData+n,
88290                        pWriter->data.nData-iDoclistData-n, NULL);
88291
88292   /* The actual amount of doclist data at this point could be smaller
88293   ** than the length we encoded.  Additionally, the space required to
88294   ** encode this length could be smaller.  For small doclists, this is
88295   ** not a big deal, we can just use memmove() to adjust things.
88296   */
88297   nActualData = pWriter->data.nData-(iDoclistData+n);
88298   nActual = fts3PutVarint(c, nActualData);
88299   assert( nActualData<=nData );
88300   assert( nActual<=n );
88301
88302   /* If the new doclist is big enough for force a standalone leaf
88303   ** node, we can immediately flush it inline without doing the
88304   ** memmove().
88305   */
88306   /* TODO(shess) This test matches leafWriterStep(), which does this
88307   ** test before it knows the cost to varint-encode the term and
88308   ** doclist lengths.  At some point, change to
88309   ** pWriter->data.nData-iTermData>STANDALONE_MIN.
88310   */
88311   if( nTerm+nActualData>STANDALONE_MIN ){
88312     /* Push leaf node from before this term. */
88313     if( iTermData>0 ){
88314       rc = leafWriterInternalFlush(v, pWriter, 0, iTermData);
88315       if( rc!=SQLITE_OK ) return rc;
88316
88317       pWriter->nTermDistinct = nTermDistinct;
88318     }
88319
88320     /* Fix the encoded doclist length. */
88321     iDoclistData += n - nActual;
88322     memcpy(pWriter->data.pData+iDoclistData, c, nActual);
88323
88324     /* Push the standalone leaf node. */
88325     rc = leafWriterInlineFlush(v, pWriter, pTerm, nTerm, iDoclistData);
88326     if( rc!=SQLITE_OK ) return rc;
88327
88328     /* Leave the node empty. */
88329     dataBufferReset(&pWriter->data);
88330
88331     return rc;
88332   }
88333
88334   /* At this point, we know that the doclist was small, so do the
88335   ** memmove if indicated.
88336   */
88337   if( nActual<n ){
88338     memmove(pWriter->data.pData+iDoclistData+nActual,
88339             pWriter->data.pData+iDoclistData+n,
88340             pWriter->data.nData-(iDoclistData+n));
88341     pWriter->data.nData -= n-nActual;
88342   }
88343
88344   /* Replace written length with actual length. */
88345   memcpy(pWriter->data.pData+iDoclistData, c, nActual);
88346
88347   /* If the node is too large, break things up. */
88348   /* TODO(shess) This test matches leafWriterStep(), which does this
88349   ** test before it knows the cost to varint-encode the term and
88350   ** doclist lengths.  At some point, change to
88351   ** pWriter->data.nData>LEAF_MAX.
88352   */
88353   if( iTermData+nTerm+nActualData>LEAF_MAX ){
88354     /* Flush out the leading data as a node */
88355     rc = leafWriterInternalFlush(v, pWriter, 0, iTermData);
88356     if( rc!=SQLITE_OK ) return rc;
88357
88358     pWriter->nTermDistinct = nTermDistinct;
88359
88360     /* Rebuild header using the current term */
88361     n = fts3PutVarint(pWriter->data.pData, 0);
88362     n += fts3PutVarint(pWriter->data.pData+n, nTerm);
88363     memcpy(pWriter->data.pData+n, pTerm, nTerm);
88364     n += nTerm;
88365
88366     /* There should always be room, because the previous encoding
88367     ** included all data necessary to construct the term.
88368     */
88369     assert( n<iDoclistData );
88370     /* So long as STANDALONE_MIN is half or less of LEAF_MAX, the
88371     ** following memcpy() is safe (as opposed to needing a memmove).
88372     */
88373     assert( 2*STANDALONE_MIN<=LEAF_MAX );
88374     assert( n+pWriter->data.nData-iDoclistData<iDoclistData );
88375     memcpy(pWriter->data.pData+n,
88376            pWriter->data.pData+iDoclistData,
88377            pWriter->data.nData-iDoclistData);
88378     pWriter->data.nData -= iDoclistData-n;
88379   }
88380   ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData);
88381
88382   return SQLITE_OK;
88383 }
88384
88385 /* Push pTerm[nTerm] along with the doclist data to the leaf layer of
88386 ** %_segments.
88387 */
88388 /* TODO(shess) Revise writeZeroSegment() so that doclists are
88389 ** constructed directly in pWriter->data.
88390 */
88391 static int leafWriterStep(fulltext_vtab *v, LeafWriter *pWriter,
88392                           const char *pTerm, int nTerm,
88393                           const char *pData, int nData){
88394   int rc;
88395   DLReader reader;
88396
88397   dlrInit(&reader, DL_DEFAULT, pData, nData);
88398   rc = leafWriterStepMerge(v, pWriter, pTerm, nTerm, &reader, 1);
88399   dlrDestroy(&reader);
88400
88401   return rc;
88402 }
88403
88404
88405 /****************************************************************/
88406 /* LeafReader is used to iterate over an individual leaf node. */
88407 typedef struct LeafReader {
88408   DataBuffer term;          /* copy of current term. */
88409
88410   const char *pData;        /* data for current term. */
88411   int nData;
88412 } LeafReader;
88413
88414 static void leafReaderDestroy(LeafReader *pReader){
88415   dataBufferDestroy(&pReader->term);
88416   SCRAMBLE(pReader);
88417 }
88418
88419 static int leafReaderAtEnd(LeafReader *pReader){
88420   return pReader->nData<=0;
88421 }
88422
88423 /* Access the current term. */
88424 static int leafReaderTermBytes(LeafReader *pReader){
88425   return pReader->term.nData;
88426 }
88427 static const char *leafReaderTerm(LeafReader *pReader){
88428   assert( pReader->term.nData>0 );
88429   return pReader->term.pData;
88430 }
88431
88432 /* Access the doclist data for the current term. */
88433 static int leafReaderDataBytes(LeafReader *pReader){
88434   int nData;
88435   assert( pReader->term.nData>0 );
88436   fts3GetVarint32(pReader->pData, &nData);
88437   return nData;
88438 }
88439 static const char *leafReaderData(LeafReader *pReader){
88440   int n, nData;
88441   assert( pReader->term.nData>0 );
88442   n = fts3GetVarint32(pReader->pData, &nData);
88443   return pReader->pData+n;
88444 }
88445
88446 static void leafReaderInit(const char *pData, int nData,
88447                            LeafReader *pReader){
88448   int nTerm, n;
88449
88450   assert( nData>0 );
88451   assert( pData[0]=='\0' );
88452
88453   CLEAR(pReader);
88454
88455   /* Read the first term, skipping the header byte. */
88456   n = fts3GetVarint32(pData+1, &nTerm);
88457   dataBufferInit(&pReader->term, nTerm);
88458   dataBufferReplace(&pReader->term, pData+1+n, nTerm);
88459
88460   /* Position after the first term. */
88461   assert( 1+n+nTerm<nData );
88462   pReader->pData = pData+1+n+nTerm;
88463   pReader->nData = nData-1-n-nTerm;
88464 }
88465
88466 /* Step the reader forward to the next term. */
88467 static void leafReaderStep(LeafReader *pReader){
88468   int n, nData, nPrefix, nSuffix;
88469   assert( !leafReaderAtEnd(pReader) );
88470
88471   /* Skip previous entry's data block. */
88472   n = fts3GetVarint32(pReader->pData, &nData);
88473   assert( n+nData<=pReader->nData );
88474   pReader->pData += n+nData;
88475   pReader->nData -= n+nData;
88476
88477   if( !leafReaderAtEnd(pReader) ){
88478     /* Construct the new term using a prefix from the old term plus a
88479     ** suffix from the leaf data.
88480     */
88481     n = fts3GetVarint32(pReader->pData, &nPrefix);
88482     n += fts3GetVarint32(pReader->pData+n, &nSuffix);
88483     assert( n+nSuffix<pReader->nData );
88484     pReader->term.nData = nPrefix;
88485     dataBufferAppend(&pReader->term, pReader->pData+n, nSuffix);
88486
88487     pReader->pData += n+nSuffix;
88488     pReader->nData -= n+nSuffix;
88489   }
88490 }
88491
88492 /* strcmp-style comparison of pReader's current term against pTerm.
88493 ** If isPrefix, equality means equal through nTerm bytes.
88494 */
88495 static int leafReaderTermCmp(LeafReader *pReader,
88496                              const char *pTerm, int nTerm, int isPrefix){
88497   int c, n = pReader->term.nData<nTerm ? pReader->term.nData : nTerm;
88498   if( n==0 ){
88499     if( pReader->term.nData>0 ) return -1;
88500     if(nTerm>0 ) return 1;
88501     return 0;
88502   }
88503
88504   c = memcmp(pReader->term.pData, pTerm, n);
88505   if( c!=0 ) return c;
88506   if( isPrefix && n==nTerm ) return 0;
88507   return pReader->term.nData - nTerm;
88508 }
88509
88510
88511 /****************************************************************/
88512 /* LeavesReader wraps LeafReader to allow iterating over the entire
88513 ** leaf layer of the tree.
88514 */
88515 typedef struct LeavesReader {
88516   int idx;                  /* Index within the segment. */
88517
88518   sqlite3_stmt *pStmt;      /* Statement we're streaming leaves from. */
88519   int eof;                  /* we've seen SQLITE_DONE from pStmt. */
88520
88521   LeafReader leafReader;    /* reader for the current leaf. */
88522   DataBuffer rootData;      /* root data for inline. */
88523 } LeavesReader;
88524
88525 /* Access the current term. */
88526 static int leavesReaderTermBytes(LeavesReader *pReader){
88527   assert( !pReader->eof );
88528   return leafReaderTermBytes(&pReader->leafReader);
88529 }
88530 static const char *leavesReaderTerm(LeavesReader *pReader){
88531   assert( !pReader->eof );
88532   return leafReaderTerm(&pReader->leafReader);
88533 }
88534
88535 /* Access the doclist data for the current term. */
88536 static int leavesReaderDataBytes(LeavesReader *pReader){
88537   assert( !pReader->eof );
88538   return leafReaderDataBytes(&pReader->leafReader);
88539 }
88540 static const char *leavesReaderData(LeavesReader *pReader){
88541   assert( !pReader->eof );
88542   return leafReaderData(&pReader->leafReader);
88543 }
88544
88545 static int leavesReaderAtEnd(LeavesReader *pReader){
88546   return pReader->eof;
88547 }
88548
88549 /* loadSegmentLeaves() may not read all the way to SQLITE_DONE, thus
88550 ** leaving the statement handle open, which locks the table.
88551 */
88552 /* TODO(shess) This "solution" is not satisfactory.  Really, there
88553 ** should be check-in function for all statement handles which
88554 ** arranges to call sqlite3_reset().  This most likely will require
88555 ** modification to control flow all over the place, though, so for now
88556 ** just punt.
88557 **
88558 ** Note the the current system assumes that segment merges will run to
88559 ** completion, which is why this particular probably hasn't arisen in
88560 ** this case.  Probably a brittle assumption.
88561 */
88562 static int leavesReaderReset(LeavesReader *pReader){
88563   return sqlite3_reset(pReader->pStmt);
88564 }
88565
88566 static void leavesReaderDestroy(LeavesReader *pReader){
88567   /* If idx is -1, that means we're using a non-cached statement
88568   ** handle in the optimize() case, so we need to release it.
88569   */
88570   if( pReader->pStmt!=NULL && pReader->idx==-1 ){
88571     sqlite3_finalize(pReader->pStmt);
88572   }
88573   leafReaderDestroy(&pReader->leafReader);
88574   dataBufferDestroy(&pReader->rootData);
88575   SCRAMBLE(pReader);
88576 }
88577
88578 /* Initialize pReader with the given root data (if iStartBlockid==0
88579 ** the leaf data was entirely contained in the root), or from the
88580 ** stream of blocks between iStartBlockid and iEndBlockid, inclusive.
88581 */
88582 static int leavesReaderInit(fulltext_vtab *v,
88583                             int idx,
88584                             sqlite_int64 iStartBlockid,
88585                             sqlite_int64 iEndBlockid,
88586                             const char *pRootData, int nRootData,
88587                             LeavesReader *pReader){
88588   CLEAR(pReader);
88589   pReader->idx = idx;
88590
88591   dataBufferInit(&pReader->rootData, 0);
88592   if( iStartBlockid==0 ){
88593     /* Entire leaf level fit in root data. */
88594     dataBufferReplace(&pReader->rootData, pRootData, nRootData);
88595     leafReaderInit(pReader->rootData.pData, pReader->rootData.nData,
88596                    &pReader->leafReader);
88597   }else{
88598     sqlite3_stmt *s;
88599     int rc = sql_get_leaf_statement(v, idx, &s);
88600     if( rc!=SQLITE_OK ) return rc;
88601
88602     rc = sqlite3_bind_int64(s, 1, iStartBlockid);
88603     if( rc!=SQLITE_OK ) return rc;
88604
88605     rc = sqlite3_bind_int64(s, 2, iEndBlockid);
88606     if( rc!=SQLITE_OK ) return rc;
88607
88608     rc = sqlite3_step(s);
88609     if( rc==SQLITE_DONE ){
88610       pReader->eof = 1;
88611       return SQLITE_OK;
88612     }
88613     if( rc!=SQLITE_ROW ) return rc;
88614
88615     pReader->pStmt = s;
88616     leafReaderInit(sqlite3_column_blob(pReader->pStmt, 0),
88617                    sqlite3_column_bytes(pReader->pStmt, 0),
88618                    &pReader->leafReader);
88619   }
88620   return SQLITE_OK;
88621 }
88622
88623 /* Step the current leaf forward to the next term.  If we reach the
88624 ** end of the current leaf, step forward to the next leaf block.
88625 */
88626 static int leavesReaderStep(fulltext_vtab *v, LeavesReader *pReader){
88627   assert( !leavesReaderAtEnd(pReader) );
88628   leafReaderStep(&pReader->leafReader);
88629
88630   if( leafReaderAtEnd(&pReader->leafReader) ){
88631     int rc;
88632     if( pReader->rootData.pData ){
88633       pReader->eof = 1;
88634       return SQLITE_OK;
88635     }
88636     rc = sqlite3_step(pReader->pStmt);
88637     if( rc!=SQLITE_ROW ){
88638       pReader->eof = 1;
88639       return rc==SQLITE_DONE ? SQLITE_OK : rc;
88640     }
88641     leafReaderDestroy(&pReader->leafReader);
88642     leafReaderInit(sqlite3_column_blob(pReader->pStmt, 0),
88643                    sqlite3_column_bytes(pReader->pStmt, 0),
88644                    &pReader->leafReader);
88645   }
88646   return SQLITE_OK;
88647 }
88648
88649 /* Order LeavesReaders by their term, ignoring idx.  Readers at eof
88650 ** always sort to the end.
88651 */
88652 static int leavesReaderTermCmp(LeavesReader *lr1, LeavesReader *lr2){
88653   if( leavesReaderAtEnd(lr1) ){
88654     if( leavesReaderAtEnd(lr2) ) return 0;
88655     return 1;
88656   }
88657   if( leavesReaderAtEnd(lr2) ) return -1;
88658
88659   return leafReaderTermCmp(&lr1->leafReader,
88660                            leavesReaderTerm(lr2), leavesReaderTermBytes(lr2),
88661                            0);
88662 }
88663
88664 /* Similar to leavesReaderTermCmp(), with additional ordering by idx
88665 ** so that older segments sort before newer segments.
88666 */
88667 static int leavesReaderCmp(LeavesReader *lr1, LeavesReader *lr2){
88668   int c = leavesReaderTermCmp(lr1, lr2);
88669   if( c!=0 ) return c;
88670   return lr1->idx-lr2->idx;
88671 }
88672
88673 /* Assume that pLr[1]..pLr[nLr] are sorted.  Bubble pLr[0] into its
88674 ** sorted position.
88675 */
88676 static void leavesReaderReorder(LeavesReader *pLr, int nLr){
88677   while( nLr>1 && leavesReaderCmp(pLr, pLr+1)>0 ){
88678     LeavesReader tmp = pLr[0];
88679     pLr[0] = pLr[1];
88680     pLr[1] = tmp;
88681     nLr--;
88682     pLr++;
88683   }
88684 }
88685
88686 /* Initializes pReaders with the segments from level iLevel, returning
88687 ** the number of segments in *piReaders.  Leaves pReaders in sorted
88688 ** order.
88689 */
88690 static int leavesReadersInit(fulltext_vtab *v, int iLevel,
88691                              LeavesReader *pReaders, int *piReaders){
88692   sqlite3_stmt *s;
88693   int i, rc = sql_get_statement(v, SEGDIR_SELECT_LEVEL_STMT, &s);
88694   if( rc!=SQLITE_OK ) return rc;
88695
88696   rc = sqlite3_bind_int(s, 1, iLevel);
88697   if( rc!=SQLITE_OK ) return rc;
88698
88699   i = 0;
88700   while( (rc = sqlite3_step(s))==SQLITE_ROW ){
88701     sqlite_int64 iStart = sqlite3_column_int64(s, 0);
88702     sqlite_int64 iEnd = sqlite3_column_int64(s, 1);
88703     const char *pRootData = sqlite3_column_blob(s, 2);
88704     int nRootData = sqlite3_column_bytes(s, 2);
88705
88706     assert( i<MERGE_COUNT );
88707     rc = leavesReaderInit(v, i, iStart, iEnd, pRootData, nRootData,
88708                           &pReaders[i]);
88709     if( rc!=SQLITE_OK ) break;
88710
88711     i++;
88712   }
88713   if( rc!=SQLITE_DONE ){
88714     while( i-->0 ){
88715       leavesReaderDestroy(&pReaders[i]);
88716     }
88717     return rc;
88718   }
88719
88720   *piReaders = i;
88721
88722   /* Leave our results sorted by term, then age. */
88723   while( i-- ){
88724     leavesReaderReorder(pReaders+i, *piReaders-i);
88725   }
88726   return SQLITE_OK;
88727 }
88728
88729 /* Merge doclists from pReaders[nReaders] into a single doclist, which
88730 ** is written to pWriter.  Assumes pReaders is ordered oldest to
88731 ** newest.
88732 */
88733 /* TODO(shess) Consider putting this inline in segmentMerge(). */
88734 static int leavesReadersMerge(fulltext_vtab *v,
88735                               LeavesReader *pReaders, int nReaders,
88736                               LeafWriter *pWriter){
88737   DLReader dlReaders[MERGE_COUNT];
88738   const char *pTerm = leavesReaderTerm(pReaders);
88739   int i, nTerm = leavesReaderTermBytes(pReaders);
88740
88741   assert( nReaders<=MERGE_COUNT );
88742
88743   for(i=0; i<nReaders; i++){
88744     dlrInit(&dlReaders[i], DL_DEFAULT,
88745             leavesReaderData(pReaders+i),
88746             leavesReaderDataBytes(pReaders+i));
88747   }
88748
88749   return leafWriterStepMerge(v, pWriter, pTerm, nTerm, dlReaders, nReaders);
88750 }
88751
88752 /* Forward ref due to mutual recursion with segdirNextIndex(). */
88753 static int segmentMerge(fulltext_vtab *v, int iLevel);
88754
88755 /* Put the next available index at iLevel into *pidx.  If iLevel
88756 ** already has MERGE_COUNT segments, they are merged to a higher
88757 ** level to make room.
88758 */
88759 static int segdirNextIndex(fulltext_vtab *v, int iLevel, int *pidx){
88760   int rc = segdir_max_index(v, iLevel, pidx);
88761   if( rc==SQLITE_DONE ){              /* No segments at iLevel. */
88762     *pidx = 0;
88763   }else if( rc==SQLITE_ROW ){
88764     if( *pidx==(MERGE_COUNT-1) ){
88765       rc = segmentMerge(v, iLevel);
88766       if( rc!=SQLITE_OK ) return rc;
88767       *pidx = 0;
88768     }else{
88769       (*pidx)++;
88770     }
88771   }else{
88772     return rc;
88773   }
88774   return SQLITE_OK;
88775 }
88776
88777 /* Merge MERGE_COUNT segments at iLevel into a new segment at
88778 ** iLevel+1.  If iLevel+1 is already full of segments, those will be
88779 ** merged to make room.
88780 */
88781 static int segmentMerge(fulltext_vtab *v, int iLevel){
88782   LeafWriter writer;
88783   LeavesReader lrs[MERGE_COUNT];
88784   int i, rc, idx = 0;
88785
88786   /* Determine the next available segment index at the next level,
88787   ** merging as necessary.
88788   */
88789   rc = segdirNextIndex(v, iLevel+1, &idx);
88790   if( rc!=SQLITE_OK ) return rc;
88791
88792   /* TODO(shess) This assumes that we'll always see exactly
88793   ** MERGE_COUNT segments to merge at a given level.  That will be
88794   ** broken if we allow the developer to request preemptive or
88795   ** deferred merging.
88796   */
88797   memset(&lrs, '\0', sizeof(lrs));
88798   rc = leavesReadersInit(v, iLevel, lrs, &i);
88799   if( rc!=SQLITE_OK ) return rc;
88800   assert( i==MERGE_COUNT );
88801
88802   leafWriterInit(iLevel+1, idx, &writer);
88803
88804   /* Since leavesReaderReorder() pushes readers at eof to the end,
88805   ** when the first reader is empty, all will be empty.
88806   */
88807   while( !leavesReaderAtEnd(lrs) ){
88808     /* Figure out how many readers share their next term. */
88809     for(i=1; i<MERGE_COUNT && !leavesReaderAtEnd(lrs+i); i++){
88810       if( 0!=leavesReaderTermCmp(lrs, lrs+i) ) break;
88811     }
88812
88813     rc = leavesReadersMerge(v, lrs, i, &writer);
88814     if( rc!=SQLITE_OK ) goto err;
88815
88816     /* Step forward those that were merged. */
88817     while( i-->0 ){
88818       rc = leavesReaderStep(v, lrs+i);
88819       if( rc!=SQLITE_OK ) goto err;
88820
88821       /* Reorder by term, then by age. */
88822       leavesReaderReorder(lrs+i, MERGE_COUNT-i);
88823     }
88824   }
88825
88826   for(i=0; i<MERGE_COUNT; i++){
88827     leavesReaderDestroy(&lrs[i]);
88828   }
88829
88830   rc = leafWriterFinalize(v, &writer);
88831   leafWriterDestroy(&writer);
88832   if( rc!=SQLITE_OK ) return rc;
88833
88834   /* Delete the merged segment data. */
88835   return segdir_delete(v, iLevel);
88836
88837  err:
88838   for(i=0; i<MERGE_COUNT; i++){
88839     leavesReaderDestroy(&lrs[i]);
88840   }
88841   leafWriterDestroy(&writer);
88842   return rc;
88843 }
88844
88845 /* Accumulate the union of *acc and *pData into *acc. */
88846 static void docListAccumulateUnion(DataBuffer *acc,
88847                                    const char *pData, int nData) {
88848   DataBuffer tmp = *acc;
88849   dataBufferInit(acc, tmp.nData+nData);
88850   docListUnion(tmp.pData, tmp.nData, pData, nData, acc);
88851   dataBufferDestroy(&tmp);
88852 }
88853
88854 /* TODO(shess) It might be interesting to explore different merge
88855 ** strategies, here.  For instance, since this is a sorted merge, we
88856 ** could easily merge many doclists in parallel.  With some
88857 ** comprehension of the storage format, we could merge all of the
88858 ** doclists within a leaf node directly from the leaf node's storage.
88859 ** It may be worthwhile to merge smaller doclists before larger
88860 ** doclists, since they can be traversed more quickly - but the
88861 ** results may have less overlap, making them more expensive in a
88862 ** different way.
88863 */
88864
88865 /* Scan pReader for pTerm/nTerm, and merge the term's doclist over
88866 ** *out (any doclists with duplicate docids overwrite those in *out).
88867 ** Internal function for loadSegmentLeaf().
88868 */
88869 static int loadSegmentLeavesInt(fulltext_vtab *v, LeavesReader *pReader,
88870                                 const char *pTerm, int nTerm, int isPrefix,
88871                                 DataBuffer *out){
88872   /* doclist data is accumulated into pBuffers similar to how one does
88873   ** increment in binary arithmetic.  If index 0 is empty, the data is
88874   ** stored there.  If there is data there, it is merged and the
88875   ** results carried into position 1, with further merge-and-carry
88876   ** until an empty position is found.
88877   */
88878   DataBuffer *pBuffers = NULL;
88879   int nBuffers = 0, nMaxBuffers = 0, rc;
88880
88881   assert( nTerm>0 );
88882
88883   for(rc=SQLITE_OK; rc==SQLITE_OK && !leavesReaderAtEnd(pReader);
88884       rc=leavesReaderStep(v, pReader)){
88885     /* TODO(shess) Really want leavesReaderTermCmp(), but that name is
88886     ** already taken to compare the terms of two LeavesReaders.  Think
88887     ** on a better name.  [Meanwhile, break encapsulation rather than
88888     ** use a confusing name.]
88889     */
88890     int c = leafReaderTermCmp(&pReader->leafReader, pTerm, nTerm, isPrefix);
88891     if( c>0 ) break;      /* Past any possible matches. */
88892     if( c==0 ){
88893       const char *pData = leavesReaderData(pReader);
88894       int iBuffer, nData = leavesReaderDataBytes(pReader);
88895
88896       /* Find the first empty buffer. */
88897       for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){
88898         if( 0==pBuffers[iBuffer].nData ) break;
88899       }
88900
88901       /* Out of buffers, add an empty one. */
88902       if( iBuffer==nBuffers ){
88903         if( nBuffers==nMaxBuffers ){
88904           DataBuffer *p;
88905           nMaxBuffers += 20;
88906
88907           /* Manual realloc so we can handle NULL appropriately. */
88908           p = sqlite3_malloc(nMaxBuffers*sizeof(*pBuffers));
88909           if( p==NULL ){
88910             rc = SQLITE_NOMEM;
88911             break;
88912           }
88913
88914           if( nBuffers>0 ){
88915             assert(pBuffers!=NULL);
88916             memcpy(p, pBuffers, nBuffers*sizeof(*pBuffers));
88917             sqlite3_free(pBuffers);
88918           }
88919           pBuffers = p;
88920         }
88921         dataBufferInit(&(pBuffers[nBuffers]), 0);
88922         nBuffers++;
88923       }
88924
88925       /* At this point, must have an empty at iBuffer. */
88926       assert(iBuffer<nBuffers && pBuffers[iBuffer].nData==0);
88927
88928       /* If empty was first buffer, no need for merge logic. */
88929       if( iBuffer==0 ){
88930         dataBufferReplace(&(pBuffers[0]), pData, nData);
88931       }else{
88932         /* pAcc is the empty buffer the merged data will end up in. */
88933         DataBuffer *pAcc = &(pBuffers[iBuffer]);
88934         DataBuffer *p = &(pBuffers[0]);
88935
88936         /* Handle position 0 specially to avoid need to prime pAcc
88937         ** with pData/nData.
88938         */
88939         dataBufferSwap(p, pAcc);
88940         docListAccumulateUnion(pAcc, pData, nData);
88941
88942         /* Accumulate remaining doclists into pAcc. */
88943         for(++p; p<pAcc; ++p){
88944           docListAccumulateUnion(pAcc, p->pData, p->nData);
88945
88946           /* dataBufferReset() could allow a large doclist to blow up
88947           ** our memory requirements.
88948           */
88949           if( p->nCapacity<1024 ){
88950             dataBufferReset(p);
88951           }else{
88952             dataBufferDestroy(p);
88953             dataBufferInit(p, 0);
88954           }
88955         }
88956       }
88957     }
88958   }
88959
88960   /* Union all the doclists together into *out. */
88961   /* TODO(shess) What if *out is big?  Sigh. */
88962   if( rc==SQLITE_OK && nBuffers>0 ){
88963     int iBuffer;
88964     for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){
88965       if( pBuffers[iBuffer].nData>0 ){
88966         if( out->nData==0 ){
88967           dataBufferSwap(out, &(pBuffers[iBuffer]));
88968         }else{
88969           docListAccumulateUnion(out, pBuffers[iBuffer].pData,
88970                                  pBuffers[iBuffer].nData);
88971         }
88972       }
88973     }
88974   }
88975
88976   while( nBuffers-- ){
88977     dataBufferDestroy(&(pBuffers[nBuffers]));
88978   }
88979   if( pBuffers!=NULL ) sqlite3_free(pBuffers);
88980
88981   return rc;
88982 }
88983
88984 /* Call loadSegmentLeavesInt() with pData/nData as input. */
88985 static int loadSegmentLeaf(fulltext_vtab *v, const char *pData, int nData,
88986                            const char *pTerm, int nTerm, int isPrefix,
88987                            DataBuffer *out){
88988   LeavesReader reader;
88989   int rc;
88990
88991   assert( nData>1 );
88992   assert( *pData=='\0' );
88993   rc = leavesReaderInit(v, 0, 0, 0, pData, nData, &reader);
88994   if( rc!=SQLITE_OK ) return rc;
88995
88996   rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out);
88997   leavesReaderReset(&reader);
88998   leavesReaderDestroy(&reader);
88999   return rc;
89000 }
89001
89002 /* Call loadSegmentLeavesInt() with the leaf nodes from iStartLeaf to
89003 ** iEndLeaf (inclusive) as input, and merge the resulting doclist into
89004 ** out.
89005 */
89006 static int loadSegmentLeaves(fulltext_vtab *v,
89007                              sqlite_int64 iStartLeaf, sqlite_int64 iEndLeaf,
89008                              const char *pTerm, int nTerm, int isPrefix,
89009                              DataBuffer *out){
89010   int rc;
89011   LeavesReader reader;
89012
89013   assert( iStartLeaf<=iEndLeaf );
89014   rc = leavesReaderInit(v, 0, iStartLeaf, iEndLeaf, NULL, 0, &reader);
89015   if( rc!=SQLITE_OK ) return rc;
89016
89017   rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out);
89018   leavesReaderReset(&reader);
89019   leavesReaderDestroy(&reader);
89020   return rc;
89021 }
89022
89023 /* Taking pData/nData as an interior node, find the sequence of child
89024 ** nodes which could include pTerm/nTerm/isPrefix.  Note that the
89025 ** interior node terms logically come between the blocks, so there is
89026 ** one more blockid than there are terms (that block contains terms >=
89027 ** the last interior-node term).
89028 */
89029 /* TODO(shess) The calling code may already know that the end child is
89030 ** not worth calculating, because the end may be in a later sibling
89031 ** node.  Consider whether breaking symmetry is worthwhile.  I suspect
89032 ** it is not worthwhile.
89033 */
89034 static void getChildrenContaining(const char *pData, int nData,
89035                                   const char *pTerm, int nTerm, int isPrefix,
89036                                   sqlite_int64 *piStartChild,
89037                                   sqlite_int64 *piEndChild){
89038   InteriorReader reader;
89039
89040   assert( nData>1 );
89041   assert( *pData!='\0' );
89042   interiorReaderInit(pData, nData, &reader);
89043
89044   /* Scan for the first child which could contain pTerm/nTerm. */
89045   while( !interiorReaderAtEnd(&reader) ){
89046     if( interiorReaderTermCmp(&reader, pTerm, nTerm, 0)>0 ) break;
89047     interiorReaderStep(&reader);
89048   }
89049   *piStartChild = interiorReaderCurrentBlockid(&reader);
89050
89051   /* Keep scanning to find a term greater than our term, using prefix
89052   ** comparison if indicated.  If isPrefix is false, this will be the
89053   ** same blockid as the starting block.
89054   */
89055   while( !interiorReaderAtEnd(&reader) ){
89056     if( interiorReaderTermCmp(&reader, pTerm, nTerm, isPrefix)>0 ) break;
89057     interiorReaderStep(&reader);
89058   }
89059   *piEndChild = interiorReaderCurrentBlockid(&reader);
89060
89061   interiorReaderDestroy(&reader);
89062
89063   /* Children must ascend, and if !prefix, both must be the same. */
89064   assert( *piEndChild>=*piStartChild );
89065   assert( isPrefix || *piStartChild==*piEndChild );
89066 }
89067
89068 /* Read block at iBlockid and pass it with other params to
89069 ** getChildrenContaining().
89070 */
89071 static int loadAndGetChildrenContaining(
89072   fulltext_vtab *v,
89073   sqlite_int64 iBlockid,
89074   const char *pTerm, int nTerm, int isPrefix,
89075   sqlite_int64 *piStartChild, sqlite_int64 *piEndChild
89076 ){
89077   sqlite3_stmt *s = NULL;
89078   int rc;
89079
89080   assert( iBlockid!=0 );
89081   assert( pTerm!=NULL );
89082   assert( nTerm!=0 );        /* TODO(shess) Why not allow this? */
89083   assert( piStartChild!=NULL );
89084   assert( piEndChild!=NULL );
89085
89086   rc = sql_get_statement(v, BLOCK_SELECT_STMT, &s);
89087   if( rc!=SQLITE_OK ) return rc;
89088
89089   rc = sqlite3_bind_int64(s, 1, iBlockid);
89090   if( rc!=SQLITE_OK ) return rc;
89091
89092   rc = sqlite3_step(s);
89093   if( rc==SQLITE_DONE ) return SQLITE_ERROR;
89094   if( rc!=SQLITE_ROW ) return rc;
89095
89096   getChildrenContaining(sqlite3_column_blob(s, 0), sqlite3_column_bytes(s, 0),
89097                         pTerm, nTerm, isPrefix, piStartChild, piEndChild);
89098
89099   /* We expect only one row.  We must execute another sqlite3_step()
89100    * to complete the iteration; otherwise the table will remain
89101    * locked. */
89102   rc = sqlite3_step(s);
89103   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
89104   if( rc!=SQLITE_DONE ) return rc;
89105
89106   return SQLITE_OK;
89107 }
89108
89109 /* Traverse the tree represented by pData[nData] looking for
89110 ** pTerm[nTerm], placing its doclist into *out.  This is internal to
89111 ** loadSegment() to make error-handling cleaner.
89112 */
89113 static int loadSegmentInt(fulltext_vtab *v, const char *pData, int nData,
89114                           sqlite_int64 iLeavesEnd,
89115                           const char *pTerm, int nTerm, int isPrefix,
89116                           DataBuffer *out){
89117   /* Special case where root is a leaf. */
89118   if( *pData=='\0' ){
89119     return loadSegmentLeaf(v, pData, nData, pTerm, nTerm, isPrefix, out);
89120   }else{
89121     int rc;
89122     sqlite_int64 iStartChild, iEndChild;
89123
89124     /* Process pData as an interior node, then loop down the tree
89125     ** until we find the set of leaf nodes to scan for the term.
89126     */
89127     getChildrenContaining(pData, nData, pTerm, nTerm, isPrefix,
89128                           &iStartChild, &iEndChild);
89129     while( iStartChild>iLeavesEnd ){
89130       sqlite_int64 iNextStart, iNextEnd;
89131       rc = loadAndGetChildrenContaining(v, iStartChild, pTerm, nTerm, isPrefix,
89132                                         &iNextStart, &iNextEnd);
89133       if( rc!=SQLITE_OK ) return rc;
89134
89135       /* If we've branched, follow the end branch, too. */
89136       if( iStartChild!=iEndChild ){
89137         sqlite_int64 iDummy;
89138         rc = loadAndGetChildrenContaining(v, iEndChild, pTerm, nTerm, isPrefix,
89139                                           &iDummy, &iNextEnd);
89140         if( rc!=SQLITE_OK ) return rc;
89141       }
89142
89143       assert( iNextStart<=iNextEnd );
89144       iStartChild = iNextStart;
89145       iEndChild = iNextEnd;
89146     }
89147     assert( iStartChild<=iLeavesEnd );
89148     assert( iEndChild<=iLeavesEnd );
89149
89150     /* Scan through the leaf segments for doclists. */
89151     return loadSegmentLeaves(v, iStartChild, iEndChild,
89152                              pTerm, nTerm, isPrefix, out);
89153   }
89154 }
89155
89156 /* Call loadSegmentInt() to collect the doclist for pTerm/nTerm, then
89157 ** merge its doclist over *out (any duplicate doclists read from the
89158 ** segment rooted at pData will overwrite those in *out).
89159 */
89160 /* TODO(shess) Consider changing this to determine the depth of the
89161 ** leaves using either the first characters of interior nodes (when
89162 ** ==1, we're one level above the leaves), or the first character of
89163 ** the root (which will describe the height of the tree directly).
89164 ** Either feels somewhat tricky to me.
89165 */
89166 /* TODO(shess) The current merge is likely to be slow for large
89167 ** doclists (though it should process from newest/smallest to
89168 ** oldest/largest, so it may not be that bad).  It might be useful to
89169 ** modify things to allow for N-way merging.  This could either be
89170 ** within a segment, with pairwise merges across segments, or across
89171 ** all segments at once.
89172 */
89173 static int loadSegment(fulltext_vtab *v, const char *pData, int nData,
89174                        sqlite_int64 iLeavesEnd,
89175                        const char *pTerm, int nTerm, int isPrefix,
89176                        DataBuffer *out){
89177   DataBuffer result;
89178   int rc;
89179
89180   assert( nData>1 );
89181
89182   /* This code should never be called with buffered updates. */
89183   assert( v->nPendingData<0 );
89184
89185   dataBufferInit(&result, 0);
89186   rc = loadSegmentInt(v, pData, nData, iLeavesEnd,
89187                       pTerm, nTerm, isPrefix, &result);
89188   if( rc==SQLITE_OK && result.nData>0 ){
89189     if( out->nData==0 ){
89190       DataBuffer tmp = *out;
89191       *out = result;
89192       result = tmp;
89193     }else{
89194       DataBuffer merged;
89195       DLReader readers[2];
89196
89197       dlrInit(&readers[0], DL_DEFAULT, out->pData, out->nData);
89198       dlrInit(&readers[1], DL_DEFAULT, result.pData, result.nData);
89199       dataBufferInit(&merged, out->nData+result.nData);
89200       docListMerge(&merged, readers, 2);
89201       dataBufferDestroy(out);
89202       *out = merged;
89203       dlrDestroy(&readers[0]);
89204       dlrDestroy(&readers[1]);
89205     }
89206   }
89207   dataBufferDestroy(&result);
89208   return rc;
89209 }
89210
89211 /* Scan the database and merge together the posting lists for the term
89212 ** into *out.
89213 */
89214 static int termSelect(fulltext_vtab *v, int iColumn,
89215                       const char *pTerm, int nTerm, int isPrefix,
89216                       DocListType iType, DataBuffer *out){
89217   DataBuffer doclist;
89218   sqlite3_stmt *s;
89219   int rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
89220   if( rc!=SQLITE_OK ) return rc;
89221
89222   /* This code should never be called with buffered updates. */
89223   assert( v->nPendingData<0 );
89224
89225   dataBufferInit(&doclist, 0);
89226
89227   /* Traverse the segments from oldest to newest so that newer doclist
89228   ** elements for given docids overwrite older elements.
89229   */
89230   while( (rc = sqlite3_step(s))==SQLITE_ROW ){
89231     const char *pData = sqlite3_column_blob(s, 2);
89232     const int nData = sqlite3_column_bytes(s, 2);
89233     const sqlite_int64 iLeavesEnd = sqlite3_column_int64(s, 1);
89234     rc = loadSegment(v, pData, nData, iLeavesEnd, pTerm, nTerm, isPrefix,
89235                      &doclist);
89236     if( rc!=SQLITE_OK ) goto err;
89237   }
89238   if( rc==SQLITE_DONE ){
89239     if( doclist.nData!=0 ){
89240       /* TODO(shess) The old term_select_all() code applied the column
89241       ** restrict as we merged segments, leading to smaller buffers.
89242       ** This is probably worthwhile to bring back, once the new storage
89243       ** system is checked in.
89244       */
89245       if( iColumn==v->nColumn) iColumn = -1;
89246       docListTrim(DL_DEFAULT, doclist.pData, doclist.nData,
89247                   iColumn, iType, out);
89248     }
89249     rc = SQLITE_OK;
89250   }
89251
89252  err:
89253   dataBufferDestroy(&doclist);
89254   return rc;
89255 }
89256
89257 /****************************************************************/
89258 /* Used to hold hashtable data for sorting. */
89259 typedef struct TermData {
89260   const char *pTerm;
89261   int nTerm;
89262   DLCollector *pCollector;
89263 } TermData;
89264
89265 /* Orders TermData elements in strcmp fashion ( <0 for less-than, 0
89266 ** for equal, >0 for greater-than).
89267 */
89268 static int termDataCmp(const void *av, const void *bv){
89269   const TermData *a = (const TermData *)av;
89270   const TermData *b = (const TermData *)bv;
89271   int n = a->nTerm<b->nTerm ? a->nTerm : b->nTerm;
89272   int c = memcmp(a->pTerm, b->pTerm, n);
89273   if( c!=0 ) return c;
89274   return a->nTerm-b->nTerm;
89275 }
89276
89277 /* Order pTerms data by term, then write a new level 0 segment using
89278 ** LeafWriter.
89279 */
89280 static int writeZeroSegment(fulltext_vtab *v, fts3Hash *pTerms){
89281   fts3HashElem *e;
89282   int idx, rc, i, n;
89283   TermData *pData;
89284   LeafWriter writer;
89285   DataBuffer dl;
89286
89287   /* Determine the next index at level 0, merging as necessary. */
89288   rc = segdirNextIndex(v, 0, &idx);
89289   if( rc!=SQLITE_OK ) return rc;
89290
89291   n = fts3HashCount(pTerms);
89292   pData = sqlite3_malloc(n*sizeof(TermData));
89293
89294   for(i = 0, e = fts3HashFirst(pTerms); e; i++, e = fts3HashNext(e)){
89295     assert( i<n );
89296     pData[i].pTerm = fts3HashKey(e);
89297     pData[i].nTerm = fts3HashKeysize(e);
89298     pData[i].pCollector = fts3HashData(e);
89299   }
89300   assert( i==n );
89301
89302   /* TODO(shess) Should we allow user-defined collation sequences,
89303   ** here?  I think we only need that once we support prefix searches.
89304   */
89305   if( n>1 ) qsort(pData, n, sizeof(*pData), termDataCmp);
89306
89307   /* TODO(shess) Refactor so that we can write directly to the segment
89308   ** DataBuffer, as happens for segment merges.
89309   */
89310   leafWriterInit(0, idx, &writer);
89311   dataBufferInit(&dl, 0);
89312   for(i=0; i<n; i++){
89313     dataBufferReset(&dl);
89314     dlcAddDoclist(pData[i].pCollector, &dl);
89315     rc = leafWriterStep(v, &writer,
89316                         pData[i].pTerm, pData[i].nTerm, dl.pData, dl.nData);
89317     if( rc!=SQLITE_OK ) goto err;
89318   }
89319   rc = leafWriterFinalize(v, &writer);
89320
89321  err:
89322   dataBufferDestroy(&dl);
89323   sqlite3_free(pData);
89324   leafWriterDestroy(&writer);
89325   return rc;
89326 }
89327
89328 /* If pendingTerms has data, free it. */
89329 static int clearPendingTerms(fulltext_vtab *v){
89330   if( v->nPendingData>=0 ){
89331     fts3HashElem *e;
89332     for(e=fts3HashFirst(&v->pendingTerms); e; e=fts3HashNext(e)){
89333       dlcDelete(fts3HashData(e));
89334     }
89335     fts3HashClear(&v->pendingTerms);
89336     v->nPendingData = -1;
89337   }
89338   return SQLITE_OK;
89339 }
89340
89341 /* If pendingTerms has data, flush it to a level-zero segment, and
89342 ** free it.
89343 */
89344 static int flushPendingTerms(fulltext_vtab *v){
89345   if( v->nPendingData>=0 ){
89346     int rc = writeZeroSegment(v, &v->pendingTerms);
89347     if( rc==SQLITE_OK ) clearPendingTerms(v);
89348     return rc;
89349   }
89350   return SQLITE_OK;
89351 }
89352
89353 /* If pendingTerms is "too big", or docid is out of order, flush it.
89354 ** Regardless, be certain that pendingTerms is initialized for use.
89355 */
89356 static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid){
89357   /* TODO(shess) Explore whether partially flushing the buffer on
89358   ** forced-flush would provide better performance.  I suspect that if
89359   ** we ordered the doclists by size and flushed the largest until the
89360   ** buffer was half empty, that would let the less frequent terms
89361   ** generate longer doclists.
89362   */
89363   if( iDocid<=v->iPrevDocid || v->nPendingData>kPendingThreshold ){
89364     int rc = flushPendingTerms(v);
89365     if( rc!=SQLITE_OK ) return rc;
89366   }
89367   if( v->nPendingData<0 ){
89368     fts3HashInit(&v->pendingTerms, FTS3_HASH_STRING, 1);
89369     v->nPendingData = 0;
89370   }
89371   v->iPrevDocid = iDocid;
89372   return SQLITE_OK;
89373 }
89374
89375 /* This function implements the xUpdate callback; it is the top-level entry
89376  * point for inserting, deleting or updating a row in a full-text table. */
89377 static int fulltextUpdate(sqlite3_vtab *pVtab, int nArg, sqlite3_value **ppArg,
89378                           sqlite_int64 *pRowid){
89379   fulltext_vtab *v = (fulltext_vtab *) pVtab;
89380   int rc;
89381
89382   FTSTRACE(("FTS3 Update %p\n", pVtab));
89383
89384   if( nArg<2 ){
89385     rc = index_delete(v, sqlite3_value_int64(ppArg[0]));
89386     if( rc==SQLITE_OK ){
89387       /* If we just deleted the last row in the table, clear out the
89388       ** index data.
89389       */
89390       rc = content_exists(v);
89391       if( rc==SQLITE_ROW ){
89392         rc = SQLITE_OK;
89393       }else if( rc==SQLITE_DONE ){
89394         /* Clear the pending terms so we don't flush a useless level-0
89395         ** segment when the transaction closes.
89396         */
89397         rc = clearPendingTerms(v);
89398         if( rc==SQLITE_OK ){
89399           rc = segdir_delete_all(v);
89400         }
89401       }
89402     }
89403   } else if( sqlite3_value_type(ppArg[0]) != SQLITE_NULL ){
89404     /* An update:
89405      * ppArg[0] = old rowid
89406      * ppArg[1] = new rowid
89407      * ppArg[2..2+v->nColumn-1] = values
89408      * ppArg[2+v->nColumn] = value for magic column (we ignore this)
89409      * ppArg[2+v->nColumn+1] = value for docid
89410      */
89411     sqlite_int64 rowid = sqlite3_value_int64(ppArg[0]);
89412     if( sqlite3_value_type(ppArg[1]) != SQLITE_INTEGER ||
89413         sqlite3_value_int64(ppArg[1]) != rowid ){
89414       rc = SQLITE_ERROR;  /* we don't allow changing the rowid */
89415     }else if( sqlite3_value_type(ppArg[2+v->nColumn+1]) != SQLITE_INTEGER ||
89416               sqlite3_value_int64(ppArg[2+v->nColumn+1]) != rowid ){
89417       rc = SQLITE_ERROR;  /* we don't allow changing the docid */
89418     }else{
89419       assert( nArg==2+v->nColumn+2);
89420       rc = index_update(v, rowid, &ppArg[2]);
89421     }
89422   } else {
89423     /* An insert:
89424      * ppArg[1] = requested rowid
89425      * ppArg[2..2+v->nColumn-1] = values
89426      * ppArg[2+v->nColumn] = value for magic column (we ignore this)
89427      * ppArg[2+v->nColumn+1] = value for docid
89428      */
89429     sqlite3_value *pRequestDocid = ppArg[2+v->nColumn+1];
89430     assert( nArg==2+v->nColumn+2);
89431     if( SQLITE_NULL != sqlite3_value_type(pRequestDocid) &&
89432         SQLITE_NULL != sqlite3_value_type(ppArg[1]) ){
89433       /* TODO(shess) Consider allowing this to work if the values are
89434       ** identical.  I'm inclined to discourage that usage, though,
89435       ** given that both rowid and docid are special columns.  Better
89436       ** would be to define one or the other as the default winner,
89437       ** but should it be fts3-centric (docid) or SQLite-centric
89438       ** (rowid)?
89439       */
89440       rc = SQLITE_ERROR;
89441     }else{
89442       if( SQLITE_NULL == sqlite3_value_type(pRequestDocid) ){
89443         pRequestDocid = ppArg[1];
89444       }
89445       rc = index_insert(v, pRequestDocid, &ppArg[2], pRowid);
89446     }
89447   }
89448
89449   return rc;
89450 }
89451
89452 static int fulltextSync(sqlite3_vtab *pVtab){
89453   FTSTRACE(("FTS3 xSync()\n"));
89454   return flushPendingTerms((fulltext_vtab *)pVtab);
89455 }
89456
89457 static int fulltextBegin(sqlite3_vtab *pVtab){
89458   fulltext_vtab *v = (fulltext_vtab *) pVtab;
89459   FTSTRACE(("FTS3 xBegin()\n"));
89460
89461   /* Any buffered updates should have been cleared by the previous
89462   ** transaction.
89463   */
89464   assert( v->nPendingData<0 );
89465   return clearPendingTerms(v);
89466 }
89467
89468 static int fulltextCommit(sqlite3_vtab *pVtab){
89469   fulltext_vtab *v = (fulltext_vtab *) pVtab;
89470   FTSTRACE(("FTS3 xCommit()\n"));
89471
89472   /* Buffered updates should have been cleared by fulltextSync(). */
89473   assert( v->nPendingData<0 );
89474   return clearPendingTerms(v);
89475 }
89476
89477 static int fulltextRollback(sqlite3_vtab *pVtab){
89478   FTSTRACE(("FTS3 xRollback()\n"));
89479   return clearPendingTerms((fulltext_vtab *)pVtab);
89480 }
89481
89482 /*
89483 ** Implementation of the snippet() function for FTS3
89484 */
89485 static void snippetFunc(
89486   sqlite3_context *pContext,
89487   int argc,
89488   sqlite3_value **argv
89489 ){
89490   fulltext_cursor *pCursor;
89491   if( argc<1 ) return;
89492   if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
89493       sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
89494     sqlite3_result_error(pContext, "illegal first argument to html_snippet",-1);
89495   }else{
89496     const char *zStart = "<b>";
89497     const char *zEnd = "</b>";
89498     const char *zEllipsis = "<b>...</b>";
89499     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
89500     if( argc>=2 ){
89501       zStart = (const char*)sqlite3_value_text(argv[1]);
89502       if( argc>=3 ){
89503         zEnd = (const char*)sqlite3_value_text(argv[2]);
89504         if( argc>=4 ){
89505           zEllipsis = (const char*)sqlite3_value_text(argv[3]);
89506         }
89507       }
89508     }
89509     snippetAllOffsets(pCursor);
89510     snippetText(pCursor, zStart, zEnd, zEllipsis);
89511     sqlite3_result_text(pContext, pCursor->snippet.zSnippet,
89512                         pCursor->snippet.nSnippet, SQLITE_STATIC);
89513   }
89514 }
89515
89516 /*
89517 ** Implementation of the offsets() function for FTS3
89518 */
89519 static void snippetOffsetsFunc(
89520   sqlite3_context *pContext,
89521   int argc,
89522   sqlite3_value **argv
89523 ){
89524   fulltext_cursor *pCursor;
89525   if( argc<1 ) return;
89526   if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
89527       sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
89528     sqlite3_result_error(pContext, "illegal first argument to offsets",-1);
89529   }else{
89530     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
89531     snippetAllOffsets(pCursor);
89532     snippetOffsetText(&pCursor->snippet);
89533     sqlite3_result_text(pContext,
89534                         pCursor->snippet.zOffset, pCursor->snippet.nOffset,
89535                         SQLITE_STATIC);
89536   }
89537 }
89538
89539 /* OptLeavesReader is nearly identical to LeavesReader, except that
89540 ** where LeavesReader is geared towards the merging of complete
89541 ** segment levels (with exactly MERGE_COUNT segments), OptLeavesReader
89542 ** is geared towards implementation of the optimize() function, and
89543 ** can merge all segments simultaneously.  This version may be
89544 ** somewhat less efficient than LeavesReader because it merges into an
89545 ** accumulator rather than doing an N-way merge, but since segment
89546 ** size grows exponentially (so segment count logrithmically) this is
89547 ** probably not an immediate problem.
89548 */
89549 /* TODO(shess): Prove that assertion, or extend the merge code to
89550 ** merge tree fashion (like the prefix-searching code does).
89551 */
89552 /* TODO(shess): OptLeavesReader and LeavesReader could probably be
89553 ** merged with little or no loss of performance for LeavesReader.  The
89554 ** merged code would need to handle >MERGE_COUNT segments, and would
89555 ** also need to be able to optionally optimize away deletes.
89556 */
89557 typedef struct OptLeavesReader {
89558   /* Segment number, to order readers by age. */
89559   int segment;
89560   LeavesReader reader;
89561 } OptLeavesReader;
89562
89563 static int optLeavesReaderAtEnd(OptLeavesReader *pReader){
89564   return leavesReaderAtEnd(&pReader->reader);
89565 }
89566 static int optLeavesReaderTermBytes(OptLeavesReader *pReader){
89567   return leavesReaderTermBytes(&pReader->reader);
89568 }
89569 static const char *optLeavesReaderData(OptLeavesReader *pReader){
89570   return leavesReaderData(&pReader->reader);
89571 }
89572 static int optLeavesReaderDataBytes(OptLeavesReader *pReader){
89573   return leavesReaderDataBytes(&pReader->reader);
89574 }
89575 static const char *optLeavesReaderTerm(OptLeavesReader *pReader){
89576   return leavesReaderTerm(&pReader->reader);
89577 }
89578 static int optLeavesReaderStep(fulltext_vtab *v, OptLeavesReader *pReader){
89579   return leavesReaderStep(v, &pReader->reader);
89580 }
89581 static int optLeavesReaderTermCmp(OptLeavesReader *lr1, OptLeavesReader *lr2){
89582   return leavesReaderTermCmp(&lr1->reader, &lr2->reader);
89583 }
89584 /* Order by term ascending, segment ascending (oldest to newest), with
89585 ** exhausted readers to the end.
89586 */
89587 static int optLeavesReaderCmp(OptLeavesReader *lr1, OptLeavesReader *lr2){
89588   int c = optLeavesReaderTermCmp(lr1, lr2);
89589   if( c!=0 ) return c;
89590   return lr1->segment-lr2->segment;
89591 }
89592 /* Bubble pLr[0] to appropriate place in pLr[1..nLr-1].  Assumes that
89593 ** pLr[1..nLr-1] is already sorted.
89594 */
89595 static void optLeavesReaderReorder(OptLeavesReader *pLr, int nLr){
89596   while( nLr>1 && optLeavesReaderCmp(pLr, pLr+1)>0 ){
89597     OptLeavesReader tmp = pLr[0];
89598     pLr[0] = pLr[1];
89599     pLr[1] = tmp;
89600     nLr--;
89601     pLr++;
89602   }
89603 }
89604
89605 /* optimize() helper function.  Put the readers in order and iterate
89606 ** through them, merging doclists for matching terms into pWriter.
89607 ** Returns SQLITE_OK on success, or the SQLite error code which
89608 ** prevented success.
89609 */
89610 static int optimizeInternal(fulltext_vtab *v,
89611                             OptLeavesReader *readers, int nReaders,
89612                             LeafWriter *pWriter){
89613   int i, rc = SQLITE_OK;
89614   DataBuffer doclist, merged, tmp;
89615
89616   /* Order the readers. */
89617   i = nReaders;
89618   while( i-- > 0 ){
89619     optLeavesReaderReorder(&readers[i], nReaders-i);
89620   }
89621
89622   dataBufferInit(&doclist, LEAF_MAX);
89623   dataBufferInit(&merged, LEAF_MAX);
89624
89625   /* Exhausted readers bubble to the end, so when the first reader is
89626   ** at eof, all are at eof.
89627   */
89628   while( !optLeavesReaderAtEnd(&readers[0]) ){
89629
89630     /* Figure out how many readers share the next term. */
89631     for(i=1; i<nReaders && !optLeavesReaderAtEnd(&readers[i]); i++){
89632       if( 0!=optLeavesReaderTermCmp(&readers[0], &readers[i]) ) break;
89633     }
89634
89635     /* Special-case for no merge. */
89636     if( i==1 ){
89637       /* Trim deletions from the doclist. */
89638       dataBufferReset(&merged);
89639       docListTrim(DL_DEFAULT,
89640                   optLeavesReaderData(&readers[0]),
89641                   optLeavesReaderDataBytes(&readers[0]),
89642                   -1, DL_DEFAULT, &merged);
89643     }else{
89644       DLReader dlReaders[MERGE_COUNT];
89645       int iReader, nReaders;
89646
89647       /* Prime the pipeline with the first reader's doclist.  After
89648       ** one pass index 0 will reference the accumulated doclist.
89649       */
89650       dlrInit(&dlReaders[0], DL_DEFAULT,
89651               optLeavesReaderData(&readers[0]),
89652               optLeavesReaderDataBytes(&readers[0]));
89653       iReader = 1;
89654
89655       assert( iReader<i );  /* Must execute the loop at least once. */
89656       while( iReader<i ){
89657         /* Merge 16 inputs per pass. */
89658         for( nReaders=1; iReader<i && nReaders<MERGE_COUNT;
89659              iReader++, nReaders++ ){
89660           dlrInit(&dlReaders[nReaders], DL_DEFAULT,
89661                   optLeavesReaderData(&readers[iReader]),
89662                   optLeavesReaderDataBytes(&readers[iReader]));
89663         }
89664
89665         /* Merge doclists and swap result into accumulator. */
89666         dataBufferReset(&merged);
89667         docListMerge(&merged, dlReaders, nReaders);
89668         tmp = merged;
89669         merged = doclist;
89670         doclist = tmp;
89671
89672         while( nReaders-- > 0 ){
89673           dlrDestroy(&dlReaders[nReaders]);
89674         }
89675
89676         /* Accumulated doclist to reader 0 for next pass. */
89677         dlrInit(&dlReaders[0], DL_DEFAULT, doclist.pData, doclist.nData);
89678       }
89679
89680       /* Destroy reader that was left in the pipeline. */
89681       dlrDestroy(&dlReaders[0]);
89682
89683       /* Trim deletions from the doclist. */
89684       dataBufferReset(&merged);
89685       docListTrim(DL_DEFAULT, doclist.pData, doclist.nData,
89686                   -1, DL_DEFAULT, &merged);
89687     }
89688
89689     /* Only pass doclists with hits (skip if all hits deleted). */
89690     if( merged.nData>0 ){
89691       rc = leafWriterStep(v, pWriter,
89692                           optLeavesReaderTerm(&readers[0]),
89693                           optLeavesReaderTermBytes(&readers[0]),
89694                           merged.pData, merged.nData);
89695       if( rc!=SQLITE_OK ) goto err;
89696     }
89697
89698     /* Step merged readers to next term and reorder. */
89699     while( i-- > 0 ){
89700       rc = optLeavesReaderStep(v, &readers[i]);
89701       if( rc!=SQLITE_OK ) goto err;
89702
89703       optLeavesReaderReorder(&readers[i], nReaders-i);
89704     }
89705   }
89706
89707  err:
89708   dataBufferDestroy(&doclist);
89709   dataBufferDestroy(&merged);
89710   return rc;
89711 }
89712
89713 /* Implement optimize() function for FTS3.  optimize(t) merges all
89714 ** segments in the fts index into a single segment.  't' is the magic
89715 ** table-named column.
89716 */
89717 static void optimizeFunc(sqlite3_context *pContext,
89718                          int argc, sqlite3_value **argv){
89719   fulltext_cursor *pCursor;
89720   if( argc>1 ){
89721     sqlite3_result_error(pContext, "excess arguments to optimize()",-1);
89722   }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
89723             sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
89724     sqlite3_result_error(pContext, "illegal first argument to optimize",-1);
89725   }else{
89726     fulltext_vtab *v;
89727     int i, rc, iMaxLevel;
89728     OptLeavesReader *readers;
89729     int nReaders;
89730     LeafWriter writer;
89731     sqlite3_stmt *s;
89732
89733     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
89734     v = cursor_vtab(pCursor);
89735
89736     /* Flush any buffered updates before optimizing. */
89737     rc = flushPendingTerms(v);
89738     if( rc!=SQLITE_OK ) goto err;
89739
89740     rc = segdir_count(v, &nReaders, &iMaxLevel);
89741     if( rc!=SQLITE_OK ) goto err;
89742     if( nReaders==0 || nReaders==1 ){
89743       sqlite3_result_text(pContext, "Index already optimal", -1,
89744                           SQLITE_STATIC);
89745       return;
89746     }
89747
89748     rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
89749     if( rc!=SQLITE_OK ) goto err;
89750
89751     readers = sqlite3_malloc(nReaders*sizeof(readers[0]));
89752     if( readers==NULL ) goto err;
89753
89754     /* Note that there will already be a segment at this position
89755     ** until we call segdir_delete() on iMaxLevel.
89756     */
89757     leafWriterInit(iMaxLevel, 0, &writer);
89758
89759     i = 0;
89760     while( (rc = sqlite3_step(s))==SQLITE_ROW ){
89761       sqlite_int64 iStart = sqlite3_column_int64(s, 0);
89762       sqlite_int64 iEnd = sqlite3_column_int64(s, 1);
89763       const char *pRootData = sqlite3_column_blob(s, 2);
89764       int nRootData = sqlite3_column_bytes(s, 2);
89765
89766       assert( i<nReaders );
89767       rc = leavesReaderInit(v, -1, iStart, iEnd, pRootData, nRootData,
89768                             &readers[i].reader);
89769       if( rc!=SQLITE_OK ) break;
89770
89771       readers[i].segment = i;
89772       i++;
89773     }
89774
89775     /* If we managed to succesfully read them all, optimize them. */
89776     if( rc==SQLITE_DONE ){
89777       assert( i==nReaders );
89778       rc = optimizeInternal(v, readers, nReaders, &writer);
89779     }
89780
89781     while( i-- > 0 ){
89782       leavesReaderDestroy(&readers[i].reader);
89783     }
89784     sqlite3_free(readers);
89785
89786     /* If we've successfully gotten to here, delete the old segments
89787     ** and flush the interior structure of the new segment.
89788     */
89789     if( rc==SQLITE_OK ){
89790       for( i=0; i<=iMaxLevel; i++ ){
89791         rc = segdir_delete(v, i);
89792         if( rc!=SQLITE_OK ) break;
89793       }
89794
89795       if( rc==SQLITE_OK ) rc = leafWriterFinalize(v, &writer);
89796     }
89797
89798     leafWriterDestroy(&writer);
89799
89800     if( rc!=SQLITE_OK ) goto err;
89801
89802     sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
89803     return;
89804
89805     /* TODO(shess): Error-handling needs to be improved along the
89806     ** lines of the dump_ functions.
89807     */
89808  err:
89809     {
89810       char buf[512];
89811       sqlite3_snprintf(sizeof(buf), buf, "Error in optimize: %s",
89812                        sqlite3_errmsg(sqlite3_context_db_handle(pContext)));
89813       sqlite3_result_error(pContext, buf, -1);
89814     }
89815   }
89816 }
89817
89818 #ifdef SQLITE_TEST
89819 /* Generate an error of the form "<prefix>: <msg>".  If msg is NULL,
89820 ** pull the error from the context's db handle.
89821 */
89822 static void generateError(sqlite3_context *pContext,
89823                           const char *prefix, const char *msg){
89824   char buf[512];
89825   if( msg==NULL ) msg = sqlite3_errmsg(sqlite3_context_db_handle(pContext));
89826   sqlite3_snprintf(sizeof(buf), buf, "%s: %s", prefix, msg);
89827   sqlite3_result_error(pContext, buf, -1);
89828 }
89829
89830 /* Helper function to collect the set of terms in the segment into
89831 ** pTerms.  The segment is defined by the leaf nodes between
89832 ** iStartBlockid and iEndBlockid, inclusive, or by the contents of
89833 ** pRootData if iStartBlockid is 0 (in which case the entire segment
89834 ** fit in a leaf).
89835 */
89836 static int collectSegmentTerms(fulltext_vtab *v, sqlite3_stmt *s,
89837                                fts3Hash *pTerms){
89838   const sqlite_int64 iStartBlockid = sqlite3_column_int64(s, 0);
89839   const sqlite_int64 iEndBlockid = sqlite3_column_int64(s, 1);
89840   const char *pRootData = sqlite3_column_blob(s, 2);
89841   const int nRootData = sqlite3_column_bytes(s, 2);
89842   LeavesReader reader;
89843   int rc = leavesReaderInit(v, 0, iStartBlockid, iEndBlockid,
89844                             pRootData, nRootData, &reader);
89845   if( rc!=SQLITE_OK ) return rc;
89846
89847   while( rc==SQLITE_OK && !leavesReaderAtEnd(&reader) ){
89848     const char *pTerm = leavesReaderTerm(&reader);
89849     const int nTerm = leavesReaderTermBytes(&reader);
89850     void *oldValue = sqlite3Fts3HashFind(pTerms, pTerm, nTerm);
89851     void *newValue = (void *)((char *)oldValue+1);
89852
89853     /* From the comment before sqlite3Fts3HashInsert in fts3_hash.c,
89854     ** the data value passed is returned in case of malloc failure.
89855     */
89856     if( newValue==sqlite3Fts3HashInsert(pTerms, pTerm, nTerm, newValue) ){
89857       rc = SQLITE_NOMEM;
89858     }else{
89859       rc = leavesReaderStep(v, &reader);
89860     }
89861   }
89862
89863   leavesReaderDestroy(&reader);
89864   return rc;
89865 }
89866
89867 /* Helper function to build the result string for dump_terms(). */
89868 static int generateTermsResult(sqlite3_context *pContext, fts3Hash *pTerms){
89869   int iTerm, nTerms, nResultBytes, iByte;
89870   char *result;
89871   TermData *pData;
89872   fts3HashElem *e;
89873
89874   /* Iterate pTerms to generate an array of terms in pData for
89875   ** sorting.
89876   */
89877   nTerms = fts3HashCount(pTerms);
89878   assert( nTerms>0 );
89879   pData = sqlite3_malloc(nTerms*sizeof(TermData));
89880   if( pData==NULL ) return SQLITE_NOMEM;
89881
89882   nResultBytes = 0;
89883   for(iTerm = 0, e = fts3HashFirst(pTerms); e; iTerm++, e = fts3HashNext(e)){
89884     nResultBytes += fts3HashKeysize(e)+1;   /* Term plus trailing space */
89885     assert( iTerm<nTerms );
89886     pData[iTerm].pTerm = fts3HashKey(e);
89887     pData[iTerm].nTerm = fts3HashKeysize(e);
89888     pData[iTerm].pCollector = fts3HashData(e);  /* unused */
89889   }
89890   assert( iTerm==nTerms );
89891
89892   assert( nResultBytes>0 );   /* nTerms>0, nResultsBytes must be, too. */
89893   result = sqlite3_malloc(nResultBytes);
89894   if( result==NULL ){
89895     sqlite3_free(pData);
89896     return SQLITE_NOMEM;
89897   }
89898
89899   if( nTerms>1 ) qsort(pData, nTerms, sizeof(*pData), termDataCmp);
89900
89901   /* Read the terms in order to build the result. */
89902   iByte = 0;
89903   for(iTerm=0; iTerm<nTerms; ++iTerm){
89904     memcpy(result+iByte, pData[iTerm].pTerm, pData[iTerm].nTerm);
89905     iByte += pData[iTerm].nTerm;
89906     result[iByte++] = ' ';
89907   }
89908   assert( iByte==nResultBytes );
89909   assert( result[nResultBytes-1]==' ' );
89910   result[nResultBytes-1] = '\0';
89911
89912   /* Passes away ownership of result. */
89913   sqlite3_result_text(pContext, result, nResultBytes-1, sqlite3_free);
89914   sqlite3_free(pData);
89915   return SQLITE_OK;
89916 }
89917
89918 /* Implements dump_terms() for use in inspecting the fts3 index from
89919 ** tests.  TEXT result containing the ordered list of terms joined by
89920 ** spaces.  dump_terms(t, level, idx) dumps the terms for the segment
89921 ** specified by level, idx (in %_segdir), while dump_terms(t) dumps
89922 ** all terms in the index.  In both cases t is the fts table's magic
89923 ** table-named column.
89924 */
89925 static void dumpTermsFunc(
89926   sqlite3_context *pContext,
89927   int argc, sqlite3_value **argv
89928 ){
89929   fulltext_cursor *pCursor;
89930   if( argc!=3 && argc!=1 ){
89931     generateError(pContext, "dump_terms", "incorrect arguments");
89932   }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
89933             sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
89934     generateError(pContext, "dump_terms", "illegal first argument");
89935   }else{
89936     fulltext_vtab *v;
89937     fts3Hash terms;
89938     sqlite3_stmt *s = NULL;
89939     int rc;
89940
89941     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
89942     v = cursor_vtab(pCursor);
89943
89944     /* If passed only the cursor column, get all segments.  Otherwise
89945     ** get the segment described by the following two arguments.
89946     */
89947     if( argc==1 ){
89948       rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
89949     }else{
89950       rc = sql_get_statement(v, SEGDIR_SELECT_SEGMENT_STMT, &s);
89951       if( rc==SQLITE_OK ){
89952         rc = sqlite3_bind_int(s, 1, sqlite3_value_int(argv[1]));
89953         if( rc==SQLITE_OK ){
89954           rc = sqlite3_bind_int(s, 2, sqlite3_value_int(argv[2]));
89955         }
89956       }
89957     }
89958
89959     if( rc!=SQLITE_OK ){
89960       generateError(pContext, "dump_terms", NULL);
89961       return;
89962     }
89963
89964     /* Collect the terms for each segment. */
89965     sqlite3Fts3HashInit(&terms, FTS3_HASH_STRING, 1);
89966     while( (rc = sqlite3_step(s))==SQLITE_ROW ){
89967       rc = collectSegmentTerms(v, s, &terms);
89968       if( rc!=SQLITE_OK ) break;
89969     }
89970
89971     if( rc!=SQLITE_DONE ){
89972       sqlite3_reset(s);
89973       generateError(pContext, "dump_terms", NULL);
89974     }else{
89975       const int nTerms = fts3HashCount(&terms);
89976       if( nTerms>0 ){
89977         rc = generateTermsResult(pContext, &terms);
89978         if( rc==SQLITE_NOMEM ){
89979           generateError(pContext, "dump_terms", "out of memory");
89980         }else{
89981           assert( rc==SQLITE_OK );
89982         }
89983       }else if( argc==3 ){
89984         /* The specific segment asked for could not be found. */
89985         generateError(pContext, "dump_terms", "segment not found");
89986       }else{
89987         /* No segments found. */
89988         /* TODO(shess): It should be impossible to reach this.  This
89989         ** case can only happen for an empty table, in which case
89990         ** SQLite has no rows to call this function on.
89991         */
89992         sqlite3_result_null(pContext);
89993       }
89994     }
89995     sqlite3Fts3HashClear(&terms);
89996   }
89997 }
89998
89999 /* Expand the DL_DEFAULT doclist in pData into a text result in
90000 ** pContext.
90001 */
90002 static void createDoclistResult(sqlite3_context *pContext,
90003                                 const char *pData, int nData){
90004   DataBuffer dump;
90005   DLReader dlReader;
90006
90007   assert( pData!=NULL && nData>0 );
90008
90009   dataBufferInit(&dump, 0);
90010   dlrInit(&dlReader, DL_DEFAULT, pData, nData);
90011   for( ; !dlrAtEnd(&dlReader); dlrStep(&dlReader) ){
90012     char buf[256];
90013     PLReader plReader;
90014
90015     plrInit(&plReader, &dlReader);
90016     if( DL_DEFAULT==DL_DOCIDS || plrAtEnd(&plReader) ){
90017       sqlite3_snprintf(sizeof(buf), buf, "[%lld] ", dlrDocid(&dlReader));
90018       dataBufferAppend(&dump, buf, strlen(buf));
90019     }else{
90020       int iColumn = plrColumn(&plReader);
90021
90022       sqlite3_snprintf(sizeof(buf), buf, "[%lld %d[",
90023                        dlrDocid(&dlReader), iColumn);
90024       dataBufferAppend(&dump, buf, strlen(buf));
90025
90026       for( ; !plrAtEnd(&plReader); plrStep(&plReader) ){
90027         if( plrColumn(&plReader)!=iColumn ){
90028           iColumn = plrColumn(&plReader);
90029           sqlite3_snprintf(sizeof(buf), buf, "] %d[", iColumn);
90030           assert( dump.nData>0 );
90031           dump.nData--;                     /* Overwrite trailing space. */
90032           assert( dump.pData[dump.nData]==' ');
90033           dataBufferAppend(&dump, buf, strlen(buf));
90034         }
90035         if( DL_DEFAULT==DL_POSITIONS_OFFSETS ){
90036           sqlite3_snprintf(sizeof(buf), buf, "%d,%d,%d ",
90037                            plrPosition(&plReader),
90038                            plrStartOffset(&plReader), plrEndOffset(&plReader));
90039         }else if( DL_DEFAULT==DL_POSITIONS ){
90040           sqlite3_snprintf(sizeof(buf), buf, "%d ", plrPosition(&plReader));
90041         }else{
90042           assert( NULL=="Unhandled DL_DEFAULT value");
90043         }
90044         dataBufferAppend(&dump, buf, strlen(buf));
90045       }
90046       plrDestroy(&plReader);
90047
90048       assert( dump.nData>0 );
90049       dump.nData--;                     /* Overwrite trailing space. */
90050       assert( dump.pData[dump.nData]==' ');
90051       dataBufferAppend(&dump, "]] ", 3);
90052     }
90053   }
90054   dlrDestroy(&dlReader);
90055
90056   assert( dump.nData>0 );
90057   dump.nData--;                     /* Overwrite trailing space. */
90058   assert( dump.pData[dump.nData]==' ');
90059   dump.pData[dump.nData] = '\0';
90060   assert( dump.nData>0 );
90061
90062   /* Passes ownership of dump's buffer to pContext. */
90063   sqlite3_result_text(pContext, dump.pData, dump.nData, sqlite3_free);
90064   dump.pData = NULL;
90065   dump.nData = dump.nCapacity = 0;
90066 }
90067
90068 /* Implements dump_doclist() for use in inspecting the fts3 index from
90069 ** tests.  TEXT result containing a string representation of the
90070 ** doclist for the indicated term.  dump_doclist(t, term, level, idx)
90071 ** dumps the doclist for term from the segment specified by level, idx
90072 ** (in %_segdir), while dump_doclist(t, term) dumps the logical
90073 ** doclist for the term across all segments.  The per-segment doclist
90074 ** can contain deletions, while the full-index doclist will not
90075 ** (deletions are omitted).
90076 **
90077 ** Result formats differ with the setting of DL_DEFAULTS.  Examples:
90078 **
90079 ** DL_DOCIDS: [1] [3] [7]
90080 ** DL_POSITIONS: [1 0[0 4] 1[17]] [3 1[5]]
90081 ** DL_POSITIONS_OFFSETS: [1 0[0,0,3 4,23,26] 1[17,102,105]] [3 1[5,20,23]]
90082 **
90083 ** In each case the number after the outer '[' is the docid.  In the
90084 ** latter two cases, the number before the inner '[' is the column
90085 ** associated with the values within.  For DL_POSITIONS the numbers
90086 ** within are the positions, for DL_POSITIONS_OFFSETS they are the
90087 ** position, the start offset, and the end offset.
90088 */
90089 static void dumpDoclistFunc(
90090   sqlite3_context *pContext,
90091   int argc, sqlite3_value **argv
90092 ){
90093   fulltext_cursor *pCursor;
90094   if( argc!=2 && argc!=4 ){
90095     generateError(pContext, "dump_doclist", "incorrect arguments");
90096   }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
90097             sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
90098     generateError(pContext, "dump_doclist", "illegal first argument");
90099   }else if( sqlite3_value_text(argv[1])==NULL ||
90100             sqlite3_value_text(argv[1])[0]=='\0' ){
90101     generateError(pContext, "dump_doclist", "empty second argument");
90102   }else{
90103     const char *pTerm = (const char *)sqlite3_value_text(argv[1]);
90104     const int nTerm = strlen(pTerm);
90105     fulltext_vtab *v;
90106     int rc;
90107     DataBuffer doclist;
90108
90109     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
90110     v = cursor_vtab(pCursor);
90111
90112     dataBufferInit(&doclist, 0);
90113
90114     /* termSelect() yields the same logical doclist that queries are
90115     ** run against.
90116     */
90117     if( argc==2 ){
90118       rc = termSelect(v, v->nColumn, pTerm, nTerm, 0, DL_DEFAULT, &doclist);
90119     }else{
90120       sqlite3_stmt *s = NULL;
90121
90122       /* Get our specific segment's information. */
90123       rc = sql_get_statement(v, SEGDIR_SELECT_SEGMENT_STMT, &s);
90124       if( rc==SQLITE_OK ){
90125         rc = sqlite3_bind_int(s, 1, sqlite3_value_int(argv[2]));
90126         if( rc==SQLITE_OK ){
90127           rc = sqlite3_bind_int(s, 2, sqlite3_value_int(argv[3]));
90128         }
90129       }
90130
90131       if( rc==SQLITE_OK ){
90132         rc = sqlite3_step(s);
90133
90134         if( rc==SQLITE_DONE ){
90135           dataBufferDestroy(&doclist);
90136           generateError(pContext, "dump_doclist", "segment not found");
90137           return;
90138         }
90139
90140         /* Found a segment, load it into doclist. */
90141         if( rc==SQLITE_ROW ){
90142           const sqlite_int64 iLeavesEnd = sqlite3_column_int64(s, 1);
90143           const char *pData = sqlite3_column_blob(s, 2);
90144           const int nData = sqlite3_column_bytes(s, 2);
90145
90146           /* loadSegment() is used by termSelect() to load each
90147           ** segment's data.
90148           */
90149           rc = loadSegment(v, pData, nData, iLeavesEnd, pTerm, nTerm, 0,
90150                            &doclist);
90151           if( rc==SQLITE_OK ){
90152             rc = sqlite3_step(s);
90153
90154             /* Should not have more than one matching segment. */
90155             if( rc!=SQLITE_DONE ){
90156               sqlite3_reset(s);
90157               dataBufferDestroy(&doclist);
90158               generateError(pContext, "dump_doclist", "invalid segdir");
90159               return;
90160             }
90161             rc = SQLITE_OK;
90162           }
90163         }
90164       }
90165
90166       sqlite3_reset(s);
90167     }
90168
90169     if( rc==SQLITE_OK ){
90170       if( doclist.nData>0 ){
90171         createDoclistResult(pContext, doclist.pData, doclist.nData);
90172       }else{
90173         /* TODO(shess): This can happen if the term is not present, or
90174         ** if all instances of the term have been deleted and this is
90175         ** an all-index dump.  It may be interesting to distinguish
90176         ** these cases.
90177         */
90178         sqlite3_result_text(pContext, "", 0, SQLITE_STATIC);
90179       }
90180     }else if( rc==SQLITE_NOMEM ){
90181       /* Handle out-of-memory cases specially because if they are
90182       ** generated in fts3 code they may not be reflected in the db
90183       ** handle.
90184       */
90185       /* TODO(shess): Handle this more comprehensively.
90186       ** sqlite3ErrStr() has what I need, but is internal.
90187       */
90188       generateError(pContext, "dump_doclist", "out of memory");
90189     }else{
90190       generateError(pContext, "dump_doclist", NULL);
90191     }
90192
90193     dataBufferDestroy(&doclist);
90194   }
90195 }
90196 #endif
90197
90198 /*
90199 ** This routine implements the xFindFunction method for the FTS3
90200 ** virtual table.
90201 */
90202 static int fulltextFindFunction(
90203   sqlite3_vtab *pVtab,
90204   int nArg,
90205   const char *zName,
90206   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
90207   void **ppArg
90208 ){
90209   if( strcmp(zName,"snippet")==0 ){
90210     *pxFunc = snippetFunc;
90211     return 1;
90212   }else if( strcmp(zName,"offsets")==0 ){
90213     *pxFunc = snippetOffsetsFunc;
90214     return 1;
90215   }else if( strcmp(zName,"optimize")==0 ){
90216     *pxFunc = optimizeFunc;
90217     return 1;
90218 #ifdef SQLITE_TEST
90219     /* NOTE(shess): These functions are present only for testing
90220     ** purposes.  No particular effort is made to optimize their
90221     ** execution or how they build their results.
90222     */
90223   }else if( strcmp(zName,"dump_terms")==0 ){
90224     /* fprintf(stderr, "Found dump_terms\n"); */
90225     *pxFunc = dumpTermsFunc;
90226     return 1;
90227   }else if( strcmp(zName,"dump_doclist")==0 ){
90228     /* fprintf(stderr, "Found dump_doclist\n"); */
90229     *pxFunc = dumpDoclistFunc;
90230     return 1;
90231 #endif
90232   }
90233   return 0;
90234 }
90235
90236 /*
90237 ** Rename an fts3 table.
90238 */
90239 static int fulltextRename(
90240   sqlite3_vtab *pVtab,
90241   const char *zName
90242 ){
90243   fulltext_vtab *p = (fulltext_vtab *)pVtab;
90244   int rc = SQLITE_NOMEM;
90245   char *zSql = sqlite3_mprintf(
90246     "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';"
90247     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';"
90248     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';"
90249     , p->zDb, p->zName, zName 
90250     , p->zDb, p->zName, zName 
90251     , p->zDb, p->zName, zName
90252   );
90253   if( zSql ){
90254     rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
90255     sqlite3_free(zSql);
90256   }
90257   return rc;
90258 }
90259
90260 static const sqlite3_module fts3Module = {
90261   /* iVersion      */ 0,
90262   /* xCreate       */ fulltextCreate,
90263   /* xConnect      */ fulltextConnect,
90264   /* xBestIndex    */ fulltextBestIndex,
90265   /* xDisconnect   */ fulltextDisconnect,
90266   /* xDestroy      */ fulltextDestroy,
90267   /* xOpen         */ fulltextOpen,
90268   /* xClose        */ fulltextClose,
90269   /* xFilter       */ fulltextFilter,
90270   /* xNext         */ fulltextNext,
90271   /* xEof          */ fulltextEof,
90272   /* xColumn       */ fulltextColumn,
90273   /* xRowid        */ fulltextRowid,
90274   /* xUpdate       */ fulltextUpdate,
90275   /* xBegin        */ fulltextBegin,
90276   /* xSync         */ fulltextSync,
90277   /* xCommit       */ fulltextCommit,
90278   /* xRollback     */ fulltextRollback,
90279   /* xFindFunction */ fulltextFindFunction,
90280   /* xRename */       fulltextRename,
90281 };
90282
90283 static void hashDestroy(void *p){
90284   fts3Hash *pHash = (fts3Hash *)p;
90285   sqlite3Fts3HashClear(pHash);
90286   sqlite3_free(pHash);
90287 }
90288
90289 /*
90290 ** The fts3 built-in tokenizers - "simple" and "porter" - are implemented
90291 ** in files fts3_tokenizer1.c and fts3_porter.c respectively. The following
90292 ** two forward declarations are for functions declared in these files
90293 ** used to retrieve the respective implementations.
90294 **
90295 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
90296 ** to by the argument to point a the "simple" tokenizer implementation.
90297 ** Function ...PorterTokenizerModule() sets *pModule to point to the
90298 ** porter tokenizer/stemmer implementation.
90299 */
90300 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
90301 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
90302 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
90303
90304 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, fts3Hash *, const char *);
90305
90306 /*
90307 ** Initialise the fts3 extension. If this extension is built as part
90308 ** of the sqlite library, then this function is called directly by
90309 ** SQLite. If fts3 is built as a dynamically loadable extension, this
90310 ** function is called by the sqlite3_extension_init() entry point.
90311 */
90312 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
90313   int rc = SQLITE_OK;
90314   fts3Hash *pHash = 0;
90315   const sqlite3_tokenizer_module *pSimple = 0;
90316   const sqlite3_tokenizer_module *pPorter = 0;
90317   const sqlite3_tokenizer_module *pIcu = 0;
90318
90319   sqlite3Fts3SimpleTokenizerModule(&pSimple);
90320   sqlite3Fts3PorterTokenizerModule(&pPorter);
90321 #ifdef SQLITE_ENABLE_ICU
90322   sqlite3Fts3IcuTokenizerModule(&pIcu);
90323 #endif
90324
90325   /* Allocate and initialise the hash-table used to store tokenizers. */
90326   pHash = sqlite3_malloc(sizeof(fts3Hash));
90327   if( !pHash ){
90328     rc = SQLITE_NOMEM;
90329   }else{
90330     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
90331   }
90332
90333   /* Load the built-in tokenizers into the hash table */
90334   if( rc==SQLITE_OK ){
90335     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
90336      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
90337      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
90338     ){
90339       rc = SQLITE_NOMEM;
90340     }
90341   }
90342
90343   /* Create the virtual table wrapper around the hash-table and overload 
90344   ** the two scalar functions. If this is successful, register the
90345   ** module with sqlite.
90346   */
90347   if( SQLITE_OK==rc 
90348    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
90349    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
90350    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", -1))
90351    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", -1))
90352 #ifdef SQLITE_TEST
90353    && SQLITE_OK==(rc = sqlite3_overload_function(db, "dump_terms", -1))
90354    && SQLITE_OK==(rc = sqlite3_overload_function(db, "dump_doclist", -1))
90355 #endif
90356   ){
90357     return sqlite3_create_module_v2(
90358         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
90359     );
90360   }
90361
90362   /* An error has occured. Delete the hash table and return the error code. */
90363   assert( rc!=SQLITE_OK );
90364   if( pHash ){
90365     sqlite3Fts3HashClear(pHash);
90366     sqlite3_free(pHash);
90367   }
90368   return rc;
90369 }
90370
90371 #if !SQLITE_CORE
90372 SQLITE_API int sqlite3_extension_init(
90373   sqlite3 *db, 
90374   char **pzErrMsg,
90375   const sqlite3_api_routines *pApi
90376 ){
90377   SQLITE_EXTENSION_INIT2(pApi)
90378   return sqlite3Fts3Init(db);
90379 }
90380 #endif
90381
90382 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
90383
90384 /************** End of fts3.c ************************************************/
90385 /************** Begin file fts3_hash.c ***************************************/
90386 /*
90387 ** 2001 September 22
90388 **
90389 ** The author disclaims copyright to this source code.  In place of
90390 ** a legal notice, here is a blessing:
90391 **
90392 **    May you do good and not evil.
90393 **    May you find forgiveness for yourself and forgive others.
90394 **    May you share freely, never taking more than you give.
90395 **
90396 *************************************************************************
90397 ** This is the implementation of generic hash-tables used in SQLite.
90398 ** We've modified it slightly to serve as a standalone hash table
90399 ** implementation for the full-text indexing module.
90400 */
90401
90402 /*
90403 ** The code in this file is only compiled if:
90404 **
90405 **     * The FTS3 module is being built as an extension
90406 **       (in which case SQLITE_CORE is not defined), or
90407 **
90408 **     * The FTS3 module is being built into the core of
90409 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
90410 */
90411 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
90412
90413
90414
90415 /*
90416 ** Malloc and Free functions
90417 */
90418 static void *fts3HashMalloc(int n){
90419   void *p = sqlite3_malloc(n);
90420   if( p ){
90421     memset(p, 0, n);
90422   }
90423   return p;
90424 }
90425 static void fts3HashFree(void *p){
90426   sqlite3_free(p);
90427 }
90428
90429 /* Turn bulk memory into a hash table object by initializing the
90430 ** fields of the Hash structure.
90431 **
90432 ** "pNew" is a pointer to the hash table that is to be initialized.
90433 ** keyClass is one of the constants 
90434 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
90435 ** determines what kind of key the hash table will use.  "copyKey" is
90436 ** true if the hash table should make its own private copy of keys and
90437 ** false if it should just use the supplied pointer.
90438 */
90439 SQLITE_PRIVATE void sqlite3Fts3HashInit(fts3Hash *pNew, int keyClass, int copyKey){
90440   assert( pNew!=0 );
90441   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
90442   pNew->keyClass = keyClass;
90443   pNew->copyKey = copyKey;
90444   pNew->first = 0;
90445   pNew->count = 0;
90446   pNew->htsize = 0;
90447   pNew->ht = 0;
90448 }
90449
90450 /* Remove all entries from a hash table.  Reclaim all memory.
90451 ** Call this routine to delete a hash table or to reset a hash table
90452 ** to the empty state.
90453 */
90454 SQLITE_PRIVATE void sqlite3Fts3HashClear(fts3Hash *pH){
90455   fts3HashElem *elem;         /* For looping over all elements of the table */
90456
90457   assert( pH!=0 );
90458   elem = pH->first;
90459   pH->first = 0;
90460   fts3HashFree(pH->ht);
90461   pH->ht = 0;
90462   pH->htsize = 0;
90463   while( elem ){
90464     fts3HashElem *next_elem = elem->next;
90465     if( pH->copyKey && elem->pKey ){
90466       fts3HashFree(elem->pKey);
90467     }
90468     fts3HashFree(elem);
90469     elem = next_elem;
90470   }
90471   pH->count = 0;
90472 }
90473
90474 /*
90475 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
90476 */
90477 static int fts3StrHash(const void *pKey, int nKey){
90478   const char *z = (const char *)pKey;
90479   int h = 0;
90480   if( nKey<=0 ) nKey = (int) strlen(z);
90481   while( nKey > 0  ){
90482     h = (h<<3) ^ h ^ *z++;
90483     nKey--;
90484   }
90485   return h & 0x7fffffff;
90486 }
90487 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
90488   if( n1!=n2 ) return 1;
90489   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
90490 }
90491
90492 /*
90493 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
90494 */
90495 static int fts3BinHash(const void *pKey, int nKey){
90496   int h = 0;
90497   const char *z = (const char *)pKey;
90498   while( nKey-- > 0 ){
90499     h = (h<<3) ^ h ^ *(z++);
90500   }
90501   return h & 0x7fffffff;
90502 }
90503 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
90504   if( n1!=n2 ) return 1;
90505   return memcmp(pKey1,pKey2,n1);
90506 }
90507
90508 /*
90509 ** Return a pointer to the appropriate hash function given the key class.
90510 **
90511 ** The C syntax in this function definition may be unfamilar to some 
90512 ** programmers, so we provide the following additional explanation:
90513 **
90514 ** The name of the function is "ftsHashFunction".  The function takes a
90515 ** single parameter "keyClass".  The return value of ftsHashFunction()
90516 ** is a pointer to another function.  Specifically, the return value
90517 ** of ftsHashFunction() is a pointer to a function that takes two parameters
90518 ** with types "const void*" and "int" and returns an "int".
90519 */
90520 static int (*ftsHashFunction(int keyClass))(const void*,int){
90521   if( keyClass==FTS3_HASH_STRING ){
90522     return &fts3StrHash;
90523   }else{
90524     assert( keyClass==FTS3_HASH_BINARY );
90525     return &fts3BinHash;
90526   }
90527 }
90528
90529 /*
90530 ** Return a pointer to the appropriate hash function given the key class.
90531 **
90532 ** For help in interpreted the obscure C code in the function definition,
90533 ** see the header comment on the previous function.
90534 */
90535 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
90536   if( keyClass==FTS3_HASH_STRING ){
90537     return &fts3StrCompare;
90538   }else{
90539     assert( keyClass==FTS3_HASH_BINARY );
90540     return &fts3BinCompare;
90541   }
90542 }
90543
90544 /* Link an element into the hash table
90545 */
90546 static void fts3HashInsertElement(
90547   fts3Hash *pH,            /* The complete hash table */
90548   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
90549   fts3HashElem *pNew       /* The element to be inserted */
90550 ){
90551   fts3HashElem *pHead;     /* First element already in pEntry */
90552   pHead = pEntry->chain;
90553   if( pHead ){
90554     pNew->next = pHead;
90555     pNew->prev = pHead->prev;
90556     if( pHead->prev ){ pHead->prev->next = pNew; }
90557     else             { pH->first = pNew; }
90558     pHead->prev = pNew;
90559   }else{
90560     pNew->next = pH->first;
90561     if( pH->first ){ pH->first->prev = pNew; }
90562     pNew->prev = 0;
90563     pH->first = pNew;
90564   }
90565   pEntry->count++;
90566   pEntry->chain = pNew;
90567 }
90568
90569
90570 /* Resize the hash table so that it cantains "new_size" buckets.
90571 ** "new_size" must be a power of 2.  The hash table might fail 
90572 ** to resize if sqliteMalloc() fails.
90573 */
90574 static void fts3Rehash(fts3Hash *pH, int new_size){
90575   struct _fts3ht *new_ht;          /* The new hash table */
90576   fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
90577   int (*xHash)(const void*,int);   /* The hash function */
90578
90579   assert( (new_size & (new_size-1))==0 );
90580   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
90581   if( new_ht==0 ) return;
90582   fts3HashFree(pH->ht);
90583   pH->ht = new_ht;
90584   pH->htsize = new_size;
90585   xHash = ftsHashFunction(pH->keyClass);
90586   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
90587     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
90588     next_elem = elem->next;
90589     fts3HashInsertElement(pH, &new_ht[h], elem);
90590   }
90591 }
90592
90593 /* This function (for internal use only) locates an element in an
90594 ** hash table that matches the given key.  The hash for this key has
90595 ** already been computed and is passed as the 4th parameter.
90596 */
90597 static fts3HashElem *fts3FindElementByHash(
90598   const fts3Hash *pH, /* The pH to be searched */
90599   const void *pKey,   /* The key we are searching for */
90600   int nKey,
90601   int h               /* The hash for this key. */
90602 ){
90603   fts3HashElem *elem;            /* Used to loop thru the element list */
90604   int count;                     /* Number of elements left to test */
90605   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
90606
90607   if( pH->ht ){
90608     struct _fts3ht *pEntry = &pH->ht[h];
90609     elem = pEntry->chain;
90610     count = pEntry->count;
90611     xCompare = ftsCompareFunction(pH->keyClass);
90612     while( count-- && elem ){
90613       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
90614         return elem;
90615       }
90616       elem = elem->next;
90617     }
90618   }
90619   return 0;
90620 }
90621
90622 /* Remove a single entry from the hash table given a pointer to that
90623 ** element and a hash on the element's key.
90624 */
90625 static void fts3RemoveElementByHash(
90626   fts3Hash *pH,         /* The pH containing "elem" */
90627   fts3HashElem* elem,   /* The element to be removed from the pH */
90628   int h                 /* Hash value for the element */
90629 ){
90630   struct _fts3ht *pEntry;
90631   if( elem->prev ){
90632     elem->prev->next = elem->next; 
90633   }else{
90634     pH->first = elem->next;
90635   }
90636   if( elem->next ){
90637     elem->next->prev = elem->prev;
90638   }
90639   pEntry = &pH->ht[h];
90640   if( pEntry->chain==elem ){
90641     pEntry->chain = elem->next;
90642   }
90643   pEntry->count--;
90644   if( pEntry->count<=0 ){
90645     pEntry->chain = 0;
90646   }
90647   if( pH->copyKey && elem->pKey ){
90648     fts3HashFree(elem->pKey);
90649   }
90650   fts3HashFree( elem );
90651   pH->count--;
90652   if( pH->count<=0 ){
90653     assert( pH->first==0 );
90654     assert( pH->count==0 );
90655     fts3HashClear(pH);
90656   }
90657 }
90658
90659 /* Attempt to locate an element of the hash table pH with a key
90660 ** that matches pKey,nKey.  Return the data for this element if it is
90661 ** found, or NULL if there is no match.
90662 */
90663 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const fts3Hash *pH, const void *pKey, int nKey){
90664   int h;                 /* A hash on key */
90665   fts3HashElem *elem;    /* The element that matches key */
90666   int (*xHash)(const void*,int);  /* The hash function */
90667
90668   if( pH==0 || pH->ht==0 ) return 0;
90669   xHash = ftsHashFunction(pH->keyClass);
90670   assert( xHash!=0 );
90671   h = (*xHash)(pKey,nKey);
90672   assert( (pH->htsize & (pH->htsize-1))==0 );
90673   elem = fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
90674   return elem ? elem->data : 0;
90675 }
90676
90677 /* Insert an element into the hash table pH.  The key is pKey,nKey
90678 ** and the data is "data".
90679 **
90680 ** If no element exists with a matching key, then a new
90681 ** element is created.  A copy of the key is made if the copyKey
90682 ** flag is set.  NULL is returned.
90683 **
90684 ** If another element already exists with the same key, then the
90685 ** new data replaces the old data and the old data is returned.
90686 ** The key is not copied in this instance.  If a malloc fails, then
90687 ** the new data is returned and the hash table is unchanged.
90688 **
90689 ** If the "data" parameter to this function is NULL, then the
90690 ** element corresponding to "key" is removed from the hash table.
90691 */
90692 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
90693   fts3Hash *pH,        /* The hash table to insert into */
90694   const void *pKey,    /* The key */
90695   int nKey,            /* Number of bytes in the key */
90696   void *data           /* The data */
90697 ){
90698   int hraw;                 /* Raw hash value of the key */
90699   int h;                    /* the hash of the key modulo hash table size */
90700   fts3HashElem *elem;       /* Used to loop thru the element list */
90701   fts3HashElem *new_elem;   /* New element added to the pH */
90702   int (*xHash)(const void*,int);  /* The hash function */
90703
90704   assert( pH!=0 );
90705   xHash = ftsHashFunction(pH->keyClass);
90706   assert( xHash!=0 );
90707   hraw = (*xHash)(pKey, nKey);
90708   assert( (pH->htsize & (pH->htsize-1))==0 );
90709   h = hraw & (pH->htsize-1);
90710   elem = fts3FindElementByHash(pH,pKey,nKey,h);
90711   if( elem ){
90712     void *old_data = elem->data;
90713     if( data==0 ){
90714       fts3RemoveElementByHash(pH,elem,h);
90715     }else{
90716       elem->data = data;
90717     }
90718     return old_data;
90719   }
90720   if( data==0 ) return 0;
90721   new_elem = (fts3HashElem*)fts3HashMalloc( sizeof(fts3HashElem) );
90722   if( new_elem==0 ) return data;
90723   if( pH->copyKey && pKey!=0 ){
90724     new_elem->pKey = fts3HashMalloc( nKey );
90725     if( new_elem->pKey==0 ){
90726       fts3HashFree(new_elem);
90727       return data;
90728     }
90729     memcpy((void*)new_elem->pKey, pKey, nKey);
90730   }else{
90731     new_elem->pKey = (void*)pKey;
90732   }
90733   new_elem->nKey = nKey;
90734   pH->count++;
90735   if( pH->htsize==0 ){
90736     fts3Rehash(pH,8);
90737     if( pH->htsize==0 ){
90738       pH->count = 0;
90739       fts3HashFree(new_elem);
90740       return data;
90741     }
90742   }
90743   if( pH->count > pH->htsize ){
90744     fts3Rehash(pH,pH->htsize*2);
90745   }
90746   assert( pH->htsize>0 );
90747   assert( (pH->htsize & (pH->htsize-1))==0 );
90748   h = hraw & (pH->htsize-1);
90749   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
90750   new_elem->data = data;
90751   return 0;
90752 }
90753
90754 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
90755
90756 /************** End of fts3_hash.c *******************************************/
90757 /************** Begin file fts3_porter.c *************************************/
90758 /*
90759 ** 2006 September 30
90760 **
90761 ** The author disclaims copyright to this source code.  In place of
90762 ** a legal notice, here is a blessing:
90763 **
90764 **    May you do good and not evil.
90765 **    May you find forgiveness for yourself and forgive others.
90766 **    May you share freely, never taking more than you give.
90767 **
90768 *************************************************************************
90769 ** Implementation of the full-text-search tokenizer that implements
90770 ** a Porter stemmer.
90771 */
90772
90773 /*
90774 ** The code in this file is only compiled if:
90775 **
90776 **     * The FTS3 module is being built as an extension
90777 **       (in which case SQLITE_CORE is not defined), or
90778 **
90779 **     * The FTS3 module is being built into the core of
90780 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
90781 */
90782 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
90783
90784
90785
90786
90787 /*
90788 ** Class derived from sqlite3_tokenizer
90789 */
90790 typedef struct porter_tokenizer {
90791   sqlite3_tokenizer base;      /* Base class */
90792 } porter_tokenizer;
90793
90794 /*
90795 ** Class derived from sqlit3_tokenizer_cursor
90796 */
90797 typedef struct porter_tokenizer_cursor {
90798   sqlite3_tokenizer_cursor base;
90799   const char *zInput;          /* input we are tokenizing */
90800   int nInput;                  /* size of the input */
90801   int iOffset;                 /* current position in zInput */
90802   int iToken;                  /* index of next token to be returned */
90803   char *zToken;                /* storage for current token */
90804   int nAllocated;              /* space allocated to zToken buffer */
90805 } porter_tokenizer_cursor;
90806
90807
90808 /* Forward declaration */
90809 static const sqlite3_tokenizer_module porterTokenizerModule;
90810
90811
90812 /*
90813 ** Create a new tokenizer instance.
90814 */
90815 static int porterCreate(
90816   int argc, const char * const *argv,
90817   sqlite3_tokenizer **ppTokenizer
90818 ){
90819   porter_tokenizer *t;
90820   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
90821   if( t==NULL ) return SQLITE_NOMEM;
90822   memset(t, 0, sizeof(*t));
90823   *ppTokenizer = &t->base;
90824   return SQLITE_OK;
90825 }
90826
90827 /*
90828 ** Destroy a tokenizer
90829 */
90830 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
90831   sqlite3_free(pTokenizer);
90832   return SQLITE_OK;
90833 }
90834
90835 /*
90836 ** Prepare to begin tokenizing a particular string.  The input
90837 ** string to be tokenized is zInput[0..nInput-1].  A cursor
90838 ** used to incrementally tokenize this string is returned in 
90839 ** *ppCursor.
90840 */
90841 static int porterOpen(
90842   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
90843   const char *zInput, int nInput,        /* String to be tokenized */
90844   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
90845 ){
90846   porter_tokenizer_cursor *c;
90847
90848   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
90849   if( c==NULL ) return SQLITE_NOMEM;
90850
90851   c->zInput = zInput;
90852   if( zInput==0 ){
90853     c->nInput = 0;
90854   }else if( nInput<0 ){
90855     c->nInput = (int)strlen(zInput);
90856   }else{
90857     c->nInput = nInput;
90858   }
90859   c->iOffset = 0;                 /* start tokenizing at the beginning */
90860   c->iToken = 0;
90861   c->zToken = NULL;               /* no space allocated, yet. */
90862   c->nAllocated = 0;
90863
90864   *ppCursor = &c->base;
90865   return SQLITE_OK;
90866 }
90867
90868 /*
90869 ** Close a tokenization cursor previously opened by a call to
90870 ** porterOpen() above.
90871 */
90872 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
90873   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
90874   sqlite3_free(c->zToken);
90875   sqlite3_free(c);
90876   return SQLITE_OK;
90877 }
90878 /*
90879 ** Vowel or consonant
90880 */
90881 static const char cType[] = {
90882    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
90883    1, 1, 1, 2, 1
90884 };
90885
90886 /*
90887 ** isConsonant() and isVowel() determine if their first character in
90888 ** the string they point to is a consonant or a vowel, according
90889 ** to Porter ruls.  
90890 **
90891 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
90892 ** 'Y' is a consonant unless it follows another consonant,
90893 ** in which case it is a vowel.
90894 **
90895 ** In these routine, the letters are in reverse order.  So the 'y' rule
90896 ** is that 'y' is a consonant unless it is followed by another
90897 ** consonent.
90898 */
90899 static int isVowel(const char*);
90900 static int isConsonant(const char *z){
90901   int j;
90902   char x = *z;
90903   if( x==0 ) return 0;
90904   assert( x>='a' && x<='z' );
90905   j = cType[x-'a'];
90906   if( j<2 ) return j;
90907   return z[1]==0 || isVowel(z + 1);
90908 }
90909 static int isVowel(const char *z){
90910   int j;
90911   char x = *z;
90912   if( x==0 ) return 0;
90913   assert( x>='a' && x<='z' );
90914   j = cType[x-'a'];
90915   if( j<2 ) return 1-j;
90916   return isConsonant(z + 1);
90917 }
90918
90919 /*
90920 ** Let any sequence of one or more vowels be represented by V and let
90921 ** C be sequence of one or more consonants.  Then every word can be
90922 ** represented as:
90923 **
90924 **           [C] (VC){m} [V]
90925 **
90926 ** In prose:  A word is an optional consonant followed by zero or
90927 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
90928 ** number of vowel consonant pairs.  This routine computes the value
90929 ** of m for the first i bytes of a word.
90930 **
90931 ** Return true if the m-value for z is 1 or more.  In other words,
90932 ** return true if z contains at least one vowel that is followed
90933 ** by a consonant.
90934 **
90935 ** In this routine z[] is in reverse order.  So we are really looking
90936 ** for an instance of of a consonant followed by a vowel.
90937 */
90938 static int m_gt_0(const char *z){
90939   while( isVowel(z) ){ z++; }
90940   if( *z==0 ) return 0;
90941   while( isConsonant(z) ){ z++; }
90942   return *z!=0;
90943 }
90944
90945 /* Like mgt0 above except we are looking for a value of m which is
90946 ** exactly 1
90947 */
90948 static int m_eq_1(const char *z){
90949   while( isVowel(z) ){ z++; }
90950   if( *z==0 ) return 0;
90951   while( isConsonant(z) ){ z++; }
90952   if( *z==0 ) return 0;
90953   while( isVowel(z) ){ z++; }
90954   if( *z==0 ) return 1;
90955   while( isConsonant(z) ){ z++; }
90956   return *z==0;
90957 }
90958
90959 /* Like mgt0 above except we are looking for a value of m>1 instead
90960 ** or m>0
90961 */
90962 static int m_gt_1(const char *z){
90963   while( isVowel(z) ){ z++; }
90964   if( *z==0 ) return 0;
90965   while( isConsonant(z) ){ z++; }
90966   if( *z==0 ) return 0;
90967   while( isVowel(z) ){ z++; }
90968   if( *z==0 ) return 0;
90969   while( isConsonant(z) ){ z++; }
90970   return *z!=0;
90971 }
90972
90973 /*
90974 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
90975 */
90976 static int hasVowel(const char *z){
90977   while( isConsonant(z) ){ z++; }
90978   return *z!=0;
90979 }
90980
90981 /*
90982 ** Return TRUE if the word ends in a double consonant.
90983 **
90984 ** The text is reversed here. So we are really looking at
90985 ** the first two characters of z[].
90986 */
90987 static int doubleConsonant(const char *z){
90988   return isConsonant(z) && z[0]==z[1] && isConsonant(z+1);
90989 }
90990
90991 /*
90992 ** Return TRUE if the word ends with three letters which
90993 ** are consonant-vowel-consonent and where the final consonant
90994 ** is not 'w', 'x', or 'y'.
90995 **
90996 ** The word is reversed here.  So we are really checking the
90997 ** first three letters and the first one cannot be in [wxy].
90998 */
90999 static int star_oh(const char *z){
91000   return
91001     z[0]!=0 && isConsonant(z) &&
91002     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
91003     z[1]!=0 && isVowel(z+1) &&
91004     z[2]!=0 && isConsonant(z+2);
91005 }
91006
91007 /*
91008 ** If the word ends with zFrom and xCond() is true for the stem
91009 ** of the word that preceeds the zFrom ending, then change the 
91010 ** ending to zTo.
91011 **
91012 ** The input word *pz and zFrom are both in reverse order.  zTo
91013 ** is in normal order. 
91014 **
91015 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
91016 ** match.  Not that TRUE is returned even if xCond() fails and
91017 ** no substitution occurs.
91018 */
91019 static int stem(
91020   char **pz,             /* The word being stemmed (Reversed) */
91021   const char *zFrom,     /* If the ending matches this... (Reversed) */
91022   const char *zTo,       /* ... change the ending to this (not reversed) */
91023   int (*xCond)(const char*)   /* Condition that must be true */
91024 ){
91025   char *z = *pz;
91026   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
91027   if( *zFrom!=0 ) return 0;
91028   if( xCond && !xCond(z) ) return 1;
91029   while( *zTo ){
91030     *(--z) = *(zTo++);
91031   }
91032   *pz = z;
91033   return 1;
91034 }
91035
91036 /*
91037 ** This is the fallback stemmer used when the porter stemmer is
91038 ** inappropriate.  The input word is copied into the output with
91039 ** US-ASCII case folding.  If the input word is too long (more
91040 ** than 20 bytes if it contains no digits or more than 6 bytes if
91041 ** it contains digits) then word is truncated to 20 or 6 bytes
91042 ** by taking 10 or 3 bytes from the beginning and end.
91043 */
91044 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
91045   int i, mx, j;
91046   int hasDigit = 0;
91047   for(i=0; i<nIn; i++){
91048     int c = zIn[i];
91049     if( c>='A' && c<='Z' ){
91050       zOut[i] = c - 'A' + 'a';
91051     }else{
91052       if( c>='0' && c<='9' ) hasDigit = 1;
91053       zOut[i] = c;
91054     }
91055   }
91056   mx = hasDigit ? 3 : 10;
91057   if( nIn>mx*2 ){
91058     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
91059       zOut[j] = zOut[i];
91060     }
91061     i = j;
91062   }
91063   zOut[i] = 0;
91064   *pnOut = i;
91065 }
91066
91067
91068 /*
91069 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
91070 ** zOut is at least big enough to hold nIn bytes.  Write the actual
91071 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
91072 **
91073 ** Any upper-case characters in the US-ASCII character set ([A-Z])
91074 ** are converted to lower case.  Upper-case UTF characters are
91075 ** unchanged.
91076 **
91077 ** Words that are longer than about 20 bytes are stemmed by retaining
91078 ** a few bytes from the beginning and the end of the word.  If the
91079 ** word contains digits, 3 bytes are taken from the beginning and
91080 ** 3 bytes from the end.  For long words without digits, 10 bytes
91081 ** are taken from each end.  US-ASCII case folding still applies.
91082 ** 
91083 ** If the input word contains not digits but does characters not 
91084 ** in [a-zA-Z] then no stemming is attempted and this routine just 
91085 ** copies the input into the input into the output with US-ASCII
91086 ** case folding.
91087 **
91088 ** Stemming never increases the length of the word.  So there is
91089 ** no chance of overflowing the zOut buffer.
91090 */
91091 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
91092   int i, j, c;
91093   char zReverse[28];
91094   char *z, *z2;
91095   if( nIn<3 || nIn>=sizeof(zReverse)-7 ){
91096     /* The word is too big or too small for the porter stemmer.
91097     ** Fallback to the copy stemmer */
91098     copy_stemmer(zIn, nIn, zOut, pnOut);
91099     return;
91100   }
91101   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
91102     c = zIn[i];
91103     if( c>='A' && c<='Z' ){
91104       zReverse[j] = c + 'a' - 'A';
91105     }else if( c>='a' && c<='z' ){
91106       zReverse[j] = c;
91107     }else{
91108       /* The use of a character not in [a-zA-Z] means that we fallback
91109       ** to the copy stemmer */
91110       copy_stemmer(zIn, nIn, zOut, pnOut);
91111       return;
91112     }
91113   }
91114   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
91115   z = &zReverse[j+1];
91116
91117
91118   /* Step 1a */
91119   if( z[0]=='s' ){
91120     if(
91121      !stem(&z, "sess", "ss", 0) &&
91122      !stem(&z, "sei", "i", 0)  &&
91123      !stem(&z, "ss", "ss", 0)
91124     ){
91125       z++;
91126     }
91127   }
91128
91129   /* Step 1b */  
91130   z2 = z;
91131   if( stem(&z, "dee", "ee", m_gt_0) ){
91132     /* Do nothing.  The work was all in the test */
91133   }else if( 
91134      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
91135       && z!=z2
91136   ){
91137      if( stem(&z, "ta", "ate", 0) ||
91138          stem(&z, "lb", "ble", 0) ||
91139          stem(&z, "zi", "ize", 0) ){
91140        /* Do nothing.  The work was all in the test */
91141      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
91142        z++;
91143      }else if( m_eq_1(z) && star_oh(z) ){
91144        *(--z) = 'e';
91145      }
91146   }
91147
91148   /* Step 1c */
91149   if( z[0]=='y' && hasVowel(z+1) ){
91150     z[0] = 'i';
91151   }
91152
91153   /* Step 2 */
91154   switch( z[1] ){
91155    case 'a':
91156      stem(&z, "lanoita", "ate", m_gt_0) ||
91157      stem(&z, "lanoit", "tion", m_gt_0);
91158      break;
91159    case 'c':
91160      stem(&z, "icne", "ence", m_gt_0) ||
91161      stem(&z, "icna", "ance", m_gt_0);
91162      break;
91163    case 'e':
91164      stem(&z, "rezi", "ize", m_gt_0);
91165      break;
91166    case 'g':
91167      stem(&z, "igol", "log", m_gt_0);
91168      break;
91169    case 'l':
91170      stem(&z, "ilb", "ble", m_gt_0) ||
91171      stem(&z, "illa", "al", m_gt_0) ||
91172      stem(&z, "iltne", "ent", m_gt_0) ||
91173      stem(&z, "ile", "e", m_gt_0) ||
91174      stem(&z, "ilsuo", "ous", m_gt_0);
91175      break;
91176    case 'o':
91177      stem(&z, "noitazi", "ize", m_gt_0) ||
91178      stem(&z, "noita", "ate", m_gt_0) ||
91179      stem(&z, "rota", "ate", m_gt_0);
91180      break;
91181    case 's':
91182      stem(&z, "msila", "al", m_gt_0) ||
91183      stem(&z, "ssenevi", "ive", m_gt_0) ||
91184      stem(&z, "ssenluf", "ful", m_gt_0) ||
91185      stem(&z, "ssensuo", "ous", m_gt_0);
91186      break;
91187    case 't':
91188      stem(&z, "itila", "al", m_gt_0) ||
91189      stem(&z, "itivi", "ive", m_gt_0) ||
91190      stem(&z, "itilib", "ble", m_gt_0);
91191      break;
91192   }
91193
91194   /* Step 3 */
91195   switch( z[0] ){
91196    case 'e':
91197      stem(&z, "etaci", "ic", m_gt_0) ||
91198      stem(&z, "evita", "", m_gt_0)   ||
91199      stem(&z, "ezila", "al", m_gt_0);
91200      break;
91201    case 'i':
91202      stem(&z, "itici", "ic", m_gt_0);
91203      break;
91204    case 'l':
91205      stem(&z, "laci", "ic", m_gt_0) ||
91206      stem(&z, "luf", "", m_gt_0);
91207      break;
91208    case 's':
91209      stem(&z, "ssen", "", m_gt_0);
91210      break;
91211   }
91212
91213   /* Step 4 */
91214   switch( z[1] ){
91215    case 'a':
91216      if( z[0]=='l' && m_gt_1(z+2) ){
91217        z += 2;
91218      }
91219      break;
91220    case 'c':
91221      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
91222        z += 4;
91223      }
91224      break;
91225    case 'e':
91226      if( z[0]=='r' && m_gt_1(z+2) ){
91227        z += 2;
91228      }
91229      break;
91230    case 'i':
91231      if( z[0]=='c' && m_gt_1(z+2) ){
91232        z += 2;
91233      }
91234      break;
91235    case 'l':
91236      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
91237        z += 4;
91238      }
91239      break;
91240    case 'n':
91241      if( z[0]=='t' ){
91242        if( z[2]=='a' ){
91243          if( m_gt_1(z+3) ){
91244            z += 3;
91245          }
91246        }else if( z[2]=='e' ){
91247          stem(&z, "tneme", "", m_gt_1) ||
91248          stem(&z, "tnem", "", m_gt_1) ||
91249          stem(&z, "tne", "", m_gt_1);
91250        }
91251      }
91252      break;
91253    case 'o':
91254      if( z[0]=='u' ){
91255        if( m_gt_1(z+2) ){
91256          z += 2;
91257        }
91258      }else if( z[3]=='s' || z[3]=='t' ){
91259        stem(&z, "noi", "", m_gt_1);
91260      }
91261      break;
91262    case 's':
91263      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
91264        z += 3;
91265      }
91266      break;
91267    case 't':
91268      stem(&z, "eta", "", m_gt_1) ||
91269      stem(&z, "iti", "", m_gt_1);
91270      break;
91271    case 'u':
91272      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
91273        z += 3;
91274      }
91275      break;
91276    case 'v':
91277    case 'z':
91278      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
91279        z += 3;
91280      }
91281      break;
91282   }
91283
91284   /* Step 5a */
91285   if( z[0]=='e' ){
91286     if( m_gt_1(z+1) ){
91287       z++;
91288     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
91289       z++;
91290     }
91291   }
91292
91293   /* Step 5b */
91294   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
91295     z++;
91296   }
91297
91298   /* z[] is now the stemmed word in reverse order.  Flip it back
91299   ** around into forward order and return.
91300   */
91301   *pnOut = i = strlen(z);
91302   zOut[i] = 0;
91303   while( *z ){
91304     zOut[--i] = *(z++);
91305   }
91306 }
91307
91308 /*
91309 ** Characters that can be part of a token.  We assume any character
91310 ** whose value is greater than 0x80 (any UTF character) can be
91311 ** part of a token.  In other words, delimiters all must have
91312 ** values of 0x7f or lower.
91313 */
91314 static const char porterIdChar[] = {
91315 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
91316     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
91317     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
91318     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
91319     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
91320     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
91321 };
91322 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
91323
91324 /*
91325 ** Extract the next token from a tokenization cursor.  The cursor must
91326 ** have been opened by a prior call to porterOpen().
91327 */
91328 static int porterNext(
91329   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
91330   const char **pzToken,               /* OUT: *pzToken is the token text */
91331   int *pnBytes,                       /* OUT: Number of bytes in token */
91332   int *piStartOffset,                 /* OUT: Starting offset of token */
91333   int *piEndOffset,                   /* OUT: Ending offset of token */
91334   int *piPosition                     /* OUT: Position integer of token */
91335 ){
91336   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
91337   const char *z = c->zInput;
91338
91339   while( c->iOffset<c->nInput ){
91340     int iStartOffset, ch;
91341
91342     /* Scan past delimiter characters */
91343     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
91344       c->iOffset++;
91345     }
91346
91347     /* Count non-delimiter characters. */
91348     iStartOffset = c->iOffset;
91349     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
91350       c->iOffset++;
91351     }
91352
91353     if( c->iOffset>iStartOffset ){
91354       int n = c->iOffset-iStartOffset;
91355       if( n>c->nAllocated ){
91356         c->nAllocated = n+20;
91357         c->zToken = sqlite3_realloc(c->zToken, c->nAllocated);
91358         if( c->zToken==NULL ) return SQLITE_NOMEM;
91359       }
91360       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
91361       *pzToken = c->zToken;
91362       *piStartOffset = iStartOffset;
91363       *piEndOffset = c->iOffset;
91364       *piPosition = c->iToken++;
91365       return SQLITE_OK;
91366     }
91367   }
91368   return SQLITE_DONE;
91369 }
91370
91371 /*
91372 ** The set of routines that implement the porter-stemmer tokenizer
91373 */
91374 static const sqlite3_tokenizer_module porterTokenizerModule = {
91375   0,
91376   porterCreate,
91377   porterDestroy,
91378   porterOpen,
91379   porterClose,
91380   porterNext,
91381 };
91382
91383 /*
91384 ** Allocate a new porter tokenizer.  Return a pointer to the new
91385 ** tokenizer in *ppModule
91386 */
91387 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
91388   sqlite3_tokenizer_module const**ppModule
91389 ){
91390   *ppModule = &porterTokenizerModule;
91391 }
91392
91393 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
91394
91395 /************** End of fts3_porter.c *****************************************/
91396 /************** Begin file fts3_tokenizer.c **********************************/
91397 /*
91398 ** 2007 June 22
91399 **
91400 ** The author disclaims copyright to this source code.  In place of
91401 ** a legal notice, here is a blessing:
91402 **
91403 **    May you do good and not evil.
91404 **    May you find forgiveness for yourself and forgive others.
91405 **    May you share freely, never taking more than you give.
91406 **
91407 ******************************************************************************
91408 **
91409 ** This is part of an SQLite module implementing full-text search.
91410 ** This particular file implements the generic tokenizer interface.
91411 */
91412
91413 /*
91414 ** The code in this file is only compiled if:
91415 **
91416 **     * The FTS3 module is being built as an extension
91417 **       (in which case SQLITE_CORE is not defined), or
91418 **
91419 **     * The FTS3 module is being built into the core of
91420 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
91421 */
91422 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
91423
91424 #ifndef SQLITE_CORE
91425   SQLITE_EXTENSION_INIT1
91426 #endif
91427
91428
91429 /*
91430 ** Implementation of the SQL scalar function for accessing the underlying 
91431 ** hash table. This function may be called as follows:
91432 **
91433 **   SELECT <function-name>(<key-name>);
91434 **   SELECT <function-name>(<key-name>, <pointer>);
91435 **
91436 ** where <function-name> is the name passed as the second argument
91437 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
91438 **
91439 ** If the <pointer> argument is specified, it must be a blob value
91440 ** containing a pointer to be stored as the hash data corresponding
91441 ** to the string <key-name>. If <pointer> is not specified, then
91442 ** the string <key-name> must already exist in the has table. Otherwise,
91443 ** an error is returned.
91444 **
91445 ** Whether or not the <pointer> argument is specified, the value returned
91446 ** is a blob containing the pointer stored as the hash data corresponding
91447 ** to string <key-name> (after the hash-table is updated, if applicable).
91448 */
91449 static void scalarFunc(
91450   sqlite3_context *context,
91451   int argc,
91452   sqlite3_value **argv
91453 ){
91454   fts3Hash *pHash;
91455   void *pPtr = 0;
91456   const unsigned char *zName;
91457   int nName;
91458
91459   assert( argc==1 || argc==2 );
91460
91461   pHash = (fts3Hash *)sqlite3_user_data(context);
91462
91463   zName = sqlite3_value_text(argv[0]);
91464   nName = sqlite3_value_bytes(argv[0])+1;
91465
91466   if( argc==2 ){
91467     void *pOld;
91468     int n = sqlite3_value_bytes(argv[1]);
91469     if( n!=sizeof(pPtr) ){
91470       sqlite3_result_error(context, "argument type mismatch", -1);
91471       return;
91472     }
91473     pPtr = *(void **)sqlite3_value_blob(argv[1]);
91474     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
91475     if( pOld==pPtr ){
91476       sqlite3_result_error(context, "out of memory", -1);
91477       return;
91478     }
91479   }else{
91480     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
91481     if( !pPtr ){
91482       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
91483       sqlite3_result_error(context, zErr, -1);
91484       sqlite3_free(zErr);
91485       return;
91486     }
91487   }
91488
91489   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
91490 }
91491
91492 #ifdef SQLITE_TEST
91493
91494
91495 /*
91496 ** Implementation of a special SQL scalar function for testing tokenizers 
91497 ** designed to be used in concert with the Tcl testing framework. This
91498 ** function must be called with two arguments:
91499 **
91500 **   SELECT <function-name>(<key-name>, <input-string>);
91501 **   SELECT <function-name>(<key-name>, <pointer>);
91502 **
91503 ** where <function-name> is the name passed as the second argument
91504 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
91505 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
91506 **
91507 ** The return value is a string that may be interpreted as a Tcl
91508 ** list. For each token in the <input-string>, three elements are
91509 ** added to the returned list. The first is the token position, the 
91510 ** second is the token text (folded, stemmed, etc.) and the third is the
91511 ** substring of <input-string> associated with the token. For example, 
91512 ** using the built-in "simple" tokenizer:
91513 **
91514 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
91515 **
91516 ** will return the string:
91517 **
91518 **   "{0 i I 1 dont don't 2 see see 3 how how}"
91519 **   
91520 */
91521 static void testFunc(
91522   sqlite3_context *context,
91523   int argc,
91524   sqlite3_value **argv
91525 ){
91526   fts3Hash *pHash;
91527   sqlite3_tokenizer_module *p;
91528   sqlite3_tokenizer *pTokenizer = 0;
91529   sqlite3_tokenizer_cursor *pCsr = 0;
91530
91531   const char *zErr = 0;
91532
91533   const char *zName;
91534   int nName;
91535   const char *zInput;
91536   int nInput;
91537
91538   const char *zArg = 0;
91539
91540   const char *zToken;
91541   int nToken;
91542   int iStart;
91543   int iEnd;
91544   int iPos;
91545
91546   Tcl_Obj *pRet;
91547
91548   assert( argc==2 || argc==3 );
91549
91550   nName = sqlite3_value_bytes(argv[0]);
91551   zName = (const char *)sqlite3_value_text(argv[0]);
91552   nInput = sqlite3_value_bytes(argv[argc-1]);
91553   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
91554
91555   if( argc==3 ){
91556     zArg = (const char *)sqlite3_value_text(argv[1]);
91557   }
91558
91559   pHash = (fts3Hash *)sqlite3_user_data(context);
91560   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
91561
91562   if( !p ){
91563     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
91564     sqlite3_result_error(context, zErr, -1);
91565     sqlite3_free(zErr);
91566     return;
91567   }
91568
91569   pRet = Tcl_NewObj();
91570   Tcl_IncrRefCount(pRet);
91571
91572   if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
91573     zErr = "error in xCreate()";
91574     goto finish;
91575   }
91576   pTokenizer->pModule = p;
91577   if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
91578     zErr = "error in xOpen()";
91579     goto finish;
91580   }
91581   pCsr->pTokenizer = pTokenizer;
91582
91583   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
91584     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
91585     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
91586     zToken = &zInput[iStart];
91587     nToken = iEnd-iStart;
91588     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
91589   }
91590
91591   if( SQLITE_OK!=p->xClose(pCsr) ){
91592     zErr = "error in xClose()";
91593     goto finish;
91594   }
91595   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
91596     zErr = "error in xDestroy()";
91597     goto finish;
91598   }
91599
91600 finish:
91601   if( zErr ){
91602     sqlite3_result_error(context, zErr, -1);
91603   }else{
91604     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
91605   }
91606   Tcl_DecrRefCount(pRet);
91607 }
91608
91609 static
91610 int registerTokenizer(
91611   sqlite3 *db, 
91612   char *zName, 
91613   const sqlite3_tokenizer_module *p
91614 ){
91615   int rc;
91616   sqlite3_stmt *pStmt;
91617   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
91618
91619   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
91620   if( rc!=SQLITE_OK ){
91621     return rc;
91622   }
91623
91624   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
91625   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
91626   sqlite3_step(pStmt);
91627
91628   return sqlite3_finalize(pStmt);
91629 }
91630
91631 static
91632 int queryTokenizer(
91633   sqlite3 *db, 
91634   char *zName,  
91635   const sqlite3_tokenizer_module **pp
91636 ){
91637   int rc;
91638   sqlite3_stmt *pStmt;
91639   const char zSql[] = "SELECT fts3_tokenizer(?)";
91640
91641   *pp = 0;
91642   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
91643   if( rc!=SQLITE_OK ){
91644     return rc;
91645   }
91646
91647   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
91648   if( SQLITE_ROW==sqlite3_step(pStmt) ){
91649     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
91650       memcpy(pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
91651     }
91652   }
91653
91654   return sqlite3_finalize(pStmt);
91655 }
91656
91657 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
91658
91659 /*
91660 ** Implementation of the scalar function fts3_tokenizer_internal_test().
91661 ** This function is used for testing only, it is not included in the
91662 ** build unless SQLITE_TEST is defined.
91663 **
91664 ** The purpose of this is to test that the fts3_tokenizer() function
91665 ** can be used as designed by the C-code in the queryTokenizer and
91666 ** registerTokenizer() functions above. These two functions are repeated
91667 ** in the README.tokenizer file as an example, so it is important to
91668 ** test them.
91669 **
91670 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
91671 ** function with no arguments. An assert() will fail if a problem is
91672 ** detected. i.e.:
91673 **
91674 **     SELECT fts3_tokenizer_internal_test();
91675 **
91676 */
91677 static void intTestFunc(
91678   sqlite3_context *context,
91679   int argc,
91680   sqlite3_value **argv
91681 ){
91682   int rc;
91683   const sqlite3_tokenizer_module *p1;
91684   const sqlite3_tokenizer_module *p2;
91685   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
91686
91687   /* Test the query function */
91688   sqlite3Fts3SimpleTokenizerModule(&p1);
91689   rc = queryTokenizer(db, "simple", &p2);
91690   assert( rc==SQLITE_OK );
91691   assert( p1==p2 );
91692   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
91693   assert( rc==SQLITE_ERROR );
91694   assert( p2==0 );
91695   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
91696
91697   /* Test the storage function */
91698   rc = registerTokenizer(db, "nosuchtokenizer", p1);
91699   assert( rc==SQLITE_OK );
91700   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
91701   assert( rc==SQLITE_OK );
91702   assert( p2==p1 );
91703
91704   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
91705 }
91706
91707 #endif
91708
91709 /*
91710 ** Set up SQL objects in database db used to access the contents of
91711 ** the hash table pointed to by argument pHash. The hash table must
91712 ** been initialised to use string keys, and to take a private copy 
91713 ** of the key when a value is inserted. i.e. by a call similar to:
91714 **
91715 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
91716 **
91717 ** This function adds a scalar function (see header comment above
91718 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
91719 ** defined at compilation time, a temporary virtual table (see header 
91720 ** comment above struct HashTableVtab) to the database schema. Both 
91721 ** provide read/write access to the contents of *pHash.
91722 **
91723 ** The third argument to this function, zName, is used as the name
91724 ** of both the scalar and, if created, the virtual table.
91725 */
91726 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
91727   sqlite3 *db, 
91728   fts3Hash *pHash, 
91729   const char *zName
91730 ){
91731   int rc = SQLITE_OK;
91732   void *p = (void *)pHash;
91733   const int any = SQLITE_ANY;
91734   char *zTest = 0;
91735   char *zTest2 = 0;
91736
91737 #ifdef SQLITE_TEST
91738   void *pdb = (void *)db;
91739   zTest = sqlite3_mprintf("%s_test", zName);
91740   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
91741   if( !zTest || !zTest2 ){
91742     rc = SQLITE_NOMEM;
91743   }
91744 #endif
91745
91746   if( rc!=SQLITE_OK
91747    || (rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0))
91748    || (rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0))
91749 #ifdef SQLITE_TEST
91750    || (rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0))
91751    || (rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0))
91752    || (rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0))
91753 #endif
91754   );
91755
91756   sqlite3_free(zTest);
91757   sqlite3_free(zTest2);
91758   return rc;
91759 }
91760
91761 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
91762
91763 /************** End of fts3_tokenizer.c **************************************/
91764 /************** Begin file fts3_tokenizer1.c *********************************/
91765 /*
91766 ** 2006 Oct 10
91767 **
91768 ** The author disclaims copyright to this source code.  In place of
91769 ** a legal notice, here is a blessing:
91770 **
91771 **    May you do good and not evil.
91772 **    May you find forgiveness for yourself and forgive others.
91773 **    May you share freely, never taking more than you give.
91774 **
91775 ******************************************************************************
91776 **
91777 ** Implementation of the "simple" full-text-search tokenizer.
91778 */
91779
91780 /*
91781 ** The code in this file is only compiled if:
91782 **
91783 **     * The FTS3 module is being built as an extension
91784 **       (in which case SQLITE_CORE is not defined), or
91785 **
91786 **     * The FTS3 module is being built into the core of
91787 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
91788 */
91789 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
91790
91791
91792
91793
91794 typedef struct simple_tokenizer {
91795   sqlite3_tokenizer base;
91796   char delim[128];             /* flag ASCII delimiters */
91797 } simple_tokenizer;
91798
91799 typedef struct simple_tokenizer_cursor {
91800   sqlite3_tokenizer_cursor base;
91801   const char *pInput;          /* input we are tokenizing */
91802   int nBytes;                  /* size of the input */
91803   int iOffset;                 /* current position in pInput */
91804   int iToken;                  /* index of next token to be returned */
91805   char *pToken;                /* storage for current token */
91806   int nTokenAllocated;         /* space allocated to zToken buffer */
91807 } simple_tokenizer_cursor;
91808
91809
91810 /* Forward declaration */
91811 static const sqlite3_tokenizer_module simpleTokenizerModule;
91812
91813 static int simpleDelim(simple_tokenizer *t, unsigned char c){
91814   return c<0x80 && t->delim[c];
91815 }
91816
91817 /*
91818 ** Create a new tokenizer instance.
91819 */
91820 static int simpleCreate(
91821   int argc, const char * const *argv,
91822   sqlite3_tokenizer **ppTokenizer
91823 ){
91824   simple_tokenizer *t;
91825
91826   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
91827   if( t==NULL ) return SQLITE_NOMEM;
91828   memset(t, 0, sizeof(*t));
91829
91830   /* TODO(shess) Delimiters need to remain the same from run to run,
91831   ** else we need to reindex.  One solution would be a meta-table to
91832   ** track such information in the database, then we'd only want this
91833   ** information on the initial create.
91834   */
91835   if( argc>1 ){
91836     int i, n = strlen(argv[1]);
91837     for(i=0; i<n; i++){
91838       unsigned char ch = argv[1][i];
91839       /* We explicitly don't support UTF-8 delimiters for now. */
91840       if( ch>=0x80 ){
91841         sqlite3_free(t);
91842         return SQLITE_ERROR;
91843       }
91844       t->delim[ch] = 1;
91845     }
91846   } else {
91847     /* Mark non-alphanumeric ASCII characters as delimiters */
91848     int i;
91849     for(i=1; i<0x80; i++){
91850       t->delim[i] = !isalnum(i);
91851     }
91852   }
91853
91854   *ppTokenizer = &t->base;
91855   return SQLITE_OK;
91856 }
91857
91858 /*
91859 ** Destroy a tokenizer
91860 */
91861 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
91862   sqlite3_free(pTokenizer);
91863   return SQLITE_OK;
91864 }
91865
91866 /*
91867 ** Prepare to begin tokenizing a particular string.  The input
91868 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
91869 ** used to incrementally tokenize this string is returned in 
91870 ** *ppCursor.
91871 */
91872 static int simpleOpen(
91873   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
91874   const char *pInput, int nBytes,        /* String to be tokenized */
91875   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
91876 ){
91877   simple_tokenizer_cursor *c;
91878
91879   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
91880   if( c==NULL ) return SQLITE_NOMEM;
91881
91882   c->pInput = pInput;
91883   if( pInput==0 ){
91884     c->nBytes = 0;
91885   }else if( nBytes<0 ){
91886     c->nBytes = (int)strlen(pInput);
91887   }else{
91888     c->nBytes = nBytes;
91889   }
91890   c->iOffset = 0;                 /* start tokenizing at the beginning */
91891   c->iToken = 0;
91892   c->pToken = NULL;               /* no space allocated, yet. */
91893   c->nTokenAllocated = 0;
91894
91895   *ppCursor = &c->base;
91896   return SQLITE_OK;
91897 }
91898
91899 /*
91900 ** Close a tokenization cursor previously opened by a call to
91901 ** simpleOpen() above.
91902 */
91903 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
91904   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
91905   sqlite3_free(c->pToken);
91906   sqlite3_free(c);
91907   return SQLITE_OK;
91908 }
91909
91910 /*
91911 ** Extract the next token from a tokenization cursor.  The cursor must
91912 ** have been opened by a prior call to simpleOpen().
91913 */
91914 static int simpleNext(
91915   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
91916   const char **ppToken,               /* OUT: *ppToken is the token text */
91917   int *pnBytes,                       /* OUT: Number of bytes in token */
91918   int *piStartOffset,                 /* OUT: Starting offset of token */
91919   int *piEndOffset,                   /* OUT: Ending offset of token */
91920   int *piPosition                     /* OUT: Position integer of token */
91921 ){
91922   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
91923   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
91924   unsigned char *p = (unsigned char *)c->pInput;
91925
91926   while( c->iOffset<c->nBytes ){
91927     int iStartOffset;
91928
91929     /* Scan past delimiter characters */
91930     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
91931       c->iOffset++;
91932     }
91933
91934     /* Count non-delimiter characters. */
91935     iStartOffset = c->iOffset;
91936     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
91937       c->iOffset++;
91938     }
91939
91940     if( c->iOffset>iStartOffset ){
91941       int i, n = c->iOffset-iStartOffset;
91942       if( n>c->nTokenAllocated ){
91943         c->nTokenAllocated = n+20;
91944         c->pToken = sqlite3_realloc(c->pToken, c->nTokenAllocated);
91945         if( c->pToken==NULL ) return SQLITE_NOMEM;
91946       }
91947       for(i=0; i<n; i++){
91948         /* TODO(shess) This needs expansion to handle UTF-8
91949         ** case-insensitivity.
91950         */
91951         unsigned char ch = p[iStartOffset+i];
91952         c->pToken[i] = ch<0x80 ? tolower(ch) : ch;
91953       }
91954       *ppToken = c->pToken;
91955       *pnBytes = n;
91956       *piStartOffset = iStartOffset;
91957       *piEndOffset = c->iOffset;
91958       *piPosition = c->iToken++;
91959
91960       return SQLITE_OK;
91961     }
91962   }
91963   return SQLITE_DONE;
91964 }
91965
91966 /*
91967 ** The set of routines that implement the simple tokenizer
91968 */
91969 static const sqlite3_tokenizer_module simpleTokenizerModule = {
91970   0,
91971   simpleCreate,
91972   simpleDestroy,
91973   simpleOpen,
91974   simpleClose,
91975   simpleNext,
91976 };
91977
91978 /*
91979 ** Allocate a new simple tokenizer.  Return a pointer to the new
91980 ** tokenizer in *ppModule
91981 */
91982 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
91983   sqlite3_tokenizer_module const**ppModule
91984 ){
91985   *ppModule = &simpleTokenizerModule;
91986 }
91987
91988 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
91989
91990 /************** End of fts3_tokenizer1.c *************************************/
91991 /************** Begin file rtree.c *******************************************/
91992 /*
91993 ** 2001 September 15
91994 **
91995 ** The author disclaims copyright to this source code.  In place of
91996 ** a legal notice, here is a blessing:
91997 **
91998 **    May you do good and not evil.
91999 **    May you find forgiveness for yourself and forgive others.
92000 **    May you share freely, never taking more than you give.
92001 **
92002 *************************************************************************
92003 ** This file contains code for implementations of the r-tree and r*-tree
92004 ** algorithms packaged as an SQLite virtual table module.
92005 **
92006 ** $Id: rtree.c,v 1.7 2008/07/16 14:43:35 drh Exp $
92007 */
92008
92009 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
92010
92011 /*
92012 ** This file contains an implementation of a couple of different variants
92013 ** of the r-tree algorithm. See the README file for further details. The 
92014 ** same data-structure is used for all, but the algorithms for insert and
92015 ** delete operations vary. The variants used are selected at compile time 
92016 ** by defining the following symbols:
92017 */
92018
92019 /* Either, both or none of the following may be set to activate 
92020 ** r*tree variant algorithms.
92021 */
92022 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
92023 #define VARIANT_RSTARTREE_REINSERT      1
92024
92025 /* 
92026 ** Exactly one of the following must be set to 1.
92027 */
92028 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
92029 #define VARIANT_GUTTMAN_LINEAR_SPLIT    0
92030 #define VARIANT_RSTARTREE_SPLIT         1
92031
92032 #define VARIANT_GUTTMAN_SPLIT \
92033         (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
92034
92035 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
92036   #define PickNext QuadraticPickNext
92037   #define PickSeeds QuadraticPickSeeds
92038   #define AssignCells splitNodeGuttman
92039 #endif
92040 #if VARIANT_GUTTMAN_LINEAR_SPLIT
92041   #define PickNext LinearPickNext
92042   #define PickSeeds LinearPickSeeds
92043   #define AssignCells splitNodeGuttman
92044 #endif
92045 #if VARIANT_RSTARTREE_SPLIT
92046   #define AssignCells splitNodeStartree
92047 #endif
92048
92049
92050 #ifndef SQLITE_CORE
92051   #include "sqlite3ext.h"
92052   SQLITE_EXTENSION_INIT1
92053 #else
92054   #include "sqlite3.h"
92055 #endif
92056
92057
92058 #ifndef SQLITE_AMALGAMATION
92059 typedef sqlite3_int64 i64;
92060 typedef unsigned char u8;
92061 typedef unsigned int u32;
92062 #endif
92063
92064 typedef struct Rtree Rtree;
92065 typedef struct RtreeCursor RtreeCursor;
92066 typedef struct RtreeNode RtreeNode;
92067 typedef struct RtreeCell RtreeCell;
92068 typedef struct RtreeConstraint RtreeConstraint;
92069 typedef union RtreeCoord RtreeCoord;
92070
92071 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
92072 #define RTREE_MAX_DIMENSIONS 5
92073
92074 /* Size of hash table Rtree.aHash. This hash table is not expected to
92075 ** ever contain very many entries, so a fixed number of buckets is 
92076 ** used.
92077 */
92078 #define HASHSIZE 128
92079
92080 /* 
92081 ** An rtree virtual-table object.
92082 */
92083 struct Rtree {
92084   sqlite3_vtab base;
92085   sqlite3 *db;                /* Host database connection */
92086   int iNodeSize;              /* Size in bytes of each node in the node table */
92087   int nDim;                   /* Number of dimensions */
92088   int nBytesPerCell;          /* Bytes consumed per cell */
92089   int iDepth;                 /* Current depth of the r-tree structure */
92090   char *zDb;                  /* Name of database containing r-tree table */
92091   char *zName;                /* Name of r-tree table */ 
92092   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 
92093   int nBusy;                  /* Current number of users of this structure */
92094
92095   /* List of nodes removed during a CondenseTree operation. List is
92096   ** linked together via the pointer normally used for hash chains -
92097   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 
92098   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
92099   */
92100   RtreeNode *pDeleted;
92101   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
92102
92103   /* Statements to read/write/delete a record from xxx_node */
92104   sqlite3_stmt *pReadNode;
92105   sqlite3_stmt *pWriteNode;
92106   sqlite3_stmt *pDeleteNode;
92107
92108   /* Statements to read/write/delete a record from xxx_rowid */
92109   sqlite3_stmt *pReadRowid;
92110   sqlite3_stmt *pWriteRowid;
92111   sqlite3_stmt *pDeleteRowid;
92112
92113   /* Statements to read/write/delete a record from xxx_parent */
92114   sqlite3_stmt *pReadParent;
92115   sqlite3_stmt *pWriteParent;
92116   sqlite3_stmt *pDeleteParent;
92117
92118   int eCoordType;
92119 };
92120
92121 /* Possible values for eCoordType: */
92122 #define RTREE_COORD_REAL32 0
92123 #define RTREE_COORD_INT32  1
92124
92125 /*
92126 ** The minimum number of cells allowed for a node is a third of the 
92127 ** maximum. In Gutman's notation:
92128 **
92129 **     m = M/3
92130 **
92131 ** If an R*-tree "Reinsert" operation is required, the same number of
92132 ** cells are removed from the overfull node and reinserted into the tree.
92133 */
92134 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
92135 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
92136 #define RTREE_MAXCELLS 51
92137
92138 /* 
92139 ** An rtree cursor object.
92140 */
92141 struct RtreeCursor {
92142   sqlite3_vtab_cursor base;
92143   RtreeNode *pNode;                 /* Node cursor is currently pointing at */
92144   int iCell;                        /* Index of current cell in pNode */
92145   int iStrategy;                    /* Copy of idxNum search parameter */
92146   int nConstraint;                  /* Number of entries in aConstraint */
92147   RtreeConstraint *aConstraint;     /* Search constraints. */
92148 };
92149
92150 union RtreeCoord {
92151   float f;
92152   int i;
92153 };
92154
92155 /*
92156 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
92157 ** formatted as a double. This macro assumes that local variable pRtree points
92158 ** to the Rtree structure associated with the RtreeCoord.
92159 */
92160 #define DCOORD(coord) (                           \
92161   (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
92162     ((double)coord.f) :                           \
92163     ((double)coord.i)                             \
92164 )
92165
92166 /*
92167 ** A search constraint.
92168 */
92169 struct RtreeConstraint {
92170   int iCoord;                       /* Index of constrained coordinate */
92171   int op;                           /* Constraining operation */
92172   double rValue;                    /* Constraint value. */
92173 };
92174
92175 /* Possible values for RtreeConstraint.op */
92176 #define RTREE_EQ 0x41
92177 #define RTREE_LE 0x42
92178 #define RTREE_LT 0x43
92179 #define RTREE_GE 0x44
92180 #define RTREE_GT 0x45
92181
92182 /* 
92183 ** An rtree structure node.
92184 **
92185 ** Data format (RtreeNode.zData):
92186 **
92187 **   1. If the node is the root node (node 1), then the first 2 bytes
92188 **      of the node contain the tree depth as a big-endian integer.
92189 **      For non-root nodes, the first 2 bytes are left unused.
92190 **
92191 **   2. The next 2 bytes contain the number of entries currently 
92192 **      stored in the node.
92193 **
92194 **   3. The remainder of the node contains the node entries. Each entry
92195 **      consists of a single 8-byte integer followed by an even number
92196 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
92197 **      of a record. For internal nodes it is the node number of a
92198 **      child page.
92199 */
92200 struct RtreeNode {
92201   RtreeNode *pParent;               /* Parent node */
92202   i64 iNode;
92203   int nRef;
92204   int isDirty;
92205   u8 *zData;
92206   RtreeNode *pNext;                 /* Next node in this hash chain */
92207 };
92208 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
92209
92210 /* 
92211 ** Structure to store a deserialized rtree record.
92212 */
92213 struct RtreeCell {
92214   i64 iRowid;
92215   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
92216 };
92217
92218 #define MAX(x,y) ((x) < (y) ? (y) : (x))
92219 #define MIN(x,y) ((x) > (y) ? (y) : (x))
92220
92221 /*
92222 ** Functions to deserialize a 16 bit integer, 32 bit real number and
92223 ** 64 bit integer. The deserialized value is returned.
92224 */
92225 static int readInt16(u8 *p){
92226   return (p[0]<<8) + p[1];
92227 }
92228 static void readCoord(u8 *p, RtreeCoord *pCoord){
92229   u32 i = (
92230     (((u32)p[0]) << 24) + 
92231     (((u32)p[1]) << 16) + 
92232     (((u32)p[2]) <<  8) + 
92233     (((u32)p[3]) <<  0)
92234   );
92235   *(u32 *)pCoord = i;
92236 }
92237 static i64 readInt64(u8 *p){
92238   return (
92239     (((i64)p[0]) << 56) + 
92240     (((i64)p[1]) << 48) + 
92241     (((i64)p[2]) << 40) + 
92242     (((i64)p[3]) << 32) + 
92243     (((i64)p[4]) << 24) + 
92244     (((i64)p[5]) << 16) + 
92245     (((i64)p[6]) <<  8) + 
92246     (((i64)p[7]) <<  0)
92247   );
92248 }
92249
92250 /*
92251 ** Functions to serialize a 16 bit integer, 32 bit real number and
92252 ** 64 bit integer. The value returned is the number of bytes written
92253 ** to the argument buffer (always 2, 4 and 8 respectively).
92254 */
92255 static int writeInt16(u8 *p, int i){
92256   p[0] = (i>> 8)&0xFF;
92257   p[1] = (i>> 0)&0xFF;
92258   return 2;
92259 }
92260 static int writeCoord(u8 *p, RtreeCoord *pCoord){
92261   u32 i;
92262   assert( sizeof(RtreeCoord)==4 );
92263   assert( sizeof(u32)==4 );
92264   i = *(u32 *)pCoord;
92265   p[0] = (i>>24)&0xFF;
92266   p[1] = (i>>16)&0xFF;
92267   p[2] = (i>> 8)&0xFF;
92268   p[3] = (i>> 0)&0xFF;
92269   return 4;
92270 }
92271 static int writeInt64(u8 *p, i64 i){
92272   p[0] = (i>>56)&0xFF;
92273   p[1] = (i>>48)&0xFF;
92274   p[2] = (i>>40)&0xFF;
92275   p[3] = (i>>32)&0xFF;
92276   p[4] = (i>>24)&0xFF;
92277   p[5] = (i>>16)&0xFF;
92278   p[6] = (i>> 8)&0xFF;
92279   p[7] = (i>> 0)&0xFF;
92280   return 8;
92281 }
92282
92283 /*
92284 ** Increment the reference count of node p.
92285 */
92286 static void nodeReference(RtreeNode *p){
92287   if( p ){
92288     p->nRef++;
92289   }
92290 }
92291
92292 /*
92293 ** Clear the content of node p (set all bytes to 0x00).
92294 */
92295 static void nodeZero(Rtree *pRtree, RtreeNode *p){
92296   if( p ){
92297     memset(&p->zData[2], 0, pRtree->iNodeSize-2);
92298     p->isDirty = 1;
92299   }
92300 }
92301
92302 /*
92303 ** Given a node number iNode, return the corresponding key to use
92304 ** in the Rtree.aHash table.
92305 */
92306 static int nodeHash(i64 iNode){
92307   return (
92308     (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^ 
92309     (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
92310   ) % HASHSIZE;
92311 }
92312
92313 /*
92314 ** Search the node hash table for node iNode. If found, return a pointer
92315 ** to it. Otherwise, return 0.
92316 */
92317 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
92318   RtreeNode *p;
92319   assert( iNode!=0 );
92320   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
92321   return p;
92322 }
92323
92324 /*
92325 ** Add node pNode to the node hash table.
92326 */
92327 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
92328   if( pNode ){
92329     int iHash;
92330     assert( pNode->pNext==0 );
92331     iHash = nodeHash(pNode->iNode);
92332     pNode->pNext = pRtree->aHash[iHash];
92333     pRtree->aHash[iHash] = pNode;
92334   }
92335 }
92336
92337 /*
92338 ** Remove node pNode from the node hash table.
92339 */
92340 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
92341   RtreeNode **pp;
92342   if( pNode->iNode!=0 ){
92343     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
92344     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
92345     *pp = pNode->pNext;
92346     pNode->pNext = 0;
92347   }
92348 }
92349
92350 /*
92351 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
92352 ** indicating that node has not yet been assigned a node number. It is
92353 ** assigned a node number when nodeWrite() is called to write the
92354 ** node contents out to the database.
92355 */
92356 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent, int zero){
92357   RtreeNode *pNode;
92358   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
92359   if( pNode ){
92360     memset(pNode, 0, sizeof(RtreeNode) + (zero?pRtree->iNodeSize:0));
92361     pNode->zData = (u8 *)&pNode[1];
92362     pNode->nRef = 1;
92363     pNode->pParent = pParent;
92364     pNode->isDirty = 1;
92365     nodeReference(pParent);
92366   }
92367   return pNode;
92368 }
92369
92370 /*
92371 ** Obtain a reference to an r-tree node.
92372 */
92373 static int
92374 nodeAcquire(
92375   Rtree *pRtree,             /* R-tree structure */
92376   i64 iNode,                 /* Node number to load */
92377   RtreeNode *pParent,        /* Either the parent node or NULL */
92378   RtreeNode **ppNode         /* OUT: Acquired node */
92379 ){
92380   int rc;
92381   RtreeNode *pNode;
92382
92383   /* Check if the requested node is already in the hash table. If so,
92384   ** increase its reference count and return it.
92385   */
92386   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
92387     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
92388     if( pParent ){
92389       pNode->pParent = pParent;
92390     }
92391     pNode->nRef++;
92392     *ppNode = pNode;
92393     return SQLITE_OK;
92394   }
92395
92396   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
92397   if( !pNode ){
92398     *ppNode = 0;
92399     return SQLITE_NOMEM;
92400   }
92401   pNode->pParent = pParent;
92402   pNode->zData = (u8 *)&pNode[1];
92403   pNode->nRef = 1;
92404   pNode->iNode = iNode;
92405   pNode->isDirty = 0;
92406   pNode->pNext = 0;
92407
92408   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
92409   rc = sqlite3_step(pRtree->pReadNode);
92410   if( rc==SQLITE_ROW ){
92411     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
92412     memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
92413     nodeReference(pParent);
92414   }else{
92415     sqlite3_free(pNode);
92416     pNode = 0;
92417   }
92418
92419   *ppNode = pNode;
92420   rc = sqlite3_reset(pRtree->pReadNode);
92421
92422   if( rc==SQLITE_OK && iNode==1 ){
92423     pRtree->iDepth = readInt16(pNode->zData);
92424   }
92425
92426   assert( (rc==SQLITE_OK && pNode) || (pNode==0 && rc!=SQLITE_OK) );
92427   nodeHashInsert(pRtree, pNode);
92428
92429   return rc;
92430 }
92431
92432 /*
92433 ** Overwrite cell iCell of node pNode with the contents of pCell.
92434 */
92435 static void nodeOverwriteCell(
92436   Rtree *pRtree, 
92437   RtreeNode *pNode,  
92438   RtreeCell *pCell, 
92439   int iCell
92440 ){
92441   int ii;
92442   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
92443   p += writeInt64(p, pCell->iRowid);
92444   for(ii=0; ii<(pRtree->nDim*2); ii++){
92445     p += writeCoord(p, &pCell->aCoord[ii]);
92446   }
92447   pNode->isDirty = 1;
92448 }
92449
92450 /*
92451 ** Remove cell the cell with index iCell from node pNode.
92452 */
92453 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
92454   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
92455   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
92456   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
92457   memmove(pDst, pSrc, nByte);
92458   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
92459   pNode->isDirty = 1;
92460 }
92461
92462 /*
92463 ** Insert the contents of cell pCell into node pNode. If the insert
92464 ** is successful, return SQLITE_OK.
92465 **
92466 ** If there is not enough free space in pNode, return SQLITE_FULL.
92467 */
92468 static int
92469 nodeInsertCell(
92470   Rtree *pRtree, 
92471   RtreeNode *pNode, 
92472   RtreeCell *pCell 
92473 ){
92474   int nCell;                    /* Current number of cells in pNode */
92475   int nMaxCell;                 /* Maximum number of cells for pNode */
92476
92477   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
92478   nCell = NCELL(pNode);
92479
92480   assert(nCell<=nMaxCell);
92481
92482   if( nCell<nMaxCell ){
92483     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
92484     writeInt16(&pNode->zData[2], nCell+1);
92485     pNode->isDirty = 1;
92486   }
92487
92488   return (nCell==nMaxCell);
92489 }
92490
92491 /*
92492 ** If the node is dirty, write it out to the database.
92493 */
92494 static int
92495 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
92496   int rc = SQLITE_OK;
92497   if( pNode->isDirty ){
92498     sqlite3_stmt *p = pRtree->pWriteNode;
92499     if( pNode->iNode ){
92500       sqlite3_bind_int64(p, 1, pNode->iNode);
92501     }else{
92502       sqlite3_bind_null(p, 1);
92503     }
92504     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
92505     sqlite3_step(p);
92506     pNode->isDirty = 0;
92507     rc = sqlite3_reset(p);
92508     if( pNode->iNode==0 && rc==SQLITE_OK ){
92509       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
92510       nodeHashInsert(pRtree, pNode);
92511     }
92512   }
92513   return rc;
92514 }
92515
92516 /*
92517 ** Release a reference to a node. If the node is dirty and the reference
92518 ** count drops to zero, the node data is written to the database.
92519 */
92520 static int
92521 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
92522   int rc = SQLITE_OK;
92523   if( pNode ){
92524     assert( pNode->nRef>0 );
92525     pNode->nRef--;
92526     if( pNode->nRef==0 ){
92527       if( pNode->iNode==1 ){
92528         pRtree->iDepth = -1;
92529       }
92530       if( pNode->pParent ){
92531         rc = nodeRelease(pRtree, pNode->pParent);
92532       }
92533       if( rc==SQLITE_OK ){
92534         rc = nodeWrite(pRtree, pNode);
92535       }
92536       nodeHashDelete(pRtree, pNode);
92537       sqlite3_free(pNode);
92538     }
92539   }
92540   return rc;
92541 }
92542
92543 /*
92544 ** Return the 64-bit integer value associated with cell iCell of
92545 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
92546 ** an internal node, then the 64-bit integer is a child page number.
92547 */
92548 static i64 nodeGetRowid(
92549   Rtree *pRtree, 
92550   RtreeNode *pNode, 
92551   int iCell
92552 ){
92553   assert( iCell<NCELL(pNode) );
92554   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
92555 }
92556
92557 /*
92558 ** Return coordinate iCoord from cell iCell in node pNode.
92559 */
92560 static void nodeGetCoord(
92561   Rtree *pRtree, 
92562   RtreeNode *pNode, 
92563   int iCell,
92564   int iCoord,
92565   RtreeCoord *pCoord           /* Space to write result to */
92566 ){
92567   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
92568 }
92569
92570 /*
92571 ** Deserialize cell iCell of node pNode. Populate the structure pointed
92572 ** to by pCell with the results.
92573 */
92574 static void nodeGetCell(
92575   Rtree *pRtree, 
92576   RtreeNode *pNode, 
92577   int iCell,
92578   RtreeCell *pCell
92579 ){
92580   int ii;
92581   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
92582   for(ii=0; ii<pRtree->nDim*2; ii++){
92583     nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
92584   }
92585 }
92586
92587
92588 /* Forward declaration for the function that does the work of
92589 ** the virtual table module xCreate() and xConnect() methods.
92590 */
92591 static int rtreeInit(
92592   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int, int
92593 );
92594
92595 /* 
92596 ** Rtree virtual table module xCreate method.
92597 */
92598 static int rtreeCreate(
92599   sqlite3 *db,
92600   void *pAux,
92601   int argc, const char *const*argv,
92602   sqlite3_vtab **ppVtab,
92603   char **pzErr
92604 ){
92605   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1, (int)pAux);
92606 }
92607
92608 /* 
92609 ** Rtree virtual table module xConnect method.
92610 */
92611 static int rtreeConnect(
92612   sqlite3 *db,
92613   void *pAux,
92614   int argc, const char *const*argv,
92615   sqlite3_vtab **ppVtab,
92616   char **pzErr
92617 ){
92618   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0, (int)pAux);
92619 }
92620
92621 /*
92622 ** Increment the r-tree reference count.
92623 */
92624 static void rtreeReference(Rtree *pRtree){
92625   pRtree->nBusy++;
92626 }
92627
92628 /*
92629 ** Decrement the r-tree reference count. When the reference count reaches
92630 ** zero the structure is deleted.
92631 */
92632 static void rtreeRelease(Rtree *pRtree){
92633   pRtree->nBusy--;
92634   if( pRtree->nBusy==0 ){
92635     sqlite3_finalize(pRtree->pReadNode);
92636     sqlite3_finalize(pRtree->pWriteNode);
92637     sqlite3_finalize(pRtree->pDeleteNode);
92638     sqlite3_finalize(pRtree->pReadRowid);
92639     sqlite3_finalize(pRtree->pWriteRowid);
92640     sqlite3_finalize(pRtree->pDeleteRowid);
92641     sqlite3_finalize(pRtree->pReadParent);
92642     sqlite3_finalize(pRtree->pWriteParent);
92643     sqlite3_finalize(pRtree->pDeleteParent);
92644     sqlite3_free(pRtree);
92645   }
92646 }
92647
92648 /* 
92649 ** Rtree virtual table module xDisconnect method.
92650 */
92651 static int rtreeDisconnect(sqlite3_vtab *pVtab){
92652   rtreeRelease((Rtree *)pVtab);
92653   return SQLITE_OK;
92654 }
92655
92656 /* 
92657 ** Rtree virtual table module xDestroy method.
92658 */
92659 static int rtreeDestroy(sqlite3_vtab *pVtab){
92660   Rtree *pRtree = (Rtree *)pVtab;
92661   int rc;
92662   char *zCreate = sqlite3_mprintf(
92663     "DROP TABLE '%q'.'%q_node';"
92664     "DROP TABLE '%q'.'%q_rowid';"
92665     "DROP TABLE '%q'.'%q_parent';",
92666     pRtree->zDb, pRtree->zName, 
92667     pRtree->zDb, pRtree->zName,
92668     pRtree->zDb, pRtree->zName
92669   );
92670   if( !zCreate ){
92671     rc = SQLITE_NOMEM;
92672   }else{
92673     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
92674     sqlite3_free(zCreate);
92675   }
92676   if( rc==SQLITE_OK ){
92677     rtreeRelease(pRtree);
92678   }
92679
92680   return rc;
92681 }
92682
92683 /* 
92684 ** Rtree virtual table module xOpen method.
92685 */
92686 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
92687   int rc = SQLITE_NOMEM;
92688   RtreeCursor *pCsr;
92689
92690   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
92691   if( pCsr ){
92692     memset(pCsr, 0, sizeof(RtreeCursor));
92693     pCsr->base.pVtab = pVTab;
92694     rc = SQLITE_OK;
92695   }
92696   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
92697
92698   return rc;
92699 }
92700
92701 /* 
92702 ** Rtree virtual table module xClose method.
92703 */
92704 static int rtreeClose(sqlite3_vtab_cursor *cur){
92705   Rtree *pRtree = (Rtree *)(cur->pVtab);
92706   int rc;
92707   RtreeCursor *pCsr = (RtreeCursor *)cur;
92708   sqlite3_free(pCsr->aConstraint);
92709   rc = nodeRelease(pRtree, pCsr->pNode);
92710   sqlite3_free(pCsr);
92711   return rc;
92712 }
92713
92714 /*
92715 ** Rtree virtual table module xEof method.
92716 **
92717 ** Return non-zero if the cursor does not currently point to a valid 
92718 ** record (i.e if the scan has finished), or zero otherwise.
92719 */
92720 static int rtreeEof(sqlite3_vtab_cursor *cur){
92721   RtreeCursor *pCsr = (RtreeCursor *)cur;
92722   return (pCsr->pNode==0);
92723 }
92724
92725 /* 
92726 ** Cursor pCursor currently points to a cell in a non-leaf page.
92727 ** Return true if the sub-tree headed by the cell is filtered
92728 ** (excluded) by the constraints in the pCursor->aConstraint[] 
92729 ** array, or false otherwise.
92730 */
92731 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor){
92732   RtreeCell cell;
92733   int ii;
92734   int bRes = 0;
92735
92736   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
92737   for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
92738     RtreeConstraint *p = &pCursor->aConstraint[ii];
92739     double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
92740     double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
92741
92742     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
92743         || p->op==RTREE_GT || p->op==RTREE_EQ
92744     );
92745
92746     switch( p->op ){
92747       case RTREE_LE: case RTREE_LT: bRes = p->rValue<cell_min; break;
92748       case RTREE_GE: case RTREE_GT: bRes = p->rValue>cell_max; break;
92749       case RTREE_EQ: 
92750         bRes = (p->rValue>cell_max || p->rValue<cell_min);
92751         break;
92752     }
92753   }
92754
92755   return bRes;
92756 }
92757
92758 /* 
92759 ** Return true if the cell that cursor pCursor currently points to
92760 ** would be filtered (excluded) by the constraints in the 
92761 ** pCursor->aConstraint[] array, or false otherwise.
92762 **
92763 ** This function assumes that the cell is part of a leaf node.
92764 */
92765 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor){
92766   RtreeCell cell;
92767   int ii;
92768
92769   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
92770   for(ii=0; ii<pCursor->nConstraint; ii++){
92771     RtreeConstraint *p = &pCursor->aConstraint[ii];
92772     double coord = DCOORD(cell.aCoord[p->iCoord]);
92773     int res;
92774     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
92775         || p->op==RTREE_GT || p->op==RTREE_EQ
92776     );
92777     switch( p->op ){
92778       case RTREE_LE: res = (coord<=p->rValue); break;
92779       case RTREE_LT: res = (coord<p->rValue);  break;
92780       case RTREE_GE: res = (coord>=p->rValue); break;
92781       case RTREE_GT: res = (coord>p->rValue);  break;
92782       case RTREE_EQ: res = (coord==p->rValue); break;
92783     }
92784
92785     if( !res ) return 1;
92786   }
92787
92788   return 0;
92789 }
92790
92791 /*
92792 ** Cursor pCursor currently points at a node that heads a sub-tree of
92793 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
92794 ** to point to the left-most cell of the sub-tree that matches the 
92795 ** configured constraints.
92796 */
92797 static int descendToCell(
92798   Rtree *pRtree, 
92799   RtreeCursor *pCursor, 
92800   int iHeight,
92801   int *pEof                 /* OUT: Set to true if cannot descend */
92802 ){
92803   int isEof;
92804   int rc;
92805   int ii;
92806   RtreeNode *pChild;
92807   sqlite3_int64 iRowid;
92808
92809   RtreeNode *pSavedNode = pCursor->pNode;
92810   int iSavedCell = pCursor->iCell;
92811
92812   assert( iHeight>=0 );
92813
92814   if( iHeight==0 ){
92815     isEof = testRtreeEntry(pRtree, pCursor);
92816   }else{
92817     isEof = testRtreeCell(pRtree, pCursor);
92818   }
92819   if( isEof || iHeight==0 ){
92820     *pEof = isEof;
92821     return SQLITE_OK;
92822   }
92823
92824   iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
92825   rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
92826   if( rc!=SQLITE_OK ){
92827     return rc;
92828   }
92829
92830   nodeRelease(pRtree, pCursor->pNode);
92831   pCursor->pNode = pChild;
92832   isEof = 1;
92833   for(ii=0; isEof && ii<NCELL(pChild); ii++){
92834     pCursor->iCell = ii;
92835     rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
92836     if( rc!=SQLITE_OK ){
92837       return rc;
92838     }
92839   }
92840
92841   if( isEof ){
92842     assert( pCursor->pNode==pChild );
92843     nodeReference(pSavedNode);
92844     nodeRelease(pRtree, pChild);
92845     pCursor->pNode = pSavedNode;
92846     pCursor->iCell = iSavedCell;
92847   }
92848
92849   *pEof = isEof;
92850   return SQLITE_OK;
92851 }
92852
92853 /*
92854 ** One of the cells in node pNode is guaranteed to have a 64-bit 
92855 ** integer value equal to iRowid. Return the index of this cell.
92856 */
92857 static int nodeRowidIndex(Rtree *pRtree, RtreeNode *pNode, i64 iRowid){
92858   int ii;
92859   for(ii=0; nodeGetRowid(pRtree, pNode, ii)!=iRowid; ii++){
92860     assert( ii<(NCELL(pNode)-1) );
92861   }
92862   return ii;
92863 }
92864
92865 /*
92866 ** Return the index of the cell containing a pointer to node pNode
92867 ** in its parent. If pNode is the root node, return -1.
92868 */
92869 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode){
92870   RtreeNode *pParent = pNode->pParent;
92871   if( pParent ){
92872     return nodeRowidIndex(pRtree, pParent, pNode->iNode);
92873   }
92874   return -1;
92875 }
92876
92877 /* 
92878 ** Rtree virtual table module xNext method.
92879 */
92880 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
92881   Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
92882   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
92883   int rc = SQLITE_OK;
92884
92885   if( pCsr->iStrategy==1 ){
92886     /* This "scan" is a direct lookup by rowid. There is no next entry. */
92887     nodeRelease(pRtree, pCsr->pNode);
92888     pCsr->pNode = 0;
92889   }
92890
92891   else if( pCsr->pNode ){
92892     /* Move to the next entry that matches the configured constraints. */
92893     int iHeight = 0;
92894     while( pCsr->pNode ){
92895       RtreeNode *pNode = pCsr->pNode;
92896       int nCell = NCELL(pNode);
92897       for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
92898         int isEof;
92899         rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
92900         if( rc!=SQLITE_OK || !isEof ){
92901           return rc;
92902         }
92903       }
92904       pCsr->pNode = pNode->pParent;
92905       pCsr->iCell = nodeParentIndex(pRtree, pNode);
92906       nodeReference(pCsr->pNode);
92907       nodeRelease(pRtree, pNode);
92908       iHeight++;
92909     }
92910   }
92911
92912   return rc;
92913 }
92914
92915 /* 
92916 ** Rtree virtual table module xRowid method.
92917 */
92918 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
92919   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
92920   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
92921
92922   assert(pCsr->pNode);
92923   *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
92924
92925   return SQLITE_OK;
92926 }
92927
92928 /* 
92929 ** Rtree virtual table module xColumn method.
92930 */
92931 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
92932   Rtree *pRtree = (Rtree *)cur->pVtab;
92933   RtreeCursor *pCsr = (RtreeCursor *)cur;
92934
92935   if( i==0 ){
92936     i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
92937     sqlite3_result_int64(ctx, iRowid);
92938   }else{
92939     RtreeCoord c;
92940     nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
92941     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
92942       sqlite3_result_double(ctx, c.f);
92943     }else{
92944       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
92945       sqlite3_result_int(ctx, c.i);
92946     }
92947   }
92948
92949   return SQLITE_OK;
92950 }
92951
92952 /* 
92953 ** Use nodeAcquire() to obtain the leaf node containing the record with 
92954 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
92955 ** return SQLITE_OK. If there is no such record in the table, set
92956 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
92957 ** to zero and return an SQLite error code.
92958 */
92959 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
92960   int rc;
92961   *ppLeaf = 0;
92962   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
92963   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
92964     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
92965     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
92966     sqlite3_reset(pRtree->pReadRowid);
92967   }else{
92968     rc = sqlite3_reset(pRtree->pReadRowid);
92969   }
92970   return rc;
92971 }
92972
92973
92974 /* 
92975 ** Rtree virtual table module xFilter method.
92976 */
92977 static int rtreeFilter(
92978   sqlite3_vtab_cursor *pVtabCursor, 
92979   int idxNum, const char *idxStr,
92980   int argc, sqlite3_value **argv
92981 ){
92982   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
92983   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
92984
92985   RtreeNode *pRoot = 0;
92986   int ii;
92987   int rc = SQLITE_OK;
92988
92989   rtreeReference(pRtree);
92990
92991   sqlite3_free(pCsr->aConstraint);
92992   pCsr->aConstraint = 0;
92993   pCsr->iStrategy = idxNum;
92994
92995   if( idxNum==1 ){
92996     /* Special case - lookup by rowid. */
92997     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
92998     i64 iRowid = sqlite3_value_int64(argv[0]);
92999     rc = findLeafNode(pRtree, iRowid, &pLeaf);
93000     pCsr->pNode = pLeaf; 
93001     if( pLeaf && rc==SQLITE_OK ){
93002       pCsr->iCell = nodeRowidIndex(pRtree, pLeaf, iRowid);
93003     }
93004   }else{
93005     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 
93006     ** with the configured constraints. 
93007     */
93008     if( argc>0 ){
93009       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
93010       pCsr->nConstraint = argc;
93011       if( !pCsr->aConstraint ){
93012         rc = SQLITE_NOMEM;
93013       }else{
93014         assert( (idxStr==0 && argc==0) || strlen(idxStr)==argc*2 );
93015         for(ii=0; ii<argc; ii++){
93016           RtreeConstraint *p = &pCsr->aConstraint[ii];
93017           p->op = idxStr[ii*2];
93018           p->iCoord = idxStr[ii*2+1]-'a';
93019           p->rValue = sqlite3_value_double(argv[ii]);
93020         }
93021       }
93022     }
93023   
93024     if( rc==SQLITE_OK ){
93025       pCsr->pNode = 0;
93026       rc = nodeAcquire(pRtree, 1, 0, &pRoot);
93027     }
93028     if( rc==SQLITE_OK ){
93029       int isEof = 1;
93030       int nCell = NCELL(pRoot);
93031       pCsr->pNode = pRoot;
93032       for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
93033         assert( pCsr->pNode==pRoot );
93034         rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
93035         if( !isEof ){
93036           break;
93037         }
93038       }
93039       if( rc==SQLITE_OK && isEof ){
93040         assert( pCsr->pNode==pRoot );
93041         nodeRelease(pRtree, pRoot);
93042         pCsr->pNode = 0;
93043       }
93044       assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
93045     }
93046   }
93047
93048   rtreeRelease(pRtree);
93049   return rc;
93050 }
93051
93052 /*
93053 ** Rtree virtual table module xBestIndex method. There are three
93054 ** table scan strategies to choose from (in order from most to 
93055 ** least desirable):
93056 **
93057 **   idxNum     idxStr        Strategy
93058 **   ------------------------------------------------
93059 **     1        Unused        Direct lookup by rowid.
93060 **     2        See below     R-tree query.
93061 **     3        Unused        Full table scan.
93062 **   ------------------------------------------------
93063 **
93064 ** If strategy 1 or 3 is used, then idxStr is not meaningful. If strategy
93065 ** 2 is used, idxStr is formatted to contain 2 bytes for each 
93066 ** constraint used. The first two bytes of idxStr correspond to 
93067 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
93068 ** (argvIndex==1) etc.
93069 **
93070 ** The first of each pair of bytes in idxStr identifies the constraint
93071 ** operator as follows:
93072 **
93073 **   Operator    Byte Value
93074 **   ----------------------
93075 **      =        0x41 ('A')
93076 **     <=        0x42 ('B')
93077 **      <        0x43 ('C')
93078 **     >=        0x44 ('D')
93079 **      >        0x45 ('E')
93080 **   ----------------------
93081 **
93082 ** The second of each pair of bytes identifies the coordinate column
93083 ** to which the constraint applies. The leftmost coordinate column
93084 ** is 'a', the second from the left 'b' etc.
93085 */
93086 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
93087   int rc = SQLITE_OK;
93088   int ii, cCol;
93089
93090   int iIdx = 0;
93091   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
93092   memset(zIdxStr, 0, sizeof(zIdxStr));
93093
93094   assert( pIdxInfo->idxStr==0 );
93095   for(ii=0; ii<pIdxInfo->nConstraint; ii++){
93096     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
93097
93098     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
93099       /* We have an equality constraint on the rowid. Use strategy 1. */
93100       int jj;
93101       for(jj=0; jj<ii; jj++){
93102         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
93103         pIdxInfo->aConstraintUsage[jj].omit = 0;
93104       }
93105       pIdxInfo->idxNum = 1;
93106       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
93107       pIdxInfo->aConstraintUsage[jj].omit = 1;
93108       return SQLITE_OK;
93109     }
93110
93111     if( p->usable && p->iColumn>0 ){
93112       u8 op = 0;
93113       switch( p->op ){
93114         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
93115         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
93116         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
93117         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
93118         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
93119       }
93120       if( op ){
93121         /* Make sure this particular constraint has not been used before.
93122         ** If it has been used before, ignore it.
93123         **
93124         ** A <= or < can be used if there is a prior >= or >.
93125         ** A >= or > can be used if there is a prior < or <=.
93126         ** A <= or < is disqualified if there is a prior <=, <, or ==.
93127         ** A >= or > is disqualified if there is a prior >=, >, or ==.
93128         ** A == is disqualifed if there is any prior constraint.
93129         */
93130         int j, opmsk;
93131         static const unsigned char compatible[] = { 0, 0, 1, 1, 2, 2 };
93132         assert( compatible[RTREE_EQ & 7]==0 );
93133         assert( compatible[RTREE_LT & 7]==1 );
93134         assert( compatible[RTREE_LE & 7]==1 );
93135         assert( compatible[RTREE_GT & 7]==2 );
93136         assert( compatible[RTREE_GE & 7]==2 );
93137         cCol = p->iColumn - 1 + 'a';
93138         opmsk = compatible[op & 7];
93139         for(j=0; j<iIdx; j+=2){
93140           if( zIdxStr[j+1]==cCol && (compatible[zIdxStr[j] & 7] & opmsk)!=0 ){
93141             op = 0;
93142             break;
93143           }
93144         }
93145       }
93146       if( op ){
93147         assert( iIdx<sizeof(zIdxStr)-1 );
93148         zIdxStr[iIdx++] = op;
93149         zIdxStr[iIdx++] = cCol;
93150         pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
93151         pIdxInfo->aConstraintUsage[ii].omit = 1;
93152       }
93153     }
93154   }
93155
93156   pIdxInfo->idxNum = 2;
93157   pIdxInfo->needToFreeIdxStr = 1;
93158   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
93159     return SQLITE_NOMEM;
93160   }
93161   return rc;
93162 }
93163
93164 /*
93165 ** Return the N-dimensional volumn of the cell stored in *p.
93166 */
93167 static float cellArea(Rtree *pRtree, RtreeCell *p){
93168   float area = 1.0;
93169   int ii;
93170   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
93171     area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
93172   }
93173   return area;
93174 }
93175
93176 /*
93177 ** Return the margin length of cell p. The margin length is the sum
93178 ** of the objects size in each dimension.
93179 */
93180 static float cellMargin(Rtree *pRtree, RtreeCell *p){
93181   float margin = 0.0;
93182   int ii;
93183   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
93184     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
93185   }
93186   return margin;
93187 }
93188
93189 /*
93190 ** Store the union of cells p1 and p2 in p1.
93191 */
93192 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
93193   int ii;
93194   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
93195     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
93196       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
93197       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
93198     }
93199   }else{
93200     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
93201       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
93202       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
93203     }
93204   }
93205 }
93206
93207 /*
93208 ** Return the amount cell p would grow by if it were unioned with pCell.
93209 */
93210 static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
93211   float area;
93212   RtreeCell cell;
93213   memcpy(&cell, p, sizeof(RtreeCell));
93214   area = cellArea(pRtree, &cell);
93215   cellUnion(pRtree, &cell, pCell);
93216   return (cellArea(pRtree, &cell)-area);
93217 }
93218
93219 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
93220 static float cellOverlap(
93221   Rtree *pRtree, 
93222   RtreeCell *p, 
93223   RtreeCell *aCell, 
93224   int nCell, 
93225   int iExclude
93226 ){
93227   int ii;
93228   float overlap = 0.0;
93229   for(ii=0; ii<nCell; ii++){
93230     if( ii!=iExclude ){
93231       int jj;
93232       float o = 1.0;
93233       for(jj=0; jj<(pRtree->nDim*2); jj+=2){
93234         double x1;
93235         double x2;
93236
93237         x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
93238         x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
93239
93240         if( x2<x1 ){
93241           o = 0.0;
93242           break;
93243         }else{
93244           o = o * (x2-x1);
93245         }
93246       }
93247       overlap += o;
93248     }
93249   }
93250   return overlap;
93251 }
93252 #endif
93253
93254 #if VARIANT_RSTARTREE_CHOOSESUBTREE
93255 static float cellOverlapEnlargement(
93256   Rtree *pRtree, 
93257   RtreeCell *p, 
93258   RtreeCell *pInsert, 
93259   RtreeCell *aCell, 
93260   int nCell, 
93261   int iExclude
93262 ){
93263   float before;
93264   float after;
93265   before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
93266   cellUnion(pRtree, p, pInsert);
93267   after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
93268   return after-before;
93269 }
93270 #endif
93271
93272
93273 /*
93274 ** This function implements the ChooseLeaf algorithm from Gutman[84].
93275 ** ChooseSubTree in r*tree terminology.
93276 */
93277 static int ChooseLeaf(
93278   Rtree *pRtree,               /* Rtree table */
93279   RtreeCell *pCell,            /* Cell to insert into rtree */
93280   int iHeight,                 /* Height of sub-tree rooted at pCell */
93281   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
93282 ){
93283   int rc;
93284   int ii;
93285   RtreeNode *pNode;
93286   rc = nodeAcquire(pRtree, 1, 0, &pNode);
93287
93288   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
93289     int iCell;
93290     sqlite3_int64 iBest;
93291
93292     float fMinGrowth;
93293     float fMinArea;
93294     float fMinOverlap;
93295
93296     int nCell = NCELL(pNode);
93297     RtreeCell cell;
93298     RtreeNode *pChild;
93299
93300     RtreeCell *aCell = 0;
93301
93302 #if VARIANT_RSTARTREE_CHOOSESUBTREE
93303     if( ii==(pRtree->iDepth-1) ){
93304       int jj;
93305       aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
93306       if( !aCell ){
93307         rc = SQLITE_NOMEM;
93308         nodeRelease(pRtree, pNode);
93309         pNode = 0;
93310         continue;
93311       }
93312       for(jj=0; jj<nCell; jj++){
93313         nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
93314       }
93315     }
93316 #endif
93317
93318     /* Select the child node which will be enlarged the least if pCell
93319     ** is inserted into it. Resolve ties by choosing the entry with
93320     ** the smallest area.
93321     */
93322     for(iCell=0; iCell<nCell; iCell++){
93323       float growth;
93324       float area;
93325       float overlap = 0.0;
93326       nodeGetCell(pRtree, pNode, iCell, &cell);
93327       growth = cellGrowth(pRtree, &cell, pCell);
93328       area = cellArea(pRtree, &cell);
93329 #if VARIANT_RSTARTREE_CHOOSESUBTREE
93330       if( ii==(pRtree->iDepth-1) ){
93331         overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
93332       }
93333 #endif
93334       if( (iCell==0) 
93335        || (overlap<fMinOverlap) 
93336        || (overlap==fMinOverlap && growth<fMinGrowth)
93337        || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
93338       ){
93339         fMinOverlap = overlap;
93340         fMinGrowth = growth;
93341         fMinArea = area;
93342         iBest = cell.iRowid;
93343       }
93344     }
93345
93346     sqlite3_free(aCell);
93347     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
93348     nodeRelease(pRtree, pNode);
93349     pNode = pChild;
93350   }
93351
93352   *ppLeaf = pNode;
93353   return rc;
93354 }
93355
93356 /*
93357 ** A cell with the same content as pCell has just been inserted into
93358 ** the node pNode. This function updates the bounding box cells in
93359 ** all ancestor elements.
93360 */
93361 static void AdjustTree(
93362   Rtree *pRtree,                    /* Rtree table */
93363   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
93364   RtreeCell *pCell                  /* This cell was just inserted */
93365 ){
93366   RtreeNode *p = pNode;
93367   while( p->pParent ){
93368     RtreeCell cell;
93369     RtreeNode *pParent = p->pParent;
93370     int iCell = nodeParentIndex(pRtree, p);
93371
93372     nodeGetCell(pRtree, pParent, iCell, &cell);
93373     if( cellGrowth(pRtree, &cell, pCell)>0.0 ){
93374       cellUnion(pRtree, &cell, pCell);
93375       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
93376     }
93377  
93378     p = pParent;
93379   }
93380 }
93381
93382 /*
93383 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
93384 */
93385 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
93386   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
93387   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
93388   sqlite3_step(pRtree->pWriteRowid);
93389   return sqlite3_reset(pRtree->pWriteRowid);
93390 }
93391
93392 /*
93393 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
93394 */
93395 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
93396   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
93397   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
93398   sqlite3_step(pRtree->pWriteParent);
93399   return sqlite3_reset(pRtree->pWriteParent);
93400 }
93401
93402 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
93403
93404 #if VARIANT_GUTTMAN_LINEAR_SPLIT
93405 /*
93406 ** Implementation of the linear variant of the PickNext() function from
93407 ** Guttman[84].
93408 */
93409 static RtreeCell *LinearPickNext(
93410   Rtree *pRtree,
93411   RtreeCell *aCell, 
93412   int nCell, 
93413   RtreeCell *pLeftBox, 
93414   RtreeCell *pRightBox,
93415   int *aiUsed
93416 ){
93417   int ii;
93418   for(ii=0; aiUsed[ii]; ii++);
93419   aiUsed[ii] = 1;
93420   return &aCell[ii];
93421 }
93422
93423 /*
93424 ** Implementation of the linear variant of the PickSeeds() function from
93425 ** Guttman[84].
93426 */
93427 static void LinearPickSeeds(
93428   Rtree *pRtree,
93429   RtreeCell *aCell, 
93430   int nCell, 
93431   int *piLeftSeed, 
93432   int *piRightSeed
93433 ){
93434   int i;
93435   int iLeftSeed = 0;
93436   int iRightSeed = 1;
93437   float maxNormalInnerWidth = 0.0;
93438
93439   /* Pick two "seed" cells from the array of cells. The algorithm used
93440   ** here is the LinearPickSeeds algorithm from Gutman[1984]. The 
93441   ** indices of the two seed cells in the array are stored in local
93442   ** variables iLeftSeek and iRightSeed.
93443   */
93444   for(i=0; i<pRtree->nDim; i++){
93445     float x1 = aCell[0].aCoord[i*2];
93446     float x2 = aCell[0].aCoord[i*2+1];
93447     float x3 = x1;
93448     float x4 = x2;
93449     int jj;
93450
93451     int iCellLeft = 0;
93452     int iCellRight = 0;
93453
93454     for(jj=1; jj<nCell; jj++){
93455       float left = aCell[jj].aCoord[i*2];
93456       float right = aCell[jj].aCoord[i*2+1];
93457
93458       if( left<x1 ) x1 = left;
93459       if( right>x4 ) x4 = right;
93460       if( left>x3 ){
93461         x3 = left;
93462         iCellRight = jj;
93463       }
93464       if( right<x2 ){
93465         x2 = right;
93466         iCellLeft = jj;
93467       }
93468     }
93469
93470     if( x4!=x1 ){
93471       float normalwidth = (x3 - x2) / (x4 - x1);
93472       if( normalwidth>maxNormalInnerWidth ){
93473         iLeftSeed = iCellLeft;
93474         iRightSeed = iCellRight;
93475       }
93476     }
93477   }
93478
93479   *piLeftSeed = iLeftSeed;
93480   *piRightSeed = iRightSeed;
93481 }
93482 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
93483
93484 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
93485 /*
93486 ** Implementation of the quadratic variant of the PickNext() function from
93487 ** Guttman[84].
93488 */
93489 static RtreeCell *QuadraticPickNext(
93490   Rtree *pRtree,
93491   RtreeCell *aCell, 
93492   int nCell, 
93493   RtreeCell *pLeftBox, 
93494   RtreeCell *pRightBox,
93495   int *aiUsed
93496 ){
93497   #define FABS(a) ((a)<0.0?-1.0*(a):(a))
93498
93499   int iSelect = -1;
93500   float fDiff;
93501   int ii;
93502   for(ii=0; ii<nCell; ii++){
93503     if( aiUsed[ii]==0 ){
93504       float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
93505       float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
93506       float diff = FABS(right-left);
93507       if( iSelect<0 || diff>fDiff ){
93508         fDiff = diff;
93509         iSelect = ii;
93510       }
93511     }
93512   }
93513   aiUsed[iSelect] = 1;
93514   return &aCell[iSelect];
93515 }
93516
93517 /*
93518 ** Implementation of the quadratic variant of the PickSeeds() function from
93519 ** Guttman[84].
93520 */
93521 static void QuadraticPickSeeds(
93522   Rtree *pRtree,
93523   RtreeCell *aCell, 
93524   int nCell, 
93525   int *piLeftSeed, 
93526   int *piRightSeed
93527 ){
93528   int ii;
93529   int jj;
93530
93531   int iLeftSeed = 0;
93532   int iRightSeed = 1;
93533   float fWaste = 0.0;
93534
93535   for(ii=0; ii<nCell; ii++){
93536     for(jj=ii+1; jj<nCell; jj++){
93537       float right = cellArea(pRtree, &aCell[jj]);
93538       float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
93539       float waste = growth - right;
93540
93541       if( waste>fWaste ){
93542         iLeftSeed = ii;
93543         iRightSeed = jj;
93544         fWaste = waste;
93545       }
93546     }
93547   }
93548
93549   *piLeftSeed = iLeftSeed;
93550   *piRightSeed = iRightSeed;
93551 }
93552 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
93553
93554 /*
93555 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
93556 ** nIdx. The aIdx array contains the set of integers from 0 to 
93557 ** (nIdx-1) in no particular order. This function sorts the values
93558 ** in aIdx according to the indexed values in aDistance. For
93559 ** example, assuming the inputs:
93560 **
93561 **   aIdx      = { 0,   1,   2,   3 }
93562 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
93563 **
93564 ** this function sets the aIdx array to contain:
93565 **
93566 **   aIdx      = { 0,   1,   2,   3 }
93567 **
93568 ** The aSpare array is used as temporary working space by the
93569 ** sorting algorithm.
93570 */
93571 static void SortByDistance(
93572   int *aIdx, 
93573   int nIdx, 
93574   float *aDistance, 
93575   int *aSpare
93576 ){
93577   if( nIdx>1 ){
93578     int iLeft = 0;
93579     int iRight = 0;
93580
93581     int nLeft = nIdx/2;
93582     int nRight = nIdx-nLeft;
93583     int *aLeft = aIdx;
93584     int *aRight = &aIdx[nLeft];
93585
93586     SortByDistance(aLeft, nLeft, aDistance, aSpare);
93587     SortByDistance(aRight, nRight, aDistance, aSpare);
93588
93589     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
93590     aLeft = aSpare;
93591
93592     while( iLeft<nLeft || iRight<nRight ){
93593       if( iLeft==nLeft ){
93594         aIdx[iLeft+iRight] = aRight[iRight];
93595         iRight++;
93596       }else if( iRight==nRight ){
93597         aIdx[iLeft+iRight] = aLeft[iLeft];
93598         iLeft++;
93599       }else{
93600         float fLeft = aDistance[aLeft[iLeft]];
93601         float fRight = aDistance[aRight[iRight]];
93602         if( fLeft<fRight ){
93603           aIdx[iLeft+iRight] = aLeft[iLeft];
93604           iLeft++;
93605         }else{
93606           aIdx[iLeft+iRight] = aRight[iRight];
93607           iRight++;
93608         }
93609       }
93610     }
93611
93612 #if 0
93613     /* Check that the sort worked */
93614     {
93615       int jj;
93616       for(jj=1; jj<nIdx; jj++){
93617         float left = aDistance[aIdx[jj-1]];
93618         float right = aDistance[aIdx[jj]];
93619         assert( left<=right );
93620       }
93621     }
93622 #endif
93623   }
93624 }
93625
93626 /*
93627 ** Arguments aIdx, aCell and aSpare all point to arrays of size
93628 ** nIdx. The aIdx array contains the set of integers from 0 to 
93629 ** (nIdx-1) in no particular order. This function sorts the values
93630 ** in aIdx according to dimension iDim of the cells in aCell. The
93631 ** minimum value of dimension iDim is considered first, the
93632 ** maximum used to break ties.
93633 **
93634 ** The aSpare array is used as temporary working space by the
93635 ** sorting algorithm.
93636 */
93637 static void SortByDimension(
93638   Rtree *pRtree,
93639   int *aIdx, 
93640   int nIdx, 
93641   int iDim, 
93642   RtreeCell *aCell, 
93643   int *aSpare
93644 ){
93645   if( nIdx>1 ){
93646
93647     int iLeft = 0;
93648     int iRight = 0;
93649
93650     int nLeft = nIdx/2;
93651     int nRight = nIdx-nLeft;
93652     int *aLeft = aIdx;
93653     int *aRight = &aIdx[nLeft];
93654
93655     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
93656     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
93657
93658     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
93659     aLeft = aSpare;
93660     while( iLeft<nLeft || iRight<nRight ){
93661       double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
93662       double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
93663       double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
93664       double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
93665       if( (iLeft!=nLeft) && ((iRight==nRight)
93666        || (xleft1<xright1)
93667        || (xleft1==xright1 && xleft2<xright2)
93668       )){
93669         aIdx[iLeft+iRight] = aLeft[iLeft];
93670         iLeft++;
93671       }else{
93672         aIdx[iLeft+iRight] = aRight[iRight];
93673         iRight++;
93674       }
93675     }
93676
93677 #if 0
93678     /* Check that the sort worked */
93679     {
93680       int jj;
93681       for(jj=1; jj<nIdx; jj++){
93682         float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
93683         float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
93684         float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
93685         float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
93686         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
93687       }
93688     }
93689 #endif
93690   }
93691 }
93692
93693 #if VARIANT_RSTARTREE_SPLIT
93694 /*
93695 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
93696 */
93697 static int splitNodeStartree(
93698   Rtree *pRtree,
93699   RtreeCell *aCell,
93700   int nCell,
93701   RtreeNode *pLeft,
93702   RtreeNode *pRight,
93703   RtreeCell *pBboxLeft,
93704   RtreeCell *pBboxRight
93705 ){
93706   int **aaSorted;
93707   int *aSpare;
93708   int ii;
93709
93710   int iBestDim;
93711   int iBestSplit;
93712   float fBestMargin;
93713
93714   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
93715
93716   aaSorted = (int **)sqlite3_malloc(nByte);
93717   if( !aaSorted ){
93718     return SQLITE_NOMEM;
93719   }
93720
93721   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
93722   memset(aaSorted, 0, nByte);
93723   for(ii=0; ii<pRtree->nDim; ii++){
93724     int jj;
93725     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
93726     for(jj=0; jj<nCell; jj++){
93727       aaSorted[ii][jj] = jj;
93728     }
93729     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
93730   }
93731
93732   for(ii=0; ii<pRtree->nDim; ii++){
93733     float margin = 0.0;
93734     float fBestOverlap;
93735     float fBestArea;
93736     int iBestLeft;
93737     int nLeft;
93738
93739     for(
93740       nLeft=RTREE_MINCELLS(pRtree); 
93741       nLeft<=(nCell-RTREE_MINCELLS(pRtree)); 
93742       nLeft++
93743     ){
93744       RtreeCell left;
93745       RtreeCell right;
93746       int kk;
93747       float overlap;
93748       float area;
93749
93750       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
93751       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
93752       for(kk=1; kk<(nCell-1); kk++){
93753         if( kk<nLeft ){
93754           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
93755         }else{
93756           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
93757         }
93758       }
93759       margin += cellMargin(pRtree, &left);
93760       margin += cellMargin(pRtree, &right);
93761       overlap = cellOverlap(pRtree, &left, &right, 1, -1);
93762       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
93763       if( (nLeft==RTREE_MINCELLS(pRtree))
93764        || (overlap<fBestOverlap)
93765        || (overlap==fBestOverlap && area<fBestArea)
93766       ){
93767         iBestLeft = nLeft;
93768         fBestOverlap = overlap;
93769         fBestArea = area;
93770       }
93771     }
93772
93773     if( ii==0 || margin<fBestMargin ){
93774       iBestDim = ii;
93775       fBestMargin = margin;
93776       iBestSplit = iBestLeft;
93777     }
93778   }
93779
93780   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
93781   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
93782   for(ii=0; ii<nCell; ii++){
93783     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
93784     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
93785     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
93786     nodeInsertCell(pRtree, pTarget, pCell);
93787     cellUnion(pRtree, pBbox, pCell);
93788   }
93789
93790   sqlite3_free(aaSorted);
93791   return SQLITE_OK;
93792 }
93793 #endif
93794
93795 #if VARIANT_GUTTMAN_SPLIT
93796 /*
93797 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
93798 */
93799 static int splitNodeGuttman(
93800   Rtree *pRtree,
93801   RtreeCell *aCell,
93802   int nCell,
93803   RtreeNode *pLeft,
93804   RtreeNode *pRight,
93805   RtreeCell *pBboxLeft,
93806   RtreeCell *pBboxRight
93807 ){
93808   int iLeftSeed = 0;
93809   int iRightSeed = 1;
93810   int *aiUsed;
93811   int i;
93812
93813   aiUsed = sqlite3_malloc(sizeof(int)*nCell);
93814   memset(aiUsed, 0, sizeof(int)*nCell);
93815
93816   PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
93817
93818   memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
93819   memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
93820   nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
93821   nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
93822   aiUsed[iLeftSeed] = 1;
93823   aiUsed[iRightSeed] = 1;
93824
93825   for(i=nCell-2; i>0; i--){
93826     RtreeCell *pNext;
93827     pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
93828     float diff =  
93829       cellGrowth(pRtree, pBboxLeft, pNext) - 
93830       cellGrowth(pRtree, pBboxRight, pNext)
93831     ;
93832     if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
93833      || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
93834     ){
93835       nodeInsertCell(pRtree, pRight, pNext);
93836       cellUnion(pRtree, pBboxRight, pNext);
93837     }else{
93838       nodeInsertCell(pRtree, pLeft, pNext);
93839       cellUnion(pRtree, pBboxLeft, pNext);
93840     }
93841   }
93842
93843   sqlite3_free(aiUsed);
93844   return SQLITE_OK;
93845 }
93846 #endif
93847
93848 static int updateMapping(
93849   Rtree *pRtree, 
93850   i64 iRowid, 
93851   RtreeNode *pNode, 
93852   int iHeight
93853 ){
93854   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
93855   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
93856   if( iHeight>0 ){
93857     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
93858     if( pChild ){
93859       nodeRelease(pRtree, pChild->pParent);
93860       nodeReference(pNode);
93861       pChild->pParent = pNode;
93862     }
93863   }
93864   return xSetMapping(pRtree, iRowid, pNode->iNode);
93865 }
93866
93867 static int SplitNode(
93868   Rtree *pRtree,
93869   RtreeNode *pNode,
93870   RtreeCell *pCell,
93871   int iHeight
93872 ){
93873   int i;
93874   int newCellIsRight = 0;
93875
93876   int rc = SQLITE_OK;
93877   int nCell = NCELL(pNode);
93878   RtreeCell *aCell;
93879   int *aiUsed;
93880
93881   RtreeNode *pLeft = 0;
93882   RtreeNode *pRight = 0;
93883
93884   RtreeCell leftbbox;
93885   RtreeCell rightbbox;
93886
93887   /* Allocate an array and populate it with a copy of pCell and 
93888   ** all cells from node pLeft. Then zero the original node.
93889   */
93890   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
93891   if( !aCell ){
93892     rc = SQLITE_NOMEM;
93893     goto splitnode_out;
93894   }
93895   aiUsed = (int *)&aCell[nCell+1];
93896   memset(aiUsed, 0, sizeof(int)*(nCell+1));
93897   for(i=0; i<nCell; i++){
93898     nodeGetCell(pRtree, pNode, i, &aCell[i]);
93899   }
93900   nodeZero(pRtree, pNode);
93901   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
93902   nCell++;
93903
93904   if( pNode->iNode==1 ){
93905     pRight = nodeNew(pRtree, pNode, 1);
93906     pLeft = nodeNew(pRtree, pNode, 1);
93907     pRtree->iDepth++;
93908     pNode->isDirty = 1;
93909     writeInt16(pNode->zData, pRtree->iDepth);
93910   }else{
93911     pLeft = pNode;
93912     pRight = nodeNew(pRtree, pLeft->pParent, 1);
93913     nodeReference(pLeft);
93914   }
93915
93916   if( !pLeft || !pRight ){
93917     rc = SQLITE_NOMEM;
93918     goto splitnode_out;
93919   }
93920
93921   memset(pLeft->zData, 0, pRtree->iNodeSize);
93922   memset(pRight->zData, 0, pRtree->iNodeSize);
93923
93924   rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
93925   if( rc!=SQLITE_OK ){
93926     goto splitnode_out;
93927   }
93928
93929   /* Ensure both child nodes have node numbers assigned to them. */
93930   if( (0==pRight->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pRight)))
93931    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
93932   ){
93933     goto splitnode_out;
93934   }
93935
93936   rightbbox.iRowid = pRight->iNode;
93937   leftbbox.iRowid = pLeft->iNode;
93938
93939   if( pNode->iNode==1 ){
93940     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
93941     if( rc!=SQLITE_OK ){
93942       goto splitnode_out;
93943     }
93944   }else{
93945     RtreeNode *pParent = pLeft->pParent;
93946     int iCell = nodeParentIndex(pRtree, pLeft);
93947     nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
93948     AdjustTree(pRtree, pParent, &leftbbox);
93949   }
93950   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
93951     goto splitnode_out;
93952   }
93953
93954   for(i=0; i<NCELL(pRight); i++){
93955     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
93956     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
93957     if( iRowid==pCell->iRowid ){
93958       newCellIsRight = 1;
93959     }
93960     if( rc!=SQLITE_OK ){
93961       goto splitnode_out;
93962     }
93963   }
93964   if( pNode->iNode==1 ){
93965     for(i=0; i<NCELL(pLeft); i++){
93966       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
93967       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
93968       if( rc!=SQLITE_OK ){
93969         goto splitnode_out;
93970       }
93971     }
93972   }else if( newCellIsRight==0 ){
93973     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
93974   }
93975
93976   if( rc==SQLITE_OK ){
93977     rc = nodeRelease(pRtree, pRight);
93978     pRight = 0;
93979   }
93980   if( rc==SQLITE_OK ){
93981     rc = nodeRelease(pRtree, pLeft);
93982     pLeft = 0;
93983   }
93984
93985 splitnode_out:
93986   nodeRelease(pRtree, pRight);
93987   nodeRelease(pRtree, pLeft);
93988   sqlite3_free(aCell);
93989   return rc;
93990 }
93991
93992 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
93993   int rc = SQLITE_OK;
93994   if( pLeaf->iNode!=1 && pLeaf->pParent==0 ){
93995     sqlite3_bind_int64(pRtree->pReadParent, 1, pLeaf->iNode);
93996     if( sqlite3_step(pRtree->pReadParent)==SQLITE_ROW ){
93997       i64 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
93998       rc = nodeAcquire(pRtree, iNode, 0, &pLeaf->pParent);
93999     }else{
94000       rc = SQLITE_ERROR;
94001     }
94002     sqlite3_reset(pRtree->pReadParent);
94003     if( rc==SQLITE_OK ){
94004       rc = fixLeafParent(pRtree, pLeaf->pParent);
94005     }
94006   }
94007   return rc;
94008 }
94009
94010 static int deleteCell(Rtree *, RtreeNode *, int, int);
94011
94012 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
94013   int rc;
94014   RtreeNode *pParent;
94015   int iCell;
94016
94017   assert( pNode->nRef==1 );
94018
94019   /* Remove the entry in the parent cell. */
94020   iCell = nodeParentIndex(pRtree, pNode);
94021   pParent = pNode->pParent;
94022   pNode->pParent = 0;
94023   if( SQLITE_OK!=(rc = deleteCell(pRtree, pParent, iCell, iHeight+1)) 
94024    || SQLITE_OK!=(rc = nodeRelease(pRtree, pParent))
94025   ){
94026     return rc;
94027   }
94028
94029   /* Remove the xxx_node entry. */
94030   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
94031   sqlite3_step(pRtree->pDeleteNode);
94032   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
94033     return rc;
94034   }
94035
94036   /* Remove the xxx_parent entry. */
94037   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
94038   sqlite3_step(pRtree->pDeleteParent);
94039   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
94040     return rc;
94041   }
94042   
94043   /* Remove the node from the in-memory hash table and link it into
94044   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
94045   */
94046   nodeHashDelete(pRtree, pNode);
94047   pNode->iNode = iHeight;
94048   pNode->pNext = pRtree->pDeleted;
94049   pNode->nRef++;
94050   pRtree->pDeleted = pNode;
94051
94052   return SQLITE_OK;
94053 }
94054
94055 static void fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
94056   RtreeNode *pParent = pNode->pParent;
94057   if( pParent ){
94058     int ii; 
94059     int nCell = NCELL(pNode);
94060     RtreeCell box;                            /* Bounding box for pNode */
94061     nodeGetCell(pRtree, pNode, 0, &box);
94062     for(ii=1; ii<nCell; ii++){
94063       RtreeCell cell;
94064       nodeGetCell(pRtree, pNode, ii, &cell);
94065       cellUnion(pRtree, &box, &cell);
94066     }
94067     box.iRowid = pNode->iNode;
94068     ii = nodeParentIndex(pRtree, pNode);
94069     nodeOverwriteCell(pRtree, pParent, &box, ii);
94070     fixBoundingBox(pRtree, pParent);
94071   }
94072 }
94073
94074 /*
94075 ** Delete the cell at index iCell of node pNode. After removing the
94076 ** cell, adjust the r-tree data structure if required.
94077 */
94078 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
94079   int rc;
94080
94081   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
94082     return rc;
94083   }
94084
94085   /* Remove the cell from the node. This call just moves bytes around
94086   ** the in-memory node image, so it cannot fail.
94087   */
94088   nodeDeleteCell(pRtree, pNode, iCell);
94089
94090   /* If the node is not the tree root and now has less than the minimum
94091   ** number of cells, remove it from the tree. Otherwise, update the
94092   ** cell in the parent node so that it tightly contains the updated
94093   ** node.
94094   */
94095   if( pNode->iNode!=1 ){
94096     RtreeNode *pParent = pNode->pParent;
94097     if( (pParent->iNode!=1 || NCELL(pParent)!=1) 
94098      && (NCELL(pNode)<RTREE_MINCELLS(pRtree))
94099     ){
94100       rc = removeNode(pRtree, pNode, iHeight);
94101     }else{
94102       fixBoundingBox(pRtree, pNode);
94103     }
94104   }
94105
94106   return rc;
94107 }
94108
94109 static int Reinsert(
94110   Rtree *pRtree, 
94111   RtreeNode *pNode, 
94112   RtreeCell *pCell, 
94113   int iHeight
94114 ){
94115   int *aOrder;
94116   int *aSpare;
94117   RtreeCell *aCell;
94118   float *aDistance;
94119   int nCell;
94120   float aCenterCoord[RTREE_MAX_DIMENSIONS];
94121   int iDim;
94122   int ii;
94123   int rc = SQLITE_OK;
94124
94125   memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
94126
94127   nCell = NCELL(pNode)+1;
94128
94129   /* Allocate the buffers used by this operation. The allocation is
94130   ** relinquished before this function returns.
94131   */
94132   aCell = (RtreeCell *)sqlite3_malloc(nCell * (
94133     sizeof(RtreeCell) +         /* aCell array */
94134     sizeof(int)       +         /* aOrder array */
94135     sizeof(int)       +         /* aSpare array */
94136     sizeof(float)               /* aDistance array */
94137   ));
94138   if( !aCell ){
94139     return SQLITE_NOMEM;
94140   }
94141   aOrder    = (int *)&aCell[nCell];
94142   aSpare    = (int *)&aOrder[nCell];
94143   aDistance = (float *)&aSpare[nCell];
94144
94145   for(ii=0; ii<nCell; ii++){
94146     if( ii==(nCell-1) ){
94147       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
94148     }else{
94149       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
94150     }
94151     aOrder[ii] = ii;
94152     for(iDim=0; iDim<pRtree->nDim; iDim++){
94153       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
94154       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
94155     }
94156   }
94157   for(iDim=0; iDim<pRtree->nDim; iDim++){
94158     aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0);
94159   }
94160
94161   for(ii=0; ii<nCell; ii++){
94162     aDistance[ii] = 0.0;
94163     for(iDim=0; iDim<pRtree->nDim; iDim++){
94164       float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) - 
94165           DCOORD(aCell[ii].aCoord[iDim*2]);
94166       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
94167     }
94168   }
94169
94170   SortByDistance(aOrder, nCell, aDistance, aSpare);
94171   nodeZero(pRtree, pNode);
94172
94173   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
94174     RtreeCell *p = &aCell[aOrder[ii]];
94175     nodeInsertCell(pRtree, pNode, p);
94176     if( p->iRowid==pCell->iRowid ){
94177       if( iHeight==0 ){
94178         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
94179       }else{
94180         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
94181       }
94182     }
94183   }
94184   if( rc==SQLITE_OK ){
94185     fixBoundingBox(pRtree, pNode);
94186   }
94187   for(; rc==SQLITE_OK && ii<nCell; ii++){
94188     /* Find a node to store this cell in. pNode->iNode currently contains
94189     ** the height of the sub-tree headed by the cell.
94190     */
94191     RtreeNode *pInsert;
94192     RtreeCell *p = &aCell[aOrder[ii]];
94193     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
94194     if( rc==SQLITE_OK ){
94195       int rc2;
94196       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
94197       rc2 = nodeRelease(pRtree, pInsert);
94198       if( rc==SQLITE_OK ){
94199         rc = rc2;
94200       }
94201     }
94202   }
94203
94204   sqlite3_free(aCell);
94205   return rc;
94206 }
94207
94208 /*
94209 ** Insert cell pCell into node pNode. Node pNode is the head of a 
94210 ** subtree iHeight high (leaf nodes have iHeight==0).
94211 */
94212 static int rtreeInsertCell(
94213   Rtree *pRtree,
94214   RtreeNode *pNode,
94215   RtreeCell *pCell,
94216   int iHeight
94217 ){
94218   int rc = SQLITE_OK;
94219   if( iHeight>0 ){
94220     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
94221     if( pChild ){
94222       nodeRelease(pRtree, pChild->pParent);
94223       nodeReference(pNode);
94224       pChild->pParent = pNode;
94225     }
94226   }
94227   if( nodeInsertCell(pRtree, pNode, pCell) ){
94228 #if VARIANT_RSTARTREE_REINSERT
94229     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
94230       rc = SplitNode(pRtree, pNode, pCell, iHeight);
94231     }else{
94232       pRtree->iReinsertHeight = iHeight;
94233       rc = Reinsert(pRtree, pNode, pCell, iHeight);
94234     }
94235 #else
94236     rc = SplitNode(pRtree, pNode, pCell, iHeight);
94237 #endif
94238   }else{
94239     AdjustTree(pRtree, pNode, pCell);
94240     if( iHeight==0 ){
94241       rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
94242     }else{
94243       rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
94244     }
94245   }
94246   return rc;
94247 }
94248
94249 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
94250   int ii;
94251   int rc = SQLITE_OK;
94252   int nCell = NCELL(pNode);
94253
94254   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
94255     RtreeNode *pInsert;
94256     RtreeCell cell;
94257     nodeGetCell(pRtree, pNode, ii, &cell);
94258
94259     /* Find a node to store this cell in. pNode->iNode currently contains
94260     ** the height of the sub-tree headed by the cell.
94261     */
94262     rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert);
94263     if( rc==SQLITE_OK ){
94264       int rc2;
94265       rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode);
94266       rc2 = nodeRelease(pRtree, pInsert);
94267       if( rc==SQLITE_OK ){
94268         rc = rc2;
94269       }
94270     }
94271   }
94272   return rc;
94273 }
94274
94275 /*
94276 ** Select a currently unused rowid for a new r-tree record.
94277 */
94278 static int newRowid(Rtree *pRtree, i64 *piRowid){
94279   int rc;
94280   sqlite3_bind_null(pRtree->pWriteRowid, 1);
94281   sqlite3_bind_null(pRtree->pWriteRowid, 2);
94282   sqlite3_step(pRtree->pWriteRowid);
94283   rc = sqlite3_reset(pRtree->pWriteRowid);
94284   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
94285   return rc;
94286 }
94287
94288 #ifndef NDEBUG
94289 static int hashIsEmpty(Rtree *pRtree){
94290   int ii;
94291   for(ii=0; ii<HASHSIZE; ii++){
94292     assert( !pRtree->aHash[ii] );
94293   }
94294   return 1;
94295 }
94296 #endif
94297
94298 /*
94299 ** The xUpdate method for rtree module virtual tables.
94300 */
94301 int rtreeUpdate(
94302   sqlite3_vtab *pVtab, 
94303   int nData, 
94304   sqlite3_value **azData, 
94305   sqlite_int64 *pRowid
94306 ){
94307   Rtree *pRtree = (Rtree *)pVtab;
94308   int rc = SQLITE_OK;
94309
94310   rtreeReference(pRtree);
94311
94312   assert(nData>=1);
94313   assert(hashIsEmpty(pRtree));
94314
94315   /* If azData[0] is not an SQL NULL value, it is the rowid of a
94316   ** record to delete from the r-tree table. The following block does
94317   ** just that.
94318   */
94319   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
94320     i64 iDelete;                /* The rowid to delete */
94321     RtreeNode *pLeaf;           /* Leaf node containing record iDelete */
94322     int iCell;                  /* Index of iDelete cell in pLeaf */
94323     RtreeNode *pRoot;
94324
94325     /* Obtain a reference to the root node to initialise Rtree.iDepth */
94326     rc = nodeAcquire(pRtree, 1, 0, &pRoot);
94327
94328     /* Obtain a reference to the leaf node that contains the entry 
94329     ** about to be deleted. 
94330     */
94331     if( rc==SQLITE_OK ){
94332       iDelete = sqlite3_value_int64(azData[0]);
94333       rc = findLeafNode(pRtree, iDelete, &pLeaf);
94334     }
94335
94336     /* Delete the cell in question from the leaf node. */
94337     if( rc==SQLITE_OK ){
94338       int rc2;
94339       iCell = nodeRowidIndex(pRtree, pLeaf, iDelete);
94340       rc = deleteCell(pRtree, pLeaf, iCell, 0);
94341       rc2 = nodeRelease(pRtree, pLeaf);
94342       if( rc==SQLITE_OK ){
94343         rc = rc2;
94344       }
94345     }
94346
94347     /* Delete the corresponding entry in the <rtree>_rowid table. */
94348     if( rc==SQLITE_OK ){
94349       sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
94350       sqlite3_step(pRtree->pDeleteRowid);
94351       rc = sqlite3_reset(pRtree->pDeleteRowid);
94352     }
94353
94354     /* Check if the root node now has exactly one child. If so, remove
94355     ** it, schedule the contents of the child for reinsertion and 
94356     ** reduce the tree height by one.
94357     **
94358     ** This is equivalent to copying the contents of the child into
94359     ** the root node (the operation that Gutman's paper says to perform 
94360     ** in this scenario).
94361     */
94362     if( rc==SQLITE_OK && pRtree->iDepth>0 ){
94363       if( rc==SQLITE_OK && NCELL(pRoot)==1 ){
94364         RtreeNode *pChild;
94365         i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
94366         rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
94367         if( rc==SQLITE_OK ){
94368           rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
94369         }
94370         if( rc==SQLITE_OK ){
94371           pRtree->iDepth--;
94372           writeInt16(pRoot->zData, pRtree->iDepth);
94373           pRoot->isDirty = 1;
94374         }
94375       }
94376     }
94377
94378     /* Re-insert the contents of any underfull nodes removed from the tree. */
94379     for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
94380       if( rc==SQLITE_OK ){
94381         rc = reinsertNodeContent(pRtree, pLeaf);
94382       }
94383       pRtree->pDeleted = pLeaf->pNext;
94384       sqlite3_free(pLeaf);
94385     }
94386
94387     /* Release the reference to the root node. */
94388     if( rc==SQLITE_OK ){
94389       rc = nodeRelease(pRtree, pRoot);
94390     }else{
94391       nodeRelease(pRtree, pRoot);
94392     }
94393   }
94394
94395   /* If the azData[] array contains more than one element, elements
94396   ** (azData[2]..azData[argc-1]) contain a new record to insert into
94397   ** the r-tree structure.
94398   */
94399   if( rc==SQLITE_OK && nData>1 ){
94400     /* Insert a new record into the r-tree */
94401     RtreeCell cell;
94402     int ii;
94403     RtreeNode *pLeaf;
94404
94405     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
94406     assert( nData==(pRtree->nDim*2 + 3) );
94407     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
94408       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
94409         cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
94410         cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
94411         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
94412           rc = SQLITE_CONSTRAINT;
94413           goto constraint;
94414         }
94415       }
94416     }else{
94417       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
94418         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
94419         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
94420         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
94421           rc = SQLITE_CONSTRAINT;
94422           goto constraint;
94423         }
94424       }
94425     }
94426
94427     /* Figure out the rowid of the new row. */
94428     if( sqlite3_value_type(azData[2])==SQLITE_NULL ){
94429       rc = newRowid(pRtree, &cell.iRowid);
94430     }else{
94431       cell.iRowid = sqlite3_value_int64(azData[2]);
94432       sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
94433       if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){
94434         sqlite3_reset(pRtree->pReadRowid);
94435         rc = SQLITE_CONSTRAINT;
94436         goto constraint;
94437       }
94438       rc = sqlite3_reset(pRtree->pReadRowid);
94439     }
94440
94441     if( rc==SQLITE_OK ){
94442       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
94443     }
94444     if( rc==SQLITE_OK ){
94445       int rc2;
94446       pRtree->iReinsertHeight = -1;
94447       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
94448       rc2 = nodeRelease(pRtree, pLeaf);
94449       if( rc==SQLITE_OK ){
94450         rc = rc2;
94451       }
94452     }
94453   }
94454
94455 constraint:
94456   rtreeRelease(pRtree);
94457   return rc;
94458 }
94459
94460 /*
94461 ** The xRename method for rtree module virtual tables.
94462 */
94463 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
94464   Rtree *pRtree = (Rtree *)pVtab;
94465   int rc = SQLITE_NOMEM;
94466   char *zSql = sqlite3_mprintf(
94467     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
94468     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
94469     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
94470     , pRtree->zDb, pRtree->zName, zNewName 
94471     , pRtree->zDb, pRtree->zName, zNewName 
94472     , pRtree->zDb, pRtree->zName, zNewName
94473   );
94474   if( zSql ){
94475     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
94476     sqlite3_free(zSql);
94477   }
94478   return rc;
94479 }
94480
94481 static sqlite3_module rtreeModule = {
94482   0,                         /* iVersion */
94483   rtreeCreate,                /* xCreate - create a table */
94484   rtreeConnect,               /* xConnect - connect to an existing table */
94485   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
94486   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
94487   rtreeDestroy,               /* xDestroy - Drop a table */
94488   rtreeOpen,                  /* xOpen - open a cursor */
94489   rtreeClose,                 /* xClose - close a cursor */
94490   rtreeFilter,                /* xFilter - configure scan constraints */
94491   rtreeNext,                  /* xNext - advance a cursor */
94492   rtreeEof,                   /* xEof */
94493   rtreeColumn,                /* xColumn - read data */
94494   rtreeRowid,                 /* xRowid - read data */
94495   rtreeUpdate,                /* xUpdate - write data */
94496   0,                          /* xBegin - begin transaction */
94497   0,                          /* xSync - sync transaction */
94498   0,                          /* xCommit - commit transaction */
94499   0,                          /* xRollback - rollback transaction */
94500   0,                          /* xFindFunction - function overloading */
94501   rtreeRename                 /* xRename - rename the table */
94502 };
94503
94504 static int rtreeSqlInit(
94505   Rtree *pRtree, 
94506   sqlite3 *db, 
94507   const char *zDb, 
94508   const char *zPrefix, 
94509   int isCreate
94510 ){
94511   int rc = SQLITE_OK;
94512
94513   #define N_STATEMENT 9
94514   static const char *azSql[N_STATEMENT] = {
94515     /* Read and write the xxx_node table */
94516     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
94517     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
94518     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
94519
94520     /* Read and write the xxx_rowid table */
94521     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
94522     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
94523     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
94524
94525     /* Read and write the xxx_parent table */
94526     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
94527     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
94528     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
94529   };
94530   sqlite3_stmt **appStmt[N_STATEMENT];
94531   int i;
94532
94533   pRtree->db = db;
94534
94535   if( isCreate ){
94536     char *zCreate = sqlite3_mprintf(
94537 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
94538 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
94539 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
94540 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
94541       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
94542     );
94543     if( !zCreate ){
94544       return SQLITE_NOMEM;
94545     }
94546     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
94547     sqlite3_free(zCreate);
94548     if( rc!=SQLITE_OK ){
94549       return rc;
94550     }
94551   }
94552
94553   appStmt[0] = &pRtree->pReadNode;
94554   appStmt[1] = &pRtree->pWriteNode;
94555   appStmt[2] = &pRtree->pDeleteNode;
94556   appStmt[3] = &pRtree->pReadRowid;
94557   appStmt[4] = &pRtree->pWriteRowid;
94558   appStmt[5] = &pRtree->pDeleteRowid;
94559   appStmt[6] = &pRtree->pReadParent;
94560   appStmt[7] = &pRtree->pWriteParent;
94561   appStmt[8] = &pRtree->pDeleteParent;
94562
94563   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
94564     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
94565     if( zSql ){
94566       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0); 
94567     }else{
94568       rc = SQLITE_NOMEM;
94569     }
94570     sqlite3_free(zSql);
94571   }
94572
94573   return rc;
94574 }
94575
94576 /*
94577 ** This routine queries database handle db for the page-size used by
94578 ** database zDb. If successful, the page-size in bytes is written to
94579 ** *piPageSize and SQLITE_OK returned. Otherwise, and an SQLite error 
94580 ** code is returned.
94581 */
94582 static int getPageSize(sqlite3 *db, const char *zDb, int *piPageSize){
94583   int rc = SQLITE_NOMEM;
94584   char *zSql;
94585   sqlite3_stmt *pStmt = 0;
94586
94587   zSql = sqlite3_mprintf("PRAGMA %Q.page_size", zDb);
94588   if( !zSql ){
94589     return SQLITE_NOMEM;
94590   }
94591
94592   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
94593   sqlite3_free(zSql);
94594   if( rc!=SQLITE_OK ){
94595     return rc;
94596   }
94597
94598   if( SQLITE_ROW==sqlite3_step(pStmt) ){
94599     *piPageSize = sqlite3_column_int(pStmt, 0);
94600   }
94601   return sqlite3_finalize(pStmt);
94602 }
94603
94604 /* 
94605 ** This function is the implementation of both the xConnect and xCreate
94606 ** methods of the r-tree virtual table.
94607 **
94608 **   argv[0]   -> module name
94609 **   argv[1]   -> database name
94610 **   argv[2]   -> table name
94611 **   argv[...] -> column names...
94612 */
94613 static int rtreeInit(
94614   sqlite3 *db,                        /* Database connection */
94615   void *pAux,                         /* Pointer to head of rtree list */
94616   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
94617   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
94618   char **pzErr,                       /* OUT: Error message, if any */
94619   int isCreate,                       /* True for xCreate, false for xConnect */
94620   int eCoordType                      /* One of the RTREE_COORD_* constants */
94621 ){
94622   int rc = SQLITE_OK;
94623   int iPageSize = 0;
94624   Rtree *pRtree;
94625   int nDb;              /* Length of string argv[1] */
94626   int nName;            /* Length of string argv[2] */
94627
94628   const char *aErrMsg[] = {
94629     0,                                                    /* 0 */
94630     "Wrong number of columns for an rtree table",         /* 1 */
94631     "Too few columns for an rtree table",                 /* 2 */
94632     "Too many columns for an rtree table"                 /* 3 */
94633   };
94634
94635   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
94636   if( aErrMsg[iErr] ){
94637     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
94638     return SQLITE_ERROR;
94639   }
94640
94641   rc = getPageSize(db, argv[1], &iPageSize);
94642   if( rc!=SQLITE_OK ){
94643     return rc;
94644   }
94645
94646   /* Allocate the sqlite3_vtab structure */
94647   nDb = strlen(argv[1]);
94648   nName = strlen(argv[2]);
94649   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
94650   if( !pRtree ){
94651     return SQLITE_NOMEM;
94652   }
94653   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
94654   pRtree->nBusy = 1;
94655   pRtree->base.pModule = &rtreeModule;
94656   pRtree->zDb = (char *)&pRtree[1];
94657   pRtree->zName = &pRtree->zDb[nDb+1];
94658   pRtree->nDim = (argc-4)/2;
94659   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
94660   pRtree->eCoordType = eCoordType;
94661   memcpy(pRtree->zDb, argv[1], nDb);
94662   memcpy(pRtree->zName, argv[2], nName);
94663
94664   /* Figure out the node size to use. By default, use 64 bytes less than
94665   ** the database page-size. This ensures that each node is stored on
94666   ** a single database page.
94667   **
94668   ** If the databasd page-size is so large that more than RTREE_MAXCELLS
94669   ** entries would fit in a single node, use a smaller node-size.
94670   */
94671   pRtree->iNodeSize = iPageSize-64;
94672   if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
94673     pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
94674   }
94675
94676   /* Create/Connect to the underlying relational database schema. If
94677   ** that is successful, call sqlite3_declare_vtab() to configure
94678   ** the r-tree table schema.
94679   */
94680   if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
94681     *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
94682   }else{
94683     char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
94684     char *zTmp;
94685     int ii;
94686     for(ii=4; zSql && ii<argc; ii++){
94687       zTmp = zSql;
94688       zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
94689       sqlite3_free(zTmp);
94690     }
94691     if( zSql ){
94692       zTmp = zSql;
94693       zSql = sqlite3_mprintf("%s);", zTmp);
94694       sqlite3_free(zTmp);
94695     }
94696     if( !zSql || sqlite3_declare_vtab(db, zSql) ){
94697       rc = SQLITE_NOMEM;
94698     }
94699     sqlite3_free(zSql);
94700   }
94701
94702   if( rc==SQLITE_OK ){
94703     *ppVtab = (sqlite3_vtab *)pRtree;
94704   }else{
94705     rtreeRelease(pRtree);
94706   }
94707   return rc;
94708 }
94709
94710
94711 /*
94712 ** Implementation of a scalar function that decodes r-tree nodes to
94713 ** human readable strings. This can be used for debugging and analysis.
94714 **
94715 ** The scalar function takes two arguments, a blob of data containing
94716 ** an r-tree node, and the number of dimensions the r-tree indexes.
94717 ** For a two-dimensional r-tree structure called "rt", to deserialize
94718 ** all nodes, a statement like:
94719 **
94720 **   SELECT rtreenode(2, data) FROM rt_node;
94721 **
94722 ** The human readable string takes the form of a Tcl list with one
94723 ** entry for each cell in the r-tree node. Each entry is itself a
94724 ** list, containing the 8-byte rowid/pageno followed by the 
94725 ** <num-dimension>*2 coordinates.
94726 */
94727 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
94728   char *zText = 0;
94729   RtreeNode node;
94730   Rtree tree;
94731   int ii;
94732
94733   memset(&node, 0, sizeof(RtreeNode));
94734   memset(&tree, 0, sizeof(Rtree));
94735   tree.nDim = sqlite3_value_int(apArg[0]);
94736   tree.nBytesPerCell = 8 + 8 * tree.nDim;
94737   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
94738
94739   for(ii=0; ii<NCELL(&node); ii++){
94740     char zCell[512];
94741     int nCell = 0;
94742     RtreeCell cell;
94743     int jj;
94744
94745     nodeGetCell(&tree, &node, ii, &cell);
94746     sqlite3_snprintf(512-nCell,&zCell[nCell],"%d", cell.iRowid);
94747     nCell = strlen(zCell);
94748     for(jj=0; jj<tree.nDim*2; jj++){
94749       sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
94750       nCell = strlen(zCell);
94751     }
94752
94753     if( zText ){
94754       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
94755       sqlite3_free(zText);
94756       zText = zTextNew;
94757     }else{
94758       zText = sqlite3_mprintf("{%s}", zCell);
94759     }
94760   }
94761   
94762   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
94763 }
94764
94765 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
94766   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB 
94767    || sqlite3_value_bytes(apArg[0])<2
94768   ){
94769     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); 
94770   }else{
94771     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
94772     sqlite3_result_int(ctx, readInt16(zBlob));
94773   }
94774 }
94775
94776 /*
94777 ** Register the r-tree module with database handle db. This creates the
94778 ** virtual table module "rtree" and the debugging/analysis scalar 
94779 ** function "rtreenode".
94780 */
94781 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
94782   int rc = SQLITE_OK;
94783
94784   if( rc==SQLITE_OK ){
94785     int utf8 = SQLITE_UTF8;
94786     rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
94787   }
94788   if( rc==SQLITE_OK ){
94789     int utf8 = SQLITE_UTF8;
94790     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
94791   }
94792   if( rc==SQLITE_OK ){
94793     void *c = (void *)RTREE_COORD_REAL32;
94794     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
94795   }
94796   if( rc==SQLITE_OK ){
94797     void *c = (void *)RTREE_COORD_INT32;
94798     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
94799   }
94800
94801   return rc;
94802 }
94803
94804 #if !SQLITE_CORE
94805 SQLITE_API int sqlite3_extension_init(
94806   sqlite3 *db,
94807   char **pzErrMsg,
94808   const sqlite3_api_routines *pApi
94809 ){
94810   SQLITE_EXTENSION_INIT2(pApi)
94811   return sqlite3RtreeInit(db);
94812 }
94813 #endif
94814
94815 #endif
94816
94817 /************** End of rtree.c ***********************************************/
94818 /************** Begin file icu.c *********************************************/
94819 /*
94820 ** 2007 May 6
94821 **
94822 ** The author disclaims copyright to this source code.  In place of
94823 ** a legal notice, here is a blessing:
94824 **
94825 **    May you do good and not evil.
94826 **    May you find forgiveness for yourself and forgive others.
94827 **    May you share freely, never taking more than you give.
94828 **
94829 *************************************************************************
94830 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
94831 **
94832 ** This file implements an integration between the ICU library 
94833 ** ("International Components for Unicode", an open-source library 
94834 ** for handling unicode data) and SQLite. The integration uses 
94835 ** ICU to provide the following to SQLite:
94836 **
94837 **   * An implementation of the SQL regexp() function (and hence REGEXP
94838 **     operator) using the ICU uregex_XX() APIs.
94839 **
94840 **   * Implementations of the SQL scalar upper() and lower() functions
94841 **     for case mapping.
94842 **
94843 **   * Integration of ICU and SQLite collation seqences.
94844 **
94845 **   * An implementation of the LIKE operator that uses ICU to 
94846 **     provide case-independent matching.
94847 */
94848
94849 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
94850
94851 /* Include ICU headers */
94852 #include <unicode/utypes.h>
94853 #include <unicode/uregex.h>
94854 #include <unicode/ustring.h>
94855 #include <unicode/ucol.h>
94856
94857
94858 #ifndef SQLITE_CORE
94859   #include "sqlite3ext.h"
94860   SQLITE_EXTENSION_INIT1
94861 #else
94862   #include "sqlite3.h"
94863 #endif
94864
94865 /*
94866 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
94867 ** operator.
94868 */
94869 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
94870 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
94871 #endif
94872
94873 /*
94874 ** Version of sqlite3_free() that is always a function, never a macro.
94875 */
94876 static void xFree(void *p){
94877   sqlite3_free(p);
94878 }
94879
94880 /*
94881 ** Compare two UTF-8 strings for equality where the first string is
94882 ** a "LIKE" expression. Return true (1) if they are the same and 
94883 ** false (0) if they are different.
94884 */
94885 static int icuLikeCompare(
94886   const uint8_t *zPattern,   /* LIKE pattern */
94887   const uint8_t *zString,    /* The UTF-8 string to compare against */
94888   const UChar32 uEsc         /* The escape character */
94889 ){
94890   static const int MATCH_ONE = (UChar32)'_';
94891   static const int MATCH_ALL = (UChar32)'%';
94892
94893   int iPattern = 0;       /* Current byte index in zPattern */
94894   int iString = 0;        /* Current byte index in zString */
94895
94896   int prevEscape = 0;     /* True if the previous character was uEsc */
94897
94898   while( zPattern[iPattern]!=0 ){
94899
94900     /* Read (and consume) the next character from the input pattern. */
94901     UChar32 uPattern;
94902     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
94903     assert(uPattern!=0);
94904
94905     /* There are now 4 possibilities:
94906     **
94907     **     1. uPattern is an unescaped match-all character "%",
94908     **     2. uPattern is an unescaped match-one character "_",
94909     **     3. uPattern is an unescaped escape character, or
94910     **     4. uPattern is to be handled as an ordinary character
94911     */
94912     if( !prevEscape && uPattern==MATCH_ALL ){
94913       /* Case 1. */
94914       uint8_t c;
94915
94916       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
94917       ** MATCH_ALL. For each MATCH_ONE, skip one character in the 
94918       ** test string.
94919       */
94920       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
94921         if( c==MATCH_ONE ){
94922           if( zString[iString]==0 ) return 0;
94923           U8_FWD_1_UNSAFE(zString, iString);
94924         }
94925         iPattern++;
94926       }
94927
94928       if( zPattern[iPattern]==0 ) return 1;
94929
94930       while( zString[iString] ){
94931         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
94932           return 1;
94933         }
94934         U8_FWD_1_UNSAFE(zString, iString);
94935       }
94936       return 0;
94937
94938     }else if( !prevEscape && uPattern==MATCH_ONE ){
94939       /* Case 2. */
94940       if( zString[iString]==0 ) return 0;
94941       U8_FWD_1_UNSAFE(zString, iString);
94942
94943     }else if( !prevEscape && uPattern==uEsc){
94944       /* Case 3. */
94945       prevEscape = 1;
94946
94947     }else{
94948       /* Case 4. */
94949       UChar32 uString;
94950       U8_NEXT_UNSAFE(zString, iString, uString);
94951       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
94952       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
94953       if( uString!=uPattern ){
94954         return 0;
94955       }
94956       prevEscape = 0;
94957     }
94958   }
94959
94960   return zString[iString]==0;
94961 }
94962
94963 /*
94964 ** Implementation of the like() SQL function.  This function implements
94965 ** the build-in LIKE operator.  The first argument to the function is the
94966 ** pattern and the second argument is the string.  So, the SQL statements:
94967 **
94968 **       A LIKE B
94969 **
94970 ** is implemented as like(B, A). If there is an escape character E, 
94971 **
94972 **       A LIKE B ESCAPE E
94973 **
94974 ** is mapped to like(B, A, E).
94975 */
94976 static void icuLikeFunc(
94977   sqlite3_context *context, 
94978   int argc, 
94979   sqlite3_value **argv
94980 ){
94981   const unsigned char *zA = sqlite3_value_text(argv[0]);
94982   const unsigned char *zB = sqlite3_value_text(argv[1]);
94983   UChar32 uEsc = 0;
94984
94985   /* Limit the length of the LIKE or GLOB pattern to avoid problems
94986   ** of deep recursion and N*N behavior in patternCompare().
94987   */
94988   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
94989     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
94990     return;
94991   }
94992
94993
94994   if( argc==3 ){
94995     /* The escape character string must consist of a single UTF-8 character.
94996     ** Otherwise, return an error.
94997     */
94998     int nE= sqlite3_value_bytes(argv[2]);
94999     const unsigned char *zE = sqlite3_value_text(argv[2]);
95000     int i = 0;
95001     if( zE==0 ) return;
95002     U8_NEXT(zE, i, nE, uEsc);
95003     if( i!=nE){
95004       sqlite3_result_error(context, 
95005           "ESCAPE expression must be a single character", -1);
95006       return;
95007     }
95008   }
95009
95010   if( zA && zB ){
95011     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
95012   }
95013 }
95014
95015 /*
95016 ** This function is called when an ICU function called from within
95017 ** the implementation of an SQL scalar function returns an error.
95018 **
95019 ** The scalar function context passed as the first argument is 
95020 ** loaded with an error message based on the following two args.
95021 */
95022 static void icuFunctionError(
95023   sqlite3_context *pCtx,       /* SQLite scalar function context */
95024   const char *zName,           /* Name of ICU function that failed */
95025   UErrorCode e                 /* Error code returned by ICU function */
95026 ){
95027   char zBuf[128];
95028   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
95029   zBuf[127] = '\0';
95030   sqlite3_result_error(pCtx, zBuf, -1);
95031 }
95032
95033 /*
95034 ** Function to delete compiled regexp objects. Registered as
95035 ** a destructor function with sqlite3_set_auxdata().
95036 */
95037 static void icuRegexpDelete(void *p){
95038   URegularExpression *pExpr = (URegularExpression *)p;
95039   uregex_close(pExpr);
95040 }
95041
95042 /*
95043 ** Implementation of SQLite REGEXP operator. This scalar function takes
95044 ** two arguments. The first is a regular expression pattern to compile
95045 ** the second is a string to match against that pattern. If either 
95046 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
95047 ** is 1 if the string matches the pattern, or 0 otherwise.
95048 **
95049 ** SQLite maps the regexp() function to the regexp() operator such
95050 ** that the following two are equivalent:
95051 **
95052 **     zString REGEXP zPattern
95053 **     regexp(zPattern, zString)
95054 **
95055 ** Uses the following ICU regexp APIs:
95056 **
95057 **     uregex_open()
95058 **     uregex_matches()
95059 **     uregex_close()
95060 */
95061 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
95062   UErrorCode status = U_ZERO_ERROR;
95063   URegularExpression *pExpr;
95064   UBool res;
95065   const UChar *zString = sqlite3_value_text16(apArg[1]);
95066
95067   /* If the left hand side of the regexp operator is NULL, 
95068   ** then the result is also NULL. 
95069   */
95070   if( !zString ){
95071     return;
95072   }
95073
95074   pExpr = sqlite3_get_auxdata(p, 0);
95075   if( !pExpr ){
95076     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
95077     if( !zPattern ){
95078       return;
95079     }
95080     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
95081
95082     if( U_SUCCESS(status) ){
95083       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
95084     }else{
95085       assert(!pExpr);
95086       icuFunctionError(p, "uregex_open", status);
95087       return;
95088     }
95089   }
95090
95091   /* Configure the text that the regular expression operates on. */
95092   uregex_setText(pExpr, zString, -1, &status);
95093   if( !U_SUCCESS(status) ){
95094     icuFunctionError(p, "uregex_setText", status);
95095     return;
95096   }
95097
95098   /* Attempt the match */
95099   res = uregex_matches(pExpr, 0, &status);
95100   if( !U_SUCCESS(status) ){
95101     icuFunctionError(p, "uregex_matches", status);
95102     return;
95103   }
95104
95105   /* Set the text that the regular expression operates on to a NULL
95106   ** pointer. This is not really necessary, but it is tidier than 
95107   ** leaving the regular expression object configured with an invalid
95108   ** pointer after this function returns.
95109   */
95110   uregex_setText(pExpr, 0, 0, &status);
95111
95112   /* Return 1 or 0. */
95113   sqlite3_result_int(p, res ? 1 : 0);
95114 }
95115
95116 /*
95117 ** Implementations of scalar functions for case mapping - upper() and 
95118 ** lower(). Function upper() converts its input to upper-case (ABC).
95119 ** Function lower() converts to lower-case (abc).
95120 **
95121 ** ICU provides two types of case mapping, "general" case mapping and
95122 ** "language specific". Refer to ICU documentation for the differences
95123 ** between the two.
95124 **
95125 ** To utilise "general" case mapping, the upper() or lower() scalar 
95126 ** functions are invoked with one argument:
95127 **
95128 **     upper('ABC') -> 'abc'
95129 **     lower('abc') -> 'ABC'
95130 **
95131 ** To access ICU "language specific" case mapping, upper() or lower()
95132 ** should be invoked with two arguments. The second argument is the name
95133 ** of the locale to use. Passing an empty string ("") or SQL NULL value
95134 ** as the second argument is the same as invoking the 1 argument version
95135 ** of upper() or lower().
95136 **
95137 **     lower('I', 'en_us') -> 'i'
95138 **     lower('I', 'tr_tr') -> 'ı' (small dotless i)
95139 **
95140 ** http://www.icu-project.org/userguide/posix.html#case_mappings
95141 */
95142 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
95143   const UChar *zInput;
95144   UChar *zOutput;
95145   int nInput;
95146   int nOutput;
95147
95148   UErrorCode status = U_ZERO_ERROR;
95149   const char *zLocale = 0;
95150
95151   assert(nArg==1 || nArg==2);
95152   if( nArg==2 ){
95153     zLocale = (const char *)sqlite3_value_text(apArg[1]);
95154   }
95155
95156   zInput = sqlite3_value_text16(apArg[0]);
95157   if( !zInput ){
95158     return;
95159   }
95160   nInput = sqlite3_value_bytes16(apArg[0]);
95161
95162   nOutput = nInput * 2 + 2;
95163   zOutput = sqlite3_malloc(nOutput);
95164   if( !zOutput ){
95165     return;
95166   }
95167
95168   if( sqlite3_user_data(p) ){
95169     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
95170   }else{
95171     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
95172   }
95173
95174   if( !U_SUCCESS(status) ){
95175     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
95176     return;
95177   }
95178
95179   sqlite3_result_text16(p, zOutput, -1, xFree);
95180 }
95181
95182 /*
95183 ** Collation sequence destructor function. The pCtx argument points to
95184 ** a UCollator structure previously allocated using ucol_open().
95185 */
95186 static void icuCollationDel(void *pCtx){
95187   UCollator *p = (UCollator *)pCtx;
95188   ucol_close(p);
95189 }
95190
95191 /*
95192 ** Collation sequence comparison function. The pCtx argument points to
95193 ** a UCollator structure previously allocated using ucol_open().
95194 */
95195 static int icuCollationColl(
95196   void *pCtx,
95197   int nLeft,
95198   const void *zLeft,
95199   int nRight,
95200   const void *zRight
95201 ){
95202   UCollationResult res;
95203   UCollator *p = (UCollator *)pCtx;
95204   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
95205   switch( res ){
95206     case UCOL_LESS:    return -1;
95207     case UCOL_GREATER: return +1;
95208     case UCOL_EQUAL:   return 0;
95209   }
95210   assert(!"Unexpected return value from ucol_strcoll()");
95211   return 0;
95212 }
95213
95214 /*
95215 ** Implementation of the scalar function icu_load_collation().
95216 **
95217 ** This scalar function is used to add ICU collation based collation 
95218 ** types to an SQLite database connection. It is intended to be called
95219 ** as follows:
95220 **
95221 **     SELECT icu_load_collation(<locale>, <collation-name>);
95222 **
95223 ** Where <locale> is a string containing an ICU locale identifier (i.e.
95224 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
95225 ** collation sequence to create.
95226 */
95227 static void icuLoadCollation(
95228   sqlite3_context *p, 
95229   int nArg, 
95230   sqlite3_value **apArg
95231 ){
95232   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
95233   UErrorCode status = U_ZERO_ERROR;
95234   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
95235   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
95236   UCollator *pUCollator;    /* ICU library collation object */
95237   int rc;                   /* Return code from sqlite3_create_collation_x() */
95238
95239   assert(nArg==2);
95240   zLocale = (const char *)sqlite3_value_text(apArg[0]);
95241   zName = (const char *)sqlite3_value_text(apArg[1]);
95242
95243   if( !zLocale || !zName ){
95244     return;
95245   }
95246
95247   pUCollator = ucol_open(zLocale, &status);
95248   if( !U_SUCCESS(status) ){
95249     icuFunctionError(p, "ucol_open", status);
95250     return;
95251   }
95252   assert(p);
95253
95254   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, 
95255       icuCollationColl, icuCollationDel
95256   );
95257   if( rc!=SQLITE_OK ){
95258     ucol_close(pUCollator);
95259     sqlite3_result_error(p, "Error registering collation function", -1);
95260   }
95261 }
95262
95263 /*
95264 ** Register the ICU extension functions with database db.
95265 */
95266 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
95267   struct IcuScalar {
95268     const char *zName;                        /* Function name */
95269     int nArg;                                 /* Number of arguments */
95270     int enc;                                  /* Optimal text encoding */
95271     void *pContext;                           /* sqlite3_user_data() context */
95272     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
95273   } scalars[] = {
95274     {"regexp",-1, SQLITE_ANY,          0, icuRegexpFunc},
95275
95276     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
95277     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
95278     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
95279     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
95280
95281     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
95282     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
95283     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
95284     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
95285
95286     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
95287     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
95288
95289     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
95290   };
95291
95292   int rc = SQLITE_OK;
95293   int i;
95294
95295   for(i=0; rc==SQLITE_OK && i<(sizeof(scalars)/sizeof(struct IcuScalar)); i++){
95296     struct IcuScalar *p = &scalars[i];
95297     rc = sqlite3_create_function(
95298         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
95299     );
95300   }
95301
95302   return rc;
95303 }
95304
95305 #if !SQLITE_CORE
95306 SQLITE_API int sqlite3_extension_init(
95307   sqlite3 *db, 
95308   char **pzErrMsg,
95309   const sqlite3_api_routines *pApi
95310 ){
95311   SQLITE_EXTENSION_INIT2(pApi)
95312   return sqlite3IcuInit(db);
95313 }
95314 #endif
95315
95316 #endif
95317
95318 /************** End of icu.c *************************************************/