version 0.3.26
[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.6.2.  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 ** 6728 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-11-26 17:54:40 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.798 2008/11/19 16:52:44 danielk1977 Exp $
45 */
46 #ifndef _SQLITEINT_H_
47 #define _SQLITEINT_H_
48
49 /*
50 ** Include the configuration header output by 'configure' if we're using the
51 ** autoconf-based build
52 */
53 #ifdef _HAVE_SQLITE_CONFIG_H
54 #include "config.h"
55 #endif
56
57 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
58 /************** Begin file sqliteLimit.h *************************************/
59 /*
60 ** 2007 May 7
61 **
62 ** The author disclaims copyright to this source code.  In place of
63 ** a legal notice, here is a blessing:
64 **
65 **    May you do good and not evil.
66 **    May you find forgiveness for yourself and forgive others.
67 **    May you share freely, never taking more than you give.
68 **
69 *************************************************************************
70 ** 
71 ** This file defines various limits of what SQLite can process.
72 **
73 ** @(#) $Id: sqliteLimit.h,v 1.8 2008/03/26 15:56:22 drh Exp $
74 */
75
76 /*
77 ** The maximum length of a TEXT or BLOB in bytes.   This also
78 ** limits the size of a row in a table or index.
79 **
80 ** The hard limit is the ability of a 32-bit signed integer
81 ** to count the size: 2^31-1 or 2147483647.
82 */
83 #ifndef SQLITE_MAX_LENGTH
84 # define SQLITE_MAX_LENGTH 1000000000
85 #endif
86
87 /*
88 ** This is the maximum number of
89 **
90 **    * Columns in a table
91 **    * Columns in an index
92 **    * Columns in a view
93 **    * Terms in the SET clause of an UPDATE statement
94 **    * Terms in the result set of a SELECT statement
95 **    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
96 **    * Terms in the VALUES clause of an INSERT statement
97 **
98 ** The hard upper limit here is 32676.  Most database people will
99 ** tell you that in a well-normalized database, you usually should
100 ** not have more than a dozen or so columns in any table.  And if
101 ** that is the case, there is no point in having more than a few
102 ** dozen values in any of the other situations described above.
103 */
104 #ifndef SQLITE_MAX_COLUMN
105 # define SQLITE_MAX_COLUMN 2000
106 #endif
107
108 /*
109 ** The maximum length of a single SQL statement in bytes.
110 **
111 ** It used to be the case that setting this value to zero would
112 ** turn the limit off.  That is no longer true.  It is not possible
113 ** to turn this limit off.
114 */
115 #ifndef SQLITE_MAX_SQL_LENGTH
116 # define SQLITE_MAX_SQL_LENGTH 1000000000
117 #endif
118
119 /*
120 ** The maximum depth of an expression tree. This is limited to 
121 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might 
122 ** want to place more severe limits on the complexity of an 
123 ** expression.
124 **
125 ** A value of 0 used to mean that the limit was not enforced.
126 ** But that is no longer true.  The limit is now strictly enforced
127 ** at all times.
128 */
129 #ifndef SQLITE_MAX_EXPR_DEPTH
130 # define SQLITE_MAX_EXPR_DEPTH 1000
131 #endif
132
133 /*
134 ** The maximum number of terms in a compound SELECT statement.
135 ** The code generator for compound SELECT statements does one
136 ** level of recursion for each term.  A stack overflow can result
137 ** if the number of terms is too large.  In practice, most SQL
138 ** never has more than 3 or 4 terms.  Use a value of 0 to disable
139 ** any limit on the number of terms in a compount SELECT.
140 */
141 #ifndef SQLITE_MAX_COMPOUND_SELECT
142 # define SQLITE_MAX_COMPOUND_SELECT 500
143 #endif
144
145 /*
146 ** The maximum number of opcodes in a VDBE program.
147 ** Not currently enforced.
148 */
149 #ifndef SQLITE_MAX_VDBE_OP
150 # define SQLITE_MAX_VDBE_OP 25000
151 #endif
152
153 /*
154 ** The maximum number of arguments to an SQL function.
155 */
156 #ifndef SQLITE_MAX_FUNCTION_ARG
157 # define SQLITE_MAX_FUNCTION_ARG 100
158 #endif
159
160 /*
161 ** The maximum number of in-memory pages to use for the main database
162 ** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
163 */
164 #ifndef SQLITE_DEFAULT_CACHE_SIZE
165 # define SQLITE_DEFAULT_CACHE_SIZE  2000
166 #endif
167 #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
168 # define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
169 #endif
170
171 /*
172 ** The maximum number of attached databases.  This must be between 0
173 ** and 30.  The upper bound on 30 is because a 32-bit integer bitmap
174 ** is used internally to track attached databases.
175 */
176 #ifndef SQLITE_MAX_ATTACHED
177 # define SQLITE_MAX_ATTACHED 10
178 #endif
179
180
181 /*
182 ** The maximum value of a ?nnn wildcard that the parser will accept.
183 */
184 #ifndef SQLITE_MAX_VARIABLE_NUMBER
185 # define SQLITE_MAX_VARIABLE_NUMBER 999
186 #endif
187
188 /* Maximum page size.  The upper bound on this value is 32768.  This a limit
189 ** imposed by the necessity of storing the value in a 2-byte unsigned integer
190 ** and the fact that the page size must be a power of 2.
191 */
192 #ifndef SQLITE_MAX_PAGE_SIZE
193 # define SQLITE_MAX_PAGE_SIZE 32768
194 #endif
195
196
197 /*
198 ** The default size of a database page.
199 */
200 #ifndef SQLITE_DEFAULT_PAGE_SIZE
201 # define SQLITE_DEFAULT_PAGE_SIZE 1024
202 #endif
203 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
204 # undef SQLITE_DEFAULT_PAGE_SIZE
205 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
206 #endif
207
208 /*
209 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
210 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
211 ** device characteristics (sector-size and atomic write() support),
212 ** SQLite may choose a larger value. This constant is the maximum value
213 ** SQLite will choose on its own.
214 */
215 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
216 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
217 #endif
218 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
219 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
220 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
221 #endif
222
223
224 /*
225 ** Maximum number of pages in one database file.
226 **
227 ** This is really just the default value for the max_page_count pragma.
228 ** This value can be lowered (or raised) at run-time using that the
229 ** max_page_count macro.
230 */
231 #ifndef SQLITE_MAX_PAGE_COUNT
232 # define SQLITE_MAX_PAGE_COUNT 1073741823
233 #endif
234
235 /*
236 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
237 ** operator.
238 */
239 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
240 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
241 #endif
242
243 /************** End of sqliteLimit.h *****************************************/
244 /************** Continuing where we left off in sqliteInt.h ******************/
245
246 /* Disable nuisance warnings on Borland compilers */
247 #if defined(__BORLANDC__)
248 #pragma warn -rch /* unreachable code */
249 #pragma warn -ccc /* Condition is always true or false */
250 #pragma warn -aus /* Assigned value is never used */
251 #pragma warn -csu /* Comparing signed and unsigned */
252 #pragma warn -spa /* Suspicous pointer arithmetic */
253 #endif
254
255 /* Needed for various definitions... */
256 #ifndef _GNU_SOURCE
257 # define _GNU_SOURCE
258 #endif
259
260 /*
261 ** Include standard header files as necessary
262 */
263 #ifdef HAVE_STDINT_H
264 #include <stdint.h>
265 #endif
266 #ifdef HAVE_INTTYPES_H
267 #include <inttypes.h>
268 #endif
269
270 /*
271 ** A macro used to aid in coverage testing.  When doing coverage
272 ** testing, the condition inside the argument must be evaluated 
273 ** both true and false in order to get full branch coverage.
274 ** This macro can be inserted to ensure adequate test coverage
275 ** in places where simple condition/decision coverage is inadequate.
276 */
277 #ifdef SQLITE_COVERAGE_TEST
278 SQLITE_PRIVATE   void sqlite3Coverage(int);
279 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
280 #else
281 # define testcase(X)
282 #endif
283
284 /*
285 ** The ALWAYS and NEVER macros surround boolean expressions which 
286 ** are intended to always be true or false, respectively.  Such
287 ** expressions could be omitted from the code completely.  But they
288 ** are included in a few cases in order to enhance the resilience
289 ** of SQLite to unexpected behavior - to make the code "self-healing"
290 ** or "ductile" rather than being "brittle" and crashing at the first
291 ** hint of unplanned behavior.
292 **
293 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
294 ** be true and false so that the unreachable code then specify will
295 ** not be counted as untested code.
296 */
297 #ifdef SQLITE_COVERAGE_TEST
298 # define ALWAYS(X)      (1)
299 # define NEVER(X)       (0)
300 #else
301 # define ALWAYS(X)      (X)
302 # define NEVER(X)       (X)
303 #endif
304
305 /*
306 ** The macro unlikely() is a hint that surrounds a boolean
307 ** expression that is usually false.  Macro likely() surrounds
308 ** a boolean expression that is usually true.  GCC is able to
309 ** use these hints to generate better code, sometimes.
310 */
311 #if defined(__GNUC__) && 0
312 # define likely(X)    __builtin_expect((X),1)
313 # define unlikely(X)  __builtin_expect((X),0)
314 #else
315 # define likely(X)    !!(X)
316 # define unlikely(X)  !!(X)
317 #endif
318
319 /*
320  * This macro is used to "hide" some ugliness in casting an int
321  * value to a ptr value under the MSVC 64-bit compiler.   Casting
322  * non 64-bit values to ptr types results in a "hard" error with 
323  * the MSVC 64-bit compiler which this attempts to avoid.  
324  *
325  * A simple compiler pragma or casting sequence could not be found
326  * to correct this in all situations, so this macro was introduced.
327  *
328  * It could be argued that the intptr_t type could be used in this
329  * case, but that type is not available on all compilers, or 
330  * requires the #include of specific headers which differs between
331  * platforms.
332  */
333 #define SQLITE_INT_TO_PTR(X)   ((void*)&((char*)0)[X])
334 #define SQLITE_PTR_TO_INT(X)   ((int)(((char*)X)-(char*)0))
335
336 /*
337 ** These #defines should enable >2GB file support on Posix if the
338 ** underlying operating system supports it.  If the OS lacks
339 ** large file support, or if the OS is windows, these should be no-ops.
340 **
341 ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
342 ** system #includes.  Hence, this block of code must be the very first
343 ** code in all source files.
344 **
345 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
346 ** on the compiler command line.  This is necessary if you are compiling
347 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
348 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
349 ** without this option, LFS is enable.  But LFS does not exist in the kernel
350 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
351 ** portability you should omit LFS.
352 **
353 ** Similar is true for MacOS.  LFS is only supported on MacOS 9 and later.
354 */
355 #ifndef SQLITE_DISABLE_LFS
356 # define _LARGE_FILE       1
357 # ifndef _FILE_OFFSET_BITS
358 #   define _FILE_OFFSET_BITS 64
359 # endif
360 # define _LARGEFILE_SOURCE 1
361 #endif
362
363
364 /*
365 ** The SQLITE_THREADSAFE macro must be defined as either 0 or 1.
366 ** Older versions of SQLite used an optional THREADSAFE macro.
367 ** We support that for legacy
368 */
369 #if !defined(SQLITE_THREADSAFE)
370 #if defined(THREADSAFE)
371 # define SQLITE_THREADSAFE THREADSAFE
372 #else
373 # define SQLITE_THREADSAFE 1
374 #endif
375 #endif
376
377 /*
378 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
379 ** It determines whether or not the features related to 
380 ** SQLITE_CONFIG_MEMSTATUS are availabe by default or not. This value can
381 ** be overridden at runtime using the sqlite3_config() API.
382 */
383 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
384 # define SQLITE_DEFAULT_MEMSTATUS 1
385 #endif
386
387 /*
388 ** Exactly one of the following macros must be defined in order to
389 ** specify which memory allocation subsystem to use.
390 **
391 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
392 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
393 **     SQLITE_MEMORY_SIZE            // internal allocator #1
394 **     SQLITE_MMAP_HEAP_SIZE         // internal mmap() allocator
395 **     SQLITE_POW2_MEMORY_SIZE       // internal power-of-two allocator
396 **
397 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
398 ** the default.
399 */
400 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
401     defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
402     defined(SQLITE_POW2_MEMORY_SIZE)>1
403 # error "At most one of the following compile-time configuration options\
404  is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG, SQLITE_MEMORY_SIZE,\
405  SQLITE_MMAP_HEAP_SIZE, SQLITE_POW2_MEMORY_SIZE"
406 #endif
407 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
408     defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
409     defined(SQLITE_POW2_MEMORY_SIZE)==0
410 # define SQLITE_SYSTEM_MALLOC 1
411 #endif
412
413 /*
414 ** If SQLITE_MALLOC_SOFT_LIMIT is defined, then try to keep the
415 ** sizes of memory allocations below this value where possible.
416 */
417 #if defined(SQLITE_POW2_MEMORY_SIZE) && !defined(SQLITE_MALLOC_SOFT_LIMIT)
418 # define SQLITE_MALLOC_SOFT_LIMIT 1024
419 #endif
420
421 /*
422 ** We need to define _XOPEN_SOURCE as follows in order to enable
423 ** recursive mutexes on most unix systems.  But Mac OS X is different.
424 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
425 ** so it is omitted there.  See ticket #2673.
426 **
427 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
428 ** implemented on some systems.  So we avoid defining it at all
429 ** if it is already defined or if it is unneeded because we are
430 ** not doing a threadsafe build.  Ticket #2681.
431 **
432 ** See also ticket #2741.
433 */
434 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
435 #  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
436 #endif
437
438 /*
439 ** The TCL headers are only needed when compiling the TCL bindings.
440 */
441 #if defined(SQLITE_TCL) || defined(TCLSH)
442 # include <tcl.h>
443 #endif
444
445 /*
446 ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
447 ** Setting NDEBUG makes the code smaller and run faster.  So the following
448 ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
449 ** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
450 ** feature.
451 */
452 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
453 # define NDEBUG 1
454 #endif
455
456 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
457 /************** Begin file sqlite3.h *****************************************/
458 /*
459 ** 2001 September 15
460 **
461 ** The author disclaims copyright to this source code.  In place of
462 ** a legal notice, here is a blessing:
463 **
464 **    May you do good and not evil.
465 **    May you find forgiveness for yourself and forgive others.
466 **    May you share freely, never taking more than you give.
467 **
468 *************************************************************************
469 ** This header file defines the interface that the SQLite library
470 ** presents to client programs.  If a C-function, structure, datatype,
471 ** or constant definition does not appear in this file, then it is
472 ** not a published API of SQLite, is subject to change without
473 ** notice, and should not be referenced by programs that use SQLite.
474 **
475 ** Some of the definitions that are in this file are marked as
476 ** "experimental".  Experimental interfaces are normally new
477 ** features recently added to SQLite.  We do not anticipate changes
478 ** to experimental interfaces but reserve to make minor changes if
479 ** experience from use "in the wild" suggest such changes are prudent.
480 **
481 ** The official C-language API documentation for SQLite is derived
482 ** from comments in this file.  This file is the authoritative source
483 ** on how SQLite interfaces are suppose to operate.
484 **
485 ** The name of this file under configuration management is "sqlite.h.in".
486 ** The makefile makes some minor changes to this file (such as inserting
487 ** the version number) and changes its name to "sqlite3.h" as
488 ** part of the build process.
489 **
490 ** @(#) $Id: sqlite.h.in,v 1.415 2008/11/19 01:20:26 drh Exp $
491 */
492 #ifndef _SQLITE3_H_
493 #define _SQLITE3_H_
494 #include <stdarg.h>     /* Needed for the definition of va_list */
495
496 /*
497 ** Make sure we can call this stuff from C++.
498 */
499 #if 0
500 extern "C" {
501 #endif
502
503
504 /*
505 ** Add the ability to override 'extern'
506 */
507 #ifndef SQLITE_EXTERN
508 # define SQLITE_EXTERN extern
509 #endif
510
511 /*
512 ** These no-op macros are used in front of interfaces to mark those
513 ** interfaces as either deprecated or experimental.  New applications
514 ** should not use deprecated intrfaces - they are support for backwards
515 ** compatibility only.  Application writers should be aware that
516 ** experimental interfaces are subject to change in point releases.
517 **
518 ** These macros used to resolve to various kinds of compiler magic that
519 ** would generate warning messages when they were used.  But that
520 ** compiler magic ended up generating such a flurry of bug reports
521 ** that we have taken it all out and gone back to using simple
522 ** noop macros.
523 */
524 #define SQLITE_DEPRECATED
525 #define SQLITE_EXPERIMENTAL
526
527 /*
528 ** Ensure these symbols were not defined by some previous header file.
529 */
530 #ifdef SQLITE_VERSION
531 # undef SQLITE_VERSION
532 #endif
533 #ifdef SQLITE_VERSION_NUMBER
534 # undef SQLITE_VERSION_NUMBER
535 #endif
536
537 /*
538 ** CAPI3REF: Compile-Time Library Version Numbers {H10010} <S60100>
539 **
540 ** The SQLITE_VERSION and SQLITE_VERSION_NUMBER #defines in
541 ** the sqlite3.h file specify the version of SQLite with which
542 ** that header file is associated.
543 **
544 ** The "version" of SQLite is a string of the form "X.Y.Z".
545 ** The phrase "alpha" or "beta" might be appended after the Z.
546 ** The X value is major version number always 3 in SQLite3.
547 ** The X value only changes when backwards compatibility is
548 ** broken and we intend to never break backwards compatibility.
549 ** The Y value is the minor version number and only changes when
550 ** there are major feature enhancements that are forwards compatible
551 ** but not backwards compatible.
552 ** The Z value is the release number and is incremented with
553 ** each release but resets back to 0 whenever Y is incremented.
554 **
555 ** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()].
556 **
557 ** INVARIANTS:
558 **
559 ** {H10011} The SQLITE_VERSION #define in the sqlite3.h header file shall
560 **          evaluate to a string literal that is the SQLite version
561 **          with which the header file is associated.
562 **
563 ** {H10014} The SQLITE_VERSION_NUMBER #define shall resolve to an integer
564 **          with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z
565 **          are the major version, minor version, and release number.
566 */
567 #define SQLITE_VERSION         "3.6.6.2"
568 #define SQLITE_VERSION_NUMBER  3006006
569
570 /*
571 ** CAPI3REF: Run-Time Library Version Numbers {H10020} <S60100>
572 ** KEYWORDS: sqlite3_version
573 **
574 ** These features provide the same information as the [SQLITE_VERSION]
575 ** and [SQLITE_VERSION_NUMBER] #defines in the header, but are associated
576 ** with the library instead of the header file.  Cautious programmers might
577 ** include a check in their application to verify that
578 ** sqlite3_libversion_number() always returns the value
579 ** [SQLITE_VERSION_NUMBER].
580 **
581 ** The sqlite3_libversion() function returns the same information as is
582 ** in the sqlite3_version[] string constant.  The function is provided
583 ** for use in DLLs since DLL users usually do not have direct access to string
584 ** constants within the DLL.
585 **
586 ** INVARIANTS:
587 **
588 ** {H10021} The [sqlite3_libversion_number()] interface shall return
589 **          an integer equal to [SQLITE_VERSION_NUMBER].
590 **
591 ** {H10022} The [sqlite3_version] string constant shall contain
592 **          the text of the [SQLITE_VERSION] string.
593 **
594 ** {H10023} The [sqlite3_libversion()] function shall return
595 **          a pointer to the [sqlite3_version] string constant.
596 */
597 SQLITE_API const char sqlite3_version[];
598 SQLITE_API const char *sqlite3_libversion(void);
599 SQLITE_API int sqlite3_libversion_number(void);
600
601 /*
602 ** CAPI3REF: Test To See If The Library Is Threadsafe {H10100} <S60100>
603 **
604 ** SQLite can be compiled with or without mutexes.  When
605 ** the [SQLITE_THREADSAFE] C preprocessor macro 1 or 2, mutexes
606 ** are enabled and SQLite is threadsafe.  When the
607 ** [SQLITE_THREADSAFE] macro is 0, 
608 ** the mutexes are omitted.  Without the mutexes, it is not safe
609 ** to use SQLite concurrently from more than one thread.
610 **
611 ** Enabling mutexes incurs a measurable performance penalty.
612 ** So if speed is of utmost importance, it makes sense to disable
613 ** the mutexes.  But for maximum safety, mutexes should be enabled.
614 ** The default behavior is for mutexes to be enabled.
615 **
616 ** This interface can be used by a program to make sure that the
617 ** version of SQLite that it is linking against was compiled with
618 ** the desired setting of the [SQLITE_THREADSAFE] macro.
619 **
620 ** This interface only reports on the compile-time mutex setting
621 ** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
622 ** SQLITE_THREADSAFE=1 then mutexes are enabled by default but
623 ** can be fully or partially disabled using a call to [sqlite3_config()]
624 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
625 ** or [SQLITE_CONFIG_MUTEX].  The return value of this function shows
626 ** only the default compile-time setting, not any run-time changes
627 ** to that setting.
628 **
629 ** See the [threading mode] documentation for additional information.
630 **
631 ** INVARIANTS:
632 **
633 ** {H10101} The [sqlite3_threadsafe()] function shall return zero if
634 **          and only if SQLite was compiled with mutexing code omitted.
635 **
636 ** {H10102} The value returned by the [sqlite3_threadsafe()] function
637 **          shall remain the same across calls to [sqlite3_config()].
638 */
639 SQLITE_API int sqlite3_threadsafe(void);
640
641 /*
642 ** CAPI3REF: Database Connection Handle {H12000} <S40200>
643 ** KEYWORDS: {database connection} {database connections}
644 **
645 ** Each open SQLite database is represented by a pointer to an instance of
646 ** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
647 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
648 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
649 ** is its destructor.  There are many other interfaces (such as
650 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
651 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
652 ** sqlite3 object.
653 */
654 typedef struct sqlite3 sqlite3;
655
656 /*
657 ** CAPI3REF: 64-Bit Integer Types {H10200} <S10110>
658 ** KEYWORDS: sqlite_int64 sqlite_uint64
659 **
660 ** Because there is no cross-platform way to specify 64-bit integer types
661 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
662 **
663 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
664 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
665 ** compatibility only.
666 **
667 ** INVARIANTS:
668 **
669 ** {H10201} The [sqlite_int64] and [sqlite3_int64] type shall specify
670 **          a 64-bit signed integer.
671 **
672 ** {H10202} The [sqlite_uint64] and [sqlite3_uint64] type shall specify
673 **          a 64-bit unsigned integer.
674 */
675 #ifdef SQLITE_INT64_TYPE
676   typedef SQLITE_INT64_TYPE sqlite_int64;
677   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
678 #elif defined(_MSC_VER) || defined(__BORLANDC__)
679   typedef __int64 sqlite_int64;
680   typedef unsigned __int64 sqlite_uint64;
681 #else
682   typedef long long int sqlite_int64;
683   typedef unsigned long long int sqlite_uint64;
684 #endif
685 typedef sqlite_int64 sqlite3_int64;
686 typedef sqlite_uint64 sqlite3_uint64;
687
688 /*
689 ** If compiling for a processor that lacks floating point support,
690 ** substitute integer for floating-point.
691 */
692 #ifdef SQLITE_OMIT_FLOATING_POINT
693 # define double sqlite3_int64
694 #endif
695
696 /*
697 ** CAPI3REF: Closing A Database Connection {H12010} <S30100><S40200>
698 **
699 ** This routine is the destructor for the [sqlite3] object.
700 **
701 ** Applications should [sqlite3_finalize | finalize] all [prepared statements]
702 ** and [sqlite3_blob_close | close] all [BLOB handles] associated with
703 ** the [sqlite3] object prior to attempting to close the object.
704 ** The [sqlite3_next_stmt()] interface can be used to locate all
705 ** [prepared statements] associated with a [database connection] if desired.
706 ** Typical code might look like this:
707 **
708 ** <blockquote><pre>
709 ** sqlite3_stmt *pStmt;
710 ** while( (pStmt = sqlite3_next_stmt(db, 0))!=0 ){
711 ** &nbsp;   sqlite3_finalize(pStmt);
712 ** }
713 ** </pre></blockquote>
714 **
715 ** If [sqlite3_close()] is invoked while a transaction is open,
716 ** the transaction is automatically rolled back.
717 **
718 ** INVARIANTS:
719 **
720 ** {H12011} A successful call to [sqlite3_close(C)] shall destroy the
721 **          [database connection] object C.
722 **
723 ** {H12012} A successful call to [sqlite3_close(C)] shall return SQLITE_OK.
724 **
725 ** {H12013} A successful call to [sqlite3_close(C)] shall release all
726 **          memory and system resources associated with [database connection]
727 **          C.
728 **
729 ** {H12014} A call to [sqlite3_close(C)] on a [database connection] C that
730 **          has one or more open [prepared statements] shall fail with
731 **          an [SQLITE_BUSY] error code.
732 **
733 ** {H12015} A call to [sqlite3_close(C)] where C is a NULL pointer shall
734 **          be a harmless no-op returning SQLITE_OK.
735 **
736 ** {H12019} When [sqlite3_close(C)] is invoked on a [database connection] C
737 **          that has a pending transaction, the transaction shall be
738 **          rolled back.
739 **
740 ** ASSUMPTIONS:
741 **
742 ** {A12016} The C parameter to [sqlite3_close(C)] must be either a NULL
743 **          pointer or an [sqlite3] object pointer obtained
744 **          from [sqlite3_open()], [sqlite3_open16()], or
745 **          [sqlite3_open_v2()], and not previously closed.
746 */
747 SQLITE_API int sqlite3_close(sqlite3 *);
748
749 /*
750 ** The type for a callback function.
751 ** This is legacy and deprecated.  It is included for historical
752 ** compatibility and is not documented.
753 */
754 typedef int (*sqlite3_callback)(void*,int,char**, char**);
755
756 /*
757 ** CAPI3REF: One-Step Query Execution Interface {H12100} <S10000>
758 **
759 ** The sqlite3_exec() interface is a convenient way of running one or more
760 ** SQL statements without having to write a lot of C code.  The UTF-8 encoded
761 ** SQL statements are passed in as the second parameter to sqlite3_exec().
762 ** The statements are evaluated one by one until either an error or
763 ** an interrupt is encountered, or until they are all done.  The 3rd parameter
764 ** is an optional callback that is invoked once for each row of any query
765 ** results produced by the SQL statements.  The 5th parameter tells where
766 ** to write any error messages.
767 **
768 ** The error message passed back through the 5th parameter is held
769 ** in memory obtained from [sqlite3_malloc()].  To avoid a memory leak,
770 ** the calling application should call [sqlite3_free()] on any error
771 ** message returned through the 5th parameter when it has finished using
772 ** the error message.
773 **
774 ** If the SQL statement in the 2nd parameter is NULL or an empty string
775 ** or a string containing only whitespace and comments, then no SQL
776 ** statements are evaluated and the database is not changed.
777 **
778 ** The sqlite3_exec() interface is implemented in terms of
779 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()].
780 ** The sqlite3_exec() routine does nothing to the database that cannot be done
781 ** by [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()].
782 **
783 ** INVARIANTS:
784 **
785 ** {H12101} A successful invocation of [sqlite3_exec(D,S,C,A,E)]
786 **          shall sequentially evaluate all of the UTF-8 encoded,
787 **          semicolon-separated SQL statements in the zero-terminated
788 **          string S within the context of the [database connection] D.
789 **
790 ** {H12102} If the S parameter to [sqlite3_exec(D,S,C,A,E)] is NULL then
791 **          the actions of the interface shall be the same as if the
792 **          S parameter were an empty string.
793 **
794 ** {H12104} The return value of [sqlite3_exec()] shall be [SQLITE_OK] if all
795 **          SQL statements run successfully and to completion.
796 **
797 ** {H12105} The return value of [sqlite3_exec()] shall be an appropriate
798 **          non-zero [error code] if any SQL statement fails.
799 **
800 ** {H12107} If one or more of the SQL statements handed to [sqlite3_exec()]
801 **          return results and the 3rd parameter is not NULL, then
802 **          the callback function specified by the 3rd parameter shall be
803 **          invoked once for each row of result.
804 **
805 ** {H12110} If the callback returns a non-zero value then [sqlite3_exec()]
806 **          shall abort the SQL statement it is currently evaluating,
807 **          skip all subsequent SQL statements, and return [SQLITE_ABORT].
808 **
809 ** {H12113} The [sqlite3_exec()] routine shall pass its 4th parameter through
810 **          as the 1st parameter of the callback.
811 **
812 ** {H12116} The [sqlite3_exec()] routine shall set the 2nd parameter of its
813 **          callback to be the number of columns in the current row of
814 **          result.
815 **
816 ** {H12119} The [sqlite3_exec()] routine shall set the 3rd parameter of its
817 **          callback to be an array of pointers to strings holding the
818 **          values for each column in the current result set row as
819 **          obtained from [sqlite3_column_text()].
820 **
821 ** {H12122} The [sqlite3_exec()] routine shall set the 4th parameter of its
822 **          callback to be an array of pointers to strings holding the
823 **          names of result columns as obtained from [sqlite3_column_name()].
824 **
825 ** {H12125} If the 3rd parameter to [sqlite3_exec()] is NULL then
826 **          [sqlite3_exec()] shall silently discard query results.
827 **
828 ** {H12131} If an error occurs while parsing or evaluating any of the SQL
829 **          statements in the S parameter of [sqlite3_exec(D,S,C,A,E)] and if
830 **          the E parameter is not NULL, then [sqlite3_exec()] shall store
831 **          in *E an appropriate error message written into memory obtained
832 **          from [sqlite3_malloc()].
833 **
834 ** {H12134} The [sqlite3_exec(D,S,C,A,E)] routine shall set the value of
835 **          *E to NULL if E is not NULL and there are no errors.
836 **
837 ** {H12137} The [sqlite3_exec(D,S,C,A,E)] function shall set the [error code]
838 **          and message accessible via [sqlite3_errcode()], 
839 **          [sqlite3_extended_errcode()],
840 **          [sqlite3_errmsg()], and [sqlite3_errmsg16()].
841 **
842 ** {H12138} If the S parameter to [sqlite3_exec(D,S,C,A,E)] is NULL or an
843 **          empty string or contains nothing other than whitespace, comments,
844 **          and/or semicolons, then results of [sqlite3_errcode()],
845 **          [sqlite3_extended_errcode()],
846 **          [sqlite3_errmsg()], and [sqlite3_errmsg16()]
847 **          shall reset to indicate no errors.
848 **
849 ** ASSUMPTIONS:
850 **
851 ** {A12141} The first parameter to [sqlite3_exec()] must be an valid and open
852 **          [database connection].
853 **
854 ** {A12142} The database connection must not be closed while
855 **          [sqlite3_exec()] is running.
856 **
857 ** {A12143} The calling function should use [sqlite3_free()] to free
858 **          the memory that *errmsg is left pointing at once the error
859 **          message is no longer needed.
860 **
861 ** {A12145} The SQL statement text in the 2nd parameter to [sqlite3_exec()]
862 **          must remain unchanged while [sqlite3_exec()] is running.
863 */
864 SQLITE_API int sqlite3_exec(
865   sqlite3*,                                  /* An open database */
866   const char *sql,                           /* SQL to be evaluated */
867   int (*callback)(void*,int,char**,char**),  /* Callback function */
868   void *,                                    /* 1st argument to callback */
869   char **errmsg                              /* Error msg written here */
870 );
871
872 /*
873 ** CAPI3REF: Result Codes {H10210} <S10700>
874 ** KEYWORDS: SQLITE_OK {error code} {error codes}
875 ** KEYWORDS: {result code} {result codes}
876 **
877 ** Many SQLite functions return an integer result code from the set shown
878 ** here in order to indicates success or failure.
879 **
880 ** New error codes may be added in future versions of SQLite.
881 **
882 ** See also: [SQLITE_IOERR_READ | extended result codes]
883 */
884 #define SQLITE_OK           0   /* Successful result */
885 /* beginning-of-error-codes */
886 #define SQLITE_ERROR        1   /* SQL error or missing database */
887 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
888 #define SQLITE_PERM         3   /* Access permission denied */
889 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
890 #define SQLITE_BUSY         5   /* The database file is locked */
891 #define SQLITE_LOCKED       6   /* A table in the database is locked */
892 #define SQLITE_NOMEM        7   /* A malloc() failed */
893 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
894 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
895 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
896 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
897 #define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
898 #define SQLITE_FULL        13   /* Insertion failed because database is full */
899 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
900 #define SQLITE_PROTOCOL    15   /* NOT USED. Database lock protocol error */
901 #define SQLITE_EMPTY       16   /* Database is empty */
902 #define SQLITE_SCHEMA      17   /* The database schema changed */
903 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
904 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
905 #define SQLITE_MISMATCH    20   /* Data type mismatch */
906 #define SQLITE_MISUSE      21   /* Library used incorrectly */
907 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
908 #define SQLITE_AUTH        23   /* Authorization denied */
909 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
910 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
911 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
912 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
913 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
914 /* end-of-error-codes */
915
916 /*
917 ** CAPI3REF: Extended Result Codes {H10220} <S10700>
918 ** KEYWORDS: {extended error code} {extended error codes}
919 ** KEYWORDS: {extended result code} {extended result codes}
920 **
921 ** In its default configuration, SQLite API routines return one of 26 integer
922 ** [SQLITE_OK | result codes].  However, experience has shown that many of
923 ** these result codes are too coarse-grained.  They do not provide as
924 ** much information about problems as programmers might like.  In an effort to
925 ** address this, newer versions of SQLite (version 3.3.8 and later) include
926 ** support for additional result codes that provide more detailed information
927 ** about errors. The extended result codes are enabled or disabled
928 ** on a per database connection basis using the
929 ** [sqlite3_extended_result_codes()] API.
930 **
931 ** Some of the available extended result codes are listed here.
932 ** One may expect the number of extended result codes will be expand
933 ** over time.  Software that uses extended result codes should expect
934 ** to see new result codes in future releases of SQLite.
935 **
936 ** The SQLITE_OK result code will never be extended.  It will always
937 ** be exactly zero.
938 **
939 ** INVARIANTS:
940 **
941 ** {H10223} The symbolic name for an extended result code shall contains
942 **          a related primary result code as a prefix.
943 **
944 ** {H10224} Primary result code names shall contain a single "_" character.
945 **
946 ** {H10225} Extended result code names shall contain two or more "_" characters.
947 **
948 ** {H10226} The numeric value of an extended result code shall contain the
949 **          numeric value of its corresponding primary result code in
950 **          its least significant 8 bits.
951 */
952 #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
953 #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
954 #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
955 #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
956 #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
957 #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
958 #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
959 #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
960 #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
961 #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
962 #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
963 #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
964 #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
965 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
966 #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
967
968 /*
969 ** CAPI3REF: Flags For File Open Operations {H10230} <H11120> <H12700>
970 **
971 ** These bit values are intended for use in the
972 ** 3rd parameter to the [sqlite3_open_v2()] interface and
973 ** in the 4th parameter to the xOpen method of the
974 ** [sqlite3_vfs] object.
975 */
976 #define SQLITE_OPEN_READONLY         0x00000001
977 #define SQLITE_OPEN_READWRITE        0x00000002
978 #define SQLITE_OPEN_CREATE           0x00000004
979 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008
980 #define SQLITE_OPEN_EXCLUSIVE        0x00000010
981 #define SQLITE_OPEN_MAIN_DB          0x00000100
982 #define SQLITE_OPEN_TEMP_DB          0x00000200
983 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400
984 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800
985 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000
986 #define SQLITE_OPEN_SUBJOURNAL       0x00002000
987 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000
988 #define SQLITE_OPEN_NOMUTEX          0x00008000
989 #define SQLITE_OPEN_FULLMUTEX        0x00010000
990
991 /*
992 ** CAPI3REF: Device Characteristics {H10240} <H11120>
993 **
994 ** The xDeviceCapabilities method of the [sqlite3_io_methods]
995 ** object returns an integer which is a vector of the these
996 ** bit values expressing I/O characteristics of the mass storage
997 ** device that holds the file that the [sqlite3_io_methods]
998 ** refers to.
999 **
1000 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1001 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1002 ** mean that writes of blocks that are nnn bytes in size and
1003 ** are aligned to an address which is an integer multiple of
1004 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1005 ** that when data is appended to a file, the data is appended
1006 ** first then the size of the file is extended, never the other
1007 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1008 ** information is written to disk in the same order as calls
1009 ** to xWrite().
1010 */
1011 #define SQLITE_IOCAP_ATOMIC          0x00000001
1012 #define SQLITE_IOCAP_ATOMIC512       0x00000002
1013 #define SQLITE_IOCAP_ATOMIC1K        0x00000004
1014 #define SQLITE_IOCAP_ATOMIC2K        0x00000008
1015 #define SQLITE_IOCAP_ATOMIC4K        0x00000010
1016 #define SQLITE_IOCAP_ATOMIC8K        0x00000020
1017 #define SQLITE_IOCAP_ATOMIC16K       0x00000040
1018 #define SQLITE_IOCAP_ATOMIC32K       0x00000080
1019 #define SQLITE_IOCAP_ATOMIC64K       0x00000100
1020 #define SQLITE_IOCAP_SAFE_APPEND     0x00000200
1021 #define SQLITE_IOCAP_SEQUENTIAL      0x00000400
1022
1023 /*
1024 ** CAPI3REF: File Locking Levels {H10250} <H11120> <H11310>
1025 **
1026 ** SQLite uses one of these integer values as the second
1027 ** argument to calls it makes to the xLock() and xUnlock() methods
1028 ** of an [sqlite3_io_methods] object.
1029 */
1030 #define SQLITE_LOCK_NONE          0
1031 #define SQLITE_LOCK_SHARED        1
1032 #define SQLITE_LOCK_RESERVED      2
1033 #define SQLITE_LOCK_PENDING       3
1034 #define SQLITE_LOCK_EXCLUSIVE     4
1035
1036 /*
1037 ** CAPI3REF: Synchronization Type Flags {H10260} <H11120>
1038 **
1039 ** When SQLite invokes the xSync() method of an
1040 ** [sqlite3_io_methods] object it uses a combination of
1041 ** these integer values as the second argument.
1042 **
1043 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1044 ** sync operation only needs to flush data to mass storage.  Inode
1045 ** information need not be flushed. The SQLITE_SYNC_NORMAL flag means
1046 ** to use normal fsync() semantics. The SQLITE_SYNC_FULL flag means
1047 ** to use Mac OS X style fullsync instead of fsync().
1048 */
1049 #define SQLITE_SYNC_NORMAL        0x00002
1050 #define SQLITE_SYNC_FULL          0x00003
1051 #define SQLITE_SYNC_DATAONLY      0x00010
1052
1053 /*
1054 ** CAPI3REF: OS Interface Open File Handle {H11110} <S20110>
1055 **
1056 ** An [sqlite3_file] object represents an open file in the OS
1057 ** interface layer.  Individual OS interface implementations will
1058 ** want to subclass this object by appending additional fields
1059 ** for their own use.  The pMethods entry is a pointer to an
1060 ** [sqlite3_io_methods] object that defines methods for performing
1061 ** I/O operations on the open file.
1062 */
1063 typedef struct sqlite3_file sqlite3_file;
1064 struct sqlite3_file {
1065   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1066 };
1067
1068 /*
1069 ** CAPI3REF: OS Interface File Virtual Methods Object {H11120} <S20110>
1070 **
1071 ** Every file opened by the [sqlite3_vfs] xOpen method populates an
1072 ** [sqlite3_file] object (or, more commonly, a subclass of the
1073 ** [sqlite3_file] object) with a pointer to an instance of this object.
1074 ** This object defines the methods used to perform various operations
1075 ** against the open file represented by the [sqlite3_file] object.
1076 **
1077 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1078 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1079 ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1080 ** flag may be ORed in to indicate that only the data of the file
1081 ** and not its inode needs to be synced.
1082 **
1083 ** The integer values to xLock() and xUnlock() are one of
1084 ** <ul>
1085 ** <li> [SQLITE_LOCK_NONE],
1086 ** <li> [SQLITE_LOCK_SHARED],
1087 ** <li> [SQLITE_LOCK_RESERVED],
1088 ** <li> [SQLITE_LOCK_PENDING], or
1089 ** <li> [SQLITE_LOCK_EXCLUSIVE].
1090 ** </ul>
1091 ** xLock() increases the lock. xUnlock() decreases the lock.
1092 ** The xCheckReservedLock() method checks whether any database connection,
1093 ** either in this process or in some other process, is holding a RESERVED,
1094 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
1095 ** if such a lock exists and false otherwise.
1096 **
1097 ** The xFileControl() method is a generic interface that allows custom
1098 ** VFS implementations to directly control an open file using the
1099 ** [sqlite3_file_control()] interface.  The second "op" argument is an
1100 ** integer opcode.  The third argument is a generic pointer intended to
1101 ** point to a structure that may contain arguments or space in which to
1102 ** write return values.  Potential uses for xFileControl() might be
1103 ** functions to enable blocking locks with timeouts, to change the
1104 ** locking strategy (for example to use dot-file locks), to inquire
1105 ** about the status of a lock, or to break stale locks.  The SQLite
1106 ** core reserves all opcodes less than 100 for its own use.
1107 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1108 ** Applications that define a custom xFileControl method should use opcodes
1109 ** greater than 100 to avoid conflicts.
1110 **
1111 ** The xSectorSize() method returns the sector size of the
1112 ** device that underlies the file.  The sector size is the
1113 ** minimum write that can be performed without disturbing
1114 ** other bytes in the file.  The xDeviceCharacteristics()
1115 ** method returns a bit vector describing behaviors of the
1116 ** underlying device:
1117 **
1118 ** <ul>
1119 ** <li> [SQLITE_IOCAP_ATOMIC]
1120 ** <li> [SQLITE_IOCAP_ATOMIC512]
1121 ** <li> [SQLITE_IOCAP_ATOMIC1K]
1122 ** <li> [SQLITE_IOCAP_ATOMIC2K]
1123 ** <li> [SQLITE_IOCAP_ATOMIC4K]
1124 ** <li> [SQLITE_IOCAP_ATOMIC8K]
1125 ** <li> [SQLITE_IOCAP_ATOMIC16K]
1126 ** <li> [SQLITE_IOCAP_ATOMIC32K]
1127 ** <li> [SQLITE_IOCAP_ATOMIC64K]
1128 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
1129 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
1130 ** </ul>
1131 **
1132 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1133 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1134 ** mean that writes of blocks that are nnn bytes in size and
1135 ** are aligned to an address which is an integer multiple of
1136 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1137 ** that when data is appended to a file, the data is appended
1138 ** first then the size of the file is extended, never the other
1139 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1140 ** information is written to disk in the same order as calls
1141 ** to xWrite().
1142 **
1143 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1144 ** in the unread portions of the buffer with zeros.  A VFS that
1145 ** fails to zero-fill short reads might seem to work.  However,
1146 ** failure to zero-fill short reads will eventually lead to
1147 ** database corruption.
1148 */
1149 typedef struct sqlite3_io_methods sqlite3_io_methods;
1150 struct sqlite3_io_methods {
1151   int iVersion;
1152   int (*xClose)(sqlite3_file*);
1153   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1154   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1155   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1156   int (*xSync)(sqlite3_file*, int flags);
1157   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1158   int (*xLock)(sqlite3_file*, int);
1159   int (*xUnlock)(sqlite3_file*, int);
1160   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1161   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1162   int (*xSectorSize)(sqlite3_file*);
1163   int (*xDeviceCharacteristics)(sqlite3_file*);
1164   /* Additional methods may be added in future releases */
1165 };
1166
1167 /*
1168 ** CAPI3REF: Standard File Control Opcodes {H11310} <S30800>
1169 **
1170 ** These integer constants are opcodes for the xFileControl method
1171 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1172 ** interface.
1173 **
1174 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1175 ** opcode causes the xFileControl method to write the current state of
1176 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1177 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1178 ** into an integer that the pArg argument points to. This capability
1179 ** is used during testing and only needs to be supported when SQLITE_TEST
1180 ** is defined.
1181 */
1182 #define SQLITE_FCNTL_LOCKSTATE        1
1183
1184 /*
1185 ** CAPI3REF: Mutex Handle {H17110} <S20130>
1186 **
1187 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1188 ** abstract type for a mutex object.  The SQLite core never looks
1189 ** at the internal representation of an [sqlite3_mutex].  It only
1190 ** deals with pointers to the [sqlite3_mutex] object.
1191 **
1192 ** Mutexes are created using [sqlite3_mutex_alloc()].
1193 */
1194 typedef struct sqlite3_mutex sqlite3_mutex;
1195
1196 /*
1197 ** CAPI3REF: OS Interface Object {H11140} <S20100>
1198 **
1199 ** An instance of the sqlite3_vfs object defines the interface between
1200 ** the SQLite core and the underlying operating system.  The "vfs"
1201 ** in the name of the object stands for "virtual file system".
1202 **
1203 ** The value of the iVersion field is initially 1 but may be larger in
1204 ** future versions of SQLite.  Additional fields may be appended to this
1205 ** object when the iVersion value is increased.  Note that the structure
1206 ** of the sqlite3_vfs object changes in the transaction between
1207 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1208 ** modified.
1209 **
1210 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1211 ** structure used by this VFS.  mxPathname is the maximum length of
1212 ** a pathname in this VFS.
1213 **
1214 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1215 ** the pNext pointer.  The [sqlite3_vfs_register()]
1216 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1217 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1218 ** searches the list.  Neither the application code nor the VFS
1219 ** implementation should use the pNext pointer.
1220 **
1221 ** The pNext field is the only field in the sqlite3_vfs
1222 ** structure that SQLite will ever modify.  SQLite will only access
1223 ** or modify this field while holding a particular static mutex.
1224 ** The application should never modify anything within the sqlite3_vfs
1225 ** object once the object has been registered.
1226 **
1227 ** The zName field holds the name of the VFS module.  The name must
1228 ** be unique across all VFS modules.
1229 **
1230 ** {H11141} SQLite will guarantee that the zFilename parameter to xOpen
1231 ** is either a NULL pointer or string obtained
1232 ** from xFullPathname().  SQLite further guarantees that
1233 ** the string will be valid and unchanged until xClose() is
1234 ** called. {END}  Because of the previous sentense,
1235 ** the [sqlite3_file] can safely store a pointer to the
1236 ** filename if it needs to remember the filename for some reason.
1237 ** If the zFilename parameter is xOpen is a NULL pointer then xOpen
1238 ** must invite its own temporary name for the file.  Whenever the 
1239 ** xFilename parameter is NULL it will also be the case that the
1240 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1241 **
1242 ** {H11142} The flags argument to xOpen() includes all bits set in
1243 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1244 ** or [sqlite3_open16()] is used, then flags includes at least
1245 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. {END}
1246 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1247 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1248 **
1249 ** {H11143} SQLite will also add one of the following flags to the xOpen()
1250 ** call, depending on the object being opened:
1251 **
1252 ** <ul>
1253 ** <li>  [SQLITE_OPEN_MAIN_DB]
1254 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1255 ** <li>  [SQLITE_OPEN_TEMP_DB]
1256 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1257 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1258 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
1259 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1260 ** </ul> {END}
1261 **
1262 ** The file I/O implementation can use the object type flags to
1263 ** change the way it deals with files.  For example, an application
1264 ** that does not care about crash recovery or rollback might make
1265 ** the open of a journal file a no-op.  Writes to this journal would
1266 ** also be no-ops, and any attempt to read the journal would return
1267 ** SQLITE_IOERR.  Or the implementation might recognize that a database
1268 ** file will be doing page-aligned sector reads and writes in a random
1269 ** order and set up its I/O subsystem accordingly.
1270 **
1271 ** SQLite might also add one of the following flags to the xOpen method:
1272 **
1273 ** <ul>
1274 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1275 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1276 ** </ul>
1277 **
1278 ** {H11145} The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1279 ** deleted when it is closed.  {H11146} The [SQLITE_OPEN_DELETEONCLOSE]
1280 ** will be set for TEMP  databases, journals and for subjournals.
1281 **
1282 ** {H11147} The [SQLITE_OPEN_EXCLUSIVE] flag means the file should be opened
1283 ** for exclusive access.  This flag is set for all files except
1284 ** for the main database file.
1285 **
1286 ** {H11148} At least szOsFile bytes of memory are allocated by SQLite
1287 ** to hold the  [sqlite3_file] structure passed as the third
1288 ** argument to xOpen. {END}  The xOpen method does not have to
1289 ** allocate the structure; it should just fill it in.
1290 **
1291 ** {H11149} The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1292 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1293 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1294 ** to test whether a file is at least readable. {END}  The file can be a
1295 ** directory.
1296 **
1297 ** {H11150} SQLite will always allocate at least mxPathname+1 bytes for the
1298 ** output buffer xFullPathname. {H11151} The exact size of the output buffer
1299 ** is also passed as a parameter to both  methods. {END}  If the output buffer
1300 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1301 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1302 ** to prevent this by setting mxPathname to a sufficiently large value.
1303 **
1304 ** The xRandomness(), xSleep(), and xCurrentTime() interfaces
1305 ** are not strictly a part of the filesystem, but they are
1306 ** included in the VFS structure for completeness.
1307 ** The xRandomness() function attempts to return nBytes bytes
1308 ** of good-quality randomness into zOut.  The return value is
1309 ** the actual number of bytes of randomness obtained.
1310 ** The xSleep() method causes the calling thread to sleep for at
1311 ** least the number of microseconds given.  The xCurrentTime()
1312 ** method returns a Julian Day Number for the current date and time.
1313 */
1314 typedef struct sqlite3_vfs sqlite3_vfs;
1315 struct sqlite3_vfs {
1316   int iVersion;            /* Structure version number */
1317   int szOsFile;            /* Size of subclassed sqlite3_file */
1318   int mxPathname;          /* Maximum file pathname length */
1319   sqlite3_vfs *pNext;      /* Next registered VFS */
1320   const char *zName;       /* Name of this virtual file system */
1321   void *pAppData;          /* Pointer to application-specific data */
1322   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1323                int flags, int *pOutFlags);
1324   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1325   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1326   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1327   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1328   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1329   void *(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol);
1330   void (*xDlClose)(sqlite3_vfs*, void*);
1331   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1332   int (*xSleep)(sqlite3_vfs*, int microseconds);
1333   int (*xCurrentTime)(sqlite3_vfs*, double*);
1334   int (*xGetLastError)(sqlite3_vfs*, int, char *);
1335   /* New fields may be appended in figure versions.  The iVersion
1336   ** value will increment whenever this happens. */
1337 };
1338
1339 /*
1340 ** CAPI3REF: Flags for the xAccess VFS method {H11190} <H11140>
1341 **
1342 ** {H11191} These integer constants can be used as the third parameter to
1343 ** the xAccess method of an [sqlite3_vfs] object. {END}  They determine
1344 ** what kind of permissions the xAccess method is looking for.
1345 ** {H11192} With SQLITE_ACCESS_EXISTS, the xAccess method
1346 ** simply checks whether the file exists.
1347 ** {H11193} With SQLITE_ACCESS_READWRITE, the xAccess method
1348 ** checks whether the file is both readable and writable.
1349 ** {H11194} With SQLITE_ACCESS_READ, the xAccess method
1350 ** checks whether the file is readable.
1351 */
1352 #define SQLITE_ACCESS_EXISTS    0
1353 #define SQLITE_ACCESS_READWRITE 1
1354 #define SQLITE_ACCESS_READ      2
1355
1356 /*
1357 ** CAPI3REF: Initialize The SQLite Library {H10130} <S20000><S30100>
1358 **
1359 ** The sqlite3_initialize() routine initializes the
1360 ** SQLite library.  The sqlite3_shutdown() routine
1361 ** deallocates any resources that were allocated by sqlite3_initialize().
1362 **
1363 ** A call to sqlite3_initialize() is an "effective" call if it is
1364 ** the first time sqlite3_initialize() is invoked during the lifetime of
1365 ** the process, or if it is the first time sqlite3_initialize() is invoked
1366 ** following a call to sqlite3_shutdown().  Only an effective call
1367 ** of sqlite3_initialize() does any initialization.  All other calls
1368 ** are harmless no-ops.
1369 **
1370 ** Among other things, sqlite3_initialize() shall invoke
1371 ** sqlite3_os_init().  Similarly, sqlite3_shutdown()
1372 ** shall invoke sqlite3_os_end().
1373 **
1374 ** The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1375 ** If for some reason, sqlite3_initialize() is unable to initialize
1376 ** the library (perhaps it is unable to allocate a needed resource such
1377 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1378 **
1379 ** The sqlite3_initialize() routine is called internally by many other
1380 ** SQLite interfaces so that an application usually does not need to
1381 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1382 ** calls sqlite3_initialize() so the SQLite library will be automatically
1383 ** initialized when [sqlite3_open()] is called if it has not be initialized
1384 ** already.  However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1385 ** compile-time option, then the automatic calls to sqlite3_initialize()
1386 ** are omitted and the application must call sqlite3_initialize() directly
1387 ** prior to using any other SQLite interface.  For maximum portability,
1388 ** it is recommended that applications always invoke sqlite3_initialize()
1389 ** directly prior to using any other SQLite interface.  Future releases
1390 ** of SQLite may require this.  In other words, the behavior exhibited
1391 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1392 ** default behavior in some future release of SQLite.
1393 **
1394 ** The sqlite3_os_init() routine does operating-system specific
1395 ** initialization of the SQLite library.  The sqlite3_os_end()
1396 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
1397 ** performed by these routines include allocation or deallocation
1398 ** of static resources, initialization of global variables,
1399 ** setting up a default [sqlite3_vfs] module, or setting up
1400 ** a default configuration using [sqlite3_config()].
1401 **
1402 ** The application should never invoke either sqlite3_os_init()
1403 ** or sqlite3_os_end() directly.  The application should only invoke
1404 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1405 ** interface is called automatically by sqlite3_initialize() and
1406 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1407 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1408 ** are built into SQLite when it is compiled for unix, windows, or os/2.
1409 ** When built for other platforms (using the [SQLITE_OS_OTHER=1] compile-time
1410 ** option) the application must supply a suitable implementation for
1411 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1412 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1413 ** must return [SQLITE_OK] on success and some other [error code] upon
1414 ** failure.
1415 */
1416 SQLITE_API int sqlite3_initialize(void);
1417 SQLITE_API int sqlite3_shutdown(void);
1418 SQLITE_API int sqlite3_os_init(void);
1419 SQLITE_API int sqlite3_os_end(void);
1420
1421 /*
1422 ** CAPI3REF: Configuring The SQLite Library {H14100} <S20000><S30200>
1423 ** EXPERIMENTAL
1424 **
1425 ** The sqlite3_config() interface is used to make global configuration
1426 ** changes to SQLite in order to tune SQLite to the specific needs of
1427 ** the application.  The default configuration is recommended for most
1428 ** applications and so this routine is usually not necessary.  It is
1429 ** provided to support rare applications with unusual needs.
1430 **
1431 ** The sqlite3_config() interface is not threadsafe.  The application
1432 ** must insure that no other SQLite interfaces are invoked by other
1433 ** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1434 ** may only be invoked prior to library initialization using
1435 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1436 ** Note, however, that sqlite3_config() can be called as part of the
1437 ** implementation of an application-defined [sqlite3_os_init()].
1438 **
1439 ** The first argument to sqlite3_config() is an integer
1440 ** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines
1441 ** what property of SQLite is to be configured.  Subsequent arguments
1442 ** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option]
1443 ** in the first argument.
1444 **
1445 ** When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1446 ** If the option is unknown or SQLite is unable to set the option
1447 ** then this routine returns a non-zero [error code].
1448 **
1449 ** INVARIANTS:
1450 **
1451 ** {H14103} A successful invocation of [sqlite3_config()] shall return
1452 **          [SQLITE_OK].
1453 **
1454 ** {H14106} The [sqlite3_config()] interface shall return [SQLITE_MISUSE]
1455 **          if it is invoked in between calls to [sqlite3_initialize()] and
1456 **          [sqlite3_shutdown()].
1457 **
1458 ** {H14120} A successful call to [sqlite3_config]([SQLITE_CONFIG_SINGLETHREAD])
1459 **          shall set the default [threading mode] to Single-thread.
1460 **
1461 ** {H14123} A successful call to [sqlite3_config]([SQLITE_CONFIG_MULTITHREAD])
1462 **          shall set the default [threading mode] to Multi-thread.
1463 **
1464 ** {H14126} A successful call to [sqlite3_config]([SQLITE_CONFIG_SERIALIZED])
1465 **          shall set the default [threading mode] to Serialized.
1466 **
1467 ** {H14129} A successful call to [sqlite3_config]([SQLITE_CONFIG_MUTEX],X)
1468 **          where X is a pointer to an initialized [sqlite3_mutex_methods]
1469 **          object shall cause all subsequent mutex operations performed
1470 **          by SQLite to use the mutex methods that were present in X
1471 **          during the call to [sqlite3_config()].
1472 **
1473 ** {H14132} A successful call to [sqlite3_config]([SQLITE_CONFIG_GETMUTEX],X)
1474 **          where X is a pointer to an [sqlite3_mutex_methods] object 
1475 **          shall overwrite the content of [sqlite3_mutex_methods] object
1476 **          with the mutex methods currently in use by SQLite.
1477 **
1478 ** {H14135} A successful call to [sqlite3_config]([SQLITE_CONFIG_MALLOC],M)
1479 **          where M is a pointer to an initialized [sqlite3_mem_methods]
1480 **          object shall cause all subsequent memory allocation operations
1481 **          performed by SQLite to use the methods that were present in 
1482 **          M during the call to [sqlite3_config()].
1483 **
1484 ** {H14138} A successful call to [sqlite3_config]([SQLITE_CONFIG_GETMALLOC],M)
1485 **          where M is a pointer to an [sqlite3_mem_methods] object shall
1486 **          overwrite the content of [sqlite3_mem_methods] object with 
1487 **          the memory allocation methods currently in use by
1488 **          SQLite.
1489 **
1490 ** {H14141} A successful call to [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],1)
1491 **          shall enable the memory allocation status collection logic.
1492 **
1493 ** {H14144} A successful call to [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],0)
1494 **          shall disable the memory allocation status collection logic.
1495 **
1496 ** {H14147} The memory allocation status collection logic shall be
1497 **          enabled by default.
1498 **
1499 ** {H14150} A successful call to [sqlite3_config]([SQLITE_CONFIG_SCRATCH],S,Z,N)
1500 **          where Z and N are non-negative integers and 
1501 **          S is a pointer to an aligned memory buffer not less than
1502 **          Z*N bytes in size shall cause S to be used by the
1503 **          [scratch memory allocator] for as many as N simulataneous
1504 **          allocations each of size Z.
1505 **
1506 ** {H14153} A successful call to [sqlite3_config]([SQLITE_CONFIG_SCRATCH],S,Z,N)
1507 **          where S is a NULL pointer shall disable the
1508 **          [scratch memory allocator].
1509 **
1510 ** {H14156} A successful call to
1511 **          [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],S,Z,N)
1512 **          where Z and N are non-negative integers and 
1513 **          S is a pointer to an aligned memory buffer not less than
1514 **          Z*N bytes in size shall cause S to be used by the
1515 **          [pagecache memory allocator] for as many as N simulataneous
1516 **          allocations each of size Z.
1517 **
1518 ** {H14159} A successful call to
1519 **          [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],S,Z,N)
1520 **          where S is a NULL pointer shall disable the
1521 **          [pagecache memory allocator].
1522 **
1523 ** {H14162} A successful call to [sqlite3_config]([SQLITE_CONFIG_HEAP],H,Z,N)
1524 **          where Z and N are non-negative integers and 
1525 **          H is a pointer to an aligned memory buffer not less than
1526 **          Z bytes in size shall enable the [memsys5] memory allocator
1527 **          and cause it to use buffer S as its memory source and to use
1528 **          a minimum allocation size of N.
1529 **
1530 ** {H14165} A successful call to [sqlite3_config]([SQLITE_CONFIG_HEAP],H,Z,N)
1531 **          where H is a NULL pointer shall disable the
1532 **          [memsys5] memory allocator.
1533 **
1534 ** {H14168} A successful call to [sqlite3_config]([SQLITE_CONFIG_LOOKASIDE],Z,N)
1535 **          shall cause the default [lookaside memory allocator] configuration
1536 **          for new [database connections] to be N slots of Z bytes each.
1537 */
1538 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_config(int, ...);
1539
1540 /*
1541 ** CAPI3REF: Configure database connections  {H14200} <S20000>
1542 ** EXPERIMENTAL
1543 **
1544 ** The sqlite3_db_config() interface is used to make configuration
1545 ** changes to a [database connection].  The interface is similar to
1546 ** [sqlite3_config()] except that the changes apply to a single
1547 ** [database connection] (specified in the first argument).  The
1548 ** sqlite3_db_config() interface can only be used immediately after
1549 ** the database connection is created using [sqlite3_open()],
1550 ** [sqlite3_open16()], or [sqlite3_open_v2()].  
1551 **
1552 ** The second argument to sqlite3_db_config(D,V,...)  is the
1553 ** configuration verb - an integer code that indicates what
1554 ** aspect of the [database connection] is being configured.
1555 ** The only choice for this value is [SQLITE_DBCONFIG_LOOKASIDE].
1556 ** New verbs are likely to be added in future releases of SQLite.
1557 ** Additional arguments depend on the verb.
1558 **
1559 ** INVARIANTS:
1560 **
1561 ** {H14203} A call to [sqlite3_db_config(D,V,...)] shall return [SQLITE_OK]
1562 **          if and only if the call is successful.
1563 **
1564 ** {H14206} If one or more slots of the [lookaside memory allocator] for
1565 **          [database connection] D are in use, then a call to
1566 **          [sqlite3_db_config](D,[SQLITE_DBCONFIG_LOOKASIDE],...) shall
1567 **          fail with an [SQLITE_BUSY] return code.
1568 **
1569 ** {H14209} A successful call to 
1570 **          [sqlite3_db_config](D,[SQLITE_DBCONFIG_LOOKASIDE],B,Z,N) where
1571 **          D is an open [database connection] and Z and N are positive
1572 **          integers and B is an aligned buffer at least Z*N bytes in size
1573 **          shall cause the [lookaside memory allocator] for D to use buffer B 
1574 **          with N slots of Z bytes each.
1575 **
1576 ** {H14212} A successful call to 
1577 **          [sqlite3_db_config](D,[SQLITE_DBCONFIG_LOOKASIDE],B,Z,N) where
1578 **          D is an open [database connection] and Z and N are positive
1579 **          integers and B is NULL pointer shall cause the
1580 **          [lookaside memory allocator] for D to a obtain Z*N byte buffer
1581 **          from the primary memory allocator and use that buffer
1582 **          with N lookaside slots of Z bytes each.
1583 **
1584 ** {H14215} A successful call to 
1585 **          [sqlite3_db_config](D,[SQLITE_DBCONFIG_LOOKASIDE],B,Z,N) where
1586 **          D is an open [database connection] and Z and N are zero shall
1587 **          disable the [lookaside memory allocator] for D.
1588 **
1589 **
1590 */
1591 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_config(sqlite3*, int op, ...);
1592
1593 /*
1594 ** CAPI3REF: Memory Allocation Routines {H10155} <S20120>
1595 ** EXPERIMENTAL
1596 **
1597 ** An instance of this object defines the interface between SQLite
1598 ** and low-level memory allocation routines.
1599 **
1600 ** This object is used in only one place in the SQLite interface.
1601 ** A pointer to an instance of this object is the argument to
1602 ** [sqlite3_config()] when the configuration option is
1603 ** [SQLITE_CONFIG_MALLOC].  By creating an instance of this object
1604 ** and passing it to [sqlite3_config()] during configuration, an
1605 ** application can specify an alternative memory allocation subsystem
1606 ** for SQLite to use for all of its dynamic memory needs.
1607 **
1608 ** Note that SQLite comes with a built-in memory allocator that is
1609 ** perfectly adequate for the overwhelming majority of applications
1610 ** and that this object is only useful to a tiny minority of applications
1611 ** with specialized memory allocation requirements.  This object is
1612 ** also used during testing of SQLite in order to specify an alternative
1613 ** memory allocator that simulates memory out-of-memory conditions in
1614 ** order to verify that SQLite recovers gracefully from such
1615 ** conditions.
1616 **
1617 ** The xMalloc, xFree, and xRealloc methods must work like the
1618 ** malloc(), free(), and realloc() functions from the standard library.
1619 **
1620 ** xSize should return the allocated size of a memory allocation
1621 ** previously obtained from xMalloc or xRealloc.  The allocated size
1622 ** is always at least as big as the requested size but may be larger.
1623 **
1624 ** The xRoundup method returns what would be the allocated size of
1625 ** a memory allocation given a particular requested size.  Most memory
1626 ** allocators round up memory allocations at least to the next multiple
1627 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1628 **
1629 ** The xInit method initializes the memory allocator.  (For example,
1630 ** it might allocate any require mutexes or initialize internal data
1631 ** structures.  The xShutdown method is invoked (indirectly) by
1632 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1633 ** by xInit.  The pAppData pointer is used as the only parameter to
1634 ** xInit and xShutdown.
1635 */
1636 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1637 struct sqlite3_mem_methods {
1638   void *(*xMalloc)(int);         /* Memory allocation function */
1639   void (*xFree)(void*);          /* Free a prior allocation */
1640   void *(*xRealloc)(void*,int);  /* Resize an allocation */
1641   int (*xSize)(void*);           /* Return the size of an allocation */
1642   int (*xRoundup)(int);          /* Round up request size to allocation size */
1643   int (*xInit)(void*);           /* Initialize the memory allocator */
1644   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1645   void *pAppData;                /* Argument to xInit() and xShutdown() */
1646 };
1647
1648 /*
1649 ** CAPI3REF: Configuration Options {H10160} <S20000>
1650 ** EXPERIMENTAL
1651 **
1652 ** These constants are the available integer configuration options that
1653 ** can be passed as the first argument to the [sqlite3_config()] interface.
1654 **
1655 ** New configuration options may be added in future releases of SQLite.
1656 ** Existing configuration options might be discontinued.  Applications
1657 ** should check the return code from [sqlite3_config()] to make sure that
1658 ** the call worked.  The [sqlite3_config()] interface will return a
1659 ** non-zero [error code] if a discontinued or unsupported configuration option
1660 ** is invoked.
1661 **
1662 ** <dl>
1663 ** <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1664 ** <dd>There are no arguments to this option.  This option disables
1665 ** all mutexing and puts SQLite into a mode where it can only be used
1666 ** by a single thread.</dd>
1667 **
1668 ** <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1669 ** <dd>There are no arguments to this option.  This option disables
1670 ** mutexing on [database connection] and [prepared statement] objects.
1671 ** The application is responsible for serializing access to
1672 ** [database connections] and [prepared statements].  But other mutexes
1673 ** are enabled so that SQLite will be safe to use in a multi-threaded
1674 ** environment as long as no two threads attempt to use the same
1675 ** [database connection] at the same time.  See the [threading mode]
1676 ** documentation for additional information.</dd>
1677 **
1678 ** <dt>SQLITE_CONFIG_SERIALIZED</dt>
1679 ** <dd>There are no arguments to this option.  This option enables
1680 ** all mutexes including the recursive
1681 ** mutexes on [database connection] and [prepared statement] objects.
1682 ** In this mode (which is the default when SQLite is compiled with
1683 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1684 ** to [database connections] and [prepared statements] so that the
1685 ** application is free to use the same [database connection] or the
1686 ** same [prepared statement] in different threads at the same time.
1687 ** See the [threading mode] documentation for additional information.</dd>
1688 **
1689 ** <dt>SQLITE_CONFIG_MALLOC</dt>
1690 ** <dd>This option takes a single argument which is a pointer to an
1691 ** instance of the [sqlite3_mem_methods] structure.  The argument specifies
1692 ** alternative low-level memory allocation routines to be used in place of
1693 ** the memory allocation routines built into SQLite.</dd>
1694 **
1695 ** <dt>SQLITE_CONFIG_GETMALLOC</dt>
1696 ** <dd>This option takes a single argument which is a pointer to an
1697 ** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
1698 ** structure is filled with the currently defined memory allocation routines.
1699 ** This option can be used to overload the default memory allocation
1700 ** routines with a wrapper that simulations memory allocation failure or
1701 ** tracks memory usage, for example.</dd>
1702 **
1703 ** <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1704 ** <dd>This option takes single argument of type int, interpreted as a 
1705 ** boolean, which enables or disables the collection of memory allocation 
1706 ** statistics. When disabled, the following SQLite interfaces become 
1707 ** non-operational:
1708 **   <ul>
1709 **   <li> [sqlite3_memory_used()]
1710 **   <li> [sqlite3_memory_highwater()]
1711 **   <li> [sqlite3_soft_heap_limit()]
1712 **   <li> [sqlite3_status()]
1713 **   </ul>
1714 ** </dd>
1715 **
1716 ** <dt>SQLITE_CONFIG_SCRATCH</dt>
1717 ** <dd>This option specifies a static memory buffer that SQLite can use for
1718 ** scratch memory.  There are three arguments:  A pointer to the memory, the
1719 ** size of each scratch buffer (sz), and the number of buffers (N).  The sz
1720 ** argument must be a multiple of 16. The sz parameter should be a few bytes
1721 ** larger than the actual scratch space required due internal overhead.
1722 ** The first
1723 ** argument should point to an allocation of at least sz*N bytes of memory.
1724 ** SQLite will use no more than one scratch buffer at once per thread, so
1725 ** N should be set to the expected maximum number of threads.  The sz
1726 ** parameter should be 6 times the size of the largest database page size.
1727 ** Scratch buffers are used as part of the btree balance operation.  If
1728 ** The btree balancer needs additional memory beyond what is provided by
1729 ** scratch buffers or if no scratch buffer space is specified, then SQLite
1730 ** goes to [sqlite3_malloc()] to obtain the memory it needs.</dd>
1731 **
1732 ** <dt>SQLITE_CONFIG_PAGECACHE</dt>
1733 ** <dd>This option specifies a static memory buffer that SQLite can use for
1734 ** the database page cache with the default page cache implemenation.  
1735 ** This configuration should not be used if an application-define page
1736 ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option.
1737 ** There are three arguments to this option: A pointer to the
1738 ** memory, the size of each page buffer (sz), and the number of pages (N).
1739 ** The sz argument must be a power of two between 512 and 32768.  The first
1740 ** argument should point to an allocation of at least sz*N bytes of memory.
1741 ** SQLite will use the memory provided by the first argument to satisfy its
1742 ** memory needs for the first N pages that it adds to cache.  If additional
1743 ** page cache memory is needed beyond what is provided by this option, then
1744 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1745 ** The implementation might use one or more of the N buffers to hold 
1746 ** memory accounting information. </dd>
1747 **
1748 ** <dt>SQLITE_CONFIG_HEAP</dt>
1749 ** <dd>This option specifies a static memory buffer that SQLite will use
1750 ** for all of its dynamic memory allocation needs beyond those provided
1751 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
1752 ** There are three arguments: A pointer to the memory, the number of
1753 ** bytes in the memory buffer, and the minimum allocation size.  If
1754 ** the first pointer (the memory pointer) is NULL, then SQLite reverts
1755 ** to using its default memory allocator (the system malloc() implementation),
1756 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  If the
1757 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
1758 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
1759 ** allocator is engaged to handle all of SQLites memory allocation needs.</dd>
1760 **
1761 ** <dt>SQLITE_CONFIG_MUTEX</dt>
1762 ** <dd>This option takes a single argument which is a pointer to an
1763 ** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
1764 ** alternative low-level mutex routines to be used in place
1765 ** the mutex routines built into SQLite.</dd>
1766 **
1767 ** <dt>SQLITE_CONFIG_GETMUTEX</dt>
1768 ** <dd>This option takes a single argument which is a pointer to an
1769 ** instance of the [sqlite3_mutex_methods] structure.  The
1770 ** [sqlite3_mutex_methods]
1771 ** structure is filled with the currently defined mutex routines.
1772 ** This option can be used to overload the default mutex allocation
1773 ** routines with a wrapper used to track mutex usage for performance
1774 ** profiling or testing, for example.</dd>
1775 **
1776 ** <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1777 ** <dd>This option takes two arguments that determine the default
1778 ** memory allcation lookaside optimization.  The first argument is the
1779 ** size of each lookaside buffer slot and the second is the number of
1780 ** slots allocated to each database connection.</dd>
1781 **
1782 ** <dt>SQLITE_CONFIG_PCACHE</dt>
1783 ** <dd>This option takes a single argument which is a pointer to
1784 ** an [sqlite3_pcache_methods] object.  This object specifies the interface
1785 ** to a custom page cache implementation.  SQLite makes a copy of the
1786 ** object and uses it for page cache memory allocations.</dd>
1787 **
1788 ** <dt>SQLITE_CONFIG_GETPCACHE</dt>
1789 ** <dd>This option takes a single argument which is a pointer to an
1790 ** [sqlite3_pcache_methods] object.  SQLite copies of the current
1791 ** page cache implementation into that object.</dd>
1792 **
1793 ** </dl>
1794 */
1795 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
1796 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
1797 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
1798 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
1799 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
1800 #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
1801 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
1802 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
1803 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
1804 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
1805 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
1806 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ 
1807 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
1808 #define SQLITE_CONFIG_PCACHE       14  /* sqlite3_pcache_methods* */
1809 #define SQLITE_CONFIG_GETPCACHE    15  /* sqlite3_pcache_methods* */
1810
1811 /*
1812 ** CAPI3REF: Configuration Options {H10170} <S20000>
1813 ** EXPERIMENTAL
1814 **
1815 ** These constants are the available integer configuration options that
1816 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
1817 **
1818 ** New configuration options may be added in future releases of SQLite.
1819 ** Existing configuration options might be discontinued.  Applications
1820 ** should check the return code from [sqlite3_db_config()] to make sure that
1821 ** the call worked.  The [sqlite3_db_config()] interface will return a
1822 ** non-zero [error code] if a discontinued or unsupported configuration option
1823 ** is invoked.
1824 **
1825 ** <dl>
1826 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
1827 ** <dd>This option takes three additional arguments that determine the 
1828 ** [lookaside memory allocator] configuration for the [database connection].
1829 ** The first argument (the third parameter to [sqlite3_db_config()] is a
1830 ** pointer to a memory buffer to use for lookaside memory.  The first
1831 ** argument may be NULL in which case SQLite will allocate the lookaside
1832 ** buffer itself using [sqlite3_malloc()].  The second argument is the
1833 ** size of each lookaside buffer slot and the third argument is the number of
1834 ** slots.  The size of the buffer in the first argument must be greater than
1835 ** or equal to the product of the second and third arguments.</dd>
1836 **
1837 ** </dl>
1838 */
1839 #define SQLITE_DBCONFIG_LOOKASIDE    1001  /* void* int int */
1840
1841
1842 /*
1843 ** CAPI3REF: Enable Or Disable Extended Result Codes {H12200} <S10700>
1844 **
1845 ** The sqlite3_extended_result_codes() routine enables or disables the
1846 ** [extended result codes] feature of SQLite. The extended result
1847 ** codes are disabled by default for historical compatibility considerations.
1848 **
1849 ** INVARIANTS:
1850 **
1851 ** {H12201} Each new [database connection] shall have the
1852 **          [extended result codes] feature disabled by default.
1853 **
1854 ** {H12202} The [sqlite3_extended_result_codes(D,F)] interface shall enable
1855 **          [extended result codes] for the  [database connection] D
1856 **          if the F parameter is true, or disable them if F is false.
1857 */
1858 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
1859
1860 /*
1861 ** CAPI3REF: Last Insert Rowid {H12220} <S10700>
1862 **
1863 ** Each entry in an SQLite table has a unique 64-bit signed
1864 ** integer key called the "rowid". The rowid is always available
1865 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
1866 ** names are not also used by explicitly declared columns. If
1867 ** the table has a column of type INTEGER PRIMARY KEY then that column
1868 ** is another alias for the rowid.
1869 **
1870 ** This routine returns the rowid of the most recent
1871 ** successful [INSERT] into the database from the [database connection]
1872 ** in the first argument.  If no successful [INSERT]s
1873 ** have ever occurred on that database connection, zero is returned.
1874 **
1875 ** If an [INSERT] occurs within a trigger, then the rowid of the inserted
1876 ** row is returned by this routine as long as the trigger is running.
1877 ** But once the trigger terminates, the value returned by this routine
1878 ** reverts to the last value inserted before the trigger fired.
1879 **
1880 ** An [INSERT] that fails due to a constraint violation is not a
1881 ** successful [INSERT] and does not change the value returned by this
1882 ** routine.  Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
1883 ** and INSERT OR ABORT make no changes to the return value of this
1884 ** routine when their insertion fails.  When INSERT OR REPLACE
1885 ** encounters a constraint violation, it does not fail.  The
1886 ** INSERT continues to completion after deleting rows that caused
1887 ** the constraint problem so INSERT OR REPLACE will always change
1888 ** the return value of this interface.
1889 **
1890 ** For the purposes of this routine, an [INSERT] is considered to
1891 ** be successful even if it is subsequently rolled back.
1892 **
1893 ** INVARIANTS:
1894 **
1895 ** {H12221} The [sqlite3_last_insert_rowid()] function shall return the rowid
1896 **          of the most recent successful [INSERT] performed on the same
1897 **          [database connection] and within the same or higher level
1898 **          trigger context, or zero if there have been no qualifying
1899 **          [INSERT] statements.
1900 **
1901 ** {H12223} The [sqlite3_last_insert_rowid()] function shall return the
1902 **          same value when called from the same trigger context
1903 **          immediately before and after a [ROLLBACK].
1904 **
1905 ** ASSUMPTIONS:
1906 **
1907 ** {A12232} If a separate thread performs a new [INSERT] on the same
1908 **          database connection while the [sqlite3_last_insert_rowid()]
1909 **          function is running and thus changes the last insert rowid,
1910 **          then the value returned by [sqlite3_last_insert_rowid()] is
1911 **          unpredictable and might not equal either the old or the new
1912 **          last insert rowid.
1913 */
1914 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
1915
1916 /*
1917 ** CAPI3REF: Count The Number Of Rows Modified {H12240} <S10600>
1918 **
1919 ** This function returns the number of database rows that were changed
1920 ** or inserted or deleted by the most recently completed SQL statement
1921 ** on the [database connection] specified by the first parameter.
1922 ** Only changes that are directly specified by the [INSERT], [UPDATE],
1923 ** or [DELETE] statement are counted.  Auxiliary changes caused by
1924 ** triggers are not counted. Use the [sqlite3_total_changes()] function
1925 ** to find the total number of changes including changes caused by triggers.
1926 **
1927 ** A "row change" is a change to a single row of a single table
1928 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
1929 ** are changed as side effects of REPLACE constraint resolution,
1930 ** rollback, ABORT processing, DROP TABLE, or by any other
1931 ** mechanisms do not count as direct row changes.
1932 **
1933 ** A "trigger context" is a scope of execution that begins and
1934 ** ends with the script of a trigger.  Most SQL statements are
1935 ** evaluated outside of any trigger.  This is the "top level"
1936 ** trigger context.  If a trigger fires from the top level, a
1937 ** new trigger context is entered for the duration of that one
1938 ** trigger.  Subtriggers create subcontexts for their duration.
1939 **
1940 ** Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
1941 ** not create a new trigger context.
1942 **
1943 ** This function returns the number of direct row changes in the
1944 ** most recent INSERT, UPDATE, or DELETE statement within the same
1945 ** trigger context.
1946 **
1947 ** Thus, when called from the top level, this function returns the
1948 ** number of changes in the most recent INSERT, UPDATE, or DELETE
1949 ** that also occurred at the top level.  Within the body of a trigger,
1950 ** the sqlite3_changes() interface can be called to find the number of
1951 ** changes in the most recently completed INSERT, UPDATE, or DELETE
1952 ** statement within the body of the same trigger.
1953 ** However, the number returned does not include changes
1954 ** caused by subtriggers since those have their own context.
1955 **
1956 ** SQLite implements the command "DELETE FROM table" without a WHERE clause
1957 ** by dropping and recreating the table.  Doing so is much faster than going
1958 ** through and deleting individual elements from the table.  Because of this
1959 ** optimization, the deletions in "DELETE FROM table" are not row changes and
1960 ** will not be counted by the sqlite3_changes() or [sqlite3_total_changes()]
1961 ** functions, regardless of the number of elements that were originally
1962 ** in the table.  To get an accurate count of the number of rows deleted, use
1963 ** "DELETE FROM table WHERE 1" instead.  Or recompile using the
1964 ** [SQLITE_OMIT_TRUNCATE_OPTIMIZATION] compile-time option to disable the
1965 ** optimization on all queries.
1966 **
1967 ** INVARIANTS:
1968 **
1969 ** {H12241} The [sqlite3_changes()] function shall return the number of
1970 **          row changes caused by the most recent INSERT, UPDATE,
1971 **          or DELETE statement on the same database connection and
1972 **          within the same or higher trigger context, or zero if there have
1973 **          not been any qualifying row changes.
1974 **
1975 ** {H12243} Statements of the form "DELETE FROM tablename" with no
1976 **          WHERE clause shall cause subsequent calls to
1977 **          [sqlite3_changes()] to return zero, regardless of the
1978 **          number of rows originally in the table.
1979 **
1980 ** ASSUMPTIONS:
1981 **
1982 ** {A12252} If a separate thread makes changes on the same database connection
1983 **          while [sqlite3_changes()] is running then the value returned
1984 **          is unpredictable and not meaningful.
1985 */
1986 SQLITE_API int sqlite3_changes(sqlite3*);
1987
1988 /*
1989 ** CAPI3REF: Total Number Of Rows Modified {H12260} <S10600>
1990 **
1991 ** This function returns the number of row changes caused by INSERT,
1992 ** UPDATE or DELETE statements since the [database connection] was opened.
1993 ** The count includes all changes from all trigger contexts.  However,
1994 ** the count does not include changes used to implement REPLACE constraints,
1995 ** do rollbacks or ABORT processing, or DROP table processing.
1996 ** The changes are counted as soon as the statement that makes them is
1997 ** completed (when the statement handle is passed to [sqlite3_reset()] or
1998 ** [sqlite3_finalize()]).
1999 **
2000 ** SQLite implements the command "DELETE FROM table" without a WHERE clause
2001 ** by dropping and recreating the table.  (This is much faster than going
2002 ** through and deleting individual elements from the table.)  Because of this
2003 ** optimization, the deletions in "DELETE FROM table" are not row changes and
2004 ** will not be counted by the sqlite3_changes() or [sqlite3_total_changes()]
2005 ** functions, regardless of the number of elements that were originally
2006 ** in the table.  To get an accurate count of the number of rows deleted, use
2007 ** "DELETE FROM table WHERE 1" instead.   Or recompile using the
2008 ** [SQLITE_OMIT_TRUNCATE_OPTIMIZATION] compile-time option to disable the
2009 ** optimization on all queries.
2010 **
2011 ** See also the [sqlite3_changes()] interface.
2012 **
2013 ** INVARIANTS:
2014 **
2015 ** {H12261} The [sqlite3_total_changes()] returns the total number
2016 **          of row changes caused by INSERT, UPDATE, and/or DELETE
2017 **          statements on the same [database connection], in any
2018 **          trigger context, since the database connection was created.
2019 **
2020 ** {H12263} Statements of the form "DELETE FROM tablename" with no
2021 **          WHERE clause shall not change the value returned
2022 **          by [sqlite3_total_changes()].
2023 **
2024 ** ASSUMPTIONS:
2025 **
2026 ** {A12264} If a separate thread makes changes on the same database connection
2027 **          while [sqlite3_total_changes()] is running then the value
2028 **          returned is unpredictable and not meaningful.
2029 */
2030 SQLITE_API int sqlite3_total_changes(sqlite3*);
2031
2032 /*
2033 ** CAPI3REF: Interrupt A Long-Running Query {H12270} <S30500>
2034 **
2035 ** This function causes any pending database operation to abort and
2036 ** return at its earliest opportunity. This routine is typically
2037 ** called in response to a user action such as pressing "Cancel"
2038 ** or Ctrl-C where the user wants a long query operation to halt
2039 ** immediately.
2040 **
2041 ** It is safe to call this routine from a thread different from the
2042 ** thread that is currently running the database operation.  But it
2043 ** is not safe to call this routine with a [database connection] that
2044 ** is closed or might close before sqlite3_interrupt() returns.
2045 **
2046 ** If an SQL operation is very nearly finished at the time when
2047 ** sqlite3_interrupt() is called, then it might not have an opportunity
2048 ** to be interrupted and might continue to completion.
2049 **
2050 ** An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2051 ** If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2052 ** that is inside an explicit transaction, then the entire transaction
2053 ** will be rolled back automatically.
2054 **
2055 ** A call to sqlite3_interrupt() has no effect on SQL statements
2056 ** that are started after sqlite3_interrupt() returns.
2057 **
2058 ** INVARIANTS:
2059 **
2060 ** {H12271} The [sqlite3_interrupt()] interface will force all running
2061 **          SQL statements associated with the same database connection
2062 **          to halt after processing at most one additional row of data.
2063 **
2064 ** {H12272} Any SQL statement that is interrupted by [sqlite3_interrupt()]
2065 **          will return [SQLITE_INTERRUPT].
2066 **
2067 ** ASSUMPTIONS:
2068 **
2069 ** {A12279} If the database connection closes while [sqlite3_interrupt()]
2070 **          is running then bad things will likely happen.
2071 */
2072 SQLITE_API void sqlite3_interrupt(sqlite3*);
2073
2074 /*
2075 ** CAPI3REF: Determine If An SQL Statement Is Complete {H10510} <S70200>
2076 **
2077 ** These routines are useful for command-line input to determine if the
2078 ** currently entered text seems to form complete a SQL statement or
2079 ** if additional input is needed before sending the text into
2080 ** SQLite for parsing.  These routines return true if the input string
2081 ** appears to be a complete SQL statement.  A statement is judged to be
2082 ** complete if it ends with a semicolon token and is not a fragment of a
2083 ** CREATE TRIGGER statement.  Semicolons that are embedded within
2084 ** string literals or quoted identifier names or comments are not
2085 ** independent tokens (they are part of the token in which they are
2086 ** embedded) and thus do not count as a statement terminator.
2087 **
2088 ** These routines do not parse the SQL statements thus
2089 ** will not detect syntactically incorrect SQL.
2090 **
2091 ** INVARIANTS:
2092 **
2093 ** {H10511} A successful evaluation of [sqlite3_complete()] or
2094 **          [sqlite3_complete16()] functions shall
2095 **          return a numeric 1 if and only if the last non-whitespace
2096 **          token in their input is a semicolon that is not in between
2097 **          the BEGIN and END of a CREATE TRIGGER statement.
2098 **
2099 ** {H10512} If a memory allocation error occurs during an invocation
2100 **          of [sqlite3_complete()] or [sqlite3_complete16()] then the
2101 **          routine shall return [SQLITE_NOMEM].
2102 **
2103 ** ASSUMPTIONS:
2104 **
2105 ** {A10512} The input to [sqlite3_complete()] must be a zero-terminated
2106 **          UTF-8 string.
2107 **
2108 ** {A10513} The input to [sqlite3_complete16()] must be a zero-terminated
2109 **          UTF-16 string in native byte order.
2110 */
2111 SQLITE_API int sqlite3_complete(const char *sql);
2112 SQLITE_API int sqlite3_complete16(const void *sql);
2113
2114 /*
2115 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {H12310} <S40400>
2116 **
2117 ** This routine sets a callback function that might be invoked whenever
2118 ** an attempt is made to open a database table that another thread
2119 ** or process has locked.
2120 **
2121 ** If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2122 ** is returned immediately upon encountering the lock. If the busy callback
2123 ** is not NULL, then the callback will be invoked with two arguments.
2124 **
2125 ** The first argument to the handler is a copy of the void* pointer which
2126 ** is the third argument to sqlite3_busy_handler().  The second argument to
2127 ** the handler callback is the number of times that the busy handler has
2128 ** been invoked for this locking event.  If the
2129 ** busy callback returns 0, then no additional attempts are made to
2130 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2131 ** If the callback returns non-zero, then another attempt
2132 ** is made to open the database for reading and the cycle repeats.
2133 **
2134 ** The presence of a busy handler does not guarantee that it will be invoked
2135 ** when there is lock contention. If SQLite determines that invoking the busy
2136 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2137 ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2138 ** Consider a scenario where one process is holding a read lock that
2139 ** it is trying to promote to a reserved lock and
2140 ** a second process is holding a reserved lock that it is trying
2141 ** to promote to an exclusive lock.  The first process cannot proceed
2142 ** because it is blocked by the second and the second process cannot
2143 ** proceed because it is blocked by the first.  If both processes
2144 ** invoke the busy handlers, neither will make any progress.  Therefore,
2145 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2146 ** will induce the first process to release its read lock and allow
2147 ** the second process to proceed.
2148 **
2149 ** The default busy callback is NULL.
2150 **
2151 ** The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2152 ** when SQLite is in the middle of a large transaction where all the
2153 ** changes will not fit into the in-memory cache.  SQLite will
2154 ** already hold a RESERVED lock on the database file, but it needs
2155 ** to promote this lock to EXCLUSIVE so that it can spill cache
2156 ** pages into the database file without harm to concurrent
2157 ** readers.  If it is unable to promote the lock, then the in-memory
2158 ** cache will be left in an inconsistent state and so the error
2159 ** code is promoted from the relatively benign [SQLITE_BUSY] to
2160 ** the more severe [SQLITE_IOERR_BLOCKED].  This error code promotion
2161 ** forces an automatic rollback of the changes.  See the
2162 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2163 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2164 ** this is important.
2165 **
2166 ** There can only be a single busy handler defined for each
2167 ** [database connection].  Setting a new busy handler clears any
2168 ** previously set handler.  Note that calling [sqlite3_busy_timeout()]
2169 ** will also set or clear the busy handler.
2170 **
2171 ** The busy callback should not take any actions which modify the
2172 ** database connection that invoked the busy handler.  Any such actions
2173 ** result in undefined behavior.
2174 ** 
2175 ** INVARIANTS:
2176 **
2177 ** {H12311} The [sqlite3_busy_handler(D,C,A)] function shall replace
2178 **          busy callback in the [database connection] D with a new
2179 **          a new busy handler C and application data pointer A.
2180 **
2181 ** {H12312} Newly created [database connections] shall have a busy
2182 **          handler of NULL.
2183 **
2184 ** {H12314} When two or more [database connections] share a
2185 **          [sqlite3_enable_shared_cache | common cache],
2186 **          the busy handler for the database connection currently using
2187 **          the cache shall be invoked when the cache encounters a lock.
2188 **
2189 ** {H12316} If a busy handler callback returns zero, then the SQLite interface
2190 **          that provoked the locking event shall return [SQLITE_BUSY].
2191 **
2192 ** {H12318} SQLite shall invokes the busy handler with two arguments which
2193 **          are a copy of the pointer supplied by the 3rd parameter to
2194 **          [sqlite3_busy_handler()] and a count of the number of prior
2195 **          invocations of the busy handler for the same locking event.
2196 **
2197 ** ASSUMPTIONS:
2198 **
2199 ** {A12319} A busy handler must not close the database connection
2200 **          or [prepared statement] that invoked the busy handler.
2201 */
2202 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2203
2204 /*
2205 ** CAPI3REF: Set A Busy Timeout {H12340} <S40410>
2206 **
2207 ** This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2208 ** for a specified amount of time when a table is locked.  The handler
2209 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2210 ** have accumulated. {H12343} After "ms" milliseconds of sleeping,
2211 ** the handler returns 0 which causes [sqlite3_step()] to return
2212 ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2213 **
2214 ** Calling this routine with an argument less than or equal to zero
2215 ** turns off all busy handlers.
2216 **
2217 ** There can only be a single busy handler for a particular
2218 ** [database connection] any any given moment.  If another busy handler
2219 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
2220 ** this routine, that other busy handler is cleared.
2221 **
2222 ** INVARIANTS:
2223 **
2224 ** {H12341} The [sqlite3_busy_timeout()] function shall override any prior
2225 **          [sqlite3_busy_timeout()] or [sqlite3_busy_handler()] setting
2226 **          on the same [database connection].
2227 **
2228 ** {H12343} If the 2nd parameter to [sqlite3_busy_timeout()] is less than
2229 **          or equal to zero, then the busy handler shall be cleared so that
2230 **          all subsequent locking events immediately return [SQLITE_BUSY].
2231 **
2232 ** {H12344} If the 2nd parameter to [sqlite3_busy_timeout()] is a positive
2233 **          number N, then a busy handler shall be set that repeatedly calls
2234 **          the xSleep() method in the [sqlite3_vfs | VFS interface] until
2235 **          either the lock clears or until the cumulative sleep time
2236 **          reported back by xSleep() exceeds N milliseconds.
2237 */
2238 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2239
2240 /*
2241 ** CAPI3REF: Convenience Routines For Running Queries {H12370} <S10000>
2242 **
2243 ** Definition: A <b>result table</b> is memory data structure created by the
2244 ** [sqlite3_get_table()] interface.  A result table records the
2245 ** complete query results from one or more queries.
2246 **
2247 ** The table conceptually has a number of rows and columns.  But
2248 ** these numbers are not part of the result table itself.  These
2249 ** numbers are obtained separately.  Let N be the number of rows
2250 ** and M be the number of columns.
2251 **
2252 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2253 ** There are (N+1)*M elements in the array.  The first M pointers point
2254 ** to zero-terminated strings that  contain the names of the columns.
2255 ** The remaining entries all point to query results.  NULL values result
2256 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2257 ** string representation as returned by [sqlite3_column_text()].
2258 **
2259 ** A result table might consist of one or more memory allocations.
2260 ** It is not safe to pass a result table directly to [sqlite3_free()].
2261 ** A result table should be deallocated using [sqlite3_free_table()].
2262 **
2263 ** As an example of the result table format, suppose a query result
2264 ** is as follows:
2265 **
2266 ** <blockquote><pre>
2267 **        Name        | Age
2268 **        -----------------------
2269 **        Alice       | 43
2270 **        Bob         | 28
2271 **        Cindy       | 21
2272 ** </pre></blockquote>
2273 **
2274 ** There are two column (M==2) and three rows (N==3).  Thus the
2275 ** result table has 8 entries.  Suppose the result table is stored
2276 ** in an array names azResult.  Then azResult holds this content:
2277 **
2278 ** <blockquote><pre>
2279 **        azResult&#91;0] = "Name";
2280 **        azResult&#91;1] = "Age";
2281 **        azResult&#91;2] = "Alice";
2282 **        azResult&#91;3] = "43";
2283 **        azResult&#91;4] = "Bob";
2284 **        azResult&#91;5] = "28";
2285 **        azResult&#91;6] = "Cindy";
2286 **        azResult&#91;7] = "21";
2287 ** </pre></blockquote>
2288 **
2289 ** The sqlite3_get_table() function evaluates one or more
2290 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2291 ** string of its 2nd parameter.  It returns a result table to the
2292 ** pointer given in its 3rd parameter.
2293 **
2294 ** After the calling function has finished using the result, it should
2295 ** pass the pointer to the result table to sqlite3_free_table() in order to
2296 ** release the memory that was malloced.  Because of the way the
2297 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2298 ** function must not try to call [sqlite3_free()] directly.  Only
2299 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2300 **
2301 ** The sqlite3_get_table() interface is implemented as a wrapper around
2302 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2303 ** to any internal data structures of SQLite.  It uses only the public
2304 ** interface defined here.  As a consequence, errors that occur in the
2305 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2306 ** reflected in subsequent calls to [sqlite3_errcode()] or [sqlite3_errmsg()].
2307 **
2308 ** INVARIANTS:
2309 **
2310 ** {H12371} If a [sqlite3_get_table()] fails a memory allocation, then
2311 **          it shall free the result table under construction, abort the
2312 **          query in process, skip any subsequent queries, set the
2313 **          *pazResult output pointer to NULL and return [SQLITE_NOMEM].
2314 **
2315 ** {H12373} If the pnColumn parameter to [sqlite3_get_table()] is not NULL
2316 **          then a successful invocation of [sqlite3_get_table()] shall
2317 **          write the number of columns in the
2318 **          result set of the query into *pnColumn.
2319 **
2320 ** {H12374} If the pnRow parameter to [sqlite3_get_table()] is not NULL
2321 **          then a successful invocation of [sqlite3_get_table()] shall
2322 **          writes the number of rows in the
2323 **          result set of the query into *pnRow.
2324 **
2325 ** {H12376} A successful invocation of [sqlite3_get_table()] that computes
2326 **          N rows of result with C columns per row shall make *pazResult
2327 **          point to an array of pointers to (N+1)*C strings where the first
2328 **          C strings are column names as obtained from
2329 **          [sqlite3_column_name()] and the rest are column result values
2330 **          obtained from [sqlite3_column_text()].
2331 **
2332 ** {H12379} The values in the pazResult array returned by [sqlite3_get_table()]
2333 **          shall remain valid until cleared by [sqlite3_free_table()].
2334 **
2335 ** {H12382} When an error occurs during evaluation of [sqlite3_get_table()]
2336 **          the function shall set *pazResult to NULL, write an error message
2337 **          into memory obtained from [sqlite3_malloc()], make
2338 **          **pzErrmsg point to that error message, and return a
2339 **          appropriate [error code].
2340 */
2341 SQLITE_API int sqlite3_get_table(
2342   sqlite3 *db,          /* An open database */
2343   const char *zSql,     /* SQL to be evaluated */
2344   char ***pazResult,    /* Results of the query */
2345   int *pnRow,           /* Number of result rows written here */
2346   int *pnColumn,        /* Number of result columns written here */
2347   char **pzErrmsg       /* Error msg written here */
2348 );
2349 SQLITE_API void sqlite3_free_table(char **result);
2350
2351 /*
2352 ** CAPI3REF: Formatted String Printing Functions {H17400} <S70000><S20000>
2353 **
2354 ** These routines are workalikes of the "printf()" family of functions
2355 ** from the standard C library.
2356 **
2357 ** The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2358 ** results into memory obtained from [sqlite3_malloc()].
2359 ** The strings returned by these two routines should be
2360 ** released by [sqlite3_free()].  Both routines return a
2361 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2362 ** memory to hold the resulting string.
2363 **
2364 ** In sqlite3_snprintf() routine is similar to "snprintf()" from
2365 ** the standard C library.  The result is written into the
2366 ** buffer supplied as the second parameter whose size is given by
2367 ** the first parameter. Note that the order of the
2368 ** first two parameters is reversed from snprintf().  This is an
2369 ** historical accident that cannot be fixed without breaking
2370 ** backwards compatibility.  Note also that sqlite3_snprintf()
2371 ** returns a pointer to its buffer instead of the number of
2372 ** characters actually written into the buffer.  We admit that
2373 ** the number of characters written would be a more useful return
2374 ** value but we cannot change the implementation of sqlite3_snprintf()
2375 ** now without breaking compatibility.
2376 **
2377 ** As long as the buffer size is greater than zero, sqlite3_snprintf()
2378 ** guarantees that the buffer is always zero-terminated.  The first
2379 ** parameter "n" is the total size of the buffer, including space for
2380 ** the zero terminator.  So the longest string that can be completely
2381 ** written will be n-1 characters.
2382 **
2383 ** These routines all implement some additional formatting
2384 ** options that are useful for constructing SQL statements.
2385 ** All of the usual printf() formatting options apply.  In addition, there
2386 ** is are "%q", "%Q", and "%z" options.
2387 **
2388 ** The %q option works like %s in that it substitutes a null-terminated
2389 ** string from the argument list.  But %q also doubles every '\'' character.
2390 ** %q is designed for use inside a string literal.  By doubling each '\''
2391 ** character it escapes that character and allows it to be inserted into
2392 ** the string.
2393 **
2394 ** For example, assume the string variable zText contains text as follows:
2395 **
2396 ** <blockquote><pre>
2397 **  char *zText = "It's a happy day!";
2398 ** </pre></blockquote>
2399 **
2400 ** One can use this text in an SQL statement as follows:
2401 **
2402 ** <blockquote><pre>
2403 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2404 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2405 **  sqlite3_free(zSQL);
2406 ** </pre></blockquote>
2407 **
2408 ** Because the %q format string is used, the '\'' character in zText
2409 ** is escaped and the SQL generated is as follows:
2410 **
2411 ** <blockquote><pre>
2412 **  INSERT INTO table1 VALUES('It''s a happy day!')
2413 ** </pre></blockquote>
2414 **
2415 ** This is correct.  Had we used %s instead of %q, the generated SQL
2416 ** would have looked like this:
2417 **
2418 ** <blockquote><pre>
2419 **  INSERT INTO table1 VALUES('It's a happy day!');
2420 ** </pre></blockquote>
2421 **
2422 ** This second example is an SQL syntax error.  As a general rule you should
2423 ** always use %q instead of %s when inserting text into a string literal.
2424 **
2425 ** The %Q option works like %q except it also adds single quotes around
2426 ** the outside of the total string.  Additionally, if the parameter in the
2427 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2428 ** single quotes) in place of the %Q option.  So, for example, one could say:
2429 **
2430 ** <blockquote><pre>
2431 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2432 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2433 **  sqlite3_free(zSQL);
2434 ** </pre></blockquote>
2435 **
2436 ** The code above will render a correct SQL statement in the zSQL
2437 ** variable even if the zText variable is a NULL pointer.
2438 **
2439 ** The "%z" formatting option works exactly like "%s" with the
2440 ** addition that after the string has been read and copied into
2441 ** the result, [sqlite3_free()] is called on the input string. {END}
2442 **
2443 ** INVARIANTS:
2444 **
2445 ** {H17403}  The [sqlite3_mprintf()] and [sqlite3_vmprintf()] interfaces
2446 **           return either pointers to zero-terminated UTF-8 strings held in
2447 **           memory obtained from [sqlite3_malloc()] or NULL pointers if
2448 **           a call to [sqlite3_malloc()] fails.
2449 **
2450 ** {H17406}  The [sqlite3_snprintf()] interface writes a zero-terminated
2451 **           UTF-8 string into the buffer pointed to by the second parameter
2452 **           provided that the first parameter is greater than zero.
2453 **
2454 ** {H17407}  The [sqlite3_snprintf()] interface does not write slots of
2455 **           its output buffer (the second parameter) outside the range
2456 **           of 0 through N-1 (where N is the first parameter)
2457 **           regardless of the length of the string
2458 **           requested by the format specification.
2459 */
2460 SQLITE_API char *sqlite3_mprintf(const char*,...);
2461 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2462 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2463
2464 /*
2465 ** CAPI3REF: Memory Allocation Subsystem {H17300} <S20000>
2466 **
2467 ** The SQLite core  uses these three routines for all of its own
2468 ** internal memory allocation needs. "Core" in the previous sentence
2469 ** does not include operating-system specific VFS implementation.  The
2470 ** Windows VFS uses native malloc() and free() for some operations.
2471 **
2472 ** The sqlite3_malloc() routine returns a pointer to a block
2473 ** of memory at least N bytes in length, where N is the parameter.
2474 ** If sqlite3_malloc() is unable to obtain sufficient free
2475 ** memory, it returns a NULL pointer.  If the parameter N to
2476 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2477 ** a NULL pointer.
2478 **
2479 ** Calling sqlite3_free() with a pointer previously returned
2480 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2481 ** that it might be reused.  The sqlite3_free() routine is
2482 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2483 ** to sqlite3_free() is harmless.  After being freed, memory
2484 ** should neither be read nor written.  Even reading previously freed
2485 ** memory might result in a segmentation fault or other severe error.
2486 ** Memory corruption, a segmentation fault, or other severe error
2487 ** might result if sqlite3_free() is called with a non-NULL pointer that
2488 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2489 **
2490 ** The sqlite3_realloc() interface attempts to resize a
2491 ** prior memory allocation to be at least N bytes, where N is the
2492 ** second parameter.  The memory allocation to be resized is the first
2493 ** parameter.  If the first parameter to sqlite3_realloc()
2494 ** is a NULL pointer then its behavior is identical to calling
2495 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2496 ** If the second parameter to sqlite3_realloc() is zero or
2497 ** negative then the behavior is exactly the same as calling
2498 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2499 ** sqlite3_realloc() returns a pointer to a memory allocation
2500 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
2501 ** If M is the size of the prior allocation, then min(N,M) bytes
2502 ** of the prior allocation are copied into the beginning of buffer returned
2503 ** by sqlite3_realloc() and the prior allocation is freed.
2504 ** If sqlite3_realloc() returns NULL, then the prior allocation
2505 ** is not freed.
2506 **
2507 ** The memory returned by sqlite3_malloc() and sqlite3_realloc()
2508 ** is always aligned to at least an 8 byte boundary. {END}
2509 **
2510 ** The default implementation of the memory allocation subsystem uses
2511 ** the malloc(), realloc() and free() provided by the standard C library.
2512 ** {H17382} However, if SQLite is compiled with the
2513 ** SQLITE_MEMORY_SIZE=<i>NNN</i> C preprocessor macro (where <i>NNN</i>
2514 ** is an integer), then SQLite create a static array of at least
2515 ** <i>NNN</i> bytes in size and uses that array for all of its dynamic
2516 ** memory allocation needs. {END}  Additional memory allocator options
2517 ** may be added in future releases.
2518 **
2519 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2520 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2521 ** implementation of these routines to be omitted.  That capability
2522 ** is no longer provided.  Only built-in memory allocators can be used.
2523 **
2524 ** The Windows OS interface layer calls
2525 ** the system malloc() and free() directly when converting
2526 ** filenames between the UTF-8 encoding used by SQLite
2527 ** and whatever filename encoding is used by the particular Windows
2528 ** installation.  Memory allocation errors are detected, but
2529 ** they are reported back as [SQLITE_CANTOPEN] or
2530 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2531 **
2532 ** INVARIANTS:
2533 **
2534 ** {H17303}  The [sqlite3_malloc(N)] interface returns either a pointer to
2535 **           a newly checked-out block of at least N bytes of memory
2536 **           that is 8-byte aligned, or it returns NULL if it is unable
2537 **           to fulfill the request.
2538 **
2539 ** {H17304}  The [sqlite3_malloc(N)] interface returns a NULL pointer if
2540 **           N is less than or equal to zero.
2541 **
2542 ** {H17305}  The [sqlite3_free(P)] interface releases memory previously
2543 **           returned from [sqlite3_malloc()] or [sqlite3_realloc()],
2544 **           making it available for reuse.
2545 **
2546 ** {H17306}  A call to [sqlite3_free(NULL)] is a harmless no-op.
2547 **
2548 ** {H17310}  A call to [sqlite3_realloc(0,N)] is equivalent to a call
2549 **           to [sqlite3_malloc(N)].
2550 **
2551 ** {H17312}  A call to [sqlite3_realloc(P,0)] is equivalent to a call
2552 **           to [sqlite3_free(P)].
2553 **
2554 ** {H17315}  The SQLite core uses [sqlite3_malloc()], [sqlite3_realloc()],
2555 **           and [sqlite3_free()] for all of its memory allocation and
2556 **           deallocation needs.
2557 **
2558 ** {H17318}  The [sqlite3_realloc(P,N)] interface returns either a pointer
2559 **           to a block of checked-out memory of at least N bytes in size
2560 **           that is 8-byte aligned, or a NULL pointer.
2561 **
2562 ** {H17321}  When [sqlite3_realloc(P,N)] returns a non-NULL pointer, it first
2563 **           copies the first K bytes of content from P into the newly
2564 **           allocated block, where K is the lesser of N and the size of
2565 **           the buffer P.
2566 **
2567 ** {H17322}  When [sqlite3_realloc(P,N)] returns a non-NULL pointer, it first
2568 **           releases the buffer P.
2569 **
2570 ** {H17323}  When [sqlite3_realloc(P,N)] returns NULL, the buffer P is
2571 **           not modified or released.
2572 **
2573 ** ASSUMPTIONS:
2574 **
2575 ** {A17350}  The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2576 **           must be either NULL or else pointers obtained from a prior
2577 **           invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2578 **           not yet been released.
2579 **
2580 ** {A17351}  The application must not read or write any part of
2581 **           a block of memory after it has been released using
2582 **           [sqlite3_free()] or [sqlite3_realloc()].
2583 */
2584 SQLITE_API void *sqlite3_malloc(int);
2585 SQLITE_API void *sqlite3_realloc(void*, int);
2586 SQLITE_API void sqlite3_free(void*);
2587
2588 /*
2589 ** CAPI3REF: Memory Allocator Statistics {H17370} <S30210>
2590 **
2591 ** SQLite provides these two interfaces for reporting on the status
2592 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2593 ** routines, which form the built-in memory allocation subsystem.
2594 **
2595 ** INVARIANTS:
2596 **
2597 ** {H17371} The [sqlite3_memory_used()] routine returns the number of bytes
2598 **          of memory currently outstanding (malloced but not freed).
2599 **
2600 ** {H17373} The [sqlite3_memory_highwater()] routine returns the maximum
2601 **          value of [sqlite3_memory_used()] since the high-water mark
2602 **          was last reset.
2603 **
2604 ** {H17374} The values returned by [sqlite3_memory_used()] and
2605 **          [sqlite3_memory_highwater()] include any overhead
2606 **          added by SQLite in its implementation of [sqlite3_malloc()],
2607 **          but not overhead added by the any underlying system library
2608 **          routines that [sqlite3_malloc()] may call.
2609 **
2610 ** {H17375} The memory high-water mark is reset to the current value of
2611 **          [sqlite3_memory_used()] if and only if the parameter to
2612 **          [sqlite3_memory_highwater()] is true.  The value returned
2613 **          by [sqlite3_memory_highwater(1)] is the high-water mark
2614 **          prior to the reset.
2615 */
2616 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2617 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2618
2619 /*
2620 ** CAPI3REF: Pseudo-Random Number Generator {H17390} <S20000>
2621 **
2622 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2623 ** select random ROWIDs when inserting new records into a table that
2624 ** already uses the largest possible ROWID.  The PRNG is also used for
2625 ** the build-in random() and randomblob() SQL functions.  This interface allows
2626 ** applications to access the same PRNG for other purposes.
2627 **
2628 ** A call to this routine stores N bytes of randomness into buffer P.
2629 **
2630 ** The first time this routine is invoked (either internally or by
2631 ** the application) the PRNG is seeded using randomness obtained
2632 ** from the xRandomness method of the default [sqlite3_vfs] object.
2633 ** On all subsequent invocations, the pseudo-randomness is generated
2634 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2635 ** method.
2636 **
2637 ** INVARIANTS:
2638 **
2639 ** {H17392} The [sqlite3_randomness(N,P)] interface writes N bytes of
2640 **          high-quality pseudo-randomness into buffer P.
2641 */
2642 SQLITE_API void sqlite3_randomness(int N, void *P);
2643
2644 /*
2645 ** CAPI3REF: Compile-Time Authorization Callbacks {H12500} <S70100>
2646 **
2647 ** This routine registers a authorizer callback with a particular
2648 ** [database connection], supplied in the first argument.
2649 ** The authorizer callback is invoked as SQL statements are being compiled
2650 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2651 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  At various
2652 ** points during the compilation process, as logic is being created
2653 ** to perform various actions, the authorizer callback is invoked to
2654 ** see if those actions are allowed.  The authorizer callback should
2655 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2656 ** specific action but allow the SQL statement to continue to be
2657 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2658 ** rejected with an error.  If the authorizer callback returns
2659 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2660 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2661 ** the authorizer will fail with an error message.
2662 **
2663 ** When the callback returns [SQLITE_OK], that means the operation
2664 ** requested is ok.  When the callback returns [SQLITE_DENY], the
2665 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2666 ** authorizer will fail with an error message explaining that
2667 ** access is denied.  If the authorizer code is [SQLITE_READ]
2668 ** and the callback returns [SQLITE_IGNORE] then the
2669 ** [prepared statement] statement is constructed to substitute
2670 ** a NULL value in place of the table column that would have
2671 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2672 ** return can be used to deny an untrusted user access to individual
2673 ** columns of a table.
2674 **
2675 ** The first parameter to the authorizer callback is a copy of the third
2676 ** parameter to the sqlite3_set_authorizer() interface. The second parameter
2677 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2678 ** the particular action to be authorized. The third through sixth parameters
2679 ** to the callback are zero-terminated strings that contain additional
2680 ** details about the action to be authorized.
2681 **
2682 ** An authorizer is used when [sqlite3_prepare | preparing]
2683 ** SQL statements from an untrusted source, to ensure that the SQL statements
2684 ** do not try to access data they are not allowed to see, or that they do not
2685 ** try to execute malicious statements that damage the database.  For
2686 ** example, an application may allow a user to enter arbitrary
2687 ** SQL queries for evaluation by a database.  But the application does
2688 ** not want the user to be able to make arbitrary changes to the
2689 ** database.  An authorizer could then be put in place while the
2690 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2691 ** disallows everything except [SELECT] statements.
2692 **
2693 ** Applications that need to process SQL from untrusted sources
2694 ** might also consider lowering resource limits using [sqlite3_limit()]
2695 ** and limiting database size using the [max_page_count] [PRAGMA]
2696 ** in addition to using an authorizer.
2697 **
2698 ** Only a single authorizer can be in place on a database connection
2699 ** at a time.  Each call to sqlite3_set_authorizer overrides the
2700 ** previous call.  Disable the authorizer by installing a NULL callback.
2701 ** The authorizer is disabled by default.
2702 **
2703 ** The authorizer callback must not do anything that will modify
2704 ** the database connection that invoked the authorizer callback.
2705 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2706 ** database connections for the meaning of "modify" in this paragraph.
2707 **
2708 ** When [sqlite3_prepare_v2()] is used to prepare a statement, the
2709 ** statement might be reprepared during [sqlite3_step()] due to a 
2710 ** schema change.  Hence, the application should ensure that the
2711 ** correct authorizer callback remains in place during the [sqlite3_step()].
2712 **
2713 ** Note that the authorizer callback is invoked only during
2714 ** [sqlite3_prepare()] or its variants.  Authorization is not
2715 ** performed during statement evaluation in [sqlite3_step()].
2716 **
2717 ** INVARIANTS:
2718 **
2719 ** {H12501} The [sqlite3_set_authorizer(D,...)] interface registers a
2720 **          authorizer callback with database connection D.
2721 **
2722 ** {H12502} The authorizer callback is invoked as SQL statements are
2723 **          being parseed and compiled.
2724 **
2725 ** {H12503} If the authorizer callback returns any value other than
2726 **          [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY], then
2727 **          the application interface call that caused
2728 **          the authorizer callback to run shall fail with an
2729 **          [SQLITE_ERROR] error code and an appropriate error message.
2730 **
2731 ** {H12504} When the authorizer callback returns [SQLITE_OK], the operation
2732 **          described is processed normally.
2733 **
2734 ** {H12505} When the authorizer callback returns [SQLITE_DENY], the
2735 **          application interface call that caused the
2736 **          authorizer callback to run shall fail
2737 **          with an [SQLITE_ERROR] error code and an error message
2738 **          explaining that access is denied.
2739 **
2740 ** {H12506} If the authorizer code (the 2nd parameter to the authorizer
2741 **          callback) is [SQLITE_READ] and the authorizer callback returns
2742 **          [SQLITE_IGNORE], then the prepared statement is constructed to
2743 **          insert a NULL value in place of the table column that would have
2744 **          been read if [SQLITE_OK] had been returned.
2745 **
2746 ** {H12507} If the authorizer code (the 2nd parameter to the authorizer
2747 **          callback) is anything other than [SQLITE_READ], then
2748 **          a return of [SQLITE_IGNORE] has the same effect as [SQLITE_DENY].
2749 **
2750 ** {H12510} The first parameter to the authorizer callback is a copy of
2751 **          the third parameter to the [sqlite3_set_authorizer()] interface.
2752 **
2753 ** {H12511} The second parameter to the callback is an integer
2754 **          [SQLITE_COPY | action code] that specifies the particular action
2755 **          to be authorized.
2756 **
2757 ** {H12512} The third through sixth parameters to the callback are
2758 **          zero-terminated strings that contain
2759 **          additional details about the action to be authorized.
2760 **
2761 ** {H12520} Each call to [sqlite3_set_authorizer()] overrides
2762 **          any previously installed authorizer.
2763 **
2764 ** {H12521} A NULL authorizer means that no authorization
2765 **          callback is invoked.
2766 **
2767 ** {H12522} The default authorizer is NULL.
2768 */
2769 SQLITE_API int sqlite3_set_authorizer(
2770   sqlite3*,
2771   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2772   void *pUserData
2773 );
2774
2775 /*
2776 ** CAPI3REF: Authorizer Return Codes {H12590} <H12500>
2777 **
2778 ** The [sqlite3_set_authorizer | authorizer callback function] must
2779 ** return either [SQLITE_OK] or one of these two constants in order
2780 ** to signal SQLite whether or not the action is permitted.  See the
2781 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2782 ** information.
2783 */
2784 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2785 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2786
2787 /*
2788 ** CAPI3REF: Authorizer Action Codes {H12550} <H12500>
2789 **
2790 ** The [sqlite3_set_authorizer()] interface registers a callback function
2791 ** that is invoked to authorize certain SQL statement actions.  The
2792 ** second parameter to the callback is an integer code that specifies
2793 ** what action is being authorized.  These are the integer action codes that
2794 ** the authorizer callback may be passed.
2795 **
2796 ** These action code values signify what kind of operation is to be
2797 ** authorized.  The 3rd and 4th parameters to the authorization
2798 ** callback function will be parameters or NULL depending on which of these
2799 ** codes is used as the second parameter.  The 5th parameter to the
2800 ** authorizer callback is the name of the database ("main", "temp",
2801 ** etc.) if applicable.  The 6th parameter to the authorizer callback
2802 ** is the name of the inner-most trigger or view that is responsible for
2803 ** the access attempt or NULL if this access attempt is directly from
2804 ** top-level SQL code.
2805 **
2806 ** INVARIANTS:
2807 **
2808 ** {H12551} The second parameter to an
2809 **          [sqlite3_set_authorizer | authorizer callback] shall be an integer
2810 **          [SQLITE_COPY | authorizer code] that specifies what action
2811 **          is being authorized.
2812 **
2813 ** {H12552} The 3rd and 4th parameters to the
2814 **          [sqlite3_set_authorizer | authorization callback]
2815 **          shall be parameters or NULL depending on which
2816 **          [SQLITE_COPY | authorizer code] is used as the second parameter.
2817 **
2818 ** {H12553} The 5th parameter to the
2819 **          [sqlite3_set_authorizer | authorizer callback] shall be the name
2820 **          of the database (example: "main", "temp", etc.) if applicable.
2821 **
2822 ** {H12554} The 6th parameter to the
2823 **          [sqlite3_set_authorizer | authorizer callback] shall be the name
2824 **          of the inner-most trigger or view that is responsible for
2825 **          the access attempt or NULL if this access attempt is directly from
2826 **          top-level SQL code.
2827 */
2828 /******************************************* 3rd ************ 4th ***********/
2829 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2830 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2831 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2832 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2833 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2834 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2835 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2836 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2837 #define SQLITE_DELETE                9   /* Table Name      NULL            */
2838 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2839 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2840 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2841 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2842 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2843 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2844 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2845 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2846 #define SQLITE_INSERT               18   /* Table Name      NULL            */
2847 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2848 #define SQLITE_READ                 20   /* Table Name      Column Name     */
2849 #define SQLITE_SELECT               21   /* NULL            NULL            */
2850 #define SQLITE_TRANSACTION          22   /* NULL            NULL            */
2851 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2852 #define SQLITE_ATTACH               24   /* Filename        NULL            */
2853 #define SQLITE_DETACH               25   /* Database Name   NULL            */
2854 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2855 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
2856 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2857 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2858 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2859 #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
2860 #define SQLITE_COPY                  0   /* No longer used */
2861
2862 /*
2863 ** CAPI3REF: Tracing And Profiling Functions {H12280} <S60400>
2864 ** EXPERIMENTAL
2865 **
2866 ** These routines register callback functions that can be used for
2867 ** tracing and profiling the execution of SQL statements.
2868 **
2869 ** The callback function registered by sqlite3_trace() is invoked at
2870 ** various times when an SQL statement is being run by [sqlite3_step()].
2871 ** The callback returns a UTF-8 rendering of the SQL statement text
2872 ** as the statement first begins executing.  Additional callbacks occur
2873 ** as each triggered subprogram is entered.  The callbacks for triggers
2874 ** contain a UTF-8 SQL comment that identifies the trigger.
2875 **
2876 ** The callback function registered by sqlite3_profile() is invoked
2877 ** as each SQL statement finishes.  The profile callback contains
2878 ** the original statement text and an estimate of wall-clock time
2879 ** of how long that statement took to run.
2880 **
2881 ** INVARIANTS:
2882 **
2883 ** {H12281} The callback function registered by [sqlite3_trace()] 
2884 **          shall be invoked
2885 **          whenever an SQL statement first begins to execute and
2886 **          whenever a trigger subprogram first begins to run.
2887 **
2888 ** {H12282} Each call to [sqlite3_trace()] shall override the previously
2889 **          registered trace callback.
2890 **
2891 ** {H12283} A NULL trace callback shall disable tracing.
2892 **
2893 ** {H12284} The first argument to the trace callback shall be a copy of
2894 **          the pointer which was the 3rd argument to [sqlite3_trace()].
2895 **
2896 ** {H12285} The second argument to the trace callback is a
2897 **          zero-terminated UTF-8 string containing the original text
2898 **          of the SQL statement as it was passed into [sqlite3_prepare_v2()]
2899 **          or the equivalent, or an SQL comment indicating the beginning
2900 **          of a trigger subprogram.
2901 **
2902 ** {H12287} The callback function registered by [sqlite3_profile()] is invoked
2903 **          as each SQL statement finishes.
2904 **
2905 ** {H12288} The first parameter to the profile callback is a copy of
2906 **          the 3rd parameter to [sqlite3_profile()].
2907 **
2908 ** {H12289} The second parameter to the profile callback is a
2909 **          zero-terminated UTF-8 string that contains the complete text of
2910 **          the SQL statement as it was processed by [sqlite3_prepare_v2()]
2911 **          or the equivalent.
2912 **
2913 ** {H12290} The third parameter to the profile callback is an estimate
2914 **          of the number of nanoseconds of wall-clock time required to
2915 **          run the SQL statement from start to finish.
2916 */
2917 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2918 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2919    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2920
2921 /*
2922 ** CAPI3REF: Query Progress Callbacks {H12910} <S60400>
2923 **
2924 ** This routine configures a callback function - the
2925 ** progress callback - that is invoked periodically during long
2926 ** running calls to [sqlite3_exec()], [sqlite3_step()] and
2927 ** [sqlite3_get_table()].  An example use for this
2928 ** interface is to keep a GUI updated during a large query.
2929 **
2930 ** If the progress callback returns non-zero, the operation is
2931 ** interrupted.  This feature can be used to implement a
2932 ** "Cancel" button on a GUI progress dialog box.
2933 **
2934 ** The progress handler must not do anything that will modify
2935 ** the database connection that invoked the progress handler.
2936 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2937 ** database connections for the meaning of "modify" in this paragraph.
2938 **
2939 ** INVARIANTS:
2940 **
2941 ** {H12911} The callback function registered by sqlite3_progress_handler()
2942 **          is invoked periodically during long running calls to
2943 **          [sqlite3_step()].
2944 **
2945 ** {H12912} The progress callback is invoked once for every N virtual
2946 **          machine opcodes, where N is the second argument to
2947 **          the [sqlite3_progress_handler()] call that registered
2948 **          the callback.  If N is less than 1, sqlite3_progress_handler()
2949 **          acts as if a NULL progress handler had been specified.
2950 **
2951 ** {H12913} The progress callback itself is identified by the third
2952 **          argument to sqlite3_progress_handler().
2953 **
2954 ** {H12914} The fourth argument to sqlite3_progress_handler() is a
2955 **          void pointer passed to the progress callback
2956 **          function each time it is invoked.
2957 **
2958 ** {H12915} If a call to [sqlite3_step()] results in fewer than N opcodes
2959 **          being executed, then the progress callback is never invoked.
2960 **
2961 ** {H12916} Every call to [sqlite3_progress_handler()]
2962 **          overwrites any previously registered progress handler.
2963 **
2964 ** {H12917} If the progress handler callback is NULL then no progress
2965 **          handler is invoked.
2966 **
2967 ** {H12918} If the progress callback returns a result other than 0, then
2968 **          the behavior is a if [sqlite3_interrupt()] had been called.
2969 **          <S30500>
2970 */
2971 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2972
2973 /*
2974 ** CAPI3REF: Opening A New Database Connection {H12700} <S40200>
2975 **
2976 ** These routines open an SQLite database file whose name is given by the
2977 ** filename argument. The filename argument is interpreted as UTF-8 for
2978 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
2979 ** order for sqlite3_open16(). A [database connection] handle is usually
2980 ** returned in *ppDb, even if an error occurs.  The only exception is that
2981 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
2982 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
2983 ** object. If the database is opened (and/or created) successfully, then
2984 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.  The
2985 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
2986 ** an English language description of the error.
2987 **
2988 ** The default encoding for the database will be UTF-8 if
2989 ** sqlite3_open() or sqlite3_open_v2() is called and
2990 ** UTF-16 in the native byte order if sqlite3_open16() is used.
2991 **
2992 ** Whether or not an error occurs when it is opened, resources
2993 ** associated with the [database connection] handle should be released by
2994 ** passing it to [sqlite3_close()] when it is no longer required.
2995 **
2996 ** The sqlite3_open_v2() interface works like sqlite3_open()
2997 ** except that it accepts two additional parameters for additional control
2998 ** over the new database connection.  The flags parameter can take one of
2999 ** the following three values, optionally combined with the 
3000 ** [SQLITE_OPEN_NOMUTEX] or [SQLITE_OPEN_FULLMUTEX] flags:
3001 **
3002 ** <dl>
3003 ** <dt>[SQLITE_OPEN_READONLY]</dt>
3004 ** <dd>The database is opened in read-only mode.  If the database does not
3005 ** already exist, an error is returned.</dd>
3006 **
3007 ** <dt>[SQLITE_OPEN_READWRITE]</dt>
3008 ** <dd>The database is opened for reading and writing if possible, or reading
3009 ** only if the file is write protected by the operating system.  In either
3010 ** case the database must already exist, otherwise an error is returned.</dd>
3011 **
3012 ** <dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
3013 ** <dd>The database is opened for reading and writing, and is creates it if
3014 ** it does not already exist. This is the behavior that is always used for
3015 ** sqlite3_open() and sqlite3_open16().</dd>
3016 ** </dl>
3017 **
3018 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
3019 ** combinations shown above or one of the combinations shown above combined
3020 ** with the [SQLITE_OPEN_NOMUTEX] or [SQLITE_OPEN_FULLMUTEX] flags,
3021 ** then the behavior is undefined.
3022 **
3023 ** If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
3024 ** opens in the multi-thread [threading mode] as long as the single-thread
3025 ** mode has not been set at compile-time or start-time.  If the
3026 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
3027 ** in the serialized [threading mode] unless single-thread was
3028 ** previously selected at compile-time or start-time.
3029 **
3030 ** If the filename is ":memory:", then a private, temporary in-memory database
3031 ** is created for the connection.  This in-memory database will vanish when
3032 ** the database connection is closed.  Future versions of SQLite might
3033 ** make use of additional special filenames that begin with the ":" character.
3034 ** It is recommended that when a database filename actually does begin with
3035 ** a ":" character you should prefix the filename with a pathname such as
3036 ** "./" to avoid ambiguity.
3037 **
3038 ** If the filename is an empty string, then a private, temporary
3039 ** on-disk database will be created.  This private database will be
3040 ** automatically deleted as soon as the database connection is closed.
3041 **
3042 ** The fourth parameter to sqlite3_open_v2() is the name of the
3043 ** [sqlite3_vfs] object that defines the operating system interface that
3044 ** the new database connection should use.  If the fourth parameter is
3045 ** a NULL pointer then the default [sqlite3_vfs] object is used.
3046 **
3047 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
3048 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
3049 ** codepage is currently defined.  Filenames containing international
3050 ** characters must be converted to UTF-8 prior to passing them into
3051 ** sqlite3_open() or sqlite3_open_v2().
3052 **
3053 ** INVARIANTS:
3054 **
3055 ** {H12701} The [sqlite3_open()], [sqlite3_open16()], and
3056 **          [sqlite3_open_v2()] interfaces create a new
3057 **          [database connection] associated with
3058 **          the database file given in their first parameter.
3059 **
3060 ** {H12702} The filename argument is interpreted as UTF-8
3061 **          for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16
3062 **          in the native byte order for [sqlite3_open16()].
3063 **
3064 ** {H12703} A successful invocation of [sqlite3_open()], [sqlite3_open16()],
3065 **          or [sqlite3_open_v2()] writes a pointer to a new
3066 **          [database connection] into *ppDb.
3067 **
3068 ** {H12704} The [sqlite3_open()], [sqlite3_open16()], and
3069 **          [sqlite3_open_v2()] interfaces return [SQLITE_OK] upon success,
3070 **          or an appropriate [error code] on failure.
3071 **
3072 ** {H12706} The default text encoding for a new database created using
3073 **          [sqlite3_open()] or [sqlite3_open_v2()] will be UTF-8.
3074 **
3075 ** {H12707} The default text encoding for a new database created using
3076 **          [sqlite3_open16()] will be UTF-16.
3077 **
3078 ** {H12709} The [sqlite3_open(F,D)] interface is equivalent to
3079 **          [sqlite3_open_v2(F,D,G,0)] where the G parameter is
3080 **          [SQLITE_OPEN_READWRITE]|[SQLITE_OPEN_CREATE].
3081 **
3082 ** {H12711} If the G parameter to [sqlite3_open_v2(F,D,G,V)] contains the
3083 **          bit value [SQLITE_OPEN_READONLY] then the database is opened
3084 **          for reading only.
3085 **
3086 ** {H12712} If the G parameter to [sqlite3_open_v2(F,D,G,V)] contains the
3087 **          bit value [SQLITE_OPEN_READWRITE] then the database is opened
3088 **          reading and writing if possible, or for reading only if the
3089 **          file is write protected by the operating system.
3090 **
3091 ** {H12713} If the G parameter to [sqlite3_open_v2(F,D,G,V)] omits the
3092 **          bit value [SQLITE_OPEN_CREATE] and the database does not
3093 **          previously exist, an error is returned.
3094 **
3095 ** {H12714} If the G parameter to [sqlite3_open_v2(F,D,G,V)] contains the
3096 **          bit value [SQLITE_OPEN_CREATE] and the database does not
3097 **          previously exist, then an attempt is made to create and
3098 **          initialize the database.
3099 **
3100 ** {H12717} If the filename argument to [sqlite3_open()], [sqlite3_open16()],
3101 **          or [sqlite3_open_v2()] is ":memory:", then an private,
3102 **          ephemeral, in-memory database is created for the connection.
3103 **          <todo>Is SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE required
3104 **          in sqlite3_open_v2()?</todo>
3105 **
3106 ** {H12719} If the filename is NULL or an empty string, then a private,
3107 **          ephemeral on-disk database will be created.
3108 **          <todo>Is SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE required
3109 **          in sqlite3_open_v2()?</todo>
3110 **
3111 ** {H12721} The [database connection] created by [sqlite3_open_v2(F,D,G,V)]
3112 **          will use the [sqlite3_vfs] object identified by the V parameter,
3113 **          or the default [sqlite3_vfs] object if V is a NULL pointer.
3114 **
3115 ** {H12723} Two [database connections] will share a common cache if both were
3116 **          opened with the same VFS while [shared cache mode] was enabled and
3117 **          if both filenames compare equal using memcmp() after having been
3118 **          processed by the [sqlite3_vfs | xFullPathname] method of the VFS.
3119 */
3120 SQLITE_API int sqlite3_open(
3121   const char *filename,   /* Database filename (UTF-8) */
3122   sqlite3 **ppDb          /* OUT: SQLite db handle */
3123 );
3124 SQLITE_API int sqlite3_open16(
3125   const void *filename,   /* Database filename (UTF-16) */
3126   sqlite3 **ppDb          /* OUT: SQLite db handle */
3127 );
3128 SQLITE_API int sqlite3_open_v2(
3129   const char *filename,   /* Database filename (UTF-8) */
3130   sqlite3 **ppDb,         /* OUT: SQLite db handle */
3131   int flags,              /* Flags */
3132   const char *zVfs        /* Name of VFS module to use */
3133 );
3134
3135 /*
3136 ** CAPI3REF: Error Codes And Messages {H12800} <S60200>
3137 **
3138 ** The sqlite3_errcode() interface returns the numeric [result code] or
3139 ** [extended result code] for the most recent failed sqlite3_* API call
3140 ** associated with a [database connection]. If a prior API call failed
3141 ** but the most recent API call succeeded, the return value from
3142 ** sqlite3_errcode() is undefined.  The sqlite3_extended_errcode()
3143 ** interface is the same except that it always returns the 
3144 ** [extended result code] even when extended result codes are
3145 ** disabled.
3146 **
3147 ** The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
3148 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
3149 ** Memory to hold the error message string is managed internally.
3150 ** The application does not need to worry about freeing the result.
3151 ** However, the error string might be overwritten or deallocated by
3152 ** subsequent calls to other SQLite interface functions.
3153 **
3154 ** When the serialized [threading mode] is in use, it might be the
3155 ** case that a second error occurs on a separate thread in between
3156 ** the time of the first error and the call to these interfaces.
3157 ** When that happens, the second error will be reported since these
3158 ** interfaces always report the most recent result.  To avoid
3159 ** this, each thread can obtain exclusive use of the [database connection] D
3160 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
3161 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
3162 ** all calls to the interfaces listed here are completed.
3163 **
3164 ** If an interface fails with SQLITE_MISUSE, that means the interface
3165 ** was invoked incorrectly by the application.  In that case, the
3166 ** error code and message may or may not be set.
3167 **
3168 ** INVARIANTS:
3169 **
3170 ** {H12801} The [sqlite3_errcode(D)] interface returns the numeric
3171 **          [result code] or [extended result code] for the most recently
3172 **          failed interface call associated with the [database connection] D.
3173 **
3174 ** {H12802} The [sqlite3_extended_errcode(D)] interface returns the numeric
3175 **          [extended result code] for the most recently
3176 **          failed interface call associated with the [database connection] D.
3177 **
3178 ** {H12803} The [sqlite3_errmsg(D)] and [sqlite3_errmsg16(D)]
3179 **          interfaces return English-language text that describes
3180 **          the error in the mostly recently failed interface call,
3181 **          encoded as either UTF-8 or UTF-16 respectively.
3182 **
3183 ** {H12807} The strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()]
3184 **          are valid until the next SQLite interface call.
3185 **
3186 ** {H12808} Calls to API routines that do not return an error code
3187 **          (example: [sqlite3_data_count()]) do not
3188 **          change the error code or message returned by
3189 **          [sqlite3_errcode()], [sqlite3_extended_errcode()],
3190 **          [sqlite3_errmsg()], or [sqlite3_errmsg16()].
3191 **
3192 ** {H12809} Interfaces that are not associated with a specific
3193 **          [database connection] (examples:
3194 **          [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()]
3195 **          do not change the values returned by
3196 **          [sqlite3_errcode()], [sqlite3_extended_errcode()],
3197 **          [sqlite3_errmsg()], or [sqlite3_errmsg16()].
3198 */
3199 SQLITE_API int sqlite3_errcode(sqlite3 *db);
3200 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
3201 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
3202 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
3203
3204 /*
3205 ** CAPI3REF: SQL Statement Object {H13000} <H13010>
3206 ** KEYWORDS: {prepared statement} {prepared statements}
3207 **
3208 ** An instance of this object represents a single SQL statement.
3209 ** This object is variously known as a "prepared statement" or a
3210 ** "compiled SQL statement" or simply as a "statement".
3211 **
3212 ** The life of a statement object goes something like this:
3213 **
3214 ** <ol>
3215 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
3216 **      function.
3217 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
3218 **      interfaces.
3219 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3220 ** <li> Reset the statement using [sqlite3_reset()] then go back
3221 **      to step 2.  Do this zero or more times.
3222 ** <li> Destroy the object using [sqlite3_finalize()].
3223 ** </ol>
3224 **
3225 ** Refer to documentation on individual methods above for additional
3226 ** information.
3227 */
3228 typedef struct sqlite3_stmt sqlite3_stmt;
3229
3230 /*
3231 ** CAPI3REF: Run-time Limits {H12760} <S20600>
3232 **
3233 ** This interface allows the size of various constructs to be limited
3234 ** on a connection by connection basis.  The first parameter is the
3235 ** [database connection] whose limit is to be set or queried.  The
3236 ** second parameter is one of the [limit categories] that define a
3237 ** class of constructs to be size limited.  The third parameter is the
3238 ** new limit for that construct.  The function returns the old limit.
3239 **
3240 ** If the new limit is a negative number, the limit is unchanged.
3241 ** For the limit category of SQLITE_LIMIT_XYZ there is a hard upper
3242 ** bound set by a compile-time C preprocessor macro named SQLITE_MAX_XYZ.
3243 ** (The "_LIMIT_" in the name is changed to "_MAX_".)
3244 ** Attempts to increase a limit above its hard upper bound are
3245 ** silently truncated to the hard upper limit.
3246 **
3247 ** Run time limits are intended for use in applications that manage
3248 ** both their own internal database and also databases that are controlled
3249 ** by untrusted external sources.  An example application might be a
3250 ** webbrowser that has its own databases for storing history and
3251 ** separate databases controlled by JavaScript applications downloaded
3252 ** off the Internet.  The internal databases can be given the
3253 ** large, default limits.  Databases managed by external sources can
3254 ** be given much smaller limits designed to prevent a denial of service
3255 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
3256 ** interface to further control untrusted SQL.  The size of the database
3257 ** created by an untrusted script can be contained using the
3258 ** [max_page_count] [PRAGMA].
3259 **
3260 ** New run-time limit categories may be added in future releases.
3261 **
3262 ** INVARIANTS:
3263 **
3264 ** {H12762} A successful call to [sqlite3_limit(D,C,V)] where V is
3265 **          positive changes the limit on the size of construct C in the
3266 **          [database connection] D to the lesser of V and the hard upper
3267 **          bound on the size of C that is set at compile-time.
3268 **
3269 ** {H12766} A successful call to [sqlite3_limit(D,C,V)] where V is negative
3270 **          leaves the state of the [database connection] D unchanged.
3271 **
3272 ** {H12769} A successful call to [sqlite3_limit(D,C,V)] returns the
3273 **          value of the limit on the size of construct C in the
3274 **          [database connection] D as it was prior to the call.
3275 */
3276 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
3277
3278 /*
3279 ** CAPI3REF: Run-Time Limit Categories {H12790} <H12760>
3280 ** KEYWORDS: {limit category} {limit categories}
3281 **
3282 ** These constants define various aspects of a [database connection]
3283 ** that can be limited in size by calls to [sqlite3_limit()].
3284 ** The meanings of the various limits are as follows:
3285 **
3286 ** <dl>
3287 ** <dt>SQLITE_LIMIT_LENGTH</dt>
3288 ** <dd>The maximum size of any string or BLOB or table row.<dd>
3289 **
3290 ** <dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3291 ** <dd>The maximum length of an SQL statement.</dd>
3292 **
3293 ** <dt>SQLITE_LIMIT_COLUMN</dt>
3294 ** <dd>The maximum number of columns in a table definition or in the
3295 ** result set of a SELECT or the maximum number of columns in an index
3296 ** or in an ORDER BY or GROUP BY clause.</dd>
3297 **
3298 ** <dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3299 ** <dd>The maximum depth of the parse tree on any expression.</dd>
3300 **
3301 ** <dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3302 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>
3303 **
3304 ** <dt>SQLITE_LIMIT_VDBE_OP</dt>
3305 ** <dd>The maximum number of instructions in a virtual machine program
3306 ** used to implement an SQL statement.</dd>
3307 **
3308 ** <dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3309 ** <dd>The maximum number of arguments on a function.</dd>
3310 **
3311 ** <dt>SQLITE_LIMIT_ATTACHED</dt>
3312 ** <dd>The maximum number of attached databases.</dd>
3313 **
3314 ** <dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3315 ** <dd>The maximum length of the pattern argument to the LIKE or
3316 ** GLOB operators.</dd>
3317 **
3318 ** <dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3319 ** <dd>The maximum number of variables in an SQL statement that can
3320 ** be bound.</dd>
3321 ** </dl>
3322 */
3323 #define SQLITE_LIMIT_LENGTH                    0
3324 #define SQLITE_LIMIT_SQL_LENGTH                1
3325 #define SQLITE_LIMIT_COLUMN                    2
3326 #define SQLITE_LIMIT_EXPR_DEPTH                3
3327 #define SQLITE_LIMIT_COMPOUND_SELECT           4
3328 #define SQLITE_LIMIT_VDBE_OP                   5
3329 #define SQLITE_LIMIT_FUNCTION_ARG              6
3330 #define SQLITE_LIMIT_ATTACHED                  7
3331 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3332 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
3333
3334 /*
3335 ** CAPI3REF: Compiling An SQL Statement {H13010} <S10000>
3336 ** KEYWORDS: {SQL statement compiler}
3337 **
3338 ** To execute an SQL query, it must first be compiled into a byte-code
3339 ** program using one of these routines.
3340 **
3341 ** The first argument, "db", is a [database connection] obtained from a
3342 ** prior call to [sqlite3_open()], [sqlite3_open_v2()] or [sqlite3_open16()].
3343 **
3344 ** The second argument, "zSql", is the statement to be compiled, encoded
3345 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3346 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3347 ** use UTF-16.
3348 **
3349 ** If the nByte argument is less than zero, then zSql is read up to the
3350 ** first zero terminator. If nByte is non-negative, then it is the maximum
3351 ** number of  bytes read from zSql.  When nByte is non-negative, the
3352 ** zSql string ends at either the first '\000' or '\u0000' character or
3353 ** the nByte-th byte, whichever comes first. If the caller knows
3354 ** that the supplied string is nul-terminated, then there is a small
3355 ** performance advantage to be gained by passing an nByte parameter that
3356 ** is equal to the number of bytes in the input string <i>including</i>
3357 ** the nul-terminator bytes.
3358 **
3359 ** *pzTail is made to point to the first byte past the end of the
3360 ** first SQL statement in zSql.  These routines only compile the first
3361 ** statement in zSql, so *pzTail is left pointing to what remains
3362 ** uncompiled.
3363 **
3364 ** *ppStmt is left pointing to a compiled [prepared statement] that can be
3365 ** executed using [sqlite3_step()].  If there is an error, *ppStmt is set
3366 ** to NULL.  If the input text contains no SQL (if the input is an empty
3367 ** string or a comment) then *ppStmt is set to NULL.
3368 ** {A13018} The calling procedure is responsible for deleting the compiled
3369 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3370 **
3371 ** On success, [SQLITE_OK] is returned, otherwise an [error code] is returned.
3372 **
3373 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3374 ** recommended for all new programs. The two older interfaces are retained
3375 ** for backwards compatibility, but their use is discouraged.
3376 ** In the "v2" interfaces, the prepared statement
3377 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3378 ** original SQL text. This causes the [sqlite3_step()] interface to
3379 ** behave a differently in two ways:
3380 **
3381 ** <ol>
3382 ** <li>
3383 ** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3384 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3385 ** statement and try to run it again.  If the schema has changed in
3386 ** a way that makes the statement no longer valid, [sqlite3_step()] will still
3387 ** return [SQLITE_SCHEMA].  But unlike the legacy behavior, [SQLITE_SCHEMA] is
3388 ** now a fatal error.  Calling [sqlite3_prepare_v2()] again will not make the
3389 ** error go away.  Note: use [sqlite3_errmsg()] to find the text
3390 ** of the parsing error that results in an [SQLITE_SCHEMA] return.
3391 ** </li>
3392 **
3393 ** <li>
3394 ** When an error occurs, [sqlite3_step()] will return one of the detailed
3395 ** [error codes] or [extended error codes].  The legacy behavior was that
3396 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3397 ** and you would have to make a second call to [sqlite3_reset()] in order
3398 ** to find the underlying cause of the problem. With the "v2" prepare
3399 ** interfaces, the underlying reason for the error is returned immediately.
3400 ** </li>
3401 ** </ol>
3402 **
3403 ** INVARIANTS:
3404 **
3405 ** {H13011} The [sqlite3_prepare(db,zSql,...)] and
3406 **          [sqlite3_prepare_v2(db,zSql,...)] interfaces interpret the
3407 **          text in their zSql parameter as UTF-8.
3408 **
3409 ** {H13012} The [sqlite3_prepare16(db,zSql,...)] and
3410 **          [sqlite3_prepare16_v2(db,zSql,...)] interfaces interpret the
3411 **          text in their zSql parameter as UTF-16 in the native byte order.
3412 **
3413 ** {H13013} If the nByte argument to [sqlite3_prepare_v2(db,zSql,nByte,...)]
3414 **          and its variants is less than zero, the SQL text is
3415 **          read from zSql is read up to the first zero terminator.
3416 **
3417 ** {H13014} If the nByte argument to [sqlite3_prepare_v2(db,zSql,nByte,...)]
3418 **          and its variants is non-negative, then at most nBytes bytes of
3419 **          SQL text is read from zSql.
3420 **
3421 ** {H13015} In [sqlite3_prepare_v2(db,zSql,N,P,pzTail)] and its variants
3422 **          if the zSql input text contains more than one SQL statement
3423 **          and pzTail is not NULL, then *pzTail is made to point to the
3424 **          first byte past the end of the first SQL statement in zSql.
3425 **          <todo>What does *pzTail point to if there is one statement?</todo>
3426 **
3427 ** {H13016} A successful call to [sqlite3_prepare_v2(db,zSql,N,ppStmt,...)]
3428 **          or one of its variants writes into *ppStmt a pointer to a new
3429 **          [prepared statement] or a pointer to NULL if zSql contains
3430 **          nothing other than whitespace or comments.
3431 **
3432 ** {H13019} The [sqlite3_prepare_v2()] interface and its variants return
3433 **          [SQLITE_OK] or an appropriate [error code] upon failure.
3434 **
3435 ** {H13021} Before [sqlite3_prepare(db,zSql,nByte,ppStmt,pzTail)] or its
3436 **          variants returns an error (any value other than [SQLITE_OK]),
3437 **          they first set *ppStmt to NULL.
3438 */
3439 SQLITE_API int sqlite3_prepare(
3440   sqlite3 *db,            /* Database handle */
3441   const char *zSql,       /* SQL statement, UTF-8 encoded */
3442   int nByte,              /* Maximum length of zSql in bytes. */
3443   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3444   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3445 );
3446 SQLITE_API int sqlite3_prepare_v2(
3447   sqlite3 *db,            /* Database handle */
3448   const char *zSql,       /* SQL statement, UTF-8 encoded */
3449   int nByte,              /* Maximum length of zSql in bytes. */
3450   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3451   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3452 );
3453 SQLITE_API int sqlite3_prepare16(
3454   sqlite3 *db,            /* Database handle */
3455   const void *zSql,       /* SQL statement, UTF-16 encoded */
3456   int nByte,              /* Maximum length of zSql in bytes. */
3457   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3458   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3459 );
3460 SQLITE_API int sqlite3_prepare16_v2(
3461   sqlite3 *db,            /* Database handle */
3462   const void *zSql,       /* SQL statement, UTF-16 encoded */
3463   int nByte,              /* Maximum length of zSql in bytes. */
3464   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3465   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3466 );
3467
3468 /*
3469 ** CAPI3REF: Retrieving Statement SQL {H13100} <H13000>
3470 **
3471 ** This interface can be used to retrieve a saved copy of the original
3472 ** SQL text used to create a [prepared statement] if that statement was
3473 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3474 **
3475 ** INVARIANTS:
3476 **
3477 ** {H13101} If the [prepared statement] passed as the argument to
3478 **          [sqlite3_sql()] was compiled using either [sqlite3_prepare_v2()] or
3479 **          [sqlite3_prepare16_v2()], then [sqlite3_sql()] returns
3480 **          a pointer to a zero-terminated string containing a UTF-8 rendering
3481 **          of the original SQL statement.
3482 **
3483 ** {H13102} If the [prepared statement] passed as the argument to
3484 **          [sqlite3_sql()] was compiled using either [sqlite3_prepare()] or
3485 **          [sqlite3_prepare16()], then [sqlite3_sql()] returns a NULL pointer.
3486 **
3487 ** {H13103} The string returned by [sqlite3_sql(S)] is valid until the
3488 **          [prepared statement] S is deleted using [sqlite3_finalize(S)].
3489 */
3490 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3491
3492 /*
3493 ** CAPI3REF: Dynamically Typed Value Object {H15000} <S20200>
3494 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3495 **
3496 ** SQLite uses the sqlite3_value object to represent all values
3497 ** that can be stored in a database table. SQLite uses dynamic typing
3498 ** for the values it stores. Values stored in sqlite3_value objects
3499 ** can be integers, floating point values, strings, BLOBs, or NULL.
3500 **
3501 ** An sqlite3_value object may be either "protected" or "unprotected".
3502 ** Some interfaces require a protected sqlite3_value.  Other interfaces
3503 ** will accept either a protected or an unprotected sqlite3_value.
3504 ** Every interface that accepts sqlite3_value arguments specifies
3505 ** whether or not it requires a protected sqlite3_value.
3506 **
3507 ** The terms "protected" and "unprotected" refer to whether or not
3508 ** a mutex is held.  A internal mutex is held for a protected
3509 ** sqlite3_value object but no mutex is held for an unprotected
3510 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
3511 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3512 ** or if SQLite is run in one of reduced mutex modes 
3513 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3514 ** then there is no distinction between protected and unprotected
3515 ** sqlite3_value objects and they can be used interchangeably.  However,
3516 ** for maximum code portability it is recommended that applications
3517 ** still make the distinction between between protected and unprotected
3518 ** sqlite3_value objects even when not strictly required.
3519 **
3520 ** The sqlite3_value objects that are passed as parameters into the
3521 ** implementation of [application-defined SQL functions] are protected.
3522 ** The sqlite3_value object returned by
3523 ** [sqlite3_column_value()] is unprotected.
3524 ** Unprotected sqlite3_value objects may only be used with
3525 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3526 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3527 ** interfaces require protected sqlite3_value objects.
3528 */
3529 typedef struct Mem sqlite3_value;
3530
3531 /*
3532 ** CAPI3REF: SQL Function Context Object {H16001} <S20200>
3533 **
3534 ** The context in which an SQL function executes is stored in an
3535 ** sqlite3_context object.  A pointer to an sqlite3_context object
3536 ** is always first parameter to [application-defined SQL functions].
3537 ** The application-defined SQL function implementation will pass this
3538 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3539 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3540 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3541 ** and/or [sqlite3_set_auxdata()].
3542 */
3543 typedef struct sqlite3_context sqlite3_context;
3544
3545 /*
3546 ** CAPI3REF: Binding Values To Prepared Statements {H13500} <S70300>
3547 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3548 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3549 **
3550 ** In the SQL strings input to [sqlite3_prepare_v2()] and its variants,
3551 ** literals may be replaced by a parameter in one of these forms:
3552 **
3553 ** <ul>
3554 ** <li>  ?
3555 ** <li>  ?NNN
3556 ** <li>  :VVV
3557 ** <li>  @VVV
3558 ** <li>  $VVV
3559 ** </ul>
3560 **
3561 ** In the parameter forms shown above NNN is an integer literal,
3562 ** and VVV is an alpha-numeric parameter name. The values of these
3563 ** parameters (also called "host parameter names" or "SQL parameters")
3564 ** can be set using the sqlite3_bind_*() routines defined here.
3565 **
3566 ** The first argument to the sqlite3_bind_*() routines is always
3567 ** a pointer to the [sqlite3_stmt] object returned from
3568 ** [sqlite3_prepare_v2()] or its variants.
3569 **
3570 ** The second argument is the index of the SQL parameter to be set.
3571 ** The leftmost SQL parameter has an index of 1.  When the same named
3572 ** SQL parameter is used more than once, second and subsequent
3573 ** occurrences have the same index as the first occurrence.
3574 ** The index for named parameters can be looked up using the
3575 ** [sqlite3_bind_parameter_index()] API if desired.  The index
3576 ** for "?NNN" parameters is the value of NNN.
3577 ** The NNN value must be between 1 and the [sqlite3_limit()]
3578 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3579 **
3580 ** The third argument is the value to bind to the parameter.
3581 **
3582 ** In those routines that have a fourth argument, its value is the
3583 ** number of bytes in the parameter.  To be clear: the value is the
3584 ** number of <u>bytes</u> in the value, not the number of characters.
3585 ** If the fourth parameter is negative, the length of the string is
3586 ** the number of bytes up to the first zero terminator.
3587 **
3588 ** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3589 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3590 ** string after SQLite has finished with it. If the fifth argument is
3591 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3592 ** information is in static, unmanaged space and does not need to be freed.
3593 ** If the fifth argument has the value [SQLITE_TRANSIENT], then
3594 ** SQLite makes its own private copy of the data immediately, before
3595 ** the sqlite3_bind_*() routine returns.
3596 **
3597 ** The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3598 ** is filled with zeroes.  A zeroblob uses a fixed amount of memory
3599 ** (just an integer to hold its size) while it is being processed.
3600 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3601 ** content is later written using
3602 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3603 ** A negative value for the zeroblob results in a zero-length BLOB.
3604 **
3605 ** The sqlite3_bind_*() routines must be called after
3606 ** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and
3607 ** before [sqlite3_step()].
3608 ** Bindings are not cleared by the [sqlite3_reset()] routine.
3609 ** Unbound parameters are interpreted as NULL.
3610 **
3611 ** These routines return [SQLITE_OK] on success or an error code if
3612 ** anything goes wrong.  [SQLITE_RANGE] is returned if the parameter
3613 ** index is out of range.  [SQLITE_NOMEM] is returned if malloc() fails.
3614 ** [SQLITE_MISUSE] might be returned if these routines are called on a
3615 ** virtual machine that is the wrong state or which has already been finalized.
3616 ** Detection of misuse is unreliable.  Applications should not depend
3617 ** on SQLITE_MISUSE returns.  SQLITE_MISUSE is intended to indicate a
3618 ** a logic error in the application.  Future versions of SQLite might
3619 ** panic rather than return SQLITE_MISUSE.
3620 **
3621 ** See also: [sqlite3_bind_parameter_count()],
3622 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3623 **
3624 ** INVARIANTS:
3625 **
3626 ** {H13506} The [SQL statement compiler] recognizes tokens of the forms
3627 **          "?", "?NNN", "$VVV", ":VVV", and "@VVV" as SQL parameters,
3628 **          where NNN is any sequence of one or more digits
3629 **          and where VVV is any sequence of one or more alphanumeric
3630 **          characters or "::" optionally followed by a string containing
3631 **          no spaces and contained within parentheses.
3632 **
3633 ** {H13509} The initial value of an SQL parameter is NULL.
3634 **
3635 ** {H13512} The index of an "?" SQL parameter is one larger than the
3636 **          largest index of SQL parameter to the left, or 1 if
3637 **          the "?" is the leftmost SQL parameter.
3638 **
3639 ** {H13515} The index of an "?NNN" SQL parameter is the integer NNN.
3640 **
3641 ** {H13518} The index of an ":VVV", "$VVV", or "@VVV" SQL parameter is
3642 **          the same as the index of leftmost occurrences of the same
3643 **          parameter, or one more than the largest index over all
3644 **          parameters to the left if this is the first occurrence
3645 **          of this parameter, or 1 if this is the leftmost parameter.
3646 **
3647 ** {H13521} The [SQL statement compiler] fails with an [SQLITE_RANGE]
3648 **          error if the index of an SQL parameter is less than 1
3649 **          or greater than the compile-time SQLITE_MAX_VARIABLE_NUMBER
3650 **          parameter.
3651 **
3652 ** {H13524} Calls to [sqlite3_bind_text | sqlite3_bind(S,N,V,...)]
3653 **          associate the value V with all SQL parameters having an
3654 **          index of N in the [prepared statement] S.
3655 **
3656 ** {H13527} Calls to [sqlite3_bind_text | sqlite3_bind(S,N,...)]
3657 **          override prior calls with the same values of S and N.
3658 **
3659 ** {H13530} Bindings established by [sqlite3_bind_text | sqlite3_bind(S,...)]
3660 **          persist across calls to [sqlite3_reset(S)].
3661 **
3662 ** {H13533} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
3663 **          [sqlite3_bind_text(S,N,V,L,D)], or
3664 **          [sqlite3_bind_text16(S,N,V,L,D)] SQLite binds the first L
3665 **          bytes of the BLOB or string pointed to by V, when L
3666 **          is non-negative.
3667 **
3668 ** {H13536} In calls to [sqlite3_bind_text(S,N,V,L,D)] or
3669 **          [sqlite3_bind_text16(S,N,V,L,D)] SQLite binds characters
3670 **          from V through the first zero character when L is negative.
3671 **
3672 ** {H13539} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
3673 **          [sqlite3_bind_text(S,N,V,L,D)], or
3674 **          [sqlite3_bind_text16(S,N,V,L,D)] when D is the special
3675 **          constant [SQLITE_STATIC], SQLite assumes that the value V
3676 **          is held in static unmanaged space that will not change
3677 **          during the lifetime of the binding.
3678 **
3679 ** {H13542} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
3680 **          [sqlite3_bind_text(S,N,V,L,D)], or
3681 **          [sqlite3_bind_text16(S,N,V,L,D)] when D is the special
3682 **          constant [SQLITE_TRANSIENT], the routine makes a
3683 **          private copy of the value V before it returns.
3684 **
3685 ** {H13545} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
3686 **          [sqlite3_bind_text(S,N,V,L,D)], or
3687 **          [sqlite3_bind_text16(S,N,V,L,D)] when D is a pointer to
3688 **          a function, SQLite invokes that function to destroy the
3689 **          value V after it has finished using the value V.
3690 **
3691 ** {H13548} In calls to [sqlite3_bind_zeroblob(S,N,V,L)] the value bound
3692 **          is a BLOB of L bytes, or a zero-length BLOB if L is negative.
3693 **
3694 ** {H13551} In calls to [sqlite3_bind_value(S,N,V)] the V argument may
3695 **          be either a [protected sqlite3_value] object or an
3696 **          [unprotected sqlite3_value] object.
3697 */
3698 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3699 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3700 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3701 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3702 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3703 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3704 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3705 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3706 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3707
3708 /*
3709 ** CAPI3REF: Number Of SQL Parameters {H13600} <S70300>
3710 **
3711 ** This routine can be used to find the number of [SQL parameters]
3712 ** in a [prepared statement].  SQL parameters are tokens of the
3713 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3714 ** placeholders for values that are [sqlite3_bind_blob | bound]
3715 ** to the parameters at a later time.
3716 **
3717 ** This routine actually returns the index of the largest (rightmost)
3718 ** parameter. For all forms except ?NNN, this will correspond to the
3719 ** number of unique parameters.  If parameters of the ?NNN are used,
3720 ** there may be gaps in the list.
3721 **
3722 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3723 ** [sqlite3_bind_parameter_name()], and
3724 ** [sqlite3_bind_parameter_index()].
3725 **
3726 ** INVARIANTS:
3727 **
3728 ** {H13601} The [sqlite3_bind_parameter_count(S)] interface returns
3729 **          the largest index of all SQL parameters in the
3730 **          [prepared statement] S, or 0 if S contains no SQL parameters.
3731 */
3732 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3733
3734 /*
3735 ** CAPI3REF: Name Of A Host Parameter {H13620} <S70300>
3736 **
3737 ** This routine returns a pointer to the name of the n-th
3738 ** [SQL parameter] in a [prepared statement].
3739 ** SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3740 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3741 ** respectively.
3742 ** In other words, the initial ":" or "$" or "@" or "?"
3743 ** is included as part of the name.
3744 ** Parameters of the form "?" without a following integer have no name
3745 ** and are also referred to as "anonymous parameters".
3746 **
3747 ** The first host parameter has an index of 1, not 0.
3748 **
3749 ** If the value n is out of range or if the n-th parameter is
3750 ** nameless, then NULL is returned.  The returned string is
3751 ** always in UTF-8 encoding even if the named parameter was
3752 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3753 ** [sqlite3_prepare16_v2()].
3754 **
3755 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3756 ** [sqlite3_bind_parameter_count()], and
3757 ** [sqlite3_bind_parameter_index()].
3758 **
3759 ** INVARIANTS:
3760 **
3761 ** {H13621} The [sqlite3_bind_parameter_name(S,N)] interface returns
3762 **          a UTF-8 rendering of the name of the SQL parameter in
3763 **          the [prepared statement] S having index N, or
3764 **          NULL if there is no SQL parameter with index N or if the
3765 **          parameter with index N is an anonymous parameter "?".
3766 */
3767 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3768
3769 /*
3770 ** CAPI3REF: Index Of A Parameter With A Given Name {H13640} <S70300>
3771 **
3772 ** Return the index of an SQL parameter given its name.  The
3773 ** index value returned is suitable for use as the second
3774 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  A zero
3775 ** is returned if no matching parameter is found.  The parameter
3776 ** name must be given in UTF-8 even if the original statement
3777 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3778 **
3779 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3780 ** [sqlite3_bind_parameter_count()], and
3781 ** [sqlite3_bind_parameter_index()].
3782 **
3783 ** INVARIANTS:
3784 **
3785 ** {H13641} The [sqlite3_bind_parameter_index(S,N)] interface returns
3786 **          the index of SQL parameter in the [prepared statement]
3787 **          S whose name matches the UTF-8 string N, or 0 if there is
3788 **          no match.
3789 */
3790 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3791
3792 /*
3793 ** CAPI3REF: Reset All Bindings On A Prepared Statement {H13660} <S70300>
3794 **
3795 ** Contrary to the intuition of many, [sqlite3_reset()] does not reset
3796 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3797 ** Use this routine to reset all host parameters to NULL.
3798 **
3799 ** INVARIANTS:
3800 **
3801 ** {H13661} The [sqlite3_clear_bindings(S)] interface resets all SQL
3802 **          parameter bindings in the [prepared statement] S back to NULL.
3803 */
3804 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3805
3806 /*
3807 ** CAPI3REF: Number Of Columns In A Result Set {H13710} <S10700>
3808 **
3809 ** Return the number of columns in the result set returned by the
3810 ** [prepared statement]. This routine returns 0 if pStmt is an SQL
3811 ** statement that does not return data (for example an [UPDATE]).
3812 **
3813 ** INVARIANTS:
3814 **
3815 ** {H13711} The [sqlite3_column_count(S)] interface returns the number of
3816 **          columns in the result set generated by the [prepared statement] S,
3817 **          or 0 if S does not generate a result set.
3818 */
3819 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3820
3821 /*
3822 ** CAPI3REF: Column Names In A Result Set {H13720} <S10700>
3823 **
3824 ** These routines return the name assigned to a particular column
3825 ** in the result set of a [SELECT] statement.  The sqlite3_column_name()
3826 ** interface returns a pointer to a zero-terminated UTF-8 string
3827 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3828 ** UTF-16 string.  The first parameter is the [prepared statement]
3829 ** that implements the [SELECT] statement. The second parameter is the
3830 ** column number.  The leftmost column is number 0.
3831 **
3832 ** The returned string pointer is valid until either the [prepared statement]
3833 ** is destroyed by [sqlite3_finalize()] or until the next call to
3834 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3835 **
3836 ** If sqlite3_malloc() fails during the processing of either routine
3837 ** (for example during a conversion from UTF-8 to UTF-16) then a
3838 ** NULL pointer is returned.
3839 **
3840 ** The name of a result column is the value of the "AS" clause for
3841 ** that column, if there is an AS clause.  If there is no AS clause
3842 ** then the name of the column is unspecified and may change from
3843 ** one release of SQLite to the next.
3844 **
3845 ** INVARIANTS:
3846 **
3847 ** {H13721} A successful invocation of the [sqlite3_column_name(S,N)]
3848 **          interface returns the name of the Nth column (where 0 is
3849 **          the leftmost column) for the result set of the
3850 **          [prepared statement] S as a zero-terminated UTF-8 string.
3851 **
3852 ** {H13723} A successful invocation of the [sqlite3_column_name16(S,N)]
3853 **          interface returns the name of the Nth column (where 0 is
3854 **          the leftmost column) for the result set of the
3855 **          [prepared statement] S as a zero-terminated UTF-16 string
3856 **          in the native byte order.
3857 **
3858 ** {H13724} The [sqlite3_column_name()] and [sqlite3_column_name16()]
3859 **          interfaces return a NULL pointer if they are unable to
3860 **          allocate memory to hold their normal return strings.
3861 **
3862 ** {H13725} If the N parameter to [sqlite3_column_name(S,N)] or
3863 **          [sqlite3_column_name16(S,N)] is out of range, then the
3864 **          interfaces return a NULL pointer.
3865 **
3866 ** {H13726} The strings returned by [sqlite3_column_name(S,N)] and
3867 **          [sqlite3_column_name16(S,N)] are valid until the next
3868 **          call to either routine with the same S and N parameters
3869 **          or until [sqlite3_finalize(S)] is called.
3870 **
3871 ** {H13727} When a result column of a [SELECT] statement contains
3872 **          an AS clause, the name of that column is the identifier
3873 **          to the right of the AS keyword.
3874 */
3875 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3876 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3877
3878 /*
3879 ** CAPI3REF: Source Of Data In A Query Result {H13740} <S10700>
3880 **
3881 ** These routines provide a means to determine what column of what
3882 ** table in which database a result of a [SELECT] statement comes from.
3883 ** The name of the database or table or column can be returned as
3884 ** either a UTF-8 or UTF-16 string.  The _database_ routines return
3885 ** the database name, the _table_ routines return the table name, and
3886 ** the origin_ routines return the column name.
3887 ** The returned string is valid until the [prepared statement] is destroyed
3888 ** using [sqlite3_finalize()] or until the same information is requested
3889 ** again in a different encoding.
3890 **
3891 ** The names returned are the original un-aliased names of the
3892 ** database, table, and column.
3893 **
3894 ** The first argument to the following calls is a [prepared statement].
3895 ** These functions return information about the Nth column returned by
3896 ** the statement, where N is the second function argument.
3897 **
3898 ** If the Nth column returned by the statement is an expression or
3899 ** subquery and is not a column value, then all of these functions return
3900 ** NULL.  These routine might also return NULL if a memory allocation error
3901 ** occurs.  Otherwise, they return the name of the attached database, table
3902 ** and column that query result column was extracted from.
3903 **
3904 ** As with all other SQLite APIs, those postfixed with "16" return
3905 ** UTF-16 encoded strings, the other functions return UTF-8. {END}
3906 **
3907 ** These APIs are only available if the library was compiled with the
3908 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
3909 **
3910 ** {A13751}
3911 ** If two or more threads call one or more of these routines against the same
3912 ** prepared statement and column at the same time then the results are
3913 ** undefined.
3914 **
3915 ** INVARIANTS:
3916 **
3917 ** {H13741} The [sqlite3_column_database_name(S,N)] interface returns either
3918 **          the UTF-8 zero-terminated name of the database from which the
3919 **          Nth result column of the [prepared statement] S is extracted,
3920 **          or NULL if the Nth column of S is a general expression
3921 **          or if unable to allocate memory to store the name.
3922 **
3923 ** {H13742} The [sqlite3_column_database_name16(S,N)] interface returns either
3924 **          the UTF-16 native byte order zero-terminated name of the database
3925 **          from which the Nth result column of the [prepared statement] S is
3926 **          extracted, or NULL if the Nth column of S is a general expression
3927 **          or if unable to allocate memory to store the name.
3928 **
3929 ** {H13743} The [sqlite3_column_table_name(S,N)] interface returns either
3930 **          the UTF-8 zero-terminated name of the table from which the
3931 **          Nth result column of the [prepared statement] S is extracted,
3932 **          or NULL if the Nth column of S is a general expression
3933 **          or if unable to allocate memory to store the name.
3934 **
3935 ** {H13744} The [sqlite3_column_table_name16(S,N)] interface returns either
3936 **          the UTF-16 native byte order zero-terminated name of the table
3937 **          from which the Nth result column of the [prepared statement] S is
3938 **          extracted, or NULL if the Nth column of S is a general expression
3939 **          or if unable to allocate memory to store the name.
3940 **
3941 ** {H13745} The [sqlite3_column_origin_name(S,N)] interface returns either
3942 **          the UTF-8 zero-terminated name of the table column from which the
3943 **          Nth result column of the [prepared statement] S is extracted,
3944 **          or NULL if the Nth column of S is a general expression
3945 **          or if unable to allocate memory to store the name.
3946 **
3947 ** {H13746} The [sqlite3_column_origin_name16(S,N)] interface returns either
3948 **          the UTF-16 native byte order zero-terminated name of the table
3949 **          column from which the Nth result column of the
3950 **          [prepared statement] S is extracted, or NULL if the Nth column
3951 **          of S is a general expression or if unable to allocate memory
3952 **          to store the name.
3953 **
3954 ** {H13748} The return values from
3955 **          [sqlite3_column_database_name | column metadata interfaces]
3956 **          are valid for the lifetime of the [prepared statement]
3957 **          or until the encoding is changed by another metadata
3958 **          interface call for the same prepared statement and column.
3959 **
3960 ** ASSUMPTIONS:
3961 **
3962 ** {A13751} If two or more threads call one or more
3963 **          [sqlite3_column_database_name | column metadata interfaces]
3964 **          for the same [prepared statement] and result column
3965 **          at the same time then the results are undefined.
3966 */
3967 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3968 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3969 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3970 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3971 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3972 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3973
3974 /*
3975 ** CAPI3REF: Declared Datatype Of A Query Result {H13760} <S10700>
3976 **
3977 ** The first parameter is a [prepared statement].
3978 ** If this statement is a [SELECT] statement and the Nth column of the
3979 ** returned result set of that [SELECT] is a table column (not an
3980 ** expression or subquery) then the declared type of the table
3981 ** column is returned.  If the Nth column of the result set is an
3982 ** expression or subquery, then a NULL pointer is returned.
3983 ** The returned string is always UTF-8 encoded. {END}
3984 **
3985 ** For example, given the database schema:
3986 **
3987 ** CREATE TABLE t1(c1 VARIANT);
3988 **
3989 ** and the following statement to be compiled:
3990 **
3991 ** SELECT c1 + 1, c1 FROM t1;
3992 **
3993 ** this routine would return the string "VARIANT" for the second result
3994 ** column (i==1), and a NULL pointer for the first result column (i==0).
3995 **
3996 ** SQLite uses dynamic run-time typing.  So just because a column
3997 ** is declared to contain a particular type does not mean that the
3998 ** data stored in that column is of the declared type.  SQLite is
3999 ** strongly typed, but the typing is dynamic not static.  Type
4000 ** is associated with individual values, not with the containers
4001 ** used to hold those values.
4002 **
4003 ** INVARIANTS:
4004 **
4005 ** {H13761}  A successful call to [sqlite3_column_decltype(S,N)] returns a
4006 **           zero-terminated UTF-8 string containing the declared datatype
4007 **           of the table column that appears as the Nth column (numbered
4008 **           from 0) of the result set to the [prepared statement] S.
4009 **
4010 ** {H13762}  A successful call to [sqlite3_column_decltype16(S,N)]
4011 **           returns a zero-terminated UTF-16 native byte order string
4012 **           containing the declared datatype of the table column that appears
4013 **           as the Nth column (numbered from 0) of the result set to the
4014 **           [prepared statement] S.
4015 **
4016 ** {H13763}  If N is less than 0 or N is greater than or equal to
4017 **           the number of columns in the [prepared statement] S,
4018 **           or if the Nth column of S is an expression or subquery rather
4019 **           than a table column, or if a memory allocation failure
4020 **           occurs during encoding conversions, then
4021 **           calls to [sqlite3_column_decltype(S,N)] or
4022 **           [sqlite3_column_decltype16(S,N)] return NULL.
4023 */
4024 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
4025 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
4026
4027 /*
4028 ** CAPI3REF: Evaluate An SQL Statement {H13200} <S10000>
4029 **
4030 ** After a [prepared statement] has been prepared using either
4031 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
4032 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
4033 ** must be called one or more times to evaluate the statement.
4034 **
4035 ** The details of the behavior of the sqlite3_step() interface depend
4036 ** on whether the statement was prepared using the newer "v2" interface
4037 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
4038 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
4039 ** new "v2" interface is recommended for new applications but the legacy
4040 ** interface will continue to be supported.
4041 **
4042 ** In the legacy interface, the return value will be either [SQLITE_BUSY],
4043 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
4044 ** With the "v2" interface, any of the other [result codes] or
4045 ** [extended result codes] might be returned as well.
4046 **
4047 ** [SQLITE_BUSY] means that the database engine was unable to acquire the
4048 ** database locks it needs to do its job.  If the statement is a [COMMIT]
4049 ** or occurs outside of an explicit transaction, then you can retry the
4050 ** statement.  If the statement is not a [COMMIT] and occurs within a
4051 ** explicit transaction then you should rollback the transaction before
4052 ** continuing.
4053 **
4054 ** [SQLITE_DONE] means that the statement has finished executing
4055 ** successfully.  sqlite3_step() should not be called again on this virtual
4056 ** machine without first calling [sqlite3_reset()] to reset the virtual
4057 ** machine back to its initial state.
4058 **
4059 ** If the SQL statement being executed returns any data, then [SQLITE_ROW]
4060 ** is returned each time a new row of data is ready for processing by the
4061 ** caller. The values may be accessed using the [column access functions].
4062 ** sqlite3_step() is called again to retrieve the next row of data.
4063 **
4064 ** [SQLITE_ERROR] means that a run-time error (such as a constraint
4065 ** violation) has occurred.  sqlite3_step() should not be called again on
4066 ** the VM. More information may be found by calling [sqlite3_errmsg()].
4067 ** With the legacy interface, a more specific error code (for example,
4068 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
4069 ** can be obtained by calling [sqlite3_reset()] on the
4070 ** [prepared statement].  In the "v2" interface,
4071 ** the more specific error code is returned directly by sqlite3_step().
4072 **
4073 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
4074 ** Perhaps it was called on a [prepared statement] that has
4075 ** already been [sqlite3_finalize | finalized] or on one that had
4076 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
4077 ** be the case that the same database connection is being used by two or
4078 ** more threads at the same moment in time.
4079 **
4080 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
4081 ** API always returns a generic error code, [SQLITE_ERROR], following any
4082 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
4083 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
4084 ** specific [error codes] that better describes the error.
4085 ** We admit that this is a goofy design.  The problem has been fixed
4086 ** with the "v2" interface.  If you prepare all of your SQL statements
4087 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
4088 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
4089 ** then the more specific [error codes] are returned directly
4090 ** by sqlite3_step().  The use of the "v2" interface is recommended.
4091 **
4092 ** INVARIANTS:
4093 **
4094 ** {H13202}  If the [prepared statement] S is ready to be run, then
4095 **           [sqlite3_step(S)] advances that prepared statement until
4096 **           completion or until it is ready to return another row of the
4097 **           result set, or until an [sqlite3_interrupt | interrupt]
4098 **           or a run-time error occurs.
4099 **
4100 ** {H15304}  When a call to [sqlite3_step(S)] causes the [prepared statement]
4101 **           S to run to completion, the function returns [SQLITE_DONE].
4102 **
4103 ** {H15306}  When a call to [sqlite3_step(S)] stops because it is ready to
4104 **           return another row of the result set, it returns [SQLITE_ROW].
4105 **
4106 ** {H15308}  If a call to [sqlite3_step(S)] encounters an
4107 **           [sqlite3_interrupt | interrupt] or a run-time error,
4108 **           it returns an appropriate error code that is not one of
4109 **           [SQLITE_OK], [SQLITE_ROW], or [SQLITE_DONE].
4110 **
4111 ** {H15310}  If an [sqlite3_interrupt | interrupt] or a run-time error
4112 **           occurs during a call to [sqlite3_step(S)]
4113 **           for a [prepared statement] S created using
4114 **           legacy interfaces [sqlite3_prepare()] or
4115 **           [sqlite3_prepare16()], then the function returns either
4116 **           [SQLITE_ERROR], [SQLITE_BUSY], or [SQLITE_MISUSE].
4117 */
4118 SQLITE_API int sqlite3_step(sqlite3_stmt*);
4119
4120 /*
4121 ** CAPI3REF: Number of columns in a result set {H13770} <S10700>
4122 **
4123 ** Returns the number of values in the current row of the result set.
4124 **
4125 ** INVARIANTS:
4126 **
4127 ** {H13771}  After a call to [sqlite3_step(S)] that returns [SQLITE_ROW],
4128 **           the [sqlite3_data_count(S)] routine will return the same value
4129 **           as the [sqlite3_column_count(S)] function.
4130 **
4131 ** {H13772}  After [sqlite3_step(S)] has returned any value other than
4132 **           [SQLITE_ROW] or before [sqlite3_step(S)] has been called on the
4133 **           [prepared statement] for the first time since it was
4134 **           [sqlite3_prepare | prepared] or [sqlite3_reset | reset],
4135 **           the [sqlite3_data_count(S)] routine returns zero.
4136 */
4137 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
4138
4139 /*
4140 ** CAPI3REF: Fundamental Datatypes {H10265} <S10110><S10120>
4141 ** KEYWORDS: SQLITE_TEXT
4142 **
4143 ** {H10266} Every value in SQLite has one of five fundamental datatypes:
4144 **
4145 ** <ul>
4146 ** <li> 64-bit signed integer
4147 ** <li> 64-bit IEEE floating point number
4148 ** <li> string
4149 ** <li> BLOB
4150 ** <li> NULL
4151 ** </ul> {END}
4152 **
4153 ** These constants are codes for each of those types.
4154 **
4155 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
4156 ** for a completely different meaning.  Software that links against both
4157 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
4158 ** SQLITE_TEXT.
4159 */
4160 #define SQLITE_INTEGER  1
4161 #define SQLITE_FLOAT    2
4162 #define SQLITE_BLOB     4
4163 #define SQLITE_NULL     5
4164 #ifdef SQLITE_TEXT
4165 # undef SQLITE_TEXT
4166 #else
4167 # define SQLITE_TEXT     3
4168 #endif
4169 #define SQLITE3_TEXT     3
4170
4171 /*
4172 ** CAPI3REF: Result Values From A Query {H13800} <S10700>
4173 ** KEYWORDS: {column access functions}
4174 **
4175 ** These routines form the "result set query" interface.
4176 **
4177 ** These routines return information about a single column of the current
4178 ** result row of a query.  In every case the first argument is a pointer
4179 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
4180 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
4181 ** and the second argument is the index of the column for which information
4182 ** should be returned.  The leftmost column of the result set has the index 0.
4183 **
4184 ** If the SQL statement does not currently point to a valid row, or if the
4185 ** column index is out of range, the result is undefined.
4186 ** These routines may only be called when the most recent call to
4187 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
4188 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
4189 ** If any of these routines are called after [sqlite3_reset()] or
4190 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
4191 ** something other than [SQLITE_ROW], the results are undefined.
4192 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
4193 ** are called from a different thread while any of these routines
4194 ** are pending, then the results are undefined.
4195 **
4196 ** The sqlite3_column_type() routine returns the
4197 ** [SQLITE_INTEGER | datatype code] for the initial data type
4198 ** of the result column.  The returned value is one of [SQLITE_INTEGER],
4199 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
4200 ** returned by sqlite3_column_type() is only meaningful if no type
4201 ** conversions have occurred as described below.  After a type conversion,
4202 ** the value returned by sqlite3_column_type() is undefined.  Future
4203 ** versions of SQLite may change the behavior of sqlite3_column_type()
4204 ** following a type conversion.
4205 **
4206 ** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
4207 ** routine returns the number of bytes in that BLOB or string.
4208 ** If the result is a UTF-16 string, then sqlite3_column_bytes() converts
4209 ** the string to UTF-8 and then returns the number of bytes.
4210 ** If the result is a numeric value then sqlite3_column_bytes() uses
4211 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
4212 ** the number of bytes in that string.
4213 ** The value returned does not include the zero terminator at the end
4214 ** of the string.  For clarity: the value returned is the number of
4215 ** bytes in the string, not the number of characters.
4216 **
4217 ** Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
4218 ** even empty strings, are always zero terminated.  The return
4219 ** value from sqlite3_column_blob() for a zero-length BLOB is an arbitrary
4220 ** pointer, possibly even a NULL pointer.
4221 **
4222 ** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
4223 ** but leaves the result in UTF-16 in native byte order instead of UTF-8.
4224 ** The zero terminator is not included in this count.
4225 **
4226 ** The object returned by [sqlite3_column_value()] is an
4227 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
4228 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
4229 ** If the [unprotected sqlite3_value] object returned by
4230 ** [sqlite3_column_value()] is used in any other way, including calls
4231 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
4232 ** or [sqlite3_value_bytes()], then the behavior is undefined.
4233 **
4234 ** These routines attempt to convert the value where appropriate.  For
4235 ** example, if the internal representation is FLOAT and a text result
4236 ** is requested, [sqlite3_snprintf()] is used internally to perform the
4237 ** conversion automatically.  The following table details the conversions
4238 ** that are applied:
4239 **
4240 ** <blockquote>
4241 ** <table border="1">
4242 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
4243 **
4244 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
4245 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
4246 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
4247 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
4248 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
4249 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
4250 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
4251 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
4252 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
4253 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
4254 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
4255 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
4256 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
4257 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
4258 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
4259 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
4260 ** </table>
4261 ** </blockquote>
4262 **
4263 ** The table above makes reference to standard C library functions atoi()
4264 ** and atof().  SQLite does not really use these functions.  It has its
4265 ** own equivalent internal routines.  The atoi() and atof() names are
4266 ** used in the table for brevity and because they are familiar to most
4267 ** C programmers.
4268 **
4269 ** Note that when type conversions occur, pointers returned by prior
4270 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
4271 ** sqlite3_column_text16() may be invalidated.
4272 ** Type conversions and pointer invalidations might occur
4273 ** in the following cases:
4274 **
4275 ** <ul>
4276 ** <li> The initial content is a BLOB and sqlite3_column_text() or
4277 **      sqlite3_column_text16() is called.  A zero-terminator might
4278 **      need to be added to the string.</li>
4279 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
4280 **      sqlite3_column_text16() is called.  The content must be converted
4281 **      to UTF-16.</li>
4282 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
4283 **      sqlite3_column_text() is called.  The content must be converted
4284 **      to UTF-8.</li>
4285 ** </ul>
4286 **
4287 ** Conversions between UTF-16be and UTF-16le are always done in place and do
4288 ** not invalidate a prior pointer, though of course the content of the buffer
4289 ** that the prior pointer points to will have been modified.  Other kinds
4290 ** of conversion are done in place when it is possible, but sometimes they
4291 ** are not possible and in those cases prior pointers are invalidated.
4292 **
4293 ** The safest and easiest to remember policy is to invoke these routines
4294 ** in one of the following ways:
4295 **
4296 ** <ul>
4297 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
4298 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
4299 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
4300 ** </ul>
4301 **
4302 ** In other words, you should call sqlite3_column_text(),
4303 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
4304 ** into the desired format, then invoke sqlite3_column_bytes() or
4305 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
4306 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
4307 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
4308 ** with calls to sqlite3_column_bytes().
4309 **
4310 ** The pointers returned are valid until a type conversion occurs as
4311 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
4312 ** [sqlite3_finalize()] is called.  The memory space used to hold strings
4313 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
4314 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
4315 ** [sqlite3_free()].
4316 **
4317 ** If a memory allocation error occurs during the evaluation of any
4318 ** of these routines, a default value is returned.  The default value
4319 ** is either the integer 0, the floating point number 0.0, or a NULL
4320 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
4321 ** [SQLITE_NOMEM].
4322 **
4323 ** INVARIANTS:
4324 **
4325 ** {H13803} The [sqlite3_column_blob(S,N)] interface converts the
4326 **          Nth column in the current row of the result set for
4327 **          the [prepared statement] S into a BLOB and then returns a
4328 **          pointer to the converted value.
4329 **
4330 ** {H13806} The [sqlite3_column_bytes(S,N)] interface returns the
4331 **          number of bytes in the BLOB or string (exclusive of the
4332 **          zero terminator on the string) that was returned by the
4333 **          most recent call to [sqlite3_column_blob(S,N)] or
4334 **          [sqlite3_column_text(S,N)].
4335 **
4336 ** {H13809} The [sqlite3_column_bytes16(S,N)] interface returns the
4337 **          number of bytes in the string (exclusive of the
4338 **          zero terminator on the string) that was returned by the
4339 **          most recent call to [sqlite3_column_text16(S,N)].
4340 **
4341 ** {H13812} The [sqlite3_column_double(S,N)] interface converts the
4342 **          Nth column in the current row of the result set for the
4343 **          [prepared statement] S into a floating point value and
4344 **          returns a copy of that value.
4345 **
4346 ** {H13815} The [sqlite3_column_int(S,N)] interface converts the
4347 **          Nth column in the current row of the result set for the
4348 **          [prepared statement] S into a 64-bit signed integer and
4349 **          returns the lower 32 bits of that integer.
4350 **
4351 ** {H13818} The [sqlite3_column_int64(S,N)] interface converts the
4352 **          Nth column in the current row of the result set for the
4353 **          [prepared statement] S into a 64-bit signed integer and
4354 **          returns a copy of that integer.
4355 **
4356 ** {H13821} The [sqlite3_column_text(S,N)] interface converts the
4357 **          Nth column in the current row of the result set for
4358 **          the [prepared statement] S into a zero-terminated UTF-8
4359 **          string and returns a pointer to that string.
4360 **
4361 ** {H13824} The [sqlite3_column_text16(S,N)] interface converts the
4362 **          Nth column in the current row of the result set for the
4363 **          [prepared statement] S into a zero-terminated 2-byte
4364 **          aligned UTF-16 native byte order string and returns
4365 **          a pointer to that string.
4366 **
4367 ** {H13827} The [sqlite3_column_type(S,N)] interface returns
4368 **          one of [SQLITE_NULL], [SQLITE_INTEGER], [SQLITE_FLOAT],
4369 **          [SQLITE_TEXT], or [SQLITE_BLOB] as appropriate for
4370 **          the Nth column in the current row of the result set for
4371 **          the [prepared statement] S.
4372 **
4373 ** {H13830} The [sqlite3_column_value(S,N)] interface returns a
4374 **          pointer to an [unprotected sqlite3_value] object for the
4375 **          Nth column in the current row of the result set for
4376 **          the [prepared statement] S.
4377 */
4378 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
4379 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
4380 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
4381 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
4382 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
4383 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
4384 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
4385 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
4386 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
4387 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
4388
4389 /*
4390 ** CAPI3REF: Destroy A Prepared Statement Object {H13300} <S70300><S30100>
4391 **
4392 ** The sqlite3_finalize() function is called to delete a [prepared statement].
4393 ** If the statement was executed successfully or not executed at all, then
4394 ** SQLITE_OK is returned. If execution of the statement failed then an
4395 ** [error code] or [extended error code] is returned.
4396 **
4397 ** This routine can be called at any point during the execution of the
4398 ** [prepared statement].  If the virtual machine has not
4399 ** completed execution when this routine is called, that is like
4400 ** encountering an error or an [sqlite3_interrupt | interrupt].
4401 ** Incomplete updates may be rolled back and transactions canceled,
4402 ** depending on the circumstances, and the
4403 ** [error code] returned will be [SQLITE_ABORT].
4404 **
4405 ** INVARIANTS:
4406 **
4407 ** {H11302} The [sqlite3_finalize(S)] interface destroys the
4408 **          [prepared statement] S and releases all
4409 **          memory and file resources held by that object.
4410 **
4411 ** {H11304} If the most recent call to [sqlite3_step(S)] for the
4412 **          [prepared statement] S returned an error,
4413 **          then [sqlite3_finalize(S)] returns that same error.
4414 */
4415 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
4416
4417 /*
4418 ** CAPI3REF: Reset A Prepared Statement Object {H13330} <S70300>
4419 **
4420 ** The sqlite3_reset() function is called to reset a [prepared statement]
4421 ** object back to its initial state, ready to be re-executed.
4422 ** Any SQL statement variables that had values bound to them using
4423 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
4424 ** Use [sqlite3_clear_bindings()] to reset the bindings.
4425 **
4426 ** {H11332} The [sqlite3_reset(S)] interface resets the [prepared statement] S
4427 **          back to the beginning of its program.
4428 **
4429 ** {H11334} If the most recent call to [sqlite3_step(S)] for the
4430 **          [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
4431 **          or if [sqlite3_step(S)] has never before been called on S,
4432 **          then [sqlite3_reset(S)] returns [SQLITE_OK].
4433 **
4434 ** {H11336} If the most recent call to [sqlite3_step(S)] for the
4435 **          [prepared statement] S indicated an error, then
4436 **          [sqlite3_reset(S)] returns an appropriate [error code].
4437 **
4438 ** {H11338} The [sqlite3_reset(S)] interface does not change the values
4439 **          of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
4440 */
4441 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
4442
4443 /*
4444 ** CAPI3REF: Create Or Redefine SQL Functions {H16100} <S20200>
4445 ** KEYWORDS: {function creation routines}
4446 ** KEYWORDS: {application-defined SQL function}
4447 ** KEYWORDS: {application-defined SQL functions}
4448 **
4449 ** These two functions (collectively known as "function creation routines")
4450 ** are used to add SQL functions or aggregates or to redefine the behavior
4451 ** of existing SQL functions or aggregates.  The only difference between the
4452 ** two is that the second parameter, the name of the (scalar) function or
4453 ** aggregate, is encoded in UTF-8 for sqlite3_create_function() and UTF-16
4454 ** for sqlite3_create_function16().
4455 **
4456 ** The first parameter is the [database connection] to which the SQL
4457 ** function is to be added.  If a single program uses more than one database
4458 ** connection internally, then SQL functions must be added individually to
4459 ** each database connection.
4460 **
4461 ** The second parameter is the name of the SQL function to be created or
4462 ** redefined.  The length of the name is limited to 255 bytes, exclusive of
4463 ** the zero-terminator.  Note that the name length limit is in bytes, not
4464 ** characters.  Any attempt to create a function with a longer name
4465 ** will result in [SQLITE_ERROR] being returned.
4466 **
4467 ** The third parameter (nArg)
4468 ** is the number of arguments that the SQL function or
4469 ** aggregate takes. If this parameter is negative, then the SQL function or
4470 ** aggregate may take any number of arguments.
4471 **
4472 ** The fourth parameter, eTextRep, specifies what
4473 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4474 ** its parameters.  Any SQL function implementation should be able to work
4475 ** work with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
4476 ** more efficient with one encoding than another.  It is allowed to
4477 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
4478 ** times with the same function but with different values of eTextRep.
4479 ** When multiple implementations of the same function are available, SQLite
4480 ** will pick the one that involves the least amount of data conversion.
4481 ** If there is only a single implementation which does not care what text
4482 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
4483 **
4484 ** The fifth parameter is an arbitrary pointer.  The implementation of the
4485 ** function can gain access to this pointer using [sqlite3_user_data()].
4486 **
4487 ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
4488 ** pointers to C-language functions that implement the SQL function or
4489 ** aggregate. A scalar SQL function requires an implementation of the xFunc
4490 ** callback only, NULL pointers should be passed as the xStep and xFinal
4491 ** parameters. An aggregate SQL function requires an implementation of xStep
4492 ** and xFinal and NULL should be passed for xFunc. To delete an existing
4493 ** SQL function or aggregate, pass NULL for all three function callbacks.
4494 **
4495 ** It is permitted to register multiple implementations of the same
4496 ** functions with the same name but with either differing numbers of
4497 ** arguments or differing preferred text encodings.  SQLite will use
4498 ** the implementation most closely matches the way in which the
4499 ** SQL function is used.  A function implementation with a non-negative
4500 ** nArg parameter is a better match than a function implementation with
4501 ** a negative nArg.  A function where the preferred text encoding
4502 ** matches the database encoding is a better
4503 ** match than a function where the encoding is different.  
4504 ** A function where the encoding difference is between UTF16le and UTF16be
4505 ** is a closer match than a function where the encoding difference is
4506 ** between UTF8 and UTF16.
4507 **
4508 ** Built-in functions may be overloaded by new application-defined functions.
4509 ** The first application-defined function with a given name overrides all
4510 ** built-in functions in the same [database connection] with the same name.
4511 ** Subsequent application-defined functions of the same name only override 
4512 ** prior application-defined functions that are an exact match for the
4513 ** number of parameters and preferred encoding.
4514 **
4515 ** An application-defined function is permitted to call other
4516 ** SQLite interfaces.  However, such calls must not
4517 ** close the database connection nor finalize or reset the prepared
4518 ** statement in which the function is running.
4519 **
4520 ** INVARIANTS:
4521 **
4522 ** {H16103} The [sqlite3_create_function16(D,X,...)] interface shall behave
4523 **          as [sqlite3_create_function(D,X,...)] in every way except that it
4524 **          interprets the X argument as zero-terminated UTF-16
4525 **          native byte order instead of as zero-terminated UTF-8.
4526 **
4527 ** {H16106} A successful invocation of the
4528 **          [sqlite3_create_function(D,X,N,E,...)] interface shall register
4529 **          or replaces callback functions in the [database connection] D
4530 **          used to implement the SQL function named X with N parameters
4531 **          and having a preferred text encoding of E.
4532 **
4533 ** {H16109} A successful call to [sqlite3_create_function(D,X,N,E,P,F,S,L)]
4534 **          shall replace the P, F, S, and L values from any prior calls with
4535 **          the same D, X, N, and E values.
4536 **
4537 ** {H16112} The [sqlite3_create_function(D,X,...)] interface shall fail
4538 **          if the SQL function name X is
4539 **          longer than 255 bytes exclusive of the zero terminator.
4540 **
4541 ** {H16118} The [sqlite3_create_function(D,X,N,E,P,F,S,L)] interface
4542 **          shall fail unless either F is NULL and S and L are non-NULL or
4543 ***         F is non-NULL and S and L are NULL.
4544 **
4545 ** {H16121} The [sqlite3_create_function(D,...)] interface shall fails with an
4546 **          error code of [SQLITE_BUSY] if there exist [prepared statements]
4547 **          associated with the [database connection] D.
4548 **
4549 ** {H16124} The [sqlite3_create_function(D,X,N,...)] interface shall fail with
4550 **          an error code of [SQLITE_ERROR] if parameter N is less
4551 **          than -1 or greater than 127.
4552 **
4553 ** {H16127} When N is non-negative, the [sqlite3_create_function(D,X,N,...)]
4554 **          interface shall register callbacks to be invoked for the
4555 **          SQL function
4556 **          named X when the number of arguments to the SQL function is
4557 **          exactly N.
4558 **
4559 ** {H16130} When N is -1, the [sqlite3_create_function(D,X,N,...)]
4560 **          interface shall register callbacks to be invoked for the SQL
4561 **          function named X with any number of arguments.
4562 **
4563 ** {H16133} When calls to [sqlite3_create_function(D,X,N,...)]
4564 **          specify multiple implementations of the same function X
4565 **          and when one implementation has N>=0 and the other has N=(-1)
4566 **          the implementation with a non-zero N shall be preferred.
4567 **
4568 ** {H16136} When calls to [sqlite3_create_function(D,X,N,E,...)]
4569 **          specify multiple implementations of the same function X with
4570 **          the same number of arguments N but with different
4571 **          encodings E, then the implementation where E matches the
4572 **          database encoding shall preferred.
4573 **
4574 ** {H16139} For an aggregate SQL function created using
4575 **          [sqlite3_create_function(D,X,N,E,P,0,S,L)] the finalizer
4576 **          function L shall always be invoked exactly once if the
4577 **          step function S is called one or more times.
4578 **
4579 ** {H16142} When SQLite invokes either the xFunc or xStep function of
4580 **          an application-defined SQL function or aggregate created
4581 **          by [sqlite3_create_function()] or [sqlite3_create_function16()],
4582 **          then the array of [sqlite3_value] objects passed as the
4583 **          third parameter shall be [protected sqlite3_value] objects.
4584 */
4585 SQLITE_API int sqlite3_create_function(
4586   sqlite3 *db,
4587   const char *zFunctionName,
4588   int nArg,
4589   int eTextRep,
4590   void *pApp,
4591   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4592   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4593   void (*xFinal)(sqlite3_context*)
4594 );
4595 SQLITE_API int sqlite3_create_function16(
4596   sqlite3 *db,
4597   const void *zFunctionName,
4598   int nArg,
4599   int eTextRep,
4600   void *pApp,
4601   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4602   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4603   void (*xFinal)(sqlite3_context*)
4604 );
4605
4606 /*
4607 ** CAPI3REF: Text Encodings {H10267} <S50200> <H16100>
4608 **
4609 ** These constant define integer codes that represent the various
4610 ** text encodings supported by SQLite.
4611 */
4612 #define SQLITE_UTF8           1
4613 #define SQLITE_UTF16LE        2
4614 #define SQLITE_UTF16BE        3
4615 #define SQLITE_UTF16          4    /* Use native byte order */
4616 #define SQLITE_ANY            5    /* sqlite3_create_function only */
4617 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
4618
4619 /*
4620 ** CAPI3REF: Deprecated Functions
4621 ** DEPRECATED
4622 **
4623 ** These functions are [deprecated].  In order to maintain
4624 ** backwards compatibility with older code, these functions continue 
4625 ** to be supported.  However, new applications should avoid
4626 ** the use of these functions.  To help encourage people to avoid
4627 ** using these functions, we are not going to tell you what they do.
4628 */
4629 #ifndef SQLITE_OMIT_DEPRECATED
4630 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
4631 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
4632 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4633 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
4634 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
4635 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
4636 #endif
4637
4638 /*
4639 ** CAPI3REF: Obtaining SQL Function Parameter Values {H15100} <S20200>
4640 **
4641 ** The C-language implementation of SQL functions and aggregates uses
4642 ** this set of interface routines to access the parameter values on
4643 ** the function or aggregate.
4644 **
4645 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4646 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4647 ** define callbacks that implement the SQL functions and aggregates.
4648 ** The 4th parameter to these callbacks is an array of pointers to
4649 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
4650 ** each parameter to the SQL function.  These routines are used to
4651 ** extract values from the [sqlite3_value] objects.
4652 **
4653 ** These routines work only with [protected sqlite3_value] objects.
4654 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4655 ** object results in undefined behavior.
4656 **
4657 ** These routines work just like the corresponding [column access functions]
4658 ** except that  these routines take a single [protected sqlite3_value] object
4659 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4660 **
4661 ** The sqlite3_value_text16() interface extracts a UTF-16 string
4662 ** in the native byte-order of the host machine.  The
4663 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4664 ** extract UTF-16 strings as big-endian and little-endian respectively.
4665 **
4666 ** The sqlite3_value_numeric_type() interface attempts to apply
4667 ** numeric affinity to the value.  This means that an attempt is
4668 ** made to convert the value to an integer or floating point.  If
4669 ** such a conversion is possible without loss of information (in other
4670 ** words, if the value is a string that looks like a number)
4671 ** then the conversion is performed.  Otherwise no conversion occurs.
4672 ** The [SQLITE_INTEGER | datatype] after conversion is returned.
4673 **
4674 ** Please pay particular attention to the fact that the pointer returned
4675 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4676 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4677 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4678 ** or [sqlite3_value_text16()].
4679 **
4680 ** These routines must be called from the same thread as
4681 ** the SQL function that supplied the [sqlite3_value*] parameters.
4682 **
4683 ** INVARIANTS:
4684 **
4685 ** {H15103} The [sqlite3_value_blob(V)] interface converts the
4686 **          [protected sqlite3_value] object V into a BLOB and then
4687 **          returns a pointer to the converted value.
4688 **
4689 ** {H15106} The [sqlite3_value_bytes(V)] interface returns the
4690 **          number of bytes in the BLOB or string (exclusive of the
4691 **          zero terminator on the string) that was returned by the
4692 **          most recent call to [sqlite3_value_blob(V)] or
4693 **          [sqlite3_value_text(V)].
4694 **
4695 ** {H15109} The [sqlite3_value_bytes16(V)] interface returns the
4696 **          number of bytes in the string (exclusive of the
4697 **          zero terminator on the string) that was returned by the
4698 **          most recent call to [sqlite3_value_text16(V)],
4699 **          [sqlite3_value_text16be(V)], or [sqlite3_value_text16le(V)].
4700 **
4701 ** {H15112} The [sqlite3_value_double(V)] interface converts the
4702 **          [protected sqlite3_value] object V into a floating point value and
4703 **          returns a copy of that value.
4704 **
4705 ** {H15115} The [sqlite3_value_int(V)] interface converts the
4706 **          [protected sqlite3_value] object V into a 64-bit signed integer and
4707 **          returns the lower 32 bits of that integer.
4708 **
4709 ** {H15118} The [sqlite3_value_int64(V)] interface converts the
4710 **          [protected sqlite3_value] object V into a 64-bit signed integer and
4711 **          returns a copy of that integer.
4712 **
4713 ** {H15121} The [sqlite3_value_text(V)] interface converts the
4714 **          [protected sqlite3_value] object V into a zero-terminated UTF-8
4715 **          string and returns a pointer to that string.
4716 **
4717 ** {H15124} The [sqlite3_value_text16(V)] interface converts the
4718 **          [protected sqlite3_value] object V into a zero-terminated 2-byte
4719 **          aligned UTF-16 native byte order
4720 **          string and returns a pointer to that string.
4721 **
4722 ** {H15127} The [sqlite3_value_text16be(V)] interface converts the
4723 **          [protected sqlite3_value] object V into a zero-terminated 2-byte
4724 **          aligned UTF-16 big-endian
4725 **          string and returns a pointer to that string.
4726 **
4727 ** {H15130} The [sqlite3_value_text16le(V)] interface converts the
4728 **          [protected sqlite3_value] object V into a zero-terminated 2-byte
4729 **          aligned UTF-16 little-endian
4730 **          string and returns a pointer to that string.
4731 **
4732 ** {H15133} The [sqlite3_value_type(V)] interface returns
4733 **          one of [SQLITE_NULL], [SQLITE_INTEGER], [SQLITE_FLOAT],
4734 **          [SQLITE_TEXT], or [SQLITE_BLOB] as appropriate for
4735 **          the [sqlite3_value] object V.
4736 **
4737 ** {H15136} The [sqlite3_value_numeric_type(V)] interface converts
4738 **          the [protected sqlite3_value] object V into either an integer or
4739 **          a floating point value if it can do so without loss of
4740 **          information, and returns one of [SQLITE_NULL],
4741 **          [SQLITE_INTEGER], [SQLITE_FLOAT], [SQLITE_TEXT], or
4742 **          [SQLITE_BLOB] as appropriate for the
4743 **          [protected sqlite3_value] object V after the conversion attempt.
4744 */
4745 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4746 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4747 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4748 SQLITE_API double sqlite3_value_double(sqlite3_value*);
4749 SQLITE_API int sqlite3_value_int(sqlite3_value*);
4750 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4751 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4752 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4753 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4754 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4755 SQLITE_API int sqlite3_value_type(sqlite3_value*);
4756 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4757
4758 /*
4759 ** CAPI3REF: Obtain Aggregate Function Context {H16210} <S20200>
4760 **
4761 ** The implementation of aggregate SQL functions use this routine to allocate
4762 ** a structure for storing their state.
4763 **
4764 ** The first time the sqlite3_aggregate_context() routine is called for a
4765 ** particular aggregate, SQLite allocates nBytes of memory, zeroes out that
4766 ** memory, and returns a pointer to it. On second and subsequent calls to
4767 ** sqlite3_aggregate_context() for the same aggregate function index,
4768 ** the same buffer is returned. The implementation of the aggregate can use
4769 ** the returned buffer to accumulate data.
4770 **
4771 ** SQLite automatically frees the allocated buffer when the aggregate
4772 ** query concludes.
4773 **
4774 ** The first parameter should be a copy of the
4775 ** [sqlite3_context | SQL function context] that is the first parameter
4776 ** to the callback routine that implements the aggregate function.
4777 **
4778 ** This routine must be called from the same thread in which
4779 ** the aggregate SQL function is running.
4780 **
4781 ** INVARIANTS:
4782 **
4783 ** {H16211} The first invocation of [sqlite3_aggregate_context(C,N)] for
4784 **          a particular instance of an aggregate function (for a particular
4785 **          context C) causes SQLite to allocate N bytes of memory,
4786 **          zero that memory, and return a pointer to the allocated memory.
4787 **
4788 ** {H16213} If a memory allocation error occurs during
4789 **          [sqlite3_aggregate_context(C,N)] then the function returns 0.
4790 **
4791 ** {H16215} Second and subsequent invocations of
4792 **          [sqlite3_aggregate_context(C,N)] for the same context pointer C
4793 **          ignore the N parameter and return a pointer to the same
4794 **          block of memory returned by the first invocation.
4795 **
4796 ** {H16217} The memory allocated by [sqlite3_aggregate_context(C,N)] is
4797 **          automatically freed on the next call to [sqlite3_reset()]
4798 **          or [sqlite3_finalize()] for the [prepared statement] containing
4799 **          the aggregate function associated with context C.
4800 */
4801 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4802
4803 /*
4804 ** CAPI3REF: User Data For Functions {H16240} <S20200>
4805 **
4806 ** The sqlite3_user_data() interface returns a copy of
4807 ** the pointer that was the pUserData parameter (the 5th parameter)
4808 ** of the [sqlite3_create_function()]
4809 ** and [sqlite3_create_function16()] routines that originally
4810 ** registered the application defined function. {END}
4811 **
4812 ** This routine must be called from the same thread in which
4813 ** the application-defined function is running.
4814 **
4815 ** INVARIANTS:
4816 **
4817 ** {H16243} The [sqlite3_user_data(C)] interface returns a copy of the
4818 **          P pointer from the [sqlite3_create_function(D,X,N,E,P,F,S,L)]
4819 **          or [sqlite3_create_function16(D,X,N,E,P,F,S,L)] call that
4820 **          registered the SQL function associated with [sqlite3_context] C.
4821 */
4822 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4823
4824 /*
4825 ** CAPI3REF: Database Connection For Functions {H16250} <S60600><S20200>
4826 **
4827 ** The sqlite3_context_db_handle() interface returns a copy of
4828 ** the pointer to the [database connection] (the 1st parameter)
4829 ** of the [sqlite3_create_function()]
4830 ** and [sqlite3_create_function16()] routines that originally
4831 ** registered the application defined function.
4832 **
4833 ** INVARIANTS:
4834 **
4835 ** {H16253} The [sqlite3_context_db_handle(C)] interface returns a copy of the
4836 **          D pointer from the [sqlite3_create_function(D,X,N,E,P,F,S,L)]
4837 **          or [sqlite3_create_function16(D,X,N,E,P,F,S,L)] call that
4838 **          registered the SQL function associated with [sqlite3_context] C.
4839 */
4840 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4841
4842 /*
4843 ** CAPI3REF: Function Auxiliary Data {H16270} <S20200>
4844 **
4845 ** The following two functions may be used by scalar SQL functions to
4846 ** associate metadata with argument values. If the same value is passed to
4847 ** multiple invocations of the same SQL function during query execution, under
4848 ** some circumstances the associated metadata may be preserved. This may
4849 ** be used, for example, to add a regular-expression matching scalar
4850 ** function. The compiled version of the regular expression is stored as
4851 ** metadata associated with the SQL value passed as the regular expression
4852 ** pattern.  The compiled regular expression can be reused on multiple
4853 ** invocations of the same function so that the original pattern string
4854 ** does not need to be recompiled on each invocation.
4855 **
4856 ** The sqlite3_get_auxdata() interface returns a pointer to the metadata
4857 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4858 ** value to the application-defined function. If no metadata has been ever
4859 ** been set for the Nth argument of the function, or if the corresponding
4860 ** function parameter has changed since the meta-data was set,
4861 ** then sqlite3_get_auxdata() returns a NULL pointer.
4862 **
4863 ** The sqlite3_set_auxdata() interface saves the metadata
4864 ** pointed to by its 3rd parameter as the metadata for the N-th
4865 ** argument of the application-defined function.  Subsequent
4866 ** calls to sqlite3_get_auxdata() might return this data, if it has
4867 ** not been destroyed.
4868 ** If it is not NULL, SQLite will invoke the destructor
4869 ** function given by the 4th parameter to sqlite3_set_auxdata() on
4870 ** the metadata when the corresponding function parameter changes
4871 ** or when the SQL statement completes, whichever comes first.
4872 **
4873 ** SQLite is free to call the destructor and drop metadata on any
4874 ** parameter of any function at any time.  The only guarantee is that
4875 ** the destructor will be called before the metadata is dropped.
4876 **
4877 ** In practice, metadata is preserved between function calls for
4878 ** expressions that are constant at compile time. This includes literal
4879 ** values and SQL variables.
4880 **
4881 ** These routines must be called from the same thread in which
4882 ** the SQL function is running.
4883 **
4884 ** INVARIANTS:
4885 **
4886 ** {H16272} The [sqlite3_get_auxdata(C,N)] interface returns a pointer
4887 **          to metadata associated with the Nth parameter of the SQL function
4888 **          whose context is C, or NULL if there is no metadata associated
4889 **          with that parameter.
4890 **
4891 ** {H16274} The [sqlite3_set_auxdata(C,N,P,D)] interface assigns a metadata
4892 **          pointer P to the Nth parameter of the SQL function with context C.
4893 **
4894 ** {H16276} SQLite will invoke the destructor D with a single argument
4895 **          which is the metadata pointer P following a call to
4896 **          [sqlite3_set_auxdata(C,N,P,D)] when SQLite ceases to hold
4897 **          the metadata.
4898 **
4899 ** {H16277} SQLite ceases to hold metadata for an SQL function parameter
4900 **          when the value of that parameter changes.
4901 **
4902 ** {H16278} When [sqlite3_set_auxdata(C,N,P,D)] is invoked, the destructor
4903 **          is called for any prior metadata associated with the same function
4904 **          context C and parameter N.
4905 **
4906 ** {H16279} SQLite will call destructors for any metadata it is holding
4907 **          in a particular [prepared statement] S when either
4908 **          [sqlite3_reset(S)] or [sqlite3_finalize(S)] is called.
4909 */
4910 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4911 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4912
4913
4914 /*
4915 ** CAPI3REF: Constants Defining Special Destructor Behavior {H10280} <S30100>
4916 **
4917 ** These are special values for the destructor that is passed in as the
4918 ** final argument to routines like [sqlite3_result_blob()].  If the destructor
4919 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4920 ** and will never change.  It does not need to be destroyed.  The
4921 ** SQLITE_TRANSIENT value means that the content will likely change in
4922 ** the near future and that SQLite should make its own private copy of
4923 ** the content before returning.
4924 **
4925 ** The typedef is necessary to work around problems in certain
4926 ** C++ compilers.  See ticket #2191.
4927 */
4928 typedef void (*sqlite3_destructor_type)(void*);
4929 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4930 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4931
4932 /*
4933 ** CAPI3REF: Setting The Result Of An SQL Function {H16400} <S20200>
4934 **
4935 ** These routines are used by the xFunc or xFinal callbacks that
4936 ** implement SQL functions and aggregates.  See
4937 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4938 ** for additional information.
4939 **
4940 ** These functions work very much like the [parameter binding] family of
4941 ** functions used to bind values to host parameters in prepared statements.
4942 ** Refer to the [SQL parameter] documentation for additional information.
4943 **
4944 ** The sqlite3_result_blob() interface sets the result from
4945 ** an application-defined function to be the BLOB whose content is pointed
4946 ** to by the second parameter and which is N bytes long where N is the
4947 ** third parameter.
4948 **
4949 ** The sqlite3_result_zeroblob() interfaces set the result of
4950 ** the application-defined function to be a BLOB containing all zero
4951 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4952 **
4953 ** The sqlite3_result_double() interface sets the result from
4954 ** an application-defined function to be a floating point value specified
4955 ** by its 2nd argument.
4956 **
4957 ** The sqlite3_result_error() and sqlite3_result_error16() functions
4958 ** cause the implemented SQL function to throw an exception.
4959 ** SQLite uses the string pointed to by the
4960 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4961 ** as the text of an error message.  SQLite interprets the error
4962 ** message string from sqlite3_result_error() as UTF-8. SQLite
4963 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
4964 ** byte order.  If the third parameter to sqlite3_result_error()
4965 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4966 ** message all text up through the first zero character.
4967 ** If the third parameter to sqlite3_result_error() or
4968 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4969 ** bytes (not characters) from the 2nd parameter as the error message.
4970 ** The sqlite3_result_error() and sqlite3_result_error16()
4971 ** routines make a private copy of the error message text before
4972 ** they return.  Hence, the calling function can deallocate or
4973 ** modify the text after they return without harm.
4974 ** The sqlite3_result_error_code() function changes the error code
4975 ** returned by SQLite as a result of an error in a function.  By default,
4976 ** the error code is SQLITE_ERROR.  A subsequent call to sqlite3_result_error()
4977 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4978 **
4979 ** The sqlite3_result_toobig() interface causes SQLite to throw an error
4980 ** indicating that a string or BLOB is to long to represent.
4981 **
4982 ** The sqlite3_result_nomem() interface causes SQLite to throw an error
4983 ** indicating that a memory allocation failed.
4984 **
4985 ** The sqlite3_result_int() interface sets the return value
4986 ** of the application-defined function to be the 32-bit signed integer
4987 ** value given in the 2nd argument.
4988 ** The sqlite3_result_int64() interface sets the return value
4989 ** of the application-defined function to be the 64-bit signed integer
4990 ** value given in the 2nd argument.
4991 **
4992 ** The sqlite3_result_null() interface sets the return value
4993 ** of the application-defined function to be NULL.
4994 **
4995 ** The sqlite3_result_text(), sqlite3_result_text16(),
4996 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4997 ** set the return value of the application-defined function to be
4998 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4999 ** UTF-16 little endian, or UTF-16 big endian, respectively.
5000 ** SQLite takes the text result from the application from
5001 ** the 2nd parameter of the sqlite3_result_text* interfaces.
5002 ** If the 3rd parameter to the sqlite3_result_text* interfaces
5003 ** is negative, then SQLite takes result text from the 2nd parameter
5004 ** through the first zero character.
5005 ** If the 3rd parameter to the sqlite3_result_text* interfaces
5006 ** is non-negative, then as many bytes (not characters) of the text
5007 ** pointed to by the 2nd parameter are taken as the application-defined
5008 ** function result.
5009 ** If the 4th parameter to the sqlite3_result_text* interfaces
5010 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
5011 ** function as the destructor on the text or BLOB result when it has
5012 ** finished using that result.
5013 ** If the 4th parameter to the sqlite3_result_text* interfaces or
5014 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
5015 ** assumes that the text or BLOB result is in constant space and does not
5016 ** copy the it or call a destructor when it has finished using that result.
5017 ** If the 4th parameter to the sqlite3_result_text* interfaces
5018 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
5019 ** then SQLite makes a copy of the result into space obtained from
5020 ** from [sqlite3_malloc()] before it returns.
5021 **
5022 ** The sqlite3_result_value() interface sets the result of
5023 ** the application-defined function to be a copy the
5024 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  The
5025 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
5026 ** so that the [sqlite3_value] specified in the parameter may change or
5027 ** be deallocated after sqlite3_result_value() returns without harm.
5028 ** A [protected sqlite3_value] object may always be used where an
5029 ** [unprotected sqlite3_value] object is required, so either
5030 ** kind of [sqlite3_value] object can be used with this interface.
5031 **
5032 ** If these routines are called from within the different thread
5033 ** than the one containing the application-defined function that received
5034 ** the [sqlite3_context] pointer, the results are undefined.
5035 **
5036 ** INVARIANTS:
5037 **
5038 ** {H16403} The default return value from any SQL function is NULL.
5039 **
5040 ** {H16406} The [sqlite3_result_blob(C,V,N,D)] interface changes the
5041 **          return value of function C to be a BLOB that is N bytes
5042 **          in length and with content pointed to by V.
5043 **
5044 ** {H16409} The [sqlite3_result_double(C,V)] interface changes the
5045 **          return value of function C to be the floating point value V.
5046 **
5047 ** {H16412} The [sqlite3_result_error(C,V,N)] interface changes the return
5048 **          value of function C to be an exception with error code
5049 **          [SQLITE_ERROR] and a UTF-8 error message copied from V up to the
5050 **          first zero byte or until N bytes are read if N is positive.
5051 **
5052 ** {H16415} The [sqlite3_result_error16(C,V,N)] interface changes the return
5053 **          value of function C to be an exception with error code
5054 **          [SQLITE_ERROR] and a UTF-16 native byte order error message
5055 **          copied from V up to the first zero terminator or until N bytes
5056 **          are read if N is positive.
5057 **
5058 ** {H16418} The [sqlite3_result_error_toobig(C)] interface changes the return
5059 **          value of the function C to be an exception with error code
5060 **          [SQLITE_TOOBIG] and an appropriate error message.
5061 **
5062 ** {H16421} The [sqlite3_result_error_nomem(C)] interface changes the return
5063 **          value of the function C to be an exception with error code
5064 **          [SQLITE_NOMEM] and an appropriate error message.
5065 **
5066 ** {H16424} The [sqlite3_result_error_code(C,E)] interface changes the return
5067 **          value of the function C to be an exception with error code E.
5068 **          The error message text is unchanged.
5069 **
5070 ** {H16427} The [sqlite3_result_int(C,V)] interface changes the
5071 **          return value of function C to be the 32-bit integer value V.
5072 **
5073 ** {H16430} The [sqlite3_result_int64(C,V)] interface changes the
5074 **          return value of function C to be the 64-bit integer value V.
5075 **
5076 ** {H16433} The [sqlite3_result_null(C)] interface changes the
5077 **          return value of function C to be NULL.
5078 **
5079 ** {H16436} The [sqlite3_result_text(C,V,N,D)] interface changes the
5080 **          return value of function C to be the UTF-8 string
5081 **          V up to the first zero if N is negative
5082 **          or the first N bytes of V if N is non-negative.
5083 **
5084 ** {H16439} The [sqlite3_result_text16(C,V,N,D)] interface changes the
5085 **          return value of function C to be the UTF-16 native byte order
5086 **          string V up to the first zero if N is negative
5087 **          or the first N bytes of V if N is non-negative.
5088 **
5089 ** {H16442} The [sqlite3_result_text16be(C,V,N,D)] interface changes the
5090 **          return value of function C to be the UTF-16 big-endian
5091 **          string V up to the first zero if N is negative
5092 **          or the first N bytes or V if N is non-negative.
5093 **
5094 ** {H16445} The [sqlite3_result_text16le(C,V,N,D)] interface changes the
5095 **          return value of function C to be the UTF-16 little-endian
5096 **          string V up to the first zero if N is negative
5097 **          or the first N bytes of V if N is non-negative.
5098 **
5099 ** {H16448} The [sqlite3_result_value(C,V)] interface changes the
5100 **          return value of function C to be the [unprotected sqlite3_value]
5101 **          object V.
5102 **
5103 ** {H16451} The [sqlite3_result_zeroblob(C,N)] interface changes the
5104 **          return value of function C to be an N-byte BLOB of all zeros.
5105 **
5106 ** {H16454} The [sqlite3_result_error()] and [sqlite3_result_error16()]
5107 **          interfaces make a copy of their error message strings before
5108 **          returning.
5109 **
5110 ** {H16457} If the D destructor parameter to [sqlite3_result_blob(C,V,N,D)],
5111 **          [sqlite3_result_text(C,V,N,D)], [sqlite3_result_text16(C,V,N,D)],
5112 **          [sqlite3_result_text16be(C,V,N,D)], or
5113 **          [sqlite3_result_text16le(C,V,N,D)] is the constant [SQLITE_STATIC]
5114 **          then no destructor is ever called on the pointer V and SQLite
5115 **          assumes that V is immutable.
5116 **
5117 ** {H16460} If the D destructor parameter to [sqlite3_result_blob(C,V,N,D)],
5118 **          [sqlite3_result_text(C,V,N,D)], [sqlite3_result_text16(C,V,N,D)],
5119 **          [sqlite3_result_text16be(C,V,N,D)], or
5120 **          [sqlite3_result_text16le(C,V,N,D)] is the constant
5121 **          [SQLITE_TRANSIENT] then the interfaces makes a copy of the
5122 **          content of V and retains the copy.
5123 **
5124 ** {H16463} If the D destructor parameter to [sqlite3_result_blob(C,V,N,D)],
5125 **          [sqlite3_result_text(C,V,N,D)], [sqlite3_result_text16(C,V,N,D)],
5126 **          [sqlite3_result_text16be(C,V,N,D)], or
5127 **          [sqlite3_result_text16le(C,V,N,D)] is some value other than
5128 **          the constants [SQLITE_STATIC] and [SQLITE_TRANSIENT] then
5129 **          SQLite will invoke the destructor D with V as its only argument
5130 **          when it has finished with the V value.
5131 */
5132 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
5133 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
5134 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
5135 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
5136 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
5137 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
5138 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
5139 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
5140 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
5141 SQLITE_API void sqlite3_result_null(sqlite3_context*);
5142 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
5143 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
5144 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
5145 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
5146 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
5147 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
5148
5149 /*
5150 ** CAPI3REF: Define New Collating Sequences {H16600} <S20300>
5151 **
5152 ** These functions are used to add new collation sequences to the
5153 ** [database connection] specified as the first argument.
5154 **
5155 ** The name of the new collation sequence is specified as a UTF-8 string
5156 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
5157 ** and a UTF-16 string for sqlite3_create_collation16(). In all cases
5158 ** the name is passed as the second function argument.
5159 **
5160 ** The third argument may be one of the constants [SQLITE_UTF8],
5161 ** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied
5162 ** routine expects to be passed pointers to strings encoded using UTF-8,
5163 ** UTF-16 little-endian, or UTF-16 big-endian, respectively. The
5164 ** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that
5165 ** the routine expects pointers to 16-bit word aligned strings
5166 ** of UTF-16 in the native byte order of the host computer.
5167 **
5168 ** A pointer to the user supplied routine must be passed as the fifth
5169 ** argument.  If it is NULL, this is the same as deleting the collation
5170 ** sequence (so that SQLite cannot call it anymore).
5171 ** Each time the application supplied function is invoked, it is passed
5172 ** as its first parameter a copy of the void* passed as the fourth argument
5173 ** to sqlite3_create_collation() or sqlite3_create_collation16().
5174 **
5175 ** The remaining arguments to the application-supplied routine are two strings,
5176 ** each represented by a (length, data) pair and encoded in the encoding
5177 ** that was passed as the third argument when the collation sequence was
5178 ** registered. {END}  The application defined collation routine should
5179 ** return negative, zero or positive if the first string is less than,
5180 ** equal to, or greater than the second string. i.e. (STRING1 - STRING2).
5181 **
5182 ** The sqlite3_create_collation_v2() works like sqlite3_create_collation()
5183 ** except that it takes an extra argument which is a destructor for
5184 ** the collation.  The destructor is called when the collation is
5185 ** destroyed and is passed a copy of the fourth parameter void* pointer
5186 ** of the sqlite3_create_collation_v2().
5187 ** Collations are destroyed when they are overridden by later calls to the
5188 ** collation creation functions or when the [database connection] is closed
5189 ** using [sqlite3_close()].
5190 **
5191 ** INVARIANTS:
5192 **
5193 ** {H16603} A successful call to the
5194 **          [sqlite3_create_collation_v2(B,X,E,P,F,D)] interface
5195 **          registers function F as the comparison function used to
5196 **          implement collation X on the [database connection] B for
5197 **          databases having encoding E.
5198 **
5199 ** {H16604} SQLite understands the X parameter to
5200 **          [sqlite3_create_collation_v2(B,X,E,P,F,D)] as a zero-terminated
5201 **          UTF-8 string in which case is ignored for ASCII characters and
5202 **          is significant for non-ASCII characters.
5203 **
5204 ** {H16606} Successive calls to [sqlite3_create_collation_v2(B,X,E,P,F,D)]
5205 **          with the same values for B, X, and E, override prior values
5206 **          of P, F, and D.
5207 **
5208 ** {H16609} If the destructor D in [sqlite3_create_collation_v2(B,X,E,P,F,D)]
5209 **          is not NULL then it is called with argument P when the
5210 **          collating function is dropped by SQLite.
5211 **
5212 ** {H16612} A collating function is dropped when it is overloaded.
5213 **
5214 ** {H16615} A collating function is dropped when the database connection
5215 **          is closed using [sqlite3_close()].
5216 **
5217 ** {H16618} The pointer P in [sqlite3_create_collation_v2(B,X,E,P,F,D)]
5218 **          is passed through as the first parameter to the comparison
5219 **          function F for all subsequent invocations of F.
5220 **
5221 ** {H16621} A call to [sqlite3_create_collation(B,X,E,P,F)] is exactly
5222 **          the same as a call to [sqlite3_create_collation_v2()] with
5223 **          the same parameters and a NULL destructor.
5224 **
5225 ** {H16624} Following a [sqlite3_create_collation_v2(B,X,E,P,F,D)],
5226 **          SQLite uses the comparison function F for all text comparison
5227 **          operations on the [database connection] B on text values that
5228 **          use the collating sequence named X.
5229 **
5230 ** {H16627} The [sqlite3_create_collation16(B,X,E,P,F)] works the same
5231 **          as [sqlite3_create_collation(B,X,E,P,F)] except that the
5232 **          collation name X is understood as UTF-16 in native byte order
5233 **          instead of UTF-8.
5234 **
5235 ** {H16630} When multiple comparison functions are available for the same
5236 **          collating sequence, SQLite chooses the one whose text encoding
5237 **          requires the least amount of conversion from the default
5238 **          text encoding of the database.
5239 */
5240 SQLITE_API int sqlite3_create_collation(
5241   sqlite3*, 
5242   const char *zName, 
5243   int eTextRep, 
5244   void*,
5245   int(*xCompare)(void*,int,const void*,int,const void*)
5246 );
5247 SQLITE_API int sqlite3_create_collation_v2(
5248   sqlite3*, 
5249   const char *zName, 
5250   int eTextRep, 
5251   void*,
5252   int(*xCompare)(void*,int,const void*,int,const void*),
5253   void(*xDestroy)(void*)
5254 );
5255 SQLITE_API int sqlite3_create_collation16(
5256   sqlite3*, 
5257   const void *zName,
5258   int eTextRep, 
5259   void*,
5260   int(*xCompare)(void*,int,const void*,int,const void*)
5261 );
5262
5263 /*
5264 ** CAPI3REF: Collation Needed Callbacks {H16700} <S20300>
5265 **
5266 ** To avoid having to register all collation sequences before a database
5267 ** can be used, a single callback function may be registered with the
5268 ** [database connection] to be called whenever an undefined collation
5269 ** sequence is required.
5270 **
5271 ** If the function is registered using the sqlite3_collation_needed() API,
5272 ** then it is passed the names of undefined collation sequences as strings
5273 ** encoded in UTF-8. {H16703} If sqlite3_collation_needed16() is used,
5274 ** the names are passed as UTF-16 in machine native byte order.
5275 ** A call to either function replaces any existing callback.
5276 **
5277 ** When the callback is invoked, the first argument passed is a copy
5278 ** of the second argument to sqlite3_collation_needed() or
5279 ** sqlite3_collation_needed16().  The second argument is the database
5280 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
5281 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
5282 ** sequence function required.  The fourth parameter is the name of the
5283 ** required collation sequence.
5284 **
5285 ** The callback function should register the desired collation using
5286 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
5287 ** [sqlite3_create_collation_v2()].
5288 **
5289 ** INVARIANTS:
5290 **
5291 ** {H16702} A successful call to [sqlite3_collation_needed(D,P,F)]
5292 **          or [sqlite3_collation_needed16(D,P,F)] causes
5293 **          the [database connection] D to invoke callback F with first
5294 **          parameter P whenever it needs a comparison function for a
5295 **          collating sequence that it does not know about.
5296 **
5297 ** {H16704} Each successful call to [sqlite3_collation_needed()] or
5298 **          [sqlite3_collation_needed16()] overrides the callback registered
5299 **          on the same [database connection] by prior calls to either
5300 **          interface.
5301 **
5302 ** {H16706} The name of the requested collating function passed in the
5303 **          4th parameter to the callback is in UTF-8 if the callback
5304 **          was registered using [sqlite3_collation_needed()] and
5305 **          is in UTF-16 native byte order if the callback was
5306 **          registered using [sqlite3_collation_needed16()].
5307 */
5308 SQLITE_API int sqlite3_collation_needed(
5309   sqlite3*, 
5310   void*, 
5311   void(*)(void*,sqlite3*,int eTextRep,const char*)
5312 );
5313 SQLITE_API int sqlite3_collation_needed16(
5314   sqlite3*, 
5315   void*,
5316   void(*)(void*,sqlite3*,int eTextRep,const void*)
5317 );
5318
5319 /*
5320 ** Specify the key for an encrypted database.  This routine should be
5321 ** called right after sqlite3_open().
5322 **
5323 ** The code to implement this API is not available in the public release
5324 ** of SQLite.
5325 */
5326 SQLITE_API int sqlite3_key(
5327   sqlite3 *db,                   /* Database to be rekeyed */
5328   const void *pKey, int nKey     /* The key */
5329 );
5330
5331 /*
5332 ** Change the key on an open database.  If the current database is not
5333 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
5334 ** database is decrypted.
5335 **
5336 ** The code to implement this API is not available in the public release
5337 ** of SQLite.
5338 */
5339 SQLITE_API int sqlite3_rekey(
5340   sqlite3 *db,                   /* Database to be rekeyed */
5341   const void *pKey, int nKey     /* The new key */
5342 );
5343
5344 /*
5345 ** CAPI3REF: Suspend Execution For A Short Time {H10530} <S40410>
5346 **
5347 ** The sqlite3_sleep() function causes the current thread to suspend execution
5348 ** for at least a number of milliseconds specified in its parameter.
5349 **
5350 ** If the operating system does not support sleep requests with
5351 ** millisecond time resolution, then the time will be rounded up to
5352 ** the nearest second. The number of milliseconds of sleep actually
5353 ** requested from the operating system is returned.
5354 **
5355 ** SQLite implements this interface by calling the xSleep()
5356 ** method of the default [sqlite3_vfs] object.
5357 **
5358 ** INVARIANTS:
5359 **
5360 ** {H10533} The [sqlite3_sleep(M)] interface invokes the xSleep
5361 **          method of the default [sqlite3_vfs|VFS] in order to
5362 **          suspend execution of the current thread for at least
5363 **          M milliseconds.
5364 **
5365 ** {H10536} The [sqlite3_sleep(M)] interface returns the number of
5366 **          milliseconds of sleep actually requested of the operating
5367 **          system, which might be larger than the parameter M.
5368 */
5369 SQLITE_API int sqlite3_sleep(int);
5370
5371 /*
5372 ** CAPI3REF: Name Of The Folder Holding Temporary Files {H10310} <S20000>
5373 **
5374 ** If this global variable is made to point to a string which is
5375 ** the name of a folder (a.k.a. directory), then all temporary files
5376 ** created by SQLite will be placed in that directory.  If this variable
5377 ** is a NULL pointer, then SQLite performs a search for an appropriate
5378 ** temporary file directory.
5379 **
5380 ** It is not safe to modify this variable once a [database connection]
5381 ** has been opened.  It is intended that this variable be set once
5382 ** as part of process initialization and before any SQLite interface
5383 ** routines have been call and remain unchanged thereafter.
5384 */
5385 SQLITE_API char *sqlite3_temp_directory;
5386
5387 /*
5388 ** CAPI3REF: Test For Auto-Commit Mode {H12930} <S60200>
5389 ** KEYWORDS: {autocommit mode}
5390 **
5391 ** The sqlite3_get_autocommit() interface returns non-zero or
5392 ** zero if the given database connection is or is not in autocommit mode,
5393 ** respectively.  Autocommit mode is on by default.
5394 ** Autocommit mode is disabled by a [BEGIN] statement.
5395 ** Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
5396 **
5397 ** If certain kinds of errors occur on a statement within a multi-statement
5398 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
5399 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
5400 ** transaction might be rolled back automatically.  The only way to
5401 ** find out whether SQLite automatically rolled back the transaction after
5402 ** an error is to use this function.
5403 **
5404 ** INVARIANTS:
5405 **
5406 ** {H12931} The [sqlite3_get_autocommit(D)] interface returns non-zero or
5407 **          zero if the [database connection] D is or is not in autocommit
5408 **          mode, respectively.
5409 **
5410 ** {H12932} Autocommit mode is on by default.
5411 **
5412 ** {H12933} Autocommit mode is disabled by a successful [BEGIN] statement.
5413 **
5414 ** {H12934} Autocommit mode is enabled by a successful [COMMIT] or [ROLLBACK]
5415 **          statement.
5416 **
5417 ** ASSUMPTIONS:
5418 **
5419 ** {A12936} If another thread changes the autocommit status of the database
5420 **          connection while this routine is running, then the return value
5421 **          is undefined.
5422 */
5423 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
5424
5425 /*
5426 ** CAPI3REF: Find The Database Handle Of A Prepared Statement {H13120} <S60600>
5427 **
5428 ** The sqlite3_db_handle interface returns the [database connection] handle
5429 ** to which a [prepared statement] belongs.  The database handle returned by
5430 ** sqlite3_db_handle is the same database handle that was the first argument
5431 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
5432 ** create the statement in the first place.
5433 **
5434 ** INVARIANTS:
5435 **
5436 ** {H13123} The [sqlite3_db_handle(S)] interface returns a pointer
5437 **          to the [database connection] associated with the
5438 **          [prepared statement] S.
5439 */
5440 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
5441
5442 /*
5443 ** CAPI3REF: Find the next prepared statement {H13140} <S60600>
5444 **
5445 ** This interface returns a pointer to the next [prepared statement] after
5446 ** pStmt associated with the [database connection] pDb.  If pStmt is NULL
5447 ** then this interface returns a pointer to the first prepared statement
5448 ** associated with the database connection pDb.  If no prepared statement
5449 ** satisfies the conditions of this routine, it returns NULL.
5450 **
5451 ** INVARIANTS:
5452 **
5453 ** {H13143} If D is a [database connection] that holds one or more
5454 **          unfinalized [prepared statements] and S is a NULL pointer,
5455 **          then [sqlite3_next_stmt(D, S)] routine shall return a pointer
5456 **          to one of the prepared statements associated with D.
5457 **
5458 ** {H13146} If D is a [database connection] that holds no unfinalized
5459 **          [prepared statements] and S is a NULL pointer, then
5460 **          [sqlite3_next_stmt(D, S)] routine shall return a NULL pointer.
5461 **
5462 ** {H13149} If S is a [prepared statement] in the [database connection] D
5463 **          and S is not the last prepared statement in D, then
5464 **          [sqlite3_next_stmt(D, S)] routine shall return a pointer
5465 **          to the next prepared statement in D after S.
5466 **
5467 ** {H13152} If S is the last [prepared statement] in the
5468 **          [database connection] D then the [sqlite3_next_stmt(D, S)]
5469 **          routine shall return a NULL pointer.
5470 **
5471 ** ASSUMPTIONS:
5472 **
5473 ** {A13154} The [database connection] pointer D in a call to
5474 **          [sqlite3_next_stmt(D,S)] must refer to an open database
5475 **          connection and in particular must not be a NULL pointer.
5476 */
5477 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
5478
5479 /*
5480 ** CAPI3REF: Commit And Rollback Notification Callbacks {H12950} <S60400>
5481 **
5482 ** The sqlite3_commit_hook() interface registers a callback
5483 ** function to be invoked whenever a transaction is committed.
5484 ** Any callback set by a previous call to sqlite3_commit_hook()
5485 ** for the same database connection is overridden.
5486 ** The sqlite3_rollback_hook() interface registers a callback
5487 ** function to be invoked whenever a transaction is committed.
5488 ** Any callback set by a previous call to sqlite3_commit_hook()
5489 ** for the same database connection is overridden.
5490 ** The pArg argument is passed through to the callback.
5491 ** If the callback on a commit hook function returns non-zero,
5492 ** then the commit is converted into a rollback.
5493 **
5494 ** If another function was previously registered, its
5495 ** pArg value is returned.  Otherwise NULL is returned.
5496 **
5497 ** The callback implementation must not do anything that will modify
5498 ** the database connection that invoked the callback.  Any actions
5499 ** to modify the database connection must be deferred until after the
5500 ** completion of the [sqlite3_step()] call that triggered the commit
5501 ** or rollback hook in the first place.
5502 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5503 ** database connections for the meaning of "modify" in this paragraph.
5504 **
5505 ** Registering a NULL function disables the callback.
5506 **
5507 ** For the purposes of this API, a transaction is said to have been
5508 ** rolled back if an explicit "ROLLBACK" statement is executed, or
5509 ** an error or constraint causes an implicit rollback to occur.
5510 ** The rollback callback is not invoked if a transaction is
5511 ** automatically rolled back because the database connection is closed.
5512 ** The rollback callback is not invoked if a transaction is
5513 ** rolled back because a commit callback returned non-zero.
5514 ** <todo> Check on this </todo>
5515 **
5516 ** INVARIANTS:
5517 **
5518 ** {H12951} The [sqlite3_commit_hook(D,F,P)] interface registers the
5519 **          callback function F to be invoked with argument P whenever
5520 **          a transaction commits on the [database connection] D.
5521 **
5522 ** {H12952} The [sqlite3_commit_hook(D,F,P)] interface returns the P argument
5523 **          from the previous call with the same [database connection] D,
5524 **          or NULL on the first call for a particular database connection D.
5525 **
5526 ** {H12953} Each call to [sqlite3_commit_hook()] overwrites the callback
5527 **          registered by prior calls.
5528 **
5529 ** {H12954} If the F argument to [sqlite3_commit_hook(D,F,P)] is NULL
5530 **          then the commit hook callback is canceled and no callback
5531 **          is invoked when a transaction commits.
5532 **
5533 ** {H12955} If the commit callback returns non-zero then the commit is
5534 **          converted into a rollback.
5535 **
5536 ** {H12961} The [sqlite3_rollback_hook(D,F,P)] interface registers the
5537 **          callback function F to be invoked with argument P whenever
5538 **          a transaction rolls back on the [database connection] D.
5539 **
5540 ** {H12962} The [sqlite3_rollback_hook(D,F,P)] interface returns the P
5541 **          argument from the previous call with the same
5542 **          [database connection] D, or NULL on the first call
5543 **          for a particular database connection D.
5544 **
5545 ** {H12963} Each call to [sqlite3_rollback_hook()] overwrites the callback
5546 **          registered by prior calls.
5547 **
5548 ** {H12964} If the F argument to [sqlite3_rollback_hook(D,F,P)] is NULL
5549 **          then the rollback hook callback is canceled and no callback
5550 **          is invoked when a transaction rolls back.
5551 */
5552 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
5553 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
5554
5555 /*
5556 ** CAPI3REF: Data Change Notification Callbacks {H12970} <S60400>
5557 **
5558 ** The sqlite3_update_hook() interface registers a callback function
5559 ** with the [database connection] identified by the first argument
5560 ** to be invoked whenever a row is updated, inserted or deleted.
5561 ** Any callback set by a previous call to this function
5562 ** for the same database connection is overridden.
5563 **
5564 ** The second argument is a pointer to the function to invoke when a
5565 ** row is updated, inserted or deleted.
5566 ** The first argument to the callback is a copy of the third argument
5567 ** to sqlite3_update_hook().
5568 ** The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
5569 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
5570 ** to be invoked.
5571 ** The third and fourth arguments to the callback contain pointers to the
5572 ** database and table name containing the affected row.
5573 ** The final callback parameter is the rowid of the row. In the case of
5574 ** an update, this is the rowid after the update takes place.
5575 **
5576 ** The update hook is not invoked when internal system tables are
5577 ** modified (i.e. sqlite_master and sqlite_sequence).
5578 **
5579 ** The update hook implementation must not do anything that will modify
5580 ** the database connection that invoked the update hook.  Any actions
5581 ** to modify the database connection must be deferred until after the
5582 ** completion of the [sqlite3_step()] call that triggered the update hook.
5583 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5584 ** database connections for the meaning of "modify" in this paragraph.
5585 **
5586 ** If another function was previously registered, its pArg value
5587 ** is returned.  Otherwise NULL is returned.
5588 **
5589 ** INVARIANTS:
5590 **
5591 ** {H12971} The [sqlite3_update_hook(D,F,P)] interface causes the callback
5592 **          function F to be invoked with first parameter P whenever
5593 **          a table row is modified, inserted, or deleted on
5594 **          the [database connection] D.
5595 **
5596 ** {H12973} The [sqlite3_update_hook(D,F,P)] interface returns the value
5597 **          of P for the previous call on the same [database connection] D,
5598 **          or NULL for the first call.
5599 **
5600 ** {H12975} If the update hook callback F in [sqlite3_update_hook(D,F,P)]
5601 **          is NULL then the no update callbacks are made.
5602 **
5603 ** {H12977} Each call to [sqlite3_update_hook(D,F,P)] overrides prior calls
5604 **          to the same interface on the same [database connection] D.
5605 **
5606 ** {H12979} The update hook callback is not invoked when internal system
5607 **          tables such as sqlite_master and sqlite_sequence are modified.
5608 **
5609 ** {H12981} The second parameter to the update callback
5610 **          is one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE],
5611 **          depending on the operation that caused the callback to be invoked.
5612 **
5613 ** {H12983} The third and fourth arguments to the callback contain pointers
5614 **          to zero-terminated UTF-8 strings which are the names of the
5615 **          database and table that is being updated.
5616
5617 ** {H12985} The final callback parameter is the rowid of the row after
5618 **          the change occurs.
5619 */
5620 SQLITE_API void *sqlite3_update_hook(
5621   sqlite3*, 
5622   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5623   void*
5624 );
5625
5626 /*
5627 ** CAPI3REF: Enable Or Disable Shared Pager Cache {H10330} <S30900>
5628 ** KEYWORDS: {shared cache} {shared cache mode}
5629 **
5630 ** This routine enables or disables the sharing of the database cache
5631 ** and schema data structures between [database connection | connections]
5632 ** to the same database. Sharing is enabled if the argument is true
5633 ** and disabled if the argument is false.
5634 **
5635 ** Cache sharing is enabled and disabled for an entire process. {END}
5636 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
5637 ** sharing was enabled or disabled for each thread separately.
5638 **
5639 ** The cache sharing mode set by this interface effects all subsequent
5640 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
5641 ** Existing database connections continue use the sharing mode
5642 ** that was in effect at the time they were opened.
5643 **
5644 ** Virtual tables cannot be used with a shared cache.  When shared
5645 ** cache is enabled, the [sqlite3_create_module()] API used to register
5646 ** virtual tables will always return an error.
5647 **
5648 ** This routine returns [SQLITE_OK] if shared cache was enabled or disabled
5649 ** successfully.  An [error code] is returned otherwise.
5650 **
5651 ** Shared cache is disabled by default. But this might change in
5652 ** future releases of SQLite.  Applications that care about shared
5653 ** cache setting should set it explicitly.
5654 **
5655 ** INVARIANTS:
5656 **
5657 ** {H10331} A successful invocation of [sqlite3_enable_shared_cache(B)]
5658 **          will enable or disable shared cache mode for any subsequently
5659 **          created [database connection] in the same process.
5660 **
5661 ** {H10336} When shared cache is enabled, the [sqlite3_create_module()]
5662 **          interface will always return an error.
5663 **
5664 ** {H10337} The [sqlite3_enable_shared_cache(B)] interface returns
5665 **          [SQLITE_OK] if shared cache was enabled or disabled successfully.
5666 **
5667 ** {H10339} Shared cache is disabled by default.
5668 */
5669 SQLITE_API int sqlite3_enable_shared_cache(int);
5670
5671 /*
5672 ** CAPI3REF: Attempt To Free Heap Memory {H17340} <S30220>
5673 **
5674 ** The sqlite3_release_memory() interface attempts to free N bytes
5675 ** of heap memory by deallocating non-essential memory allocations
5676 ** held by the database library. {END}  Memory used to cache database
5677 ** pages to improve performance is an example of non-essential memory.
5678 ** sqlite3_release_memory() returns the number of bytes actually freed,
5679 ** which might be more or less than the amount requested.
5680 **
5681 ** INVARIANTS:
5682 **
5683 ** {H17341} The [sqlite3_release_memory(N)] interface attempts to
5684 **          free N bytes of heap memory by deallocating non-essential
5685 **          memory allocations held by the database library.
5686 **
5687 ** {H16342} The [sqlite3_release_memory(N)] returns the number
5688 **          of bytes actually freed, which might be more or less
5689 **          than the amount requested.
5690 */
5691 SQLITE_API int sqlite3_release_memory(int);
5692
5693 /*
5694 ** CAPI3REF: Impose A Limit On Heap Size {H17350} <S30220>
5695 **
5696 ** The sqlite3_soft_heap_limit() interface places a "soft" limit
5697 ** on the amount of heap memory that may be allocated by SQLite.
5698 ** If an internal allocation is requested that would exceed the
5699 ** soft heap limit, [sqlite3_release_memory()] is invoked one or
5700 ** more times to free up some space before the allocation is performed.
5701 **
5702 ** The limit is called "soft", because if [sqlite3_release_memory()]
5703 ** cannot free sufficient memory to prevent the limit from being exceeded,
5704 ** the memory is allocated anyway and the current operation proceeds.
5705 **
5706 ** A negative or zero value for N means that there is no soft heap limit and
5707 ** [sqlite3_release_memory()] will only be called when memory is exhausted.
5708 ** The default value for the soft heap limit is zero.
5709 **
5710 ** SQLite makes a best effort to honor the soft heap limit.
5711 ** But if the soft heap limit cannot be honored, execution will
5712 ** continue without error or notification.  This is why the limit is
5713 ** called a "soft" limit.  It is advisory only.
5714 **
5715 ** Prior to SQLite version 3.5.0, this routine only constrained the memory
5716 ** allocated by a single thread - the same thread in which this routine
5717 ** runs.  Beginning with SQLite version 3.5.0, the soft heap limit is
5718 ** applied to all threads. The value specified for the soft heap limit
5719 ** is an upper bound on the total memory allocation for all threads. In
5720 ** version 3.5.0 there is no mechanism for limiting the heap usage for
5721 ** individual threads.
5722 **
5723 ** INVARIANTS:
5724 **
5725 ** {H16351} The [sqlite3_soft_heap_limit(N)] interface places a soft limit
5726 **          of N bytes on the amount of heap memory that may be allocated
5727 **          using [sqlite3_malloc()] or [sqlite3_realloc()] at any point
5728 **          in time.
5729 **
5730 ** {H16352} If a call to [sqlite3_malloc()] or [sqlite3_realloc()] would
5731 **          cause the total amount of allocated memory to exceed the
5732 **          soft heap limit, then [sqlite3_release_memory()] is invoked
5733 **          in an attempt to reduce the memory usage prior to proceeding
5734 **          with the memory allocation attempt.
5735 **
5736 ** {H16353} Calls to [sqlite3_malloc()] or [sqlite3_realloc()] that trigger
5737 **          attempts to reduce memory usage through the soft heap limit
5738 **          mechanism continue even if the attempt to reduce memory
5739 **          usage is unsuccessful.
5740 **
5741 ** {H16354} A negative or zero value for N in a call to
5742 **          [sqlite3_soft_heap_limit(N)] means that there is no soft
5743 **          heap limit and [sqlite3_release_memory()] will only be
5744 **          called when memory is completely exhausted.
5745 **
5746 ** {H16355} The default value for the soft heap limit is zero.
5747 **
5748 ** {H16358} Each call to [sqlite3_soft_heap_limit(N)] overrides the
5749 **          values set by all prior calls.
5750 */
5751 SQLITE_API void sqlite3_soft_heap_limit(int);
5752
5753 /*
5754 ** CAPI3REF: Extract Metadata About A Column Of A Table {H12850} <S60300>
5755 **
5756 ** This routine returns metadata about a specific column of a specific
5757 ** database table accessible using the [database connection] handle
5758 ** passed as the first function argument.
5759 **
5760 ** The column is identified by the second, third and fourth parameters to
5761 ** this function. The second parameter is either the name of the database
5762 ** (i.e. "main", "temp" or an attached database) containing the specified
5763 ** table or NULL. If it is NULL, then all attached databases are searched
5764 ** for the table using the same algorithm used by the database engine to
5765 ** resolve unqualified table references.
5766 **
5767 ** The third and fourth parameters to this function are the table and column
5768 ** name of the desired column, respectively. Neither of these parameters
5769 ** may be NULL.
5770 **
5771 ** Metadata is returned by writing to the memory locations passed as the 5th
5772 ** and subsequent parameters to this function. Any of these arguments may be
5773 ** NULL, in which case the corresponding element of metadata is omitted.
5774 **
5775 ** <blockquote>
5776 ** <table border="1">
5777 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
5778 **
5779 ** <tr><td> 5th <td> const char* <td> Data type
5780 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5781 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
5782 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
5783 ** <tr><td> 9th <td> int         <td> True if column is AUTOINCREMENT
5784 ** </table>
5785 ** </blockquote>
5786 **
5787 ** The memory pointed to by the character pointers returned for the
5788 ** declaration type and collation sequence is valid only until the next
5789 ** call to any SQLite API function.
5790 **
5791 ** If the specified table is actually a view, an [error code] is returned.
5792 **
5793 ** If the specified column is "rowid", "oid" or "_rowid_" and an
5794 ** INTEGER PRIMARY KEY column has been explicitly declared, then the output
5795 ** parameters are set for the explicitly declared column. If there is no
5796 ** explicitly declared INTEGER PRIMARY KEY column, then the output
5797 ** parameters are set as follows:
5798 **
5799 ** <pre>
5800 **     data type: "INTEGER"
5801 **     collation sequence: "BINARY"
5802 **     not null: 0
5803 **     primary key: 1
5804 **     auto increment: 0
5805 ** </pre>
5806 **
5807 ** This function may load one or more schemas from database files. If an
5808 ** error occurs during this process, or if the requested table or column
5809 ** cannot be found, an [error code] is returned and an error message left
5810 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).
5811 **
5812 ** This API is only available if the library was compiled with the
5813 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
5814 */
5815 SQLITE_API int sqlite3_table_column_metadata(
5816   sqlite3 *db,                /* Connection handle */
5817   const char *zDbName,        /* Database name or NULL */
5818   const char *zTableName,     /* Table name */
5819   const char *zColumnName,    /* Column name */
5820   char const **pzDataType,    /* OUTPUT: Declared data type */
5821   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
5822   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
5823   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
5824   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
5825 );
5826
5827 /*
5828 ** CAPI3REF: Load An Extension {H12600} <S20500>
5829 **
5830 ** This interface loads an SQLite extension library from the named file.
5831 **
5832 ** {H12601} The sqlite3_load_extension() interface attempts to load an
5833 **          SQLite extension library contained in the file zFile.
5834 **
5835 ** {H12602} The entry point is zProc.
5836 **
5837 ** {H12603} zProc may be 0, in which case the name of the entry point
5838 **          defaults to "sqlite3_extension_init".
5839 **
5840 ** {H12604} The sqlite3_load_extension() interface shall return
5841 **          [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5842 **
5843 ** {H12605} If an error occurs and pzErrMsg is not 0, then the
5844 **          [sqlite3_load_extension()] interface shall attempt to
5845 **          fill *pzErrMsg with error message text stored in memory
5846 **          obtained from [sqlite3_malloc()]. {END}  The calling function
5847 **          should free this memory by calling [sqlite3_free()].
5848 **
5849 ** {H12606} Extension loading must be enabled using
5850 **          [sqlite3_enable_load_extension()] prior to calling this API,
5851 **          otherwise an error will be returned.
5852 */
5853 SQLITE_API int sqlite3_load_extension(
5854   sqlite3 *db,          /* Load the extension into this database connection */
5855   const char *zFile,    /* Name of the shared library containing extension */
5856   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
5857   char **pzErrMsg       /* Put error message here if not 0 */
5858 );
5859
5860 /*
5861 ** CAPI3REF: Enable Or Disable Extension Loading {H12620} <S20500>
5862 **
5863 ** So as not to open security holes in older applications that are
5864 ** unprepared to deal with extension loading, and as a means of disabling
5865 ** extension loading while evaluating user-entered SQL, the following API
5866 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5867 **
5868 ** Extension loading is off by default. See ticket #1863.
5869 **
5870 ** {H12621} Call the sqlite3_enable_load_extension() routine with onoff==1
5871 **          to turn extension loading on and call it with onoff==0 to turn
5872 **          it back off again.
5873 **
5874 ** {H12622} Extension loading is off by default.
5875 */
5876 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5877
5878 /*
5879 ** CAPI3REF: Automatically Load An Extensions {H12640} <S20500>
5880 **
5881 ** This API can be invoked at program startup in order to register
5882 ** one or more statically linked extensions that will be available
5883 ** to all new [database connections]. {END}
5884 **
5885 ** This routine stores a pointer to the extension in an array that is
5886 ** obtained from [sqlite3_malloc()].  If you run a memory leak checker
5887 ** on your program and it reports a leak because of this array, invoke
5888 ** [sqlite3_reset_auto_extension()] prior to shutdown to free the memory.
5889 **
5890 ** {H12641} This function registers an extension entry point that is
5891 **          automatically invoked whenever a new [database connection]
5892 **          is opened using [sqlite3_open()], [sqlite3_open16()],
5893 **          or [sqlite3_open_v2()].
5894 **
5895 ** {H12642} Duplicate extensions are detected so calling this routine
5896 **          multiple times with the same extension is harmless.
5897 **
5898 ** {H12643} This routine stores a pointer to the extension in an array
5899 **          that is obtained from [sqlite3_malloc()].
5900 **
5901 ** {H12644} Automatic extensions apply across all threads.
5902 */
5903 SQLITE_API int sqlite3_auto_extension(void *xEntryPoint);
5904
5905 /*
5906 ** CAPI3REF: Reset Automatic Extension Loading {H12660} <S20500>
5907 **
5908 ** This function disables all previously registered automatic
5909 ** extensions. {END}  It undoes the effect of all prior
5910 ** [sqlite3_auto_extension()] calls.
5911 **
5912 ** {H12661} This function disables all previously registered
5913 **          automatic extensions.
5914 **
5915 ** {H12662} This function disables automatic extensions in all threads.
5916 */
5917 SQLITE_API void sqlite3_reset_auto_extension(void);
5918
5919 /*
5920 ****** EXPERIMENTAL - subject to change without notice **************
5921 **
5922 ** The interface to the virtual-table mechanism is currently considered
5923 ** to be experimental.  The interface might change in incompatible ways.
5924 ** If this is a problem for you, do not use the interface at this time.
5925 **
5926 ** When the virtual-table mechanism stabilizes, we will declare the
5927 ** interface fixed, support it indefinitely, and remove this comment.
5928 */
5929
5930 /*
5931 ** Structures used by the virtual table interface
5932 */
5933 typedef struct sqlite3_vtab sqlite3_vtab;
5934 typedef struct sqlite3_index_info sqlite3_index_info;
5935 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5936 typedef struct sqlite3_module sqlite3_module;
5937
5938 /*
5939 ** CAPI3REF: Virtual Table Object {H18000} <S20400>
5940 ** KEYWORDS: sqlite3_module
5941 ** EXPERIMENTAL
5942 **
5943 ** A module is a class of virtual tables.  Each module is defined
5944 ** by an instance of the following structure.  This structure consists
5945 ** mostly of methods for the module.
5946 **
5947 ** This interface is experimental and is subject to change or
5948 ** removal in future releases of SQLite.
5949 */
5950 struct sqlite3_module {
5951   int iVersion;
5952   int (*xCreate)(sqlite3*, void *pAux,
5953                int argc, const char *const*argv,
5954                sqlite3_vtab **ppVTab, char**);
5955   int (*xConnect)(sqlite3*, void *pAux,
5956                int argc, const char *const*argv,
5957                sqlite3_vtab **ppVTab, char**);
5958   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5959   int (*xDisconnect)(sqlite3_vtab *pVTab);
5960   int (*xDestroy)(sqlite3_vtab *pVTab);
5961   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5962   int (*xClose)(sqlite3_vtab_cursor*);
5963   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5964                 int argc, sqlite3_value **argv);
5965   int (*xNext)(sqlite3_vtab_cursor*);
5966   int (*xEof)(sqlite3_vtab_cursor*);
5967   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5968   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5969   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5970   int (*xBegin)(sqlite3_vtab *pVTab);
5971   int (*xSync)(sqlite3_vtab *pVTab);
5972   int (*xCommit)(sqlite3_vtab *pVTab);
5973   int (*xRollback)(sqlite3_vtab *pVTab);
5974   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5975                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5976                        void **ppArg);
5977   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5978 };
5979
5980 /*
5981 ** CAPI3REF: Virtual Table Indexing Information {H18100} <S20400>
5982 ** KEYWORDS: sqlite3_index_info
5983 ** EXPERIMENTAL
5984 **
5985 ** The sqlite3_index_info structure and its substructures is used to
5986 ** pass information into and receive the reply from the xBestIndex
5987 ** method of an sqlite3_module.  The fields under **Inputs** are the
5988 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
5989 ** results into the **Outputs** fields.
5990 **
5991 ** The aConstraint[] array records WHERE clause constraints of the form:
5992 **
5993 ** <pre>column OP expr</pre>
5994 **
5995 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.  The particular operator is
5996 ** stored in aConstraint[].op.  The index of the column is stored in
5997 ** aConstraint[].iColumn.  aConstraint[].usable is TRUE if the
5998 ** expr on the right-hand side can be evaluated (and thus the constraint
5999 ** is usable) and false if it cannot.
6000 **
6001 ** The optimizer automatically inverts terms of the form "expr OP column"
6002 ** and makes other simplifications to the WHERE clause in an attempt to
6003 ** get as many WHERE clause terms into the form shown above as possible.
6004 ** The aConstraint[] array only reports WHERE clause terms in the correct
6005 ** form that refer to the particular virtual table being queried.
6006 **
6007 ** Information about the ORDER BY clause is stored in aOrderBy[].
6008 ** Each term of aOrderBy records a column of the ORDER BY clause.
6009 **
6010 ** The xBestIndex method must fill aConstraintUsage[] with information
6011 ** about what parameters to pass to xFilter.  If argvIndex>0 then
6012 ** the right-hand side of the corresponding aConstraint[] is evaluated
6013 ** and becomes the argvIndex-th entry in argv.  If aConstraintUsage[].omit
6014 ** is true, then the constraint is assumed to be fully handled by the
6015 ** virtual table and is not checked again by SQLite.
6016 **
6017 ** The idxNum and idxPtr values are recorded and passed into xFilter.
6018 ** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true.
6019 **
6020 ** The orderByConsumed means that output from xFilter will occur in
6021 ** the correct order to satisfy the ORDER BY clause so that no separate
6022 ** sorting step is required.
6023 **
6024 ** The estimatedCost value is an estimate of the cost of doing the
6025 ** particular lookup.  A full scan of a table with N entries should have
6026 ** a cost of N.  A binary search of a table of N entries should have a
6027 ** cost of approximately log(N).
6028 **
6029 ** This interface is experimental and is subject to change or
6030 ** removal in future releases of SQLite.
6031 */
6032 struct sqlite3_index_info {
6033   /* Inputs */
6034   int nConstraint;           /* Number of entries in aConstraint */
6035   struct sqlite3_index_constraint {
6036      int iColumn;              /* Column on left-hand side of constraint */
6037      unsigned char op;         /* Constraint operator */
6038      unsigned char usable;     /* True if this constraint is usable */
6039      int iTermOffset;          /* Used internally - xBestIndex should ignore */
6040   } *aConstraint;            /* Table of WHERE clause constraints */
6041   int nOrderBy;              /* Number of terms in the ORDER BY clause */
6042   struct sqlite3_index_orderby {
6043      int iColumn;              /* Column number */
6044      unsigned char desc;       /* True for DESC.  False for ASC. */
6045   } *aOrderBy;               /* The ORDER BY clause */
6046   /* Outputs */
6047   struct sqlite3_index_constraint_usage {
6048     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
6049     unsigned char omit;      /* Do not code a test for this constraint */
6050   } *aConstraintUsage;
6051   int idxNum;                /* Number used to identify the index */
6052   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
6053   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
6054   int orderByConsumed;       /* True if output is already ordered */
6055   double estimatedCost;      /* Estimated cost of using this index */
6056 };
6057 #define SQLITE_INDEX_CONSTRAINT_EQ    2
6058 #define SQLITE_INDEX_CONSTRAINT_GT    4
6059 #define SQLITE_INDEX_CONSTRAINT_LE    8
6060 #define SQLITE_INDEX_CONSTRAINT_LT    16
6061 #define SQLITE_INDEX_CONSTRAINT_GE    32
6062 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
6063
6064 /*
6065 ** CAPI3REF: Register A Virtual Table Implementation {H18200} <S20400>
6066 ** EXPERIMENTAL
6067 **
6068 ** This routine is used to register a new module name with a
6069 ** [database connection].  Module names must be registered before
6070 ** creating new virtual tables on the module, or before using
6071 ** preexisting virtual tables of the module.
6072 **
6073 ** This interface is experimental and is subject to change or
6074 ** removal in future releases of SQLite.
6075 */
6076 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module(
6077   sqlite3 *db,               /* SQLite connection to register module with */
6078   const char *zName,         /* Name of the module */
6079   const sqlite3_module *,    /* Methods for the module */
6080   void *                     /* Client data for xCreate/xConnect */
6081 );
6082
6083 /*
6084 ** CAPI3REF: Register A Virtual Table Implementation {H18210} <S20400>
6085 ** EXPERIMENTAL
6086 **
6087 ** This routine is identical to the [sqlite3_create_module()] method above,
6088 ** except that it allows a destructor function to be specified. It is
6089 ** even more experimental than the rest of the virtual tables API.
6090 */
6091 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module_v2(
6092   sqlite3 *db,               /* SQLite connection to register module with */
6093   const char *zName,         /* Name of the module */
6094   const sqlite3_module *,    /* Methods for the module */
6095   void *,                    /* Client data for xCreate/xConnect */
6096   void(*xDestroy)(void*)     /* Module destructor function */
6097 );
6098
6099 /*
6100 ** CAPI3REF: Virtual Table Instance Object {H18010} <S20400>
6101 ** KEYWORDS: sqlite3_vtab
6102 ** EXPERIMENTAL
6103 **
6104 ** Every module implementation uses a subclass of the following structure
6105 ** to describe a particular instance of the module.  Each subclass will
6106 ** be tailored to the specific needs of the module implementation.
6107 ** The purpose of this superclass is to define certain fields that are
6108 ** common to all module implementations.
6109 **
6110 ** Virtual tables methods can set an error message by assigning a
6111 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
6112 ** take care that any prior string is freed by a call to [sqlite3_free()]
6113 ** prior to assigning a new string to zErrMsg.  After the error message
6114 ** is delivered up to the client application, the string will be automatically
6115 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.  Note
6116 ** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field
6117 ** since virtual tables are commonly implemented in loadable extensions which
6118 ** do not have access to sqlite3MPrintf() or sqlite3Free().
6119 **
6120 ** This interface is experimental and is subject to change or
6121 ** removal in future releases of SQLite.
6122 */
6123 struct sqlite3_vtab {
6124   const sqlite3_module *pModule;  /* The module for this virtual table */
6125   int nRef;                       /* Used internally */
6126   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
6127   /* Virtual table implementations will typically add additional fields */
6128 };
6129
6130 /*
6131 ** CAPI3REF: Virtual Table Cursor Object  {H18020} <S20400>
6132 ** KEYWORDS: sqlite3_vtab_cursor
6133 ** EXPERIMENTAL
6134 **
6135 ** Every module implementation uses a subclass of the following structure
6136 ** to describe cursors that point into the virtual table and are used
6137 ** to loop through the virtual table.  Cursors are created using the
6138 ** xOpen method of the module.  Each module implementation will define
6139 ** the content of a cursor structure to suit its own needs.
6140 **
6141 ** This superclass exists in order to define fields of the cursor that
6142 ** are common to all implementations.
6143 **
6144 ** This interface is experimental and is subject to change or
6145 ** removal in future releases of SQLite.
6146 */
6147 struct sqlite3_vtab_cursor {
6148   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
6149   /* Virtual table implementations will typically add additional fields */
6150 };
6151
6152 /*
6153 ** CAPI3REF: Declare The Schema Of A Virtual Table {H18280} <S20400>
6154 ** EXPERIMENTAL
6155 **
6156 ** The xCreate and xConnect methods of a module use the following API
6157 ** to declare the format (the names and datatypes of the columns) of
6158 ** the virtual tables they implement.
6159 **
6160 ** This interface is experimental and is subject to change or
6161 ** removal in future releases of SQLite.
6162 */
6163 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable);
6164
6165 /*
6166 ** CAPI3REF: Overload A Function For A Virtual Table {H18300} <S20400>
6167 ** EXPERIMENTAL
6168 **
6169 ** Virtual tables can provide alternative implementations of functions
6170 ** using the xFindFunction method.  But global versions of those functions
6171 ** must exist in order to be overloaded.
6172 **
6173 ** This API makes sure a global version of a function with a particular
6174 ** name and number of parameters exists.  If no such function exists
6175 ** before this API is called, a new function is created.  The implementation
6176 ** of the new function always causes an exception to be thrown.  So
6177 ** the new function is not good for anything by itself.  Its only
6178 ** purpose is to be a placeholder function that can be overloaded
6179 ** by virtual tables.
6180 **
6181 ** This API should be considered part of the virtual table interface,
6182 ** which is experimental and subject to change.
6183 */
6184 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
6185
6186 /*
6187 ** The interface to the virtual-table mechanism defined above (back up
6188 ** to a comment remarkably similar to this one) is currently considered
6189 ** to be experimental.  The interface might change in incompatible ways.
6190 ** If this is a problem for you, do not use the interface at this time.
6191 **
6192 ** When the virtual-table mechanism stabilizes, we will declare the
6193 ** interface fixed, support it indefinitely, and remove this comment.
6194 **
6195 ****** EXPERIMENTAL - subject to change without notice **************
6196 */
6197
6198 /*
6199 ** CAPI3REF: A Handle To An Open BLOB {H17800} <S30230>
6200 ** KEYWORDS: {BLOB handle} {BLOB handles}
6201 **
6202 ** An instance of this object represents an open BLOB on which
6203 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
6204 ** Objects of this type are created by [sqlite3_blob_open()]
6205 ** and destroyed by [sqlite3_blob_close()].
6206 ** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
6207 ** can be used to read or write small subsections of the BLOB.
6208 ** The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
6209 */
6210 typedef struct sqlite3_blob sqlite3_blob;
6211
6212 /*
6213 ** CAPI3REF: Open A BLOB For Incremental I/O {H17810} <S30230>
6214 **
6215 ** This interfaces opens a [BLOB handle | handle] to the BLOB located
6216 ** in row iRow, column zColumn, table zTable in database zDb;
6217 ** in other words, the same BLOB that would be selected by:
6218 **
6219 ** <pre>
6220 **     SELECT zColumn FROM zDb.zTable WHERE rowid = iRow;
6221 ** </pre> {END}
6222 **
6223 ** If the flags parameter is non-zero, the the BLOB is opened for read
6224 ** and write access. If it is zero, the BLOB is opened for read access.
6225 **
6226 ** Note that the database name is not the filename that contains
6227 ** the database but rather the symbolic name of the database that
6228 ** is assigned when the database is connected using [ATTACH].
6229 ** For the main database file, the database name is "main".
6230 ** For TEMP tables, the database name is "temp".
6231 **
6232 ** On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
6233 ** to *ppBlob. Otherwise an [error code] is returned and any value written
6234 ** to *ppBlob should not be used by the caller.
6235 ** This function sets the [database connection] error code and message
6236 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()].
6237 **
6238 ** If the row that a BLOB handle points to is modified by an
6239 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
6240 ** then the BLOB handle is marked as "expired".
6241 ** This is true if any column of the row is changed, even a column
6242 ** other than the one the BLOB handle is open on.
6243 ** Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
6244 ** a expired BLOB handle fail with an return code of [SQLITE_ABORT].
6245 ** Changes written into a BLOB prior to the BLOB expiring are not
6246 ** rollback by the expiration of the BLOB.  Such changes will eventually
6247 ** commit if the transaction continues to completion.
6248 **
6249 ** INVARIANTS:
6250 **
6251 ** {H17813} A successful invocation of the [sqlite3_blob_open(D,B,T,C,R,F,P)]
6252 **          interface shall open an [sqlite3_blob] object P on the BLOB
6253 **          in column C of the table T in the database B on
6254 **          the [database connection] D.
6255 **
6256 ** {H17814} A successful invocation of [sqlite3_blob_open(D,...)] shall start
6257 **          a new transaction on the [database connection] D if that
6258 **          connection is not already in a transaction.
6259 **
6260 ** {H17816} The [sqlite3_blob_open(D,B,T,C,R,F,P)] interface shall open
6261 **          the BLOB for read and write access if and only if the F
6262 **          parameter is non-zero.
6263 **
6264 ** {H17819} The [sqlite3_blob_open()] interface shall return [SQLITE_OK] on
6265 **          success and an appropriate [error code] on failure.
6266 **
6267 ** {H17821} If an error occurs during evaluation of [sqlite3_blob_open(D,...)]
6268 **          then subsequent calls to [sqlite3_errcode(D)],
6269 **          [sqlite3_extended_errcode()], 
6270 **          [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] shall return
6271 **          information appropriate for that error.
6272 **
6273 ** {H17824} If any column in the row that a [sqlite3_blob] has open is
6274 **          changed by a separate [UPDATE] or [DELETE] statement or by
6275 **          an [ON CONFLICT] side effect, then the [sqlite3_blob] shall
6276 **          be marked as invalid.
6277 */
6278 SQLITE_API int sqlite3_blob_open(
6279   sqlite3*,
6280   const char *zDb,
6281   const char *zTable,
6282   const char *zColumn,
6283   sqlite3_int64 iRow,
6284   int flags,
6285   sqlite3_blob **ppBlob
6286 );
6287
6288 /*
6289 ** CAPI3REF: Close A BLOB Handle {H17830} <S30230>
6290 **
6291 ** Closes an open [BLOB handle].
6292 **
6293 ** Closing a BLOB shall cause the current transaction to commit
6294 ** if there are no other BLOBs, no pending prepared statements, and the
6295 ** database connection is in [autocommit mode].
6296 ** If any writes were made to the BLOB, they might be held in cache
6297 ** until the close operation if they will fit. {END}
6298 **
6299 ** Closing the BLOB often forces the changes
6300 ** out to disk and so if any I/O errors occur, they will likely occur
6301 ** at the time when the BLOB is closed.  {H17833} Any errors that occur during
6302 ** closing are reported as a non-zero return value.
6303 **
6304 ** The BLOB is closed unconditionally.  Even if this routine returns
6305 ** an error code, the BLOB is still closed.
6306 **
6307 ** INVARIANTS:
6308 **
6309 ** {H17833} The [sqlite3_blob_close(P)] interface closes an [sqlite3_blob]
6310 **          object P previously opened using [sqlite3_blob_open()].
6311 **
6312 ** {H17836} Closing an [sqlite3_blob] object using
6313 **          [sqlite3_blob_close()] shall cause the current transaction to
6314 **          commit if there are no other open [sqlite3_blob] objects
6315 **          or [prepared statements] on the same [database connection] and
6316 **          the database connection is in [autocommit mode].
6317 **
6318 ** {H17839} The [sqlite3_blob_close(P)] interfaces shall close the
6319 **          [sqlite3_blob] object P unconditionally, even if
6320 **          [sqlite3_blob_close(P)] returns something other than [SQLITE_OK].
6321 */
6322 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
6323
6324 /*
6325 ** CAPI3REF: Return The Size Of An Open BLOB {H17840} <S30230>
6326 **
6327 ** Returns the size in bytes of the BLOB accessible via the open
6328 ** []BLOB handle] in its only argument.
6329 **
6330 ** INVARIANTS:
6331 **
6332 ** {H17843} The [sqlite3_blob_bytes(P)] interface returns the size
6333 **          in bytes of the BLOB that the [sqlite3_blob] object P
6334 **          refers to.
6335 */
6336 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
6337
6338 /*
6339 ** CAPI3REF: Read Data From A BLOB Incrementally {H17850} <S30230>
6340 **
6341 ** This function is used to read data from an open [BLOB handle] into a
6342 ** caller-supplied buffer. N bytes of data are copied into buffer Z
6343 ** from the open BLOB, starting at offset iOffset.
6344 **
6345 ** If offset iOffset is less than N bytes from the end of the BLOB,
6346 ** [SQLITE_ERROR] is returned and no data is read.  If N or iOffset is
6347 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
6348 **
6349 ** An attempt to read from an expired [BLOB handle] fails with an
6350 ** error code of [SQLITE_ABORT].
6351 **
6352 ** On success, SQLITE_OK is returned.
6353 ** Otherwise, an [error code] or an [extended error code] is returned.
6354 **
6355 ** INVARIANTS:
6356 **
6357 ** {H17853} A successful invocation of [sqlite3_blob_read(P,Z,N,X)] 
6358 **          shall reads N bytes of data out of the BLOB referenced by
6359 **          [BLOB handle] P beginning at offset X and store those bytes
6360 **          into buffer Z.
6361 **
6362 ** {H17856} In [sqlite3_blob_read(P,Z,N,X)] if the size of the BLOB
6363 **          is less than N+X bytes, then the function shall leave the
6364 **          Z buffer unchanged and return [SQLITE_ERROR].
6365 **
6366 ** {H17859} In [sqlite3_blob_read(P,Z,N,X)] if X or N is less than zero
6367 **          then the function shall leave the Z buffer unchanged
6368 **          and return [SQLITE_ERROR].
6369 **
6370 ** {H17862} The [sqlite3_blob_read(P,Z,N,X)] interface shall return [SQLITE_OK]
6371 **          if N bytes are successfully read into buffer Z.
6372 **
6373 ** {H17863} If the [BLOB handle] P is expired and X and N are within bounds
6374 **          then [sqlite3_blob_read(P,Z,N,X)] shall leave the Z buffer
6375 **          unchanged and return [SQLITE_ABORT].
6376 **
6377 ** {H17865} If the requested read could not be completed,
6378 **          the [sqlite3_blob_read(P,Z,N,X)] interface shall return an
6379 **          appropriate [error code] or [extended error code].
6380 **
6381 ** {H17868} If an error occurs during evaluation of [sqlite3_blob_read(P,...)]
6382 **          then subsequent calls to [sqlite3_errcode(D)],
6383 **          [sqlite3_extended_errcode()],
6384 **          [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] shall return
6385 **          information appropriate for that error, where D is the
6386 **          [database connection] that was used to open the [BLOB handle] P.
6387 */
6388 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
6389
6390 /*
6391 ** CAPI3REF: Write Data Into A BLOB Incrementally {H17870} <S30230>
6392 **
6393 ** This function is used to write data into an open [BLOB handle] from a
6394 ** caller-supplied buffer. N bytes of data are copied from the buffer Z
6395 ** into the open BLOB, starting at offset iOffset.
6396 **
6397 ** If the [BLOB handle] passed as the first argument was not opened for
6398 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
6399 ** this function returns [SQLITE_READONLY].
6400 **
6401 ** This function may only modify the contents of the BLOB; it is
6402 ** not possible to increase the size of a BLOB using this API.
6403 ** If offset iOffset is less than N bytes from the end of the BLOB,
6404 ** [SQLITE_ERROR] is returned and no data is written.  If N is
6405 ** less than zero [SQLITE_ERROR] is returned and no data is written.
6406 **
6407 ** An attempt to write to an expired [BLOB handle] fails with an
6408 ** error code of [SQLITE_ABORT].  Writes to the BLOB that occurred
6409 ** before the [BLOB handle] expired are not rolled back by the
6410 ** expiration of the handle, though of course those changes might
6411 ** have been overwritten by the statement that expired the BLOB handle
6412 ** or by other independent statements.
6413 **
6414 ** On success, SQLITE_OK is returned.
6415 ** Otherwise, an  [error code] or an [extended error code] is returned.
6416 **
6417 ** INVARIANTS:
6418 **
6419 ** {H17873} A successful invocation of [sqlite3_blob_write(P,Z,N,X)]
6420 **          shall write N bytes of data from buffer Z into the BLOB 
6421 **          referenced by [BLOB handle] P beginning at offset X into
6422 **          the BLOB.
6423 **
6424 ** {H17874} In the absence of other overridding changes, the changes
6425 **          written to a BLOB by [sqlite3_blob_write()] shall
6426 **          remain in effect after the associated [BLOB handle] expires.
6427 **
6428 ** {H17875} If the [BLOB handle] P was opened for reading only then
6429 **          an invocation of [sqlite3_blob_write(P,Z,N,X)] shall leave
6430 **          the referenced BLOB unchanged and return [SQLITE_READONLY].
6431 **
6432 ** {H17876} If the size of the BLOB referenced by [BLOB handle] P is
6433 **          less than N+X bytes then [sqlite3_blob_write(P,Z,N,X)] shall
6434 **          leave the BLOB unchanged and return [SQLITE_ERROR].
6435 **
6436 ** {H17877} If the [BLOB handle] P is expired and X and N are within bounds
6437 **          then [sqlite3_blob_read(P,Z,N,X)] shall leave the BLOB
6438 **          unchanged and return [SQLITE_ABORT].
6439 **
6440 ** {H17879} If X or N are less than zero then [sqlite3_blob_write(P,Z,N,X)]
6441 **          shall leave the BLOB referenced by [BLOB handle] P unchanged
6442 **          and return [SQLITE_ERROR].
6443 **
6444 ** {H17882} The [sqlite3_blob_write(P,Z,N,X)] interface shall return
6445 **          [SQLITE_OK] if N bytes where successfully written into the BLOB.
6446 **
6447 ** {H17885} If the requested write could not be completed,
6448 **          the [sqlite3_blob_write(P,Z,N,X)] interface shall return an
6449 **          appropriate [error code] or [extended error code].
6450 **
6451 ** {H17888} If an error occurs during evaluation of [sqlite3_blob_write(D,...)]
6452 **          then subsequent calls to [sqlite3_errcode(D)],
6453 **          [sqlite3_extended_errcode()],
6454 **          [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] shall return
6455 **          information appropriate for that error.
6456 */
6457 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
6458
6459 /*
6460 ** CAPI3REF: Virtual File System Objects {H11200} <S20100>
6461 **
6462 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
6463 ** that SQLite uses to interact
6464 ** with the underlying operating system.  Most SQLite builds come with a
6465 ** single default VFS that is appropriate for the host computer.
6466 ** New VFSes can be registered and existing VFSes can be unregistered.
6467 ** The following interfaces are provided.
6468 **
6469 ** The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
6470 ** Names are case sensitive.
6471 ** Names are zero-terminated UTF-8 strings.
6472 ** If there is no match, a NULL pointer is returned.
6473 ** If zVfsName is NULL then the default VFS is returned.
6474 **
6475 ** New VFSes are registered with sqlite3_vfs_register().
6476 ** Each new VFS becomes the default VFS if the makeDflt flag is set.
6477 ** The same VFS can be registered multiple times without injury.
6478 ** To make an existing VFS into the default VFS, register it again
6479 ** with the makeDflt flag set.  If two different VFSes with the
6480 ** same name are registered, the behavior is undefined.  If a
6481 ** VFS is registered with a name that is NULL or an empty string,
6482 ** then the behavior is undefined.
6483 **
6484 ** Unregister a VFS with the sqlite3_vfs_unregister() interface.
6485 ** If the default VFS is unregistered, another VFS is chosen as
6486 ** the default.  The choice for the new VFS is arbitrary.
6487 **
6488 ** INVARIANTS:
6489 **
6490 ** {H11203} The [sqlite3_vfs_find(N)] interface returns a pointer to the
6491 **          registered [sqlite3_vfs] object whose name exactly matches
6492 **          the zero-terminated UTF-8 string N, or it returns NULL if
6493 **          there is no match.
6494 **
6495 ** {H11206} If the N parameter to [sqlite3_vfs_find(N)] is NULL then
6496 **          the function returns a pointer to the default [sqlite3_vfs]
6497 **          object if there is one, or NULL if there is no default
6498 **          [sqlite3_vfs] object.
6499 **
6500 ** {H11209} The [sqlite3_vfs_register(P,F)] interface registers the
6501 **          well-formed [sqlite3_vfs] object P using the name given
6502 **          by the zName field of the object.
6503 **
6504 ** {H11212} Using the [sqlite3_vfs_register(P,F)] interface to register
6505 **          the same [sqlite3_vfs] object multiple times is a harmless no-op.
6506 **
6507 ** {H11215} The [sqlite3_vfs_register(P,F)] interface makes the [sqlite3_vfs]
6508 **          object P the default [sqlite3_vfs] object if F is non-zero.
6509 **
6510 ** {H11218} The [sqlite3_vfs_unregister(P)] interface unregisters the
6511 **          [sqlite3_vfs] object P so that it is no longer returned by
6512 **          subsequent calls to [sqlite3_vfs_find()].
6513 */
6514 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
6515 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
6516 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
6517
6518 /*
6519 ** CAPI3REF: Mutexes {H17000} <S20000>
6520 **
6521 ** The SQLite core uses these routines for thread
6522 ** synchronization. Though they are intended for internal
6523 ** use by SQLite, code that links against SQLite is
6524 ** permitted to use any of these routines.
6525 **
6526 ** The SQLite source code contains multiple implementations
6527 ** of these mutex routines.  An appropriate implementation
6528 ** is selected automatically at compile-time.  The following
6529 ** implementations are available in the SQLite core:
6530 **
6531 ** <ul>
6532 ** <li>   SQLITE_MUTEX_OS2
6533 ** <li>   SQLITE_MUTEX_PTHREAD
6534 ** <li>   SQLITE_MUTEX_W32
6535 ** <li>   SQLITE_MUTEX_NOOP
6536 ** </ul>
6537 **
6538 ** The SQLITE_MUTEX_NOOP implementation is a set of routines
6539 ** that does no real locking and is appropriate for use in
6540 ** a single-threaded application.  The SQLITE_MUTEX_OS2,
6541 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
6542 ** are appropriate for use on OS/2, Unix, and Windows.
6543 **
6544 ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
6545 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
6546 ** implementation is included with the library. In this case the
6547 ** application must supply a custom mutex implementation using the
6548 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
6549 ** before calling sqlite3_initialize() or any other public sqlite3_
6550 ** function that calls sqlite3_initialize().
6551 **
6552 ** {H17011} The sqlite3_mutex_alloc() routine allocates a new
6553 ** mutex and returns a pointer to it. {H17012} If it returns NULL
6554 ** that means that a mutex could not be allocated. {H17013} SQLite
6555 ** will unwind its stack and return an error. {H17014} The argument
6556 ** to sqlite3_mutex_alloc() is one of these integer constants:
6557 **
6558 ** <ul>
6559 ** <li>  SQLITE_MUTEX_FAST
6560 ** <li>  SQLITE_MUTEX_RECURSIVE
6561 ** <li>  SQLITE_MUTEX_STATIC_MASTER
6562 ** <li>  SQLITE_MUTEX_STATIC_MEM
6563 ** <li>  SQLITE_MUTEX_STATIC_MEM2
6564 ** <li>  SQLITE_MUTEX_STATIC_PRNG
6565 ** <li>  SQLITE_MUTEX_STATIC_LRU
6566 ** <li>  SQLITE_MUTEX_STATIC_LRU2
6567 ** </ul>
6568 **
6569 ** {H17015} The first two constants cause sqlite3_mutex_alloc() to create
6570 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
6571 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. {END}
6572 ** The mutex implementation does not need to make a distinction
6573 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
6574 ** not want to.  {H17016} But SQLite will only request a recursive mutex in
6575 ** cases where it really needs one.  {END} If a faster non-recursive mutex
6576 ** implementation is available on the host platform, the mutex subsystem
6577 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
6578 **
6579 ** {H17017} The other allowed parameters to sqlite3_mutex_alloc() each return
6580 ** a pointer to a static preexisting mutex. {END}  Four static mutexes are
6581 ** used by the current version of SQLite.  Future versions of SQLite
6582 ** may add additional static mutexes.  Static mutexes are for internal
6583 ** use by SQLite only.  Applications that use SQLite mutexes should
6584 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
6585 ** SQLITE_MUTEX_RECURSIVE.
6586 **
6587 ** {H17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
6588 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
6589 ** returns a different mutex on every call.  {H17034} But for the static
6590 ** mutex types, the same mutex is returned on every call that has
6591 ** the same type number.
6592 **
6593 ** {H17019} The sqlite3_mutex_free() routine deallocates a previously
6594 ** allocated dynamic mutex. {H17020} SQLite is careful to deallocate every
6595 ** dynamic mutex that it allocates. {A17021} The dynamic mutexes must not be in
6596 ** use when they are deallocated. {A17022} Attempting to deallocate a static
6597 ** mutex results in undefined behavior. {H17023} SQLite never deallocates
6598 ** a static mutex. {END}
6599 **
6600 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
6601 ** to enter a mutex. {H17024} If another thread is already within the mutex,
6602 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
6603 ** SQLITE_BUSY. {H17025}  The sqlite3_mutex_try() interface returns [SQLITE_OK]
6604 ** upon successful entry.  {H17026} Mutexes created using
6605 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
6606 ** {H17027} In such cases the,
6607 ** mutex must be exited an equal number of times before another thread
6608 ** can enter.  {A17028} If the same thread tries to enter any other
6609 ** kind of mutex more than once, the behavior is undefined.
6610 ** {H17029} SQLite will never exhibit
6611 ** such behavior in its own use of mutexes.
6612 **
6613 ** Some systems (for example, Windows 95) do not support the operation
6614 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
6615 ** will always return SQLITE_BUSY.  {H17030} The SQLite core only ever uses
6616 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.
6617 **
6618 ** {H17031} The sqlite3_mutex_leave() routine exits a mutex that was
6619 ** previously entered by the same thread.  {A17032} The behavior
6620 ** is undefined if the mutex is not currently entered by the
6621 ** calling thread or is not currently allocated.  {H17033} SQLite will
6622 ** never do either. {END}
6623 **
6624 ** If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
6625 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
6626 ** behave as no-ops.
6627 **
6628 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
6629 */
6630 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
6631 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
6632 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
6633 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
6634 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
6635
6636 /*
6637 ** CAPI3REF: Mutex Methods Object {H17120} <S20130>
6638 ** EXPERIMENTAL
6639 **
6640 ** An instance of this structure defines the low-level routines
6641 ** used to allocate and use mutexes.
6642 **
6643 ** Usually, the default mutex implementations provided by SQLite are
6644 ** sufficient, however the user has the option of substituting a custom
6645 ** implementation for specialized deployments or systems for which SQLite
6646 ** does not provide a suitable implementation. In this case, the user
6647 ** creates and populates an instance of this structure to pass
6648 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
6649 ** Additionally, an instance of this structure can be used as an
6650 ** output variable when querying the system for the current mutex
6651 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
6652 **
6653 ** The xMutexInit method defined by this structure is invoked as
6654 ** part of system initialization by the sqlite3_initialize() function.
6655 ** {H17001} The xMutexInit routine shall be called by SQLite once for each
6656 ** effective call to [sqlite3_initialize()].
6657 **
6658 ** The xMutexEnd method defined by this structure is invoked as
6659 ** part of system shutdown by the sqlite3_shutdown() function. The
6660 ** implementation of this method is expected to release all outstanding
6661 ** resources obtained by the mutex methods implementation, especially
6662 ** those obtained by the xMutexInit method. {H17003} The xMutexEnd()
6663 ** interface shall be invoked once for each call to [sqlite3_shutdown()].
6664 **
6665 ** The remaining seven methods defined by this structure (xMutexAlloc,
6666 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
6667 ** xMutexNotheld) implement the following interfaces (respectively):
6668 **
6669 ** <ul>
6670 **   <li>  [sqlite3_mutex_alloc()] </li>
6671 **   <li>  [sqlite3_mutex_free()] </li>
6672 **   <li>  [sqlite3_mutex_enter()] </li>
6673 **   <li>  [sqlite3_mutex_try()] </li>
6674 **   <li>  [sqlite3_mutex_leave()] </li>
6675 **   <li>  [sqlite3_mutex_held()] </li>
6676 **   <li>  [sqlite3_mutex_notheld()] </li>
6677 ** </ul>
6678 **
6679 ** The only difference is that the public sqlite3_XXX functions enumerated
6680 ** above silently ignore any invocations that pass a NULL pointer instead
6681 ** of a valid mutex handle. The implementations of the methods defined
6682 ** by this structure are not required to handle this case, the results
6683 ** of passing a NULL pointer instead of a valid mutex handle are undefined
6684 ** (i.e. it is acceptable to provide an implementation that segfaults if
6685 ** it is passed a NULL pointer).
6686 */
6687 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
6688 struct sqlite3_mutex_methods {
6689   int (*xMutexInit)(void);
6690   int (*xMutexEnd)(void);
6691   sqlite3_mutex *(*xMutexAlloc)(int);
6692   void (*xMutexFree)(sqlite3_mutex *);
6693   void (*xMutexEnter)(sqlite3_mutex *);
6694   int (*xMutexTry)(sqlite3_mutex *);
6695   void (*xMutexLeave)(sqlite3_mutex *);
6696   int (*xMutexHeld)(sqlite3_mutex *);
6697   int (*xMutexNotheld)(sqlite3_mutex *);
6698 };
6699
6700 /*
6701 ** CAPI3REF: Mutex Verification Routines {H17080} <S20130> <S30800>
6702 **
6703 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
6704 ** are intended for use inside assert() statements. {H17081} The SQLite core
6705 ** never uses these routines except inside an assert() and applications
6706 ** are advised to follow the lead of the core.  {H17082} The core only
6707 ** provides implementations for these routines when it is compiled
6708 ** with the SQLITE_DEBUG flag.  {A17087} External mutex implementations
6709 ** are only required to provide these routines if SQLITE_DEBUG is
6710 ** defined and if NDEBUG is not defined.
6711 **
6712 ** {H17083} These routines should return true if the mutex in their argument
6713 ** is held or not held, respectively, by the calling thread.
6714 **
6715 ** {X17084} The implementation is not required to provided versions of these
6716 ** routines that actually work. If the implementation does not provide working
6717 ** versions of these routines, it should at least provide stubs that always
6718 ** return true so that one does not get spurious assertion failures.
6719 **
6720 ** {H17085} If the argument to sqlite3_mutex_held() is a NULL pointer then
6721 ** the routine should return 1.  {END} This seems counter-intuitive since
6722 ** clearly the mutex cannot be held if it does not exist.  But the
6723 ** the reason the mutex does not exist is because the build is not
6724 ** using mutexes.  And we do not want the assert() containing the
6725 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
6726 ** the appropriate thing to do.  {H17086} The sqlite3_mutex_notheld()
6727 ** interface should also return 1 when given a NULL pointer.
6728 */
6729 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
6730 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
6731
6732 /*
6733 ** CAPI3REF: Mutex Types {H17001} <H17000>
6734 **
6735 ** The [sqlite3_mutex_alloc()] interface takes a single argument
6736 ** which is one of these integer constants.
6737 **
6738 ** The set of static mutexes may change from one SQLite release to the
6739 ** next.  Applications that override the built-in mutex logic must be
6740 ** prepared to accommodate additional static mutexes.
6741 */
6742 #define SQLITE_MUTEX_FAST             0
6743 #define SQLITE_MUTEX_RECURSIVE        1
6744 #define SQLITE_MUTEX_STATIC_MASTER    2
6745 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
6746 #define SQLITE_MUTEX_STATIC_MEM2      4  /* sqlite3_release_memory() */
6747 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
6748 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
6749 #define SQLITE_MUTEX_STATIC_LRU2      7  /* lru page list */
6750
6751 /*
6752 ** CAPI3REF: Retrieve the mutex for a database connection {H17002} <H17000>
6753 **
6754 ** This interface returns a pointer the [sqlite3_mutex] object that 
6755 ** serializes access to the [database connection] given in the argument
6756 ** when the [threading mode] is Serialized.
6757 ** If the [threading mode] is Single-thread or Multi-thread then this
6758 ** routine returns a NULL pointer.
6759 */
6760 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
6761
6762 /*
6763 ** CAPI3REF: Low-Level Control Of Database Files {H11300} <S30800>
6764 **
6765 ** {H11301} The [sqlite3_file_control()] interface makes a direct call to the
6766 ** xFileControl method for the [sqlite3_io_methods] object associated
6767 ** with a particular database identified by the second argument. {H11302} The
6768 ** name of the database is the name assigned to the database by the
6769 ** <a href="lang_attach.html">ATTACH</a> SQL command that opened the
6770 ** database. {H11303} To control the main database file, use the name "main"
6771 ** or a NULL pointer. {H11304} The third and fourth parameters to this routine
6772 ** are passed directly through to the second and third parameters of
6773 ** the xFileControl method.  {H11305} The return value of the xFileControl
6774 ** method becomes the return value of this routine.
6775 **
6776 ** {H11306} If the second parameter (zDbName) does not match the name of any
6777 ** open database file, then SQLITE_ERROR is returned. {H11307} This error
6778 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
6779 ** or [sqlite3_errmsg()]. {A11308} The underlying xFileControl method might
6780 ** also return SQLITE_ERROR.  {A11309} There is no way to distinguish between
6781 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
6782 ** xFileControl method. {END}
6783 **
6784 ** See also: [SQLITE_FCNTL_LOCKSTATE]
6785 */
6786 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
6787
6788 /*
6789 ** CAPI3REF: Testing Interface {H11400} <S30800>
6790 **
6791 ** The sqlite3_test_control() interface is used to read out internal
6792 ** state of SQLite and to inject faults into SQLite for testing
6793 ** purposes.  The first parameter is an operation code that determines
6794 ** the number, meaning, and operation of all subsequent parameters.
6795 **
6796 ** This interface is not for use by applications.  It exists solely
6797 ** for verifying the correct operation of the SQLite library.  Depending
6798 ** on how the SQLite library is compiled, this interface might not exist.
6799 **
6800 ** The details of the operation codes, their meanings, the parameters
6801 ** they take, and what they do are all subject to change without notice.
6802 ** Unlike most of the SQLite API, this function is not guaranteed to
6803 ** operate consistently from one release to the next.
6804 */
6805 SQLITE_API int sqlite3_test_control(int op, ...);
6806
6807 /*
6808 ** CAPI3REF: Testing Interface Operation Codes {H11410} <H11400>
6809 **
6810 ** These constants are the valid operation code parameters used
6811 ** as the first argument to [sqlite3_test_control()].
6812 **
6813 ** These parameters and their meanings are subject to change
6814 ** without notice.  These values are for testing purposes only.
6815 ** Applications should not use any of these parameters or the
6816 ** [sqlite3_test_control()] interface.
6817 */
6818 #define SQLITE_TESTCTRL_PRNG_SAVE                5
6819 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
6820 #define SQLITE_TESTCTRL_PRNG_RESET               7
6821 #define SQLITE_TESTCTRL_BITVEC_TEST              8
6822 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
6823 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
6824
6825 /*
6826 ** CAPI3REF: SQLite Runtime Status {H17200} <S60200>
6827 ** EXPERIMENTAL
6828 **
6829 ** This interface is used to retrieve runtime status information
6830 ** about the preformance of SQLite, and optionally to reset various
6831 ** highwater marks.  The first argument is an integer code for
6832 ** the specific parameter to measure.  Recognized integer codes
6833 ** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].
6834 ** The current value of the parameter is returned into *pCurrent.
6835 ** The highest recorded value is returned in *pHighwater.  If the
6836 ** resetFlag is true, then the highest record value is reset after
6837 ** *pHighwater is written. Some parameters do not record the highest
6838 ** value.  For those parameters
6839 ** nothing is written into *pHighwater and the resetFlag is ignored.
6840 ** Other parameters record only the highwater mark and not the current
6841 ** value.  For these latter parameters nothing is written into *pCurrent.
6842 **
6843 ** This routine returns SQLITE_OK on success and a non-zero
6844 ** [error code] on failure.
6845 **
6846 ** This routine is threadsafe but is not atomic.  This routine can
6847 ** called while other threads are running the same or different SQLite
6848 ** interfaces.  However the values returned in *pCurrent and
6849 ** *pHighwater reflect the status of SQLite at different points in time
6850 ** and it is possible that another thread might change the parameter
6851 ** in between the times when *pCurrent and *pHighwater are written.
6852 **
6853 ** See also: [sqlite3_db_status()]
6854 */
6855 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
6856
6857
6858 /*
6859 ** CAPI3REF: Status Parameters {H17250} <H17200>
6860 ** EXPERIMENTAL
6861 **
6862 ** These integer constants designate various run-time status parameters
6863 ** that can be returned by [sqlite3_status()].
6864 **
6865 ** <dl>
6866 ** <dt>SQLITE_STATUS_MEMORY_USED</dt>
6867 ** <dd>This parameter is the current amount of memory checked out
6868 ** using [sqlite3_malloc()], either directly or indirectly.  The
6869 ** figure includes calls made to [sqlite3_malloc()] by the application
6870 ** and internal memory usage by the SQLite library.  Scratch memory
6871 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
6872 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
6873 ** this parameter.  The amount returned is the sum of the allocation
6874 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>
6875 **
6876 ** <dt>SQLITE_STATUS_MALLOC_SIZE</dt>
6877 ** <dd>This parameter records the largest memory allocation request
6878 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
6879 ** internal equivalents).  Only the value returned in the
6880 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6881 ** The value written into the *pCurrent parameter is undefined.</dd>
6882 **
6883 ** <dt>SQLITE_STATUS_PAGECACHE_USED</dt>
6884 ** <dd>This parameter returns the number of pages used out of the
6885 ** [pagecache memory allocator] that was configured using 
6886 ** [SQLITE_CONFIG_PAGECACHE].  The
6887 ** value returned is in pages, not in bytes.</dd>
6888 **
6889 ** <dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
6890 ** <dd>This parameter returns the number of bytes of page cache
6891 ** allocation which could not be statisfied by the [SQLITE_CONFIG_PAGECACHE]
6892 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
6893 ** returned value includes allocations that overflowed because they
6894 ** where too large (they were larger than the "sz" parameter to
6895 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
6896 ** no space was left in the page cache.</dd>
6897 **
6898 ** <dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
6899 ** <dd>This parameter records the largest memory allocation request
6900 ** handed to [pagecache memory allocator].  Only the value returned in the
6901 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6902 ** The value written into the *pCurrent parameter is undefined.</dd>
6903 **
6904 ** <dt>SQLITE_STATUS_SCRATCH_USED</dt>
6905 ** <dd>This parameter returns the number of allocations used out of the
6906 ** [scratch memory allocator] configured using
6907 ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
6908 ** in bytes.  Since a single thread may only have one scratch allocation
6909 ** outstanding at time, this parameter also reports the number of threads
6910 ** using scratch memory at the same time.</dd>
6911 **
6912 ** <dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6913 ** <dd>This parameter returns the number of bytes of scratch memory
6914 ** allocation which could not be statisfied by the [SQLITE_CONFIG_SCRATCH]
6915 ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
6916 ** returned include overflows because the requested allocation was too
6917 ** larger (that is, because the requested allocation was larger than the
6918 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6919 ** slots were available.
6920 ** </dd>
6921 **
6922 ** <dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6923 ** <dd>This parameter records the largest memory allocation request
6924 ** handed to [scratch memory allocator].  Only the value returned in the
6925 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6926 ** The value written into the *pCurrent parameter is undefined.</dd>
6927 **
6928 ** <dt>SQLITE_STATUS_PARSER_STACK</dt>
6929 ** <dd>This parameter records the deepest parser stack.  It is only
6930 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>
6931 ** </dl>
6932 **
6933 ** New status parameters may be added from time to time.
6934 */
6935 #define SQLITE_STATUS_MEMORY_USED          0
6936 #define SQLITE_STATUS_PAGECACHE_USED       1
6937 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
6938 #define SQLITE_STATUS_SCRATCH_USED         3
6939 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
6940 #define SQLITE_STATUS_MALLOC_SIZE          5
6941 #define SQLITE_STATUS_PARSER_STACK         6
6942 #define SQLITE_STATUS_PAGECACHE_SIZE       7
6943 #define SQLITE_STATUS_SCRATCH_SIZE         8
6944
6945 /*
6946 ** CAPI3REF: Database Connection Status {H17500} <S60200>
6947 ** EXPERIMENTAL
6948 **
6949 ** This interface is used to retrieve runtime status information 
6950 ** about a single [database connection].  The first argument is the
6951 ** database connection object to be interrogated.  The second argument
6952 ** is the parameter to interrogate.  Currently, the only allowed value
6953 ** for the second parameter is [SQLITE_DBSTATUS_LOOKASIDE_USED].
6954 ** Additional options will likely appear in future releases of SQLite.
6955 **
6956 ** The current value of the requested parameter is written into *pCur
6957 ** and the highest instantaneous value is written into *pHiwtr.  If
6958 ** the resetFlg is true, then the highest instantaneous value is
6959 ** reset back down to the current value.
6960 **
6961 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
6962 */
6963 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6964
6965 /*
6966 ** CAPI3REF: Status Parameters for database connections {H17520} <H17500>
6967 ** EXPERIMENTAL
6968 **
6969 ** Status verbs for [sqlite3_db_status()].
6970 **
6971 ** <dl>
6972 ** <dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6973 ** <dd>This parameter returns the number of lookaside memory slots currently
6974 ** checked out.</dd>
6975 ** </dl>
6976 */
6977 #define SQLITE_DBSTATUS_LOOKASIDE_USED     0
6978
6979
6980 /*
6981 ** CAPI3REF: Prepared Statement Status {H17550} <S60200>
6982 ** EXPERIMENTAL
6983 **
6984 ** Each prepared statement maintains various
6985 ** [SQLITE_STMTSTATUS_SORT | counters] that measure the number
6986 ** of times it has performed specific operations.  These counters can
6987 ** be used to monitor the performance characteristics of the prepared
6988 ** statements.  For example, if the number of table steps greatly exceeds
6989 ** the number of table searches or result rows, that would tend to indicate
6990 ** that the prepared statement is using a full table scan rather than
6991 ** an index.  
6992 **
6993 ** This interface is used to retrieve and reset counter values from
6994 ** a [prepared statement].  The first argument is the prepared statement
6995 ** object to be interrogated.  The second argument
6996 ** is an integer code for a specific [SQLITE_STMTSTATUS_SORT | counter]
6997 ** to be interrogated. 
6998 ** The current value of the requested counter is returned.
6999 ** If the resetFlg is true, then the counter is reset to zero after this
7000 ** interface call returns.
7001 **
7002 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
7003 */
7004 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
7005
7006 /*
7007 ** CAPI3REF: Status Parameters for prepared statements {H17570} <H17550>
7008 ** EXPERIMENTAL
7009 **
7010 ** These preprocessor macros define integer codes that name counter
7011 ** values associated with the [sqlite3_stmt_status()] interface.
7012 ** The meanings of the various counters are as follows:
7013 **
7014 ** <dl>
7015 ** <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
7016 ** <dd>This is the number of times that SQLite has stepped forward in
7017 ** a table as part of a full table scan.  Large numbers for this counter
7018 ** may indicate opportunities for performance improvement through 
7019 ** careful use of indices.</dd>
7020 **
7021 ** <dt>SQLITE_STMTSTATUS_SORT</dt>
7022 ** <dd>This is the number of sort operations that have occurred.
7023 ** A non-zero value in this counter may indicate an opportunity to
7024 ** improvement performance through careful use of indices.</dd>
7025 **
7026 ** </dl>
7027 */
7028 #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
7029 #define SQLITE_STMTSTATUS_SORT              2
7030
7031 /*
7032 ** CAPI3REF: Custom Page Cache Object
7033 ** EXPERIMENTAL
7034 **
7035 ** The sqlite3_pcache type is opaque.  It is implemented by
7036 ** the pluggable module.  The SQLite core has no knowledge of
7037 ** its size or internal structure and never deals with the
7038 ** sqlite3_pcache object except by holding and passing pointers
7039 ** to the object.
7040 **
7041 ** See [sqlite3_pcache_methods] for additional information.
7042 */
7043 typedef struct sqlite3_pcache sqlite3_pcache;
7044
7045 /*
7046 ** CAPI3REF: Application Defined Page Cache.
7047 ** EXPERIMENTAL
7048 **
7049 ** The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
7050 ** register an alternative page cache implementation by passing in an 
7051 ** instance of the sqlite3_pcache_methods structure. The majority of the 
7052 ** heap memory used by sqlite is used by the page cache to cache data read 
7053 ** from, or ready to be written to, the database file. By implementing a 
7054 ** custom page cache using this API, an application can control more 
7055 ** precisely the amount of memory consumed by sqlite, the way in which 
7056 ** said memory is allocated and released, and the policies used to 
7057 ** determine exactly which parts of a database file are cached and for 
7058 ** how long.
7059 **
7060 ** The contents of the structure are copied to an internal buffer by sqlite
7061 ** within the call to [sqlite3_config].
7062 **
7063 ** The xInit() method is called once for each call to [sqlite3_initialize()]
7064 ** (usually only once during the lifetime of the process). It is passed
7065 ** a copy of the sqlite3_pcache_methods.pArg value. It can be used to set
7066 ** up global structures and mutexes required by the custom page cache 
7067 ** implementation. The xShutdown() method is called from within 
7068 ** [sqlite3_shutdown()], if the application invokes this API. It can be used
7069 ** to clean up any outstanding resources before process shutdown, if required.
7070 **
7071 ** The xCreate() method is used to construct a new cache instance. The
7072 ** first parameter, szPage, is the size in bytes of the pages that must
7073 ** be allocated by the cache. szPage will not be a power of two. The
7074 ** second argument, bPurgeable, is true if the cache being created will
7075 ** be used to cache database pages read from a file stored on disk, or
7076 ** false if it is used for an in-memory database. The cache implementation
7077 ** does not have to do anything special based on the value of bPurgeable,
7078 ** it is purely advisory. 
7079 **
7080 ** The xCachesize() method may be called at any time by SQLite to set the
7081 ** suggested maximum cache-size (number of pages stored by) the cache
7082 ** instance passed as the first argument. This is the value configured using
7083 ** the SQLite "[PRAGMA cache_size]" command. As with the bPurgeable parameter,
7084 ** the implementation is not required to do anything special with this
7085 ** value, it is advisory only.
7086 **
7087 ** The xPagecount() method should return the number of pages currently
7088 ** stored in the cache supplied as an argument.
7089 ** 
7090 ** The xFetch() method is used to fetch a page and return a pointer to it. 
7091 ** A 'page', in this context, is a buffer of szPage bytes aligned at an
7092 ** 8-byte boundary. The page to be fetched is determined by the key. The
7093 ** mimimum key value is 1. After it has been retrieved using xFetch, the page 
7094 ** is considered to be pinned.
7095 **
7096 ** If the requested page is already in the page cache, then a pointer to
7097 ** the cached buffer should be returned with its contents intact. If the
7098 ** page is not already in the cache, then the expected behaviour of the
7099 ** cache is determined by the value of the createFlag parameter passed
7100 ** to xFetch, according to the following table:
7101 **
7102 ** <table border=1 width=85% align=center>
7103 **   <tr><th>createFlag<th>Expected Behaviour
7104 **   <tr><td>0<td>NULL should be returned. No new cache entry is created.
7105 **   <tr><td>1<td>If createFlag is set to 1, this indicates that 
7106 **                SQLite is holding pinned pages that can be unpinned
7107 **                by writing their contents to the database file (a
7108 **                relatively expensive operation). In this situation the
7109 **                cache implementation has two choices: it can return NULL,
7110 **                in which case SQLite will attempt to unpin one or more 
7111 **                pages before re-requesting the same page, or it can
7112 **                allocate a new page and return a pointer to it. If a new
7113 **                page is allocated, then it must be completely zeroed before 
7114 **                it is returned.
7115 **   <tr><td>2<td>If createFlag is set to 2, then SQLite is not holding any
7116 **                pinned pages associated with the specific cache passed
7117 **                as the first argument to xFetch() that can be unpinned. The
7118 **                cache implementation should attempt to allocate a new
7119 **                cache entry and return a pointer to it. Again, the new
7120 **                page should be zeroed before it is returned. If the xFetch()
7121 **                method returns NULL when createFlag==2, SQLite assumes that
7122 **                a memory allocation failed and returns SQLITE_NOMEM to the
7123 **                user.
7124 ** </table>
7125 **
7126 ** xUnpin() is called by SQLite with a pointer to a currently pinned page
7127 ** as its second argument. If the third parameter, discard, is non-zero,
7128 ** then the page should be evicted from the cache. In this case SQLite 
7129 ** assumes that the next time the page is retrieved from the cache using
7130 ** the xFetch() method, it will be zeroed. If the discard parameter is
7131 ** zero, then the page is considered to be unpinned. The cache implementation
7132 ** may choose to reclaim (free or recycle) unpinned pages at any time.
7133 ** SQLite assumes that next time the page is retrieved from the cache
7134 ** it will either be zeroed, or contain the same data that it did when it
7135 ** was unpinned.
7136 **
7137 ** The cache is not required to perform any reference counting. A single 
7138 ** call to xUnpin() unpins the page regardless of the number of prior calls 
7139 ** to xFetch().
7140 **
7141 ** The xRekey() method is used to change the key value associated with the
7142 ** page passed as the second argument from oldKey to newKey. If the cache
7143 ** previously contains an entry associated with newKey, it should be
7144 ** discarded. Any prior cache entry associated with newKey is guaranteed not
7145 ** to be pinned.
7146 **
7147 ** When SQLite calls the xTruncate() method, the cache must discard all
7148 ** existing cache entries with page numbers (keys) greater than or equal
7149 ** to the value of the iLimit parameter passed to xTruncate(). If any
7150 ** of these pages are pinned, they are implicitly unpinned, meaning that
7151 ** they can be safely discarded.
7152 **
7153 ** The xDestroy() method is used to delete a cache allocated by xCreate().
7154 ** All resources associated with the specified cache should be freed. After
7155 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
7156 ** handle invalid, and will not use it with any other sqlite3_pcache_methods
7157 ** functions.
7158 */
7159 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
7160 struct sqlite3_pcache_methods {
7161   void *pArg;
7162   int (*xInit)(void*);
7163   void (*xShutdown)(void*);
7164   sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
7165   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7166   int (*xPagecount)(sqlite3_pcache*);
7167   void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7168   void (*xUnpin)(sqlite3_pcache*, void*, int discard);
7169   void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
7170   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7171   void (*xDestroy)(sqlite3_pcache*);
7172 };
7173
7174 /*
7175 ** Undo the hack that converts floating point types to integer for
7176 ** builds on processors without floating point support.
7177 */
7178 #ifdef SQLITE_OMIT_FLOATING_POINT
7179 # undef double
7180 #endif
7181
7182 #if 0
7183 }  /* End of the 'extern "C"' block */
7184 #endif
7185 #endif
7186
7187 /************** End of sqlite3.h *********************************************/
7188 /************** Continuing where we left off in sqliteInt.h ******************/
7189 /************** Include hash.h in the middle of sqliteInt.h ******************/
7190 /************** Begin file hash.h ********************************************/
7191 /*
7192 ** 2001 September 22
7193 **
7194 ** The author disclaims copyright to this source code.  In place of
7195 ** a legal notice, here is a blessing:
7196 **
7197 **    May you do good and not evil.
7198 **    May you find forgiveness for yourself and forgive others.
7199 **    May you share freely, never taking more than you give.
7200 **
7201 *************************************************************************
7202 ** This is the header file for the generic hash-table implemenation
7203 ** used in SQLite.
7204 **
7205 ** $Id: hash.h,v 1.12 2008/10/10 17:41:29 drh Exp $
7206 */
7207 #ifndef _SQLITE_HASH_H_
7208 #define _SQLITE_HASH_H_
7209
7210 /* Forward declarations of structures. */
7211 typedef struct Hash Hash;
7212 typedef struct HashElem HashElem;
7213
7214 /* A complete hash table is an instance of the following structure.
7215 ** The internals of this structure are intended to be opaque -- client
7216 ** code should not attempt to access or modify the fields of this structure
7217 ** directly.  Change this structure only by using the routines below.
7218 ** However, many of the "procedures" and "functions" for modifying and
7219 ** accessing this structure are really macros, so we can't really make
7220 ** this structure opaque.
7221 */
7222 struct Hash {
7223   unsigned int copyKey: 1;  /* True if copy of key made on insert */
7224   unsigned int htsize : 31; /* Number of buckets in the hash table */
7225   unsigned int count;       /* Number of entries in this table */
7226   HashElem *first;          /* The first element of the array */
7227   struct _ht {              /* the hash table */
7228     int count;                 /* Number of entries with this hash */
7229     HashElem *chain;           /* Pointer to first entry with this hash */
7230   } *ht;
7231 };
7232
7233 /* Each element in the hash table is an instance of the following 
7234 ** structure.  All elements are stored on a single doubly-linked list.
7235 **
7236 ** Again, this structure is intended to be opaque, but it can't really
7237 ** be opaque because it is used by macros.
7238 */
7239 struct HashElem {
7240   HashElem *next, *prev;   /* Next and previous elements in the table */
7241   void *data;              /* Data associated with this element */
7242   void *pKey; int nKey;    /* Key associated with this element */
7243 };
7244
7245 /*
7246 ** Access routines.  To delete, insert a NULL pointer.
7247 */
7248 SQLITE_PRIVATE void sqlite3HashInit(Hash*, int copyKey);
7249 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const void *pKey, int nKey, void *pData);
7250 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const void *pKey, int nKey);
7251 SQLITE_PRIVATE HashElem *sqlite3HashFindElem(const Hash*, const void *pKey, int nKey);
7252 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
7253
7254 /*
7255 ** Macros for looping over all elements of a hash table.  The idiom is
7256 ** like this:
7257 **
7258 **   Hash h;
7259 **   HashElem *p;
7260 **   ...
7261 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
7262 **     SomeStructure *pData = sqliteHashData(p);
7263 **     // do something with pData
7264 **   }
7265 */
7266 #define sqliteHashFirst(H)  ((H)->first)
7267 #define sqliteHashNext(E)   ((E)->next)
7268 #define sqliteHashData(E)   ((E)->data)
7269 #define sqliteHashKey(E)    ((E)->pKey)
7270 #define sqliteHashKeysize(E) ((E)->nKey)
7271
7272 /*
7273 ** Number of entries in a hash table
7274 */
7275 #define sqliteHashCount(H)  ((H)->count)
7276
7277 #endif /* _SQLITE_HASH_H_ */
7278
7279 /************** End of hash.h ************************************************/
7280 /************** Continuing where we left off in sqliteInt.h ******************/
7281 /************** Include parse.h in the middle of sqliteInt.h *****************/
7282 /************** Begin file parse.h *******************************************/
7283 #define TK_SEMI                            1
7284 #define TK_EXPLAIN                         2
7285 #define TK_QUERY                           3
7286 #define TK_PLAN                            4
7287 #define TK_BEGIN                           5
7288 #define TK_TRANSACTION                     6
7289 #define TK_DEFERRED                        7
7290 #define TK_IMMEDIATE                       8
7291 #define TK_EXCLUSIVE                       9
7292 #define TK_COMMIT                         10
7293 #define TK_END                            11
7294 #define TK_ROLLBACK                       12
7295 #define TK_CREATE                         13
7296 #define TK_TABLE                          14
7297 #define TK_IF                             15
7298 #define TK_NOT                            16
7299 #define TK_EXISTS                         17
7300 #define TK_TEMP                           18
7301 #define TK_LP                             19
7302 #define TK_RP                             20
7303 #define TK_AS                             21
7304 #define TK_COMMA                          22
7305 #define TK_ID                             23
7306 #define TK_ABORT                          24
7307 #define TK_AFTER                          25
7308 #define TK_ANALYZE                        26
7309 #define TK_ASC                            27
7310 #define TK_ATTACH                         28
7311 #define TK_BEFORE                         29
7312 #define TK_CASCADE                        30
7313 #define TK_CAST                           31
7314 #define TK_CONFLICT                       32
7315 #define TK_DATABASE                       33
7316 #define TK_DESC                           34
7317 #define TK_DETACH                         35
7318 #define TK_EACH                           36
7319 #define TK_FAIL                           37
7320 #define TK_FOR                            38
7321 #define TK_IGNORE                         39
7322 #define TK_INITIALLY                      40
7323 #define TK_INSTEAD                        41
7324 #define TK_LIKE_KW                        42
7325 #define TK_MATCH                          43
7326 #define TK_KEY                            44
7327 #define TK_OF                             45
7328 #define TK_OFFSET                         46
7329 #define TK_PRAGMA                         47
7330 #define TK_RAISE                          48
7331 #define TK_REPLACE                        49
7332 #define TK_RESTRICT                       50
7333 #define TK_ROW                            51
7334 #define TK_TRIGGER                        52
7335 #define TK_VACUUM                         53
7336 #define TK_VIEW                           54
7337 #define TK_VIRTUAL                        55
7338 #define TK_REINDEX                        56
7339 #define TK_RENAME                         57
7340 #define TK_CTIME_KW                       58
7341 #define TK_ANY                            59
7342 #define TK_OR                             60
7343 #define TK_AND                            61
7344 #define TK_IS                             62
7345 #define TK_BETWEEN                        63
7346 #define TK_IN                             64
7347 #define TK_ISNULL                         65
7348 #define TK_NOTNULL                        66
7349 #define TK_NE                             67
7350 #define TK_EQ                             68
7351 #define TK_GT                             69
7352 #define TK_LE                             70
7353 #define TK_LT                             71
7354 #define TK_GE                             72
7355 #define TK_ESCAPE                         73
7356 #define TK_BITAND                         74
7357 #define TK_BITOR                          75
7358 #define TK_LSHIFT                         76
7359 #define TK_RSHIFT                         77
7360 #define TK_PLUS                           78
7361 #define TK_MINUS                          79
7362 #define TK_STAR                           80
7363 #define TK_SLASH                          81
7364 #define TK_REM                            82
7365 #define TK_CONCAT                         83
7366 #define TK_COLLATE                        84
7367 #define TK_UMINUS                         85
7368 #define TK_UPLUS                          86
7369 #define TK_BITNOT                         87
7370 #define TK_STRING                         88
7371 #define TK_JOIN_KW                        89
7372 #define TK_CONSTRAINT                     90
7373 #define TK_DEFAULT                        91
7374 #define TK_NULL                           92
7375 #define TK_PRIMARY                        93
7376 #define TK_UNIQUE                         94
7377 #define TK_CHECK                          95
7378 #define TK_REFERENCES                     96
7379 #define TK_AUTOINCR                       97
7380 #define TK_ON                             98
7381 #define TK_DELETE                         99
7382 #define TK_UPDATE                         100
7383 #define TK_INSERT                         101
7384 #define TK_SET                            102
7385 #define TK_DEFERRABLE                     103
7386 #define TK_FOREIGN                        104
7387 #define TK_DROP                           105
7388 #define TK_UNION                          106
7389 #define TK_ALL                            107
7390 #define TK_EXCEPT                         108
7391 #define TK_INTERSECT                      109
7392 #define TK_SELECT                         110
7393 #define TK_DISTINCT                       111
7394 #define TK_DOT                            112
7395 #define TK_FROM                           113
7396 #define TK_JOIN                           114
7397 #define TK_INDEXED                        115
7398 #define TK_BY                             116
7399 #define TK_USING                          117
7400 #define TK_ORDER                          118
7401 #define TK_GROUP                          119
7402 #define TK_HAVING                         120
7403 #define TK_LIMIT                          121
7404 #define TK_WHERE                          122
7405 #define TK_INTO                           123
7406 #define TK_VALUES                         124
7407 #define TK_INTEGER                        125
7408 #define TK_FLOAT                          126
7409 #define TK_BLOB                           127
7410 #define TK_REGISTER                       128
7411 #define TK_VARIABLE                       129
7412 #define TK_CASE                           130
7413 #define TK_WHEN                           131
7414 #define TK_THEN                           132
7415 #define TK_ELSE                           133
7416 #define TK_INDEX                          134
7417 #define TK_ALTER                          135
7418 #define TK_TO                             136
7419 #define TK_ADD                            137
7420 #define TK_COLUMNKW                       138
7421 #define TK_TO_TEXT                        139
7422 #define TK_TO_BLOB                        140
7423 #define TK_TO_NUMERIC                     141
7424 #define TK_TO_INT                         142
7425 #define TK_TO_REAL                        143
7426 #define TK_END_OF_FILE                    144
7427 #define TK_ILLEGAL                        145
7428 #define TK_SPACE                          146
7429 #define TK_UNCLOSED_STRING                147
7430 #define TK_FUNCTION                       148
7431 #define TK_COLUMN                         149
7432 #define TK_AGG_FUNCTION                   150
7433 #define TK_AGG_COLUMN                     151
7434 #define TK_CONST_FUNC                     152
7435
7436 /************** End of parse.h ***********************************************/
7437 /************** Continuing where we left off in sqliteInt.h ******************/
7438 #include <stdio.h>
7439 #include <stdlib.h>
7440 #include <string.h>
7441 #include <assert.h>
7442 #include <stddef.h>
7443
7444 /*
7445 ** If compiling for a processor that lacks floating point support,
7446 ** substitute integer for floating-point
7447 */
7448 #ifdef SQLITE_OMIT_FLOATING_POINT
7449 # define double sqlite_int64
7450 # define LONGDOUBLE_TYPE sqlite_int64
7451 # ifndef SQLITE_BIG_DBL
7452 #   define SQLITE_BIG_DBL (0x7fffffffffffffff)
7453 # endif
7454 # define SQLITE_OMIT_DATETIME_FUNCS 1
7455 # define SQLITE_OMIT_TRACE 1
7456 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
7457 #endif
7458 #ifndef SQLITE_BIG_DBL
7459 # define SQLITE_BIG_DBL (1e99)
7460 #endif
7461
7462 /*
7463 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
7464 ** afterward. Having this macro allows us to cause the C compiler 
7465 ** to omit code used by TEMP tables without messy #ifndef statements.
7466 */
7467 #ifdef SQLITE_OMIT_TEMPDB
7468 #define OMIT_TEMPDB 1
7469 #else
7470 #define OMIT_TEMPDB 0
7471 #endif
7472
7473 /*
7474 ** If the following macro is set to 1, then NULL values are considered
7475 ** distinct when determining whether or not two entries are the same
7476 ** in a UNIQUE index.  This is the way PostgreSQL, Oracle, DB2, MySQL,
7477 ** OCELOT, and Firebird all work.  The SQL92 spec explicitly says this
7478 ** is the way things are suppose to work.
7479 **
7480 ** If the following macro is set to 0, the NULLs are indistinct for
7481 ** a UNIQUE index.  In this mode, you can only have a single NULL entry
7482 ** for a column declared UNIQUE.  This is the way Informix and SQL Server
7483 ** work.
7484 */
7485 #define NULL_DISTINCT_FOR_UNIQUE 1
7486
7487 /*
7488 ** The "file format" number is an integer that is incremented whenever
7489 ** the VDBE-level file format changes.  The following macros define the
7490 ** the default file format for new databases and the maximum file format
7491 ** that the library can read.
7492 */
7493 #define SQLITE_MAX_FILE_FORMAT 4
7494 #ifndef SQLITE_DEFAULT_FILE_FORMAT
7495 # define SQLITE_DEFAULT_FILE_FORMAT 1
7496 #endif
7497
7498 /*
7499 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
7500 ** on the command-line
7501 */
7502 #ifndef SQLITE_TEMP_STORE
7503 # define SQLITE_TEMP_STORE 1
7504 #endif
7505
7506 /*
7507 ** GCC does not define the offsetof() macro so we'll have to do it
7508 ** ourselves.
7509 */
7510 #ifndef offsetof
7511 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
7512 #endif
7513
7514 /*
7515 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
7516 ** not, there are still machines out there that use EBCDIC.)
7517 */
7518 #if 'A' == '\301'
7519 # define SQLITE_EBCDIC 1
7520 #else
7521 # define SQLITE_ASCII 1
7522 #endif
7523
7524 /*
7525 ** Integers of known sizes.  These typedefs might change for architectures
7526 ** where the sizes very.  Preprocessor macros are available so that the
7527 ** types can be conveniently redefined at compile-type.  Like this:
7528 **
7529 **         cc '-DUINTPTR_TYPE=long long int' ...
7530 */
7531 #ifndef UINT32_TYPE
7532 # ifdef HAVE_UINT32_T
7533 #  define UINT32_TYPE uint32_t
7534 # else
7535 #  define UINT32_TYPE unsigned int
7536 # endif
7537 #endif
7538 #ifndef UINT16_TYPE
7539 # ifdef HAVE_UINT16_T
7540 #  define UINT16_TYPE uint16_t
7541 # else
7542 #  define UINT16_TYPE unsigned short int
7543 # endif
7544 #endif
7545 #ifndef INT16_TYPE
7546 # ifdef HAVE_INT16_T
7547 #  define INT16_TYPE int16_t
7548 # else
7549 #  define INT16_TYPE short int
7550 # endif
7551 #endif
7552 #ifndef UINT8_TYPE
7553 # ifdef HAVE_UINT8_T
7554 #  define UINT8_TYPE uint8_t
7555 # else
7556 #  define UINT8_TYPE unsigned char
7557 # endif
7558 #endif
7559 #ifndef INT8_TYPE
7560 # ifdef HAVE_INT8_T
7561 #  define INT8_TYPE int8_t
7562 # else
7563 #  define INT8_TYPE signed char
7564 # endif
7565 #endif
7566 #ifndef LONGDOUBLE_TYPE
7567 # define LONGDOUBLE_TYPE long double
7568 #endif
7569 typedef sqlite_int64 i64;          /* 8-byte signed integer */
7570 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
7571 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
7572 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
7573 typedef INT16_TYPE i16;            /* 2-byte signed integer */
7574 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
7575 typedef INT8_TYPE i8;              /* 1-byte signed integer */
7576
7577 /*
7578 ** Macros to determine whether the machine is big or little endian,
7579 ** evaluated at runtime.
7580 */
7581 #ifdef SQLITE_AMALGAMATION
7582 SQLITE_PRIVATE const int sqlite3one;
7583 #else
7584 SQLITE_PRIVATE const int sqlite3one;
7585 #endif
7586 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
7587                              || defined(__x86_64) || defined(__x86_64__)
7588 # define SQLITE_BIGENDIAN    0
7589 # define SQLITE_LITTLEENDIAN 1
7590 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
7591 #else
7592 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
7593 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
7594 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
7595 #endif
7596
7597 /*
7598 ** Constants for the largest and smallest possible 64-bit signed integers.
7599 ** These macros are designed to work correctly on both 32-bit and 64-bit
7600 ** compilers.
7601 */
7602 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
7603 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
7604
7605 /*
7606 ** An instance of the following structure is used to store the busy-handler
7607 ** callback for a given sqlite handle. 
7608 **
7609 ** The sqlite.busyHandler member of the sqlite struct contains the busy
7610 ** callback for the database handle. Each pager opened via the sqlite
7611 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
7612 ** callback is currently invoked only from within pager.c.
7613 */
7614 typedef struct BusyHandler BusyHandler;
7615 struct BusyHandler {
7616   int (*xFunc)(void *,int);  /* The busy callback */
7617   void *pArg;                /* First arg to busy callback */
7618   int nBusy;                 /* Incremented with each busy call */
7619 };
7620
7621 /*
7622 ** Name of the master database table.  The master database table
7623 ** is a special table that holds the names and attributes of all
7624 ** user tables and indices.
7625 */
7626 #define MASTER_NAME       "sqlite_master"
7627 #define TEMP_MASTER_NAME  "sqlite_temp_master"
7628
7629 /*
7630 ** The root-page of the master database table.
7631 */
7632 #define MASTER_ROOT       1
7633
7634 /*
7635 ** The name of the schema table.
7636 */
7637 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
7638
7639 /*
7640 ** A convenience macro that returns the number of elements in
7641 ** an array.
7642 */
7643 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
7644
7645 /*
7646 ** The following value as a destructor means to use sqlite3DbFree().
7647 ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
7648 */
7649 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3DbFree)
7650
7651 /*
7652 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
7653 ** not support Writable Static Data (WSD) such as global and static variables.
7654 ** All variables must either be on the stack or dynamically allocated from
7655 ** the heap.  When WSD is unsupported, the variable declarations scattered
7656 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
7657 ** macro is used for this purpose.  And instead of referencing the variable
7658 ** directly, we use its constant as a key to lookup the run-time allocated
7659 ** buffer that holds real variable.  The constant is also the initializer
7660 ** for the run-time allocated buffer.
7661 **
7662 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
7663 ** macros become no-ops and have zero performance impact.
7664 */
7665 #ifdef SQLITE_OMIT_WSD
7666   #define SQLITE_WSD const
7667   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
7668   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
7669 SQLITE_API   int sqlite3_wsd_init(int N, int J);
7670 SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
7671 #else
7672   #define SQLITE_WSD 
7673   #define GLOBAL(t,v) v
7674   #define sqlite3GlobalConfig sqlite3Config
7675 #endif
7676
7677 /*
7678 ** The following macros are used to suppress compiler warnings and to
7679 ** make it clear to human readers when a function parameter is deliberately 
7680 ** left unused within the body of a function. This usually happens when
7681 ** a function is called via a function pointer. For example the 
7682 ** implementation of an SQL aggregate step callback may not use the
7683 ** parameter indicating the number of arguments passed to the aggregate,
7684 ** if it knows that this is enforced elsewhere.
7685 **
7686 ** When a function parameter is not used at all within the body of a function,
7687 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
7688 ** However, these macros may also be used to suppress warnings related to
7689 ** parameters that may or may not be used depending on compilation options.
7690 ** For example those parameters only used in assert() statements. In these
7691 ** cases the parameters are named as per the usual conventions.
7692 */
7693 #define UNUSED_PARAMETER(x) (void)(x)
7694 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
7695
7696 /*
7697 ** Forward references to structures
7698 */
7699 typedef struct AggInfo AggInfo;
7700 typedef struct AuthContext AuthContext;
7701 typedef struct Bitvec Bitvec;
7702 typedef struct CollSeq CollSeq;
7703 typedef struct Column Column;
7704 typedef struct Db Db;
7705 typedef struct Schema Schema;
7706 typedef struct Expr Expr;
7707 typedef struct ExprList ExprList;
7708 typedef struct FKey FKey;
7709 typedef struct FuncDef FuncDef;
7710 typedef struct FuncDefHash FuncDefHash;
7711 typedef struct IdList IdList;
7712 typedef struct Index Index;
7713 typedef struct KeyClass KeyClass;
7714 typedef struct KeyInfo KeyInfo;
7715 typedef struct Lookaside Lookaside;
7716 typedef struct LookasideSlot LookasideSlot;
7717 typedef struct Module Module;
7718 typedef struct NameContext NameContext;
7719 typedef struct Parse Parse;
7720 typedef struct Select Select;
7721 typedef struct SrcList SrcList;
7722 typedef struct StrAccum StrAccum;
7723 typedef struct Table Table;
7724 typedef struct TableLock TableLock;
7725 typedef struct Token Token;
7726 typedef struct TriggerStack TriggerStack;
7727 typedef struct TriggerStep TriggerStep;
7728 typedef struct Trigger Trigger;
7729 typedef struct UnpackedRecord UnpackedRecord;
7730 typedef struct Walker Walker;
7731 typedef struct WhereInfo WhereInfo;
7732 typedef struct WhereLevel WhereLevel;
7733
7734 /*
7735 ** Defer sourcing vdbe.h and btree.h until after the "u8" and 
7736 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
7737 ** pointer types (i.e. FuncDef) defined above.
7738 */
7739 /************** Include btree.h in the middle of sqliteInt.h *****************/
7740 /************** Begin file btree.h *******************************************/
7741 /*
7742 ** 2001 September 15
7743 **
7744 ** The author disclaims copyright to this source code.  In place of
7745 ** a legal notice, here is a blessing:
7746 **
7747 **    May you do good and not evil.
7748 **    May you find forgiveness for yourself and forgive others.
7749 **    May you share freely, never taking more than you give.
7750 **
7751 *************************************************************************
7752 ** This header file defines the interface that the sqlite B-Tree file
7753 ** subsystem.  See comments in the source code for a detailed description
7754 ** of what each interface routine does.
7755 **
7756 ** @(#) $Id: btree.h,v 1.105 2008/10/27 13:59:34 danielk1977 Exp $
7757 */
7758 #ifndef _BTREE_H_
7759 #define _BTREE_H_
7760
7761 /* TODO: This definition is just included so other modules compile. It
7762 ** needs to be revisited.
7763 */
7764 #define SQLITE_N_BTREE_META 10
7765
7766 /*
7767 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
7768 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
7769 */
7770 #ifndef SQLITE_DEFAULT_AUTOVACUUM
7771   #define SQLITE_DEFAULT_AUTOVACUUM 0
7772 #endif
7773
7774 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
7775 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
7776 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
7777
7778 /*
7779 ** Forward declarations of structure
7780 */
7781 typedef struct Btree Btree;
7782 typedef struct BtCursor BtCursor;
7783 typedef struct BtShared BtShared;
7784 typedef struct BtreeMutexArray BtreeMutexArray;
7785
7786 /*
7787 ** This structure records all of the Btrees that need to hold
7788 ** a mutex before we enter sqlite3VdbeExec().  The Btrees are
7789 ** are placed in aBtree[] in order of aBtree[]->pBt.  That way,
7790 ** we can always lock and unlock them all quickly.
7791 */
7792 struct BtreeMutexArray {
7793   int nMutex;
7794   Btree *aBtree[SQLITE_MAX_ATTACHED+1];
7795 };
7796
7797
7798 SQLITE_PRIVATE int sqlite3BtreeOpen(
7799   const char *zFilename,   /* Name of database file to open */
7800   sqlite3 *db,             /* Associated database connection */
7801   Btree **,                /* Return open Btree* here */
7802   int flags,               /* Flags */
7803   int vfsFlags             /* Flags passed through to VFS open */
7804 );
7805
7806 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
7807 ** following values.
7808 **
7809 ** NOTE:  These values must match the corresponding PAGER_ values in
7810 ** pager.h.
7811 */
7812 #define BTREE_OMIT_JOURNAL  1  /* Do not use journal.  No argument */
7813 #define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
7814 #define BTREE_MEMORY        4  /* In-memory DB.  No argument */
7815 #define BTREE_READONLY      8  /* Open the database in read-only mode */
7816 #define BTREE_READWRITE    16  /* Open for both reading and writing */
7817 #define BTREE_CREATE       32  /* Create the database if it does not exist */
7818
7819 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
7820 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
7821 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
7822 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
7823 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree*,int,int);
7824 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
7825 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
7826 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
7827 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
7828 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
7829 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
7830 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
7831 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*);
7832 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
7833 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
7834 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*);
7835 SQLITE_PRIVATE int sqlite3BtreeCommitStmt(Btree*);
7836 SQLITE_PRIVATE int sqlite3BtreeRollbackStmt(Btree*);
7837 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
7838 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
7839 SQLITE_PRIVATE int sqlite3BtreeIsInStmt(Btree*);
7840 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
7841 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
7842 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *);
7843 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *, int, u8);
7844
7845 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
7846 SQLITE_PRIVATE const char *sqlite3BtreeGetDirname(Btree *);
7847 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
7848 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
7849
7850 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
7851
7852 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
7853 ** of the following flags:
7854 */
7855 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
7856 #define BTREE_ZERODATA   2    /* Table has keys only - no data */
7857 #define BTREE_LEAFDATA   4    /* Data stored in leaves only.  Implies INTKEY */
7858
7859 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
7860 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
7861 SQLITE_PRIVATE int sqlite3BtreeGetMeta(Btree*, int idx, u32 *pValue);
7862 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
7863 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
7864
7865 SQLITE_PRIVATE int sqlite3BtreeCursor(
7866   Btree*,                              /* BTree containing table to open */
7867   int iTable,                          /* Index of root page */
7868   int wrFlag,                          /* 1 for writing.  0 for read-only */
7869   struct KeyInfo*,                     /* First argument to compare function */
7870   BtCursor *pCursor                    /* Space to write cursor structure */
7871 );
7872 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
7873
7874 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
7875 SQLITE_PRIVATE int sqlite3BtreeMoveto(
7876   BtCursor*,
7877   const void *pKey,
7878   i64 nKey,
7879   int bias,
7880   int *pRes
7881 );
7882 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
7883   BtCursor*,
7884   UnpackedRecord *pUnKey,
7885   i64 intKey,
7886   int bias,
7887   int *pRes
7888 );
7889 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
7890 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
7891 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
7892                                   const void *pData, int nData,
7893                                   int nZero, int bias);
7894 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
7895 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
7896 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
7897 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
7898 SQLITE_PRIVATE int sqlite3BtreeFlags(BtCursor*);
7899 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
7900 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
7901 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
7902 SQLITE_PRIVATE sqlite3 *sqlite3BtreeCursorDb(const BtCursor*);
7903 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
7904 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
7905 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
7906 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
7907
7908 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
7909 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
7910
7911 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
7912 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
7913 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
7914
7915 #ifdef SQLITE_TEST
7916 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
7917 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
7918 #endif
7919
7920 /*
7921 ** If we are not using shared cache, then there is no need to
7922 ** use mutexes to access the BtShared structures.  So make the
7923 ** Enter and Leave procedures no-ops.
7924 */
7925 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
7926 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
7927 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
7928 #ifndef NDEBUG
7929   /* This routine is used inside assert() statements only. */
7930 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
7931 #endif
7932 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
7933 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
7934 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
7935 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
7936 #ifndef NDEBUG
7937   /* This routine is used inside assert() statements only. */
7938 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
7939 #endif
7940 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*);
7941 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*);
7942 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*);
7943 #else
7944 # define sqlite3BtreeEnter(X)
7945 # define sqlite3BtreeLeave(X)
7946 #ifndef NDEBUG
7947   /* This routine is used inside assert() statements only. */
7948 # define sqlite3BtreeHoldsMutex(X) 1
7949 #endif
7950 # define sqlite3BtreeEnterCursor(X)
7951 # define sqlite3BtreeLeaveCursor(X)
7952 # define sqlite3BtreeEnterAll(X)
7953 # define sqlite3BtreeLeaveAll(X)
7954 #ifndef NDEBUG
7955   /* This routine is used inside assert() statements only. */
7956 # define sqlite3BtreeHoldsAllMutexes(X) 1
7957 #endif
7958 # define sqlite3BtreeMutexArrayEnter(X)
7959 # define sqlite3BtreeMutexArrayLeave(X)
7960 # define sqlite3BtreeMutexArrayInsert(X,Y)
7961 #endif
7962
7963
7964 #endif /* _BTREE_H_ */
7965
7966 /************** End of btree.h ***********************************************/
7967 /************** Continuing where we left off in sqliteInt.h ******************/
7968 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
7969 /************** Begin file vdbe.h ********************************************/
7970 /*
7971 ** 2001 September 15
7972 **
7973 ** The author disclaims copyright to this source code.  In place of
7974 ** a legal notice, here is a blessing:
7975 **
7976 **    May you do good and not evil.
7977 **    May you find forgiveness for yourself and forgive others.
7978 **    May you share freely, never taking more than you give.
7979 **
7980 *************************************************************************
7981 ** Header file for the Virtual DataBase Engine (VDBE)
7982 **
7983 ** This header defines the interface to the virtual database engine
7984 ** or VDBE.  The VDBE implements an abstract machine that runs a
7985 ** simple program to access and modify the underlying database.
7986 **
7987 ** $Id: vdbe.h,v 1.139 2008/10/31 10:53:23 danielk1977 Exp $
7988 */
7989 #ifndef _SQLITE_VDBE_H_
7990 #define _SQLITE_VDBE_H_
7991
7992 /*
7993 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
7994 ** in the source file sqliteVdbe.c are allowed to see the insides
7995 ** of this structure.
7996 */
7997 typedef struct Vdbe Vdbe;
7998
7999 /*
8000 ** The names of the following types declared in vdbeInt.h are required
8001 ** for the VdbeOp definition.
8002 */
8003 typedef struct VdbeFunc VdbeFunc;
8004 typedef struct Mem Mem;
8005
8006 /*
8007 ** A single instruction of the virtual machine has an opcode
8008 ** and as many as three operands.  The instruction is recorded
8009 ** as an instance of the following structure:
8010 */
8011 struct VdbeOp {
8012   u8 opcode;          /* What operation to perform */
8013   signed char p4type; /* One of the P4_xxx constants for p4 */
8014   u8 opflags;         /* Not currently used */
8015   u8 p5;              /* Fifth parameter is an unsigned character */
8016   int p1;             /* First operand */
8017   int p2;             /* Second parameter (often the jump destination) */
8018   int p3;             /* The third parameter */
8019   union {             /* forth parameter */
8020     int i;                 /* Integer value if p4type==P4_INT32 */
8021     void *p;               /* Generic pointer */
8022     char *z;               /* Pointer to data for string (char array) types */
8023     i64 *pI64;             /* Used when p4type is P4_INT64 */
8024     double *pReal;         /* Used when p4type is P4_REAL */
8025     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
8026     VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
8027     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
8028     Mem *pMem;             /* Used when p4type is P4_MEM */
8029     sqlite3_vtab *pVtab;   /* Used when p4type is P4_VTAB */
8030     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
8031     int *ai;               /* Used when p4type is P4_INTARRAY */
8032   } p4;
8033 #ifdef SQLITE_DEBUG
8034   char *zComment;          /* Comment to improve readability */
8035 #endif
8036 #ifdef VDBE_PROFILE
8037   int cnt;                 /* Number of times this instruction was executed */
8038   u64 cycles;              /* Total time spent executing this instruction */
8039 #endif
8040 };
8041 typedef struct VdbeOp VdbeOp;
8042
8043 /*
8044 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
8045 ** it takes up less space.
8046 */
8047 struct VdbeOpList {
8048   u8 opcode;          /* What operation to perform */
8049   signed char p1;     /* First operand */
8050   signed char p2;     /* Second parameter (often the jump destination) */
8051   signed char p3;     /* Third parameter */
8052 };
8053 typedef struct VdbeOpList VdbeOpList;
8054
8055 /*
8056 ** Allowed values of VdbeOp.p3type
8057 */
8058 #define P4_NOTUSED    0   /* The P4 parameter is not used */
8059 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
8060 #define P4_STATIC   (-2)  /* Pointer to a static string */
8061 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
8062 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
8063 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
8064 #define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
8065 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
8066 #define P4_TRANSIENT (-9) /* P4 is a pointer to a transient string */
8067 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
8068 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
8069 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
8070 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
8071 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
8072 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
8073
8074 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
8075 ** is made.  That copy is freed when the Vdbe is finalized.  But if the
8076 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
8077 ** gets freed when the Vdbe is finalized so it still should be obtained
8078 ** from a single sqliteMalloc().  But no copy is made and the calling
8079 ** function should *not* try to free the KeyInfo.
8080 */
8081 #define P4_KEYINFO_HANDOFF (-16)
8082 #define P4_KEYINFO_STATIC  (-17)
8083
8084 /*
8085 ** The Vdbe.aColName array contains 5n Mem structures, where n is the 
8086 ** number of columns of data returned by the statement.
8087 */
8088 #define COLNAME_NAME     0
8089 #define COLNAME_DECLTYPE 1
8090 #define COLNAME_DATABASE 2
8091 #define COLNAME_TABLE    3
8092 #define COLNAME_COLUMN   4
8093 #ifdef SQLITE_ENABLE_COLUMN_METADATA
8094 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
8095 #else
8096 # ifdef SQLITE_OMIT_DECLTYPE
8097 #   define COLNAME_N      1      /* Store only the name */
8098 # else
8099 #   define COLNAME_N      2      /* Store the name and decltype */
8100 # endif
8101 #endif
8102
8103 /*
8104 ** The following macro converts a relative address in the p2 field
8105 ** of a VdbeOp structure into a negative number so that 
8106 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
8107 ** the macro again restores the address.
8108 */
8109 #define ADDR(X)  (-1-(X))
8110
8111 /*
8112 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
8113 ** header file that defines a number for each opcode used by the VDBE.
8114 */
8115 /************** Include opcodes.h in the middle of vdbe.h ********************/
8116 /************** Begin file opcodes.h *****************************************/
8117 /* Automatically generated.  Do not edit */
8118 /* See the mkopcodeh.awk script for details */
8119 #define OP_VNext                                1
8120 #define OP_Affinity                             2
8121 #define OP_Column                               3
8122 #define OP_SetCookie                            4
8123 #define OP_Real                               126   /* same as TK_FLOAT    */
8124 #define OP_Sequence                             5
8125 #define OP_MoveGt                               6
8126 #define OP_Ge                                  72   /* same as TK_GE       */
8127 #define OP_RowKey                               7
8128 #define OP_SCopy                                8
8129 #define OP_Eq                                  68   /* same as TK_EQ       */
8130 #define OP_OpenWrite                            9
8131 #define OP_NotNull                             66   /* same as TK_NOTNULL  */
8132 #define OP_If                                  10
8133 #define OP_ToInt                              142   /* same as TK_TO_INT   */
8134 #define OP_String8                             88   /* same as TK_STRING   */
8135 #define OP_VRowid                              11
8136 #define OP_CollSeq                             12
8137 #define OP_OpenRead                            13
8138 #define OP_Expire                              14
8139 #define OP_AutoCommit                          15
8140 #define OP_Gt                                  69   /* same as TK_GT       */
8141 #define OP_Pagecount                           17
8142 #define OP_IntegrityCk                         18
8143 #define OP_Sort                                19
8144 #define OP_Copy                                20
8145 #define OP_Trace                               21
8146 #define OP_Function                            22
8147 #define OP_IfNeg                               23
8148 #define OP_And                                 61   /* same as TK_AND      */
8149 #define OP_Subtract                            79   /* same as TK_MINUS    */
8150 #define OP_Noop                                24
8151 #define OP_Return                              25
8152 #define OP_Remainder                           82   /* same as TK_REM      */
8153 #define OP_NewRowid                            26
8154 #define OP_Multiply                            80   /* same as TK_STAR     */
8155 #define OP_Variable                            27
8156 #define OP_String                              28
8157 #define OP_RealAffinity                        29
8158 #define OP_VRename                             30
8159 #define OP_ParseSchema                         31
8160 #define OP_VOpen                               32
8161 #define OP_Close                               33
8162 #define OP_CreateIndex                         34
8163 #define OP_IsUnique                            35
8164 #define OP_NotFound                            36
8165 #define OP_Int64                               37
8166 #define OP_MustBeInt                           38
8167 #define OP_Halt                                39
8168 #define OP_Rowid                               40
8169 #define OP_IdxLT                               41
8170 #define OP_AddImm                              42
8171 #define OP_Statement                           43
8172 #define OP_RowData                             44
8173 #define OP_MemMax                              45
8174 #define OP_Or                                  60   /* same as TK_OR       */
8175 #define OP_NotExists                           46
8176 #define OP_Gosub                               47
8177 #define OP_Divide                              81   /* same as TK_SLASH    */
8178 #define OP_Integer                             48
8179 #define OP_ToNumeric                          141   /* same as TK_TO_NUMERIC*/
8180 #define OP_Prev                                49
8181 #define OP_Concat                              83   /* same as TK_CONCAT   */
8182 #define OP_BitAnd                              74   /* same as TK_BITAND   */
8183 #define OP_VColumn                             50
8184 #define OP_CreateTable                         51
8185 #define OP_Last                                52
8186 #define OP_IsNull                              65   /* same as TK_ISNULL   */
8187 #define OP_IncrVacuum                          53
8188 #define OP_IdxRowid                            54
8189 #define OP_ShiftRight                          77   /* same as TK_RSHIFT   */
8190 #define OP_ResetCount                          55
8191 #define OP_FifoWrite                           56
8192 #define OP_ContextPush                         57
8193 #define OP_Yield                               58
8194 #define OP_DropTrigger                         59
8195 #define OP_DropIndex                           62
8196 #define OP_IdxGE                               63
8197 #define OP_IdxDelete                           64
8198 #define OP_Vacuum                              73
8199 #define OP_MoveLe                              84
8200 #define OP_IfNot                               85
8201 #define OP_DropTable                           86
8202 #define OP_MakeRecord                          89
8203 #define OP_ToBlob                             140   /* same as TK_TO_BLOB  */
8204 #define OP_ResultRow                           90
8205 #define OP_Delete                              91
8206 #define OP_AggFinal                            92
8207 #define OP_Compare                             93
8208 #define OP_ShiftLeft                           76   /* same as TK_LSHIFT   */
8209 #define OP_Goto                                94
8210 #define OP_TableLock                           95
8211 #define OP_FifoRead                            96
8212 #define OP_Clear                               97
8213 #define OP_MoveLt                              98
8214 #define OP_Le                                  70   /* same as TK_LE       */
8215 #define OP_VerifyCookie                        99
8216 #define OP_AggStep                            100
8217 #define OP_ToText                             139   /* same as TK_TO_TEXT  */
8218 #define OP_Not                                 16   /* same as TK_NOT      */
8219 #define OP_ToReal                             143   /* same as TK_TO_REAL  */
8220 #define OP_SetNumColumns                      101
8221 #define OP_Transaction                        102
8222 #define OP_VFilter                            103
8223 #define OP_Ne                                  67   /* same as TK_NE       */
8224 #define OP_VDestroy                           104
8225 #define OP_ContextPop                         105
8226 #define OP_BitOr                               75   /* same as TK_BITOR    */
8227 #define OP_Next                               106
8228 #define OP_IdxInsert                          107
8229 #define OP_Lt                                  71   /* same as TK_LT       */
8230 #define OP_Insert                             108
8231 #define OP_Destroy                            109
8232 #define OP_ReadCookie                         110
8233 #define OP_ForceInt                           111
8234 #define OP_LoadAnalysis                       112
8235 #define OP_Explain                            113
8236 #define OP_OpenPseudo                         114
8237 #define OP_OpenEphemeral                      115
8238 #define OP_Null                               116
8239 #define OP_Move                               117
8240 #define OP_Blob                               118
8241 #define OP_Add                                 78   /* same as TK_PLUS     */
8242 #define OP_Rewind                             119
8243 #define OP_MoveGe                             120
8244 #define OP_VBegin                             121
8245 #define OP_VUpdate                            122
8246 #define OP_IfZero                             123
8247 #define OP_BitNot                              87   /* same as TK_BITNOT   */
8248 #define OP_VCreate                            124
8249 #define OP_Found                              125
8250 #define OP_IfPos                              127
8251 #define OP_NullRow                            128
8252 #define OP_Jump                               129
8253 #define OP_Permutation                        130
8254
8255 /* The following opcode values are never used */
8256 #define OP_NotUsed_131                        131
8257 #define OP_NotUsed_132                        132
8258 #define OP_NotUsed_133                        133
8259 #define OP_NotUsed_134                        134
8260 #define OP_NotUsed_135                        135
8261 #define OP_NotUsed_136                        136
8262 #define OP_NotUsed_137                        137
8263 #define OP_NotUsed_138                        138
8264
8265
8266 /* Properties such as "out2" or "jump" that are specified in
8267 ** comments following the "case" for each opcode in the vdbe.c
8268 ** are encoded into bitvectors as follows:
8269 */
8270 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
8271 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
8272 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
8273 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
8274 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
8275 #define OPFLG_OUT3            0x0020  /* out3:  P3 is an output */
8276 #define OPFLG_INITIALIZER {\
8277 /*   0 */ 0x00, 0x01, 0x00, 0x00, 0x10, 0x02, 0x11, 0x00,\
8278 /*   8 */ 0x00, 0x00, 0x05, 0x02, 0x00, 0x00, 0x00, 0x00,\
8279 /*  16 */ 0x04, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x05,\
8280 /*  24 */ 0x00, 0x04, 0x02, 0x02, 0x02, 0x04, 0x00, 0x00,\
8281 /*  32 */ 0x00, 0x00, 0x02, 0x11, 0x11, 0x02, 0x05, 0x00,\
8282 /*  40 */ 0x02, 0x11, 0x04, 0x00, 0x00, 0x0c, 0x11, 0x01,\
8283 /*  48 */ 0x02, 0x01, 0x00, 0x02, 0x01, 0x01, 0x02, 0x00,\
8284 /*  56 */ 0x04, 0x00, 0x00, 0x00, 0x2c, 0x2c, 0x00, 0x11,\
8285 /*  64 */ 0x00, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
8286 /*  72 */ 0x15, 0x00, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c,\
8287 /*  80 */ 0x2c, 0x2c, 0x2c, 0x2c, 0x11, 0x05, 0x00, 0x04,\
8288 /*  88 */ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00,\
8289 /*  96 */ 0x01, 0x00, 0x11, 0x00, 0x00, 0x00, 0x00, 0x01,\
8290 /* 104 */ 0x00, 0x00, 0x01, 0x08, 0x00, 0x02, 0x02, 0x05,\
8291 /* 112 */ 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x02, 0x01,\
8292 /* 120 */ 0x11, 0x00, 0x00, 0x05, 0x00, 0x11, 0x02, 0x05,\
8293 /* 128 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8294 /* 136 */ 0x00, 0x00, 0x00, 0x04, 0x04, 0x04, 0x04, 0x04,\
8295 }
8296
8297 /************** End of opcodes.h *********************************************/
8298 /************** Continuing where we left off in vdbe.h ***********************/
8299
8300 /*
8301 ** Prototypes for the VDBE interface.  See comments on the implementation
8302 ** for a description of what each of these routines does.
8303 */
8304 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
8305 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
8306 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
8307 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
8308 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
8309 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
8310 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
8311 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
8312 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
8313 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
8314 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
8315 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
8316 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
8317 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
8318 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
8319 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
8320 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
8321 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
8322 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int);
8323 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
8324 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
8325 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
8326 #ifdef SQLITE_DEBUG
8327 SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
8328 #endif
8329 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
8330 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
8331 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
8332 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
8333 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
8334 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
8335 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n);
8336 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
8337
8338 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
8339 SQLITE_PRIVATE int sqlite3VdbeReleaseMemory(int);
8340 #endif
8341 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,
8342                                         UnpackedRecord*,int);
8343 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
8344 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
8345
8346
8347 #ifndef NDEBUG
8348 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
8349 # define VdbeComment(X)  sqlite3VdbeComment X
8350 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
8351 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
8352 #else
8353 # define VdbeComment(X)
8354 # define VdbeNoopComment(X)
8355 #endif
8356
8357 #endif
8358
8359 /************** End of vdbe.h ************************************************/
8360 /************** Continuing where we left off in sqliteInt.h ******************/
8361 /************** Include pager.h in the middle of sqliteInt.h *****************/
8362 /************** Begin file pager.h *******************************************/
8363 /*
8364 ** 2001 September 15
8365 **
8366 ** The author disclaims copyright to this source code.  In place of
8367 ** a legal notice, here is a blessing:
8368 **
8369 **    May you do good and not evil.
8370 **    May you find forgiveness for yourself and forgive others.
8371 **    May you share freely, never taking more than you give.
8372 **
8373 *************************************************************************
8374 ** This header file defines the interface that the sqlite page cache
8375 ** subsystem.  The page cache subsystem reads and writes a file a page
8376 ** at a time and provides a journal for rollback.
8377 **
8378 ** @(#) $Id: pager.h,v 1.87 2008/11/19 10:22:33 danielk1977 Exp $
8379 */
8380
8381 #ifndef _PAGER_H_
8382 #define _PAGER_H_
8383
8384 /*
8385 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
8386 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
8387 */
8388 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
8389   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
8390 #endif
8391
8392 /*
8393 ** The type used to represent a page number.  The first page in a file
8394 ** is called page 1.  0 is used to represent "not a page".
8395 */
8396 typedef u32 Pgno;
8397
8398 /*
8399 ** Each open file is managed by a separate instance of the "Pager" structure.
8400 */
8401 typedef struct Pager Pager;
8402
8403 /*
8404 ** Handle type for pages.
8405 */
8406 typedef struct PgHdr DbPage;
8407
8408 /*
8409 ** Allowed values for the flags parameter to sqlite3PagerOpen().
8410 **
8411 ** NOTE: This values must match the corresponding BTREE_ values in btree.h.
8412 */
8413 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
8414 #define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */
8415
8416 /*
8417 ** Valid values for the second argument to sqlite3PagerLockingMode().
8418 */
8419 #define PAGER_LOCKINGMODE_QUERY      -1
8420 #define PAGER_LOCKINGMODE_NORMAL      0
8421 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
8422
8423 /*
8424 ** Valid values for the second argument to sqlite3PagerJournalMode().
8425 */
8426 #define PAGER_JOURNALMODE_QUERY      -1
8427 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
8428 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
8429 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
8430 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
8431 #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
8432
8433 /*
8434 ** See source code comments for a detailed description of the following
8435 ** routines:
8436 */
8437 SQLITE_PRIVATE int sqlite3PagerOpen(sqlite3_vfs *, Pager **ppPager, const char*, int,int,int);
8438 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
8439 SQLITE_PRIVATE void sqlite3PagerSetReiniter(Pager*, void(*)(DbPage*));
8440 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u16*);
8441 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
8442 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
8443 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
8444 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
8445 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
8446 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
8447 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
8448 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
8449 SQLITE_PRIVATE int sqlite3PagerRef(DbPage*);
8450 SQLITE_PRIVATE int sqlite3PagerUnref(DbPage*);
8451 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
8452 SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*, int*);
8453 SQLITE_PRIVATE int sqlite3PagerTruncate(Pager*,Pgno);
8454 SQLITE_PRIVATE int sqlite3PagerBegin(DbPage*, int exFlag);
8455 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, Pgno, int);
8456 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
8457 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
8458 SQLITE_PRIVATE int sqlite3PagerIsreadonly(Pager*);
8459 SQLITE_PRIVATE int sqlite3PagerStmtBegin(Pager*);
8460 SQLITE_PRIVATE int sqlite3PagerStmtCommit(Pager*);
8461 SQLITE_PRIVATE int sqlite3PagerStmtRollback(Pager*);
8462 SQLITE_PRIVATE void sqlite3PagerDontRollback(DbPage*);
8463 SQLITE_PRIVATE int sqlite3PagerDontWrite(DbPage*);
8464 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
8465 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int);
8466 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
8467 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
8468 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
8469 SQLITE_PRIVATE const char *sqlite3PagerDirname(Pager*);
8470 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
8471 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
8472 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
8473 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
8474 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
8475 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
8476 SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *, int);
8477 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
8478 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
8479 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
8480
8481 #ifdef SQLITE_HAS_CODEC
8482 SQLITE_PRIVATE   void sqlite3PagerSetCodec(Pager*,void*(*)(void*,void*,Pgno,int),void*);
8483 #endif
8484
8485 #if !defined(NDEBUG) || defined(SQLITE_TEST)
8486 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
8487 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
8488 #endif
8489
8490 #ifdef SQLITE_TEST
8491 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
8492 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
8493 SQLITE_PRIVATE   int sqlite3PagerIsMemdb(Pager*);
8494 #endif
8495
8496 #ifdef SQLITE_TEST
8497 void disable_simulated_io_errors(void);
8498 void enable_simulated_io_errors(void);
8499 #else
8500 # define disable_simulated_io_errors()
8501 # define enable_simulated_io_errors()
8502 #endif
8503
8504 #endif /* _PAGER_H_ */
8505
8506 /************** End of pager.h ***********************************************/
8507 /************** Continuing where we left off in sqliteInt.h ******************/
8508 /************** Include pcache.h in the middle of sqliteInt.h ****************/
8509 /************** Begin file pcache.h ******************************************/
8510 /*
8511 ** 2008 August 05
8512 **
8513 ** The author disclaims copyright to this source code.  In place of
8514 ** a legal notice, here is a blessing:
8515 **
8516 **    May you do good and not evil.
8517 **    May you find forgiveness for yourself and forgive others.
8518 **    May you share freely, never taking more than you give.
8519 **
8520 *************************************************************************
8521 ** This header file defines the interface that the sqlite page cache
8522 ** subsystem. 
8523 **
8524 ** @(#) $Id: pcache.h,v 1.16 2008/11/19 16:52:44 danielk1977 Exp $
8525 */
8526
8527 #ifndef _PCACHE_H_
8528
8529 typedef struct PgHdr PgHdr;
8530 typedef struct PCache PCache;
8531
8532 /*
8533 ** Every page in the cache is controlled by an instance of the following
8534 ** structure.
8535 */
8536 struct PgHdr {
8537   void *pData;                   /* Content of this page */
8538   void *pExtra;                  /* Extra content */
8539   PgHdr *pDirty;                 /* Transient list of dirty pages */
8540   Pgno pgno;                     /* Page number for this page */
8541   Pager *pPager;                 /* The pager this page is part of */
8542 #ifdef SQLITE_CHECK_PAGES
8543   u32 pageHash;                  /* Hash of page content */
8544 #endif
8545   u16 flags;                     /* PGHDR flags defined below */
8546
8547   /**********************************************************************
8548   ** Elements above are public.  All that follows is private to pcache.c
8549   ** and should not be accessed by other modules.
8550   */
8551   i16 nRef;                      /* Number of users of this page */
8552   PCache *pCache;                /* Cache that owns this page */
8553
8554   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
8555   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
8556 };
8557
8558 /* Bit values for PgHdr.flags */
8559 #define PGHDR_DIRTY             0x002  /* Page has changed */
8560 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
8561                                        ** writing this page to the database */
8562 #define PGHDR_NEED_READ         0x008  /* Content is unread */
8563 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
8564 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
8565
8566 /* Initialize and shutdown the page cache subsystem */
8567 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
8568 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
8569
8570 /* Page cache buffer management:
8571 ** These routines implement SQLITE_CONFIG_PAGECACHE.
8572 */
8573 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
8574
8575 /* Create a new pager cache.
8576 ** Under memory stress, invoke xStress to try to make pages clean.
8577 ** Only clean and unpinned pages can be reclaimed.
8578 */
8579 SQLITE_PRIVATE void sqlite3PcacheOpen(
8580   int szPage,                    /* Size of every page */
8581   int szExtra,                   /* Extra space associated with each page */
8582   int bPurgeable,                /* True if pages are on backing store */
8583   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
8584   void *pStress,                 /* Argument to xStress */
8585   PCache *pToInit                /* Preallocated space for the PCache */
8586 );
8587
8588 /* Modify the page-size after the cache has been created. */
8589 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
8590
8591 /* Return the size in bytes of a PCache object.  Used to preallocate
8592 ** storage space.
8593 */
8594 SQLITE_PRIVATE int sqlite3PcacheSize(void);
8595
8596 /* One release per successful fetch.  Page is pinned until released.
8597 ** Reference counted. 
8598 */
8599 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
8600 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
8601
8602 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
8603 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
8604 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
8605 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
8606
8607 /* Change a page number.  Used by incr-vacuum. */
8608 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
8609
8610 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
8611 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
8612
8613 /* Get a list of all dirty pages in the cache, sorted by page number */
8614 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
8615
8616 /* Reset and close the cache object */
8617 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
8618
8619 /* Clear flags from pages of the page cache */
8620 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
8621
8622 /* Discard the contents of the cache */
8623 SQLITE_PRIVATE int sqlite3PcacheClear(PCache*);
8624
8625 /* Return the total number of outstanding page references */
8626 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
8627
8628 /* Increment the reference count of an existing page */
8629 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
8630
8631 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
8632
8633 /* Return the total number of pages stored in the cache */
8634 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
8635
8636 #ifdef SQLITE_CHECK_PAGES
8637 /* Iterate through all dirty pages currently stored in the cache. This
8638 ** interface is only available if SQLITE_CHECK_PAGES is defined when the 
8639 ** library is built.
8640 */
8641 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
8642 #endif
8643
8644 /* Set and get the suggested cache-size for the specified pager-cache.
8645 **
8646 ** If no global maximum is configured, then the system attempts to limit
8647 ** the total number of pages cached by purgeable pager-caches to the sum
8648 ** of the suggested cache-sizes.
8649 */
8650 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
8651 #ifdef SQLITE_TEST
8652 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
8653 #endif
8654
8655 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
8656 /* Try to return memory used by the pcache module to the main memory heap */
8657 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
8658 #endif
8659
8660 #ifdef SQLITE_TEST
8661 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
8662 #endif
8663
8664 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
8665
8666 #endif /* _PCACHE_H_ */
8667
8668 /************** End of pcache.h **********************************************/
8669 /************** Continuing where we left off in sqliteInt.h ******************/
8670
8671 /************** Include os.h in the middle of sqliteInt.h ********************/
8672 /************** Begin file os.h **********************************************/
8673 /*
8674 ** 2001 September 16
8675 **
8676 ** The author disclaims copyright to this source code.  In place of
8677 ** a legal notice, here is a blessing:
8678 **
8679 **    May you do good and not evil.
8680 **    May you find forgiveness for yourself and forgive others.
8681 **    May you share freely, never taking more than you give.
8682 **
8683 ******************************************************************************
8684 **
8685 ** This header file (together with is companion C source-code file
8686 ** "os.c") attempt to abstract the underlying operating system so that
8687 ** the SQLite library will work on both POSIX and windows systems.
8688 **
8689 ** This header file is #include-ed by sqliteInt.h and thus ends up
8690 ** being included by every source file.
8691 **
8692 ** $Id: os.h,v 1.105 2008/06/26 10:41:19 danielk1977 Exp $
8693 */
8694 #ifndef _SQLITE_OS_H_
8695 #define _SQLITE_OS_H_
8696
8697 /*
8698 ** Figure out if we are dealing with Unix, Windows, or some other
8699 ** operating system.  After the following block of preprocess macros,
8700 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER 
8701 ** will defined to either 1 or 0.  One of the four will be 1.  The other 
8702 ** three will be 0.
8703 */
8704 #if defined(SQLITE_OS_OTHER)
8705 # if SQLITE_OS_OTHER==1
8706 #   undef SQLITE_OS_UNIX
8707 #   define SQLITE_OS_UNIX 0
8708 #   undef SQLITE_OS_WIN
8709 #   define SQLITE_OS_WIN 0
8710 #   undef SQLITE_OS_OS2
8711 #   define SQLITE_OS_OS2 0
8712 # else
8713 #   undef SQLITE_OS_OTHER
8714 # endif
8715 #endif
8716 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
8717 # define SQLITE_OS_OTHER 0
8718 # ifndef SQLITE_OS_WIN
8719 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
8720 #     define SQLITE_OS_WIN 1
8721 #     define SQLITE_OS_UNIX 0
8722 #     define SQLITE_OS_OS2 0
8723 #   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
8724 #     define SQLITE_OS_WIN 0
8725 #     define SQLITE_OS_UNIX 0
8726 #     define SQLITE_OS_OS2 1
8727 #   else
8728 #     define SQLITE_OS_WIN 0
8729 #     define SQLITE_OS_UNIX 1
8730 #     define SQLITE_OS_OS2 0
8731 #  endif
8732 # else
8733 #  define SQLITE_OS_UNIX 0
8734 #  define SQLITE_OS_OS2 0
8735 # endif
8736 #else
8737 # ifndef SQLITE_OS_WIN
8738 #  define SQLITE_OS_WIN 0
8739 # endif
8740 #endif
8741
8742 /*
8743 ** Determine if we are dealing with WindowsCE - which has a much
8744 ** reduced API.
8745 */
8746 #if defined(_WIN32_WCE)
8747 # define SQLITE_OS_WINCE 1
8748 #else
8749 # define SQLITE_OS_WINCE 0
8750 #endif
8751
8752
8753 /*
8754 ** Define the maximum size of a temporary filename
8755 */
8756 #if SQLITE_OS_WIN
8757 # include <windows.h>
8758 # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
8759 #elif SQLITE_OS_OS2
8760 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
8761 #  include <os2safe.h> /* has to be included before os2.h for linking to work */
8762 # endif
8763 # define INCL_DOSDATETIME
8764 # define INCL_DOSFILEMGR
8765 # define INCL_DOSERRORS
8766 # define INCL_DOSMISC
8767 # define INCL_DOSPROCESS
8768 # define INCL_DOSMODULEMGR
8769 # define INCL_DOSSEMAPHORES
8770 # include <os2.h>
8771 # include <uconv.h>
8772 # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
8773 #else
8774 # define SQLITE_TEMPNAME_SIZE 200
8775 #endif
8776
8777 /* If the SET_FULLSYNC macro is not defined above, then make it
8778 ** a no-op
8779 */
8780 #ifndef SET_FULLSYNC
8781 # define SET_FULLSYNC(x,y)
8782 #endif
8783
8784 /*
8785 ** The default size of a disk sector
8786 */
8787 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
8788 # define SQLITE_DEFAULT_SECTOR_SIZE 512
8789 #endif
8790
8791 /*
8792 ** Temporary files are named starting with this prefix followed by 16 random
8793 ** alphanumeric characters, and no file extension. They are stored in the
8794 ** OS's standard temporary file directory, and are deleted prior to exit.
8795 ** If sqlite is being embedded in another program, you may wish to change the
8796 ** prefix to reflect your program's name, so that if your program exits
8797 ** prematurely, old temporary files can be easily identified. This can be done
8798 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
8799 **
8800 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
8801 ** Mcafee started using SQLite in their anti-virus product and it
8802 ** started putting files with the "sqlite" name in the c:/temp folder.
8803 ** This annoyed many windows users.  Those users would then do a 
8804 ** Google search for "sqlite", find the telephone numbers of the
8805 ** developers and call to wake them up at night and complain.
8806 ** For this reason, the default name prefix is changed to be "sqlite" 
8807 ** spelled backwards.  So the temp files are still identified, but
8808 ** anybody smart enough to figure out the code is also likely smart
8809 ** enough to know that calling the developer will not help get rid
8810 ** of the file.
8811 */
8812 #ifndef SQLITE_TEMP_FILE_PREFIX
8813 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
8814 #endif
8815
8816 /*
8817 ** The following values may be passed as the second argument to
8818 ** sqlite3OsLock(). The various locks exhibit the following semantics:
8819 **
8820 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
8821 ** RESERVED:  A single process may hold a RESERVED lock on a file at
8822 **            any time. Other processes may hold and obtain new SHARED locks.
8823 ** PENDING:   A single process may hold a PENDING lock on a file at
8824 **            any one time. Existing SHARED locks may persist, but no new
8825 **            SHARED locks may be obtained by other processes.
8826 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
8827 **
8828 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
8829 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
8830 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
8831 ** sqlite3OsLock().
8832 */
8833 #define NO_LOCK         0
8834 #define SHARED_LOCK     1
8835 #define RESERVED_LOCK   2
8836 #define PENDING_LOCK    3
8837 #define EXCLUSIVE_LOCK  4
8838
8839 /*
8840 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
8841 **
8842 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
8843 ** those functions are not available.  So we use only LockFile() and
8844 ** UnlockFile().
8845 **
8846 ** LockFile() prevents not just writing but also reading by other processes.
8847 ** A SHARED_LOCK is obtained by locking a single randomly-chosen 
8848 ** byte out of a specific range of bytes. The lock byte is obtained at 
8849 ** random so two separate readers can probably access the file at the 
8850 ** same time, unless they are unlucky and choose the same lock byte.
8851 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
8852 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
8853 ** a single byte of the file that is designated as the reserved lock byte.
8854 ** A PENDING_LOCK is obtained by locking a designated byte different from
8855 ** the RESERVED_LOCK byte.
8856 **
8857 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
8858 ** which means we can use reader/writer locks.  When reader/writer locks
8859 ** are used, the lock is placed on the same range of bytes that is used
8860 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
8861 ** will support two or more Win95 readers or two or more WinNT readers.
8862 ** But a single Win95 reader will lock out all WinNT readers and a single
8863 ** WinNT reader will lock out all other Win95 readers.
8864 **
8865 ** The following #defines specify the range of bytes used for locking.
8866 ** SHARED_SIZE is the number of bytes available in the pool from which
8867 ** a random byte is selected for a shared lock.  The pool of bytes for
8868 ** shared locks begins at SHARED_FIRST. 
8869 **
8870 ** These #defines are available in sqlite_aux.h so that adaptors for
8871 ** connecting SQLite to other operating systems can use the same byte
8872 ** ranges for locking.  In particular, the same locking strategy and
8873 ** byte ranges are used for Unix.  This leaves open the possiblity of having
8874 ** clients on win95, winNT, and unix all talking to the same shared file
8875 ** and all locking correctly.  To do so would require that samba (or whatever
8876 ** tool is being used for file sharing) implements locks correctly between
8877 ** windows and unix.  I'm guessing that isn't likely to happen, but by
8878 ** using the same locking range we are at least open to the possibility.
8879 **
8880 ** Locking in windows is manditory.  For this reason, we cannot store
8881 ** actual data in the bytes used for locking.  The pager never allocates
8882 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
8883 ** that all locks will fit on a single page even at the minimum page size.
8884 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
8885 ** is set high so that we don't have to allocate an unused page except
8886 ** for very large databases.  But one should test the page skipping logic 
8887 ** by setting PENDING_BYTE low and running the entire regression suite.
8888 **
8889 ** Changing the value of PENDING_BYTE results in a subtly incompatible
8890 ** file format.  Depending on how it is changed, you might not notice
8891 ** the incompatibility right away, even running a full regression test.
8892 ** The default location of PENDING_BYTE is the first byte past the
8893 ** 1GB boundary.
8894 **
8895 */
8896 #ifndef SQLITE_TEST
8897 #define PENDING_BYTE      0x40000000  /* First byte past the 1GB boundary */
8898 #else
8899 SQLITE_API extern unsigned int sqlite3_pending_byte;
8900 #define PENDING_BYTE sqlite3_pending_byte
8901 #endif
8902
8903 #define RESERVED_BYTE     (PENDING_BYTE+1)
8904 #define SHARED_FIRST      (PENDING_BYTE+2)
8905 #define SHARED_SIZE       510
8906
8907 /* 
8908 ** Functions for accessing sqlite3_file methods 
8909 */
8910 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
8911 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
8912 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
8913 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
8914 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
8915 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
8916 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
8917 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
8918 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
8919 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
8920 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
8921 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
8922
8923 /* 
8924 ** Functions for accessing sqlite3_vfs methods 
8925 */
8926 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
8927 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
8928 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
8929 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
8930 #ifndef SQLITE_OMIT_LOAD_EXTENSION
8931 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
8932 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
8933 SQLITE_PRIVATE void *sqlite3OsDlSym(sqlite3_vfs *, void *, const char *);
8934 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
8935 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
8936 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
8937 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
8938 SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *, double*);
8939
8940 /*
8941 ** Convenience functions for opening and closing files using 
8942 ** sqlite3_malloc() to obtain space for the file-handle structure.
8943 */
8944 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
8945 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
8946
8947 #endif /* _SQLITE_OS_H_ */
8948
8949 /************** End of os.h **************************************************/
8950 /************** Continuing where we left off in sqliteInt.h ******************/
8951 /************** Include mutex.h in the middle of sqliteInt.h *****************/
8952 /************** Begin file mutex.h *******************************************/
8953 /*
8954 ** 2007 August 28
8955 **
8956 ** The author disclaims copyright to this source code.  In place of
8957 ** a legal notice, here is a blessing:
8958 **
8959 **    May you do good and not evil.
8960 **    May you find forgiveness for yourself and forgive others.
8961 **    May you share freely, never taking more than you give.
8962 **
8963 *************************************************************************
8964 **
8965 ** This file contains the common header for all mutex implementations.
8966 ** The sqliteInt.h header #includes this file so that it is available
8967 ** to all source files.  We break it out in an effort to keep the code
8968 ** better organized.
8969 **
8970 ** NOTE:  source files should *not* #include this header file directly.
8971 ** Source files should #include the sqliteInt.h file and let that file
8972 ** include this one indirectly.
8973 **
8974 ** $Id: mutex.h,v 1.9 2008/10/07 15:25:48 drh Exp $
8975 */
8976
8977
8978 /*
8979 ** Figure out what version of the code to use.  The choices are
8980 **
8981 **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
8982 **                             mutexes implemention cannot be overridden
8983 **                             at start-time.
8984 **
8985 **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
8986 **                             mutual exclusion is provided.  But this
8987 **                             implementation can be overridden at
8988 **                             start-time.
8989 **
8990 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
8991 **
8992 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
8993 **
8994 **   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
8995 */
8996 #if !SQLITE_THREADSAFE
8997 # define SQLITE_MUTEX_OMIT
8998 #endif
8999 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
9000 #  if SQLITE_OS_UNIX
9001 #    define SQLITE_MUTEX_PTHREADS
9002 #  elif SQLITE_OS_WIN
9003 #    define SQLITE_MUTEX_W32
9004 #  elif SQLITE_OS_OS2
9005 #    define SQLITE_MUTEX_OS2
9006 #  else
9007 #    define SQLITE_MUTEX_NOOP
9008 #  endif
9009 #endif
9010
9011 #ifdef SQLITE_MUTEX_OMIT
9012 /*
9013 ** If this is a no-op implementation, implement everything as macros.
9014 */
9015 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
9016 #define sqlite3_mutex_free(X)
9017 #define sqlite3_mutex_enter(X)
9018 #define sqlite3_mutex_try(X)      SQLITE_OK
9019 #define sqlite3_mutex_leave(X)
9020 #define sqlite3_mutex_held(X)     1
9021 #define sqlite3_mutex_notheld(X)  1
9022 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
9023 #define sqlite3MutexInit()        SQLITE_OK
9024 #define sqlite3MutexEnd()
9025 #endif /* defined(SQLITE_OMIT_MUTEX) */
9026
9027 /************** End of mutex.h ***********************************************/
9028 /************** Continuing where we left off in sqliteInt.h ******************/
9029
9030
9031 /*
9032 ** Each database file to be accessed by the system is an instance
9033 ** of the following structure.  There are normally two of these structures
9034 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
9035 ** aDb[1] is the database file used to hold temporary tables.  Additional
9036 ** databases may be attached.
9037 */
9038 struct Db {
9039   char *zName;         /* Name of this database */
9040   Btree *pBt;          /* The B*Tree structure for this database file */
9041   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
9042   u8 safety_level;     /* How aggressive at synching data to disk */
9043   void *pAux;               /* Auxiliary data.  Usually NULL */
9044   void (*xFreeAux)(void*);  /* Routine to free pAux */
9045   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
9046 };
9047
9048 /*
9049 ** An instance of the following structure stores a database schema.
9050 **
9051 ** If there are no virtual tables configured in this schema, the
9052 ** Schema.db variable is set to NULL. After the first virtual table
9053 ** has been added, it is set to point to the database connection 
9054 ** used to create the connection. Once a virtual table has been
9055 ** added to the Schema structure and the Schema.db variable populated, 
9056 ** only that database connection may use the Schema to prepare 
9057 ** statements.
9058 */
9059 struct Schema {
9060   int schema_cookie;   /* Database schema version number for this file */
9061   Hash tblHash;        /* All tables indexed by name */
9062   Hash idxHash;        /* All (named) indices indexed by name */
9063   Hash trigHash;       /* All triggers indexed by name */
9064   Hash aFKey;          /* Foreign keys indexed by to-table */
9065   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
9066   u8 file_format;      /* Schema format version for this file */
9067   u8 enc;              /* Text encoding used by this database */
9068   u16 flags;           /* Flags associated with this schema */
9069   int cache_size;      /* Number of pages to use in the cache */
9070 #ifndef SQLITE_OMIT_VIRTUALTABLE
9071   sqlite3 *db;         /* "Owner" connection. See comment above */
9072 #endif
9073 };
9074
9075 /*
9076 ** These macros can be used to test, set, or clear bits in the 
9077 ** Db.flags field.
9078 */
9079 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
9080 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
9081 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
9082 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
9083
9084 /*
9085 ** Allowed values for the DB.flags field.
9086 **
9087 ** The DB_SchemaLoaded flag is set after the database schema has been
9088 ** read into internal hash tables.
9089 **
9090 ** DB_UnresetViews means that one or more views have column names that
9091 ** have been filled out.  If the schema changes, these column names might
9092 ** changes and so the view will need to be reset.
9093 */
9094 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
9095 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
9096 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
9097
9098 /*
9099 ** The number of different kinds of things that can be limited
9100 ** using the sqlite3_limit() interface.
9101 */
9102 #define SQLITE_N_LIMIT (SQLITE_LIMIT_VARIABLE_NUMBER+1)
9103
9104 /*
9105 ** Lookaside malloc is a set of fixed-size buffers that can be used
9106 ** to satisify small transient memory allocation requests for objects
9107 ** associated with a particular database connection.  The use of
9108 ** lookaside malloc provides a significant performance enhancement
9109 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
9110 ** SQL statements.
9111 **
9112 ** The Lookaside structure holds configuration information about the
9113 ** lookaside malloc subsystem.  Each available memory allocation in
9114 ** the lookaside subsystem is stored on a linked list of LookasideSlot
9115 ** objects.
9116 */
9117 struct Lookaside {
9118   u16 sz;                 /* Size of each buffer in bytes */
9119   u8 bEnabled;            /* True if use lookaside.  False to ignore it */
9120   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
9121   int nOut;               /* Number of buffers currently checked out */
9122   int mxOut;              /* Highwater mark for nOut */
9123   LookasideSlot *pFree;   /* List of available buffers */
9124   void *pStart;           /* First byte of available memory space */
9125   void *pEnd;             /* First byte past end of available space */
9126 };
9127 struct LookasideSlot {
9128   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
9129 };
9130
9131 /*
9132 ** A hash table for function definitions.
9133 **
9134 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
9135 ** Collisions are on the FuncDef.pHash chain.
9136 */
9137 struct FuncDefHash {
9138   FuncDef *a[23];       /* Hash table for functions */
9139 };
9140
9141 /*
9142 ** Each database is an instance of the following structure.
9143 **
9144 ** The sqlite.lastRowid records the last insert rowid generated by an
9145 ** insert statement.  Inserts on views do not affect its value.  Each
9146 ** trigger has its own context, so that lastRowid can be updated inside
9147 ** triggers as usual.  The previous value will be restored once the trigger
9148 ** exits.  Upon entering a before or instead of trigger, lastRowid is no
9149 ** longer (since after version 2.8.12) reset to -1.
9150 **
9151 ** The sqlite.nChange does not count changes within triggers and keeps no
9152 ** context.  It is reset at start of sqlite3_exec.
9153 ** The sqlite.lsChange represents the number of changes made by the last
9154 ** insert, update, or delete statement.  It remains constant throughout the
9155 ** length of a statement and is then updated by OP_SetCounts.  It keeps a
9156 ** context stack just like lastRowid so that the count of changes
9157 ** within a trigger is not seen outside the trigger.  Changes to views do not
9158 ** affect the value of lsChange.
9159 ** The sqlite.csChange keeps track of the number of current changes (since
9160 ** the last statement) and is used to update sqlite_lsChange.
9161 **
9162 ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
9163 ** store the most recent error code and, if applicable, string. The
9164 ** internal function sqlite3Error() is used to set these variables
9165 ** consistently.
9166 */
9167 struct sqlite3 {
9168   sqlite3_vfs *pVfs;            /* OS Interface */
9169   int nDb;                      /* Number of backends currently in use */
9170   Db *aDb;                      /* All backends */
9171   int flags;                    /* Miscellanous flags. See below */
9172   int openFlags;                /* Flags passed to sqlite3_vfs.xOpen() */
9173   int errCode;                  /* Most recent error code (SQLITE_*) */
9174   int errMask;                  /* & result codes with this before returning */
9175   u8 autoCommit;                /* The auto-commit flag. */
9176   u8 temp_store;                /* 1: file 2: memory 0: default */
9177   u8 mallocFailed;              /* True if we have seen a malloc failure */
9178   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
9179   u8 dfltJournalMode;           /* Default journal mode for attached dbs */
9180   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
9181   int nextPagesize;             /* Pagesize after VACUUM if >0 */
9182   int nTable;                   /* Number of tables in the database */
9183   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
9184   i64 lastRowid;                /* ROWID of most recent insert (see above) */
9185   i64 priorNewRowid;            /* Last randomly generated ROWID */
9186   u32 magic;                    /* Magic number for detect library misuse */
9187   int nChange;                  /* Value returned by sqlite3_changes() */
9188   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
9189   sqlite3_mutex *mutex;         /* Connection mutex */
9190   int aLimit[SQLITE_N_LIMIT];   /* Limits */
9191   struct sqlite3InitInfo {      /* Information used during initialization */
9192     int iDb;                    /* When back is being initialized */
9193     int newTnum;                /* Rootpage of table being initialized */
9194     u8 busy;                    /* TRUE if currently initializing */
9195   } init;
9196   int nExtension;               /* Number of loaded extensions */
9197   void **aExtension;            /* Array of shared libraray handles */
9198   struct Vdbe *pVdbe;           /* List of active virtual machines */
9199   int activeVdbeCnt;            /* Number of vdbes currently executing */
9200   int writeVdbeCnt;             /* Number of active VDBEs that are writing */
9201   void (*xTrace)(void*,const char*);        /* Trace function */
9202   void *pTraceArg;                          /* Argument to the trace function */
9203   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
9204   void *pProfileArg;                        /* Argument to profile function */
9205   void *pCommitArg;                 /* Argument to xCommitCallback() */   
9206   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
9207   void *pRollbackArg;               /* Argument to xRollbackCallback() */   
9208   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
9209   void *pUpdateArg;
9210   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
9211   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
9212   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
9213   void *pCollNeededArg;
9214   sqlite3_value *pErr;          /* Most recent error message */
9215   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
9216   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
9217   union {
9218     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
9219     double notUsed1;            /* Spacer */
9220   } u1;
9221   Lookaside lookaside;          /* Lookaside malloc configuration */
9222 #ifndef SQLITE_OMIT_AUTHORIZATION
9223   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
9224                                 /* Access authorization function */
9225   void *pAuthArg;               /* 1st argument to the access auth function */
9226 #endif
9227 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9228   int (*xProgress)(void *);     /* The progress callback */
9229   void *pProgressArg;           /* Argument to the progress callback */
9230   int nProgressOps;             /* Number of opcodes for progress callback */
9231 #endif
9232 #ifndef SQLITE_OMIT_VIRTUALTABLE
9233   Hash aModule;                 /* populated by sqlite3_create_module() */
9234   Table *pVTab;                 /* vtab with active Connect/Create method */
9235   sqlite3_vtab **aVTrans;       /* Virtual tables with open transactions */
9236   int nVTrans;                  /* Allocated size of aVTrans */
9237 #endif
9238   FuncDefHash aFunc;            /* Hash table of connection functions */
9239   Hash aCollSeq;                /* All collating sequences */
9240   BusyHandler busyHandler;      /* Busy callback */
9241   int busyTimeout;              /* Busy handler timeout, in msec */
9242   Db aDbStatic[2];              /* Static space for the 2 default backends */
9243 #ifdef SQLITE_SSE
9244   sqlite3_stmt *pFetch;         /* Used by SSE to fetch stored statements */
9245 #endif
9246 };
9247
9248 /*
9249 ** A macro to discover the encoding of a database.
9250 */
9251 #define ENC(db) ((db)->aDb[0].pSchema->enc)
9252
9253 /*
9254 ** Possible values for the sqlite.flags and or Db.flags fields.
9255 **
9256 ** On sqlite.flags, the SQLITE_InTrans value means that we have
9257 ** executed a BEGIN.  On Db.flags, SQLITE_InTrans means a statement
9258 ** transaction is active on that particular database file.
9259 */
9260 #define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
9261 #define SQLITE_InTrans        0x00000008  /* True if in a transaction */
9262 #define SQLITE_InternChanges  0x00000010  /* Uncommitted Hash table changes */
9263 #define SQLITE_FullColNames   0x00000020  /* Show full column names on SELECT */
9264 #define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
9265 #define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
9266                                           /*   DELETE, or UPDATE and return */
9267                                           /*   the count using a callback. */
9268 #define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
9269                                           /*   result set is empty */
9270 #define SQLITE_SqlTrace       0x00000200  /* Debug print SQL as it executes */
9271 #define SQLITE_VdbeListing    0x00000400  /* Debug listings of VDBE programs */
9272 #define SQLITE_WriteSchema    0x00000800  /* OK to update SQLITE_MASTER */
9273 #define SQLITE_NoReadlock     0x00001000  /* Readlocks are omitted when 
9274                                           ** accessing read-only databases */
9275 #define SQLITE_IgnoreChecks   0x00002000  /* Do not enforce check constraints */
9276 #define SQLITE_ReadUncommitted 0x00004000 /* For shared-cache mode */
9277 #define SQLITE_LegacyFileFmt  0x00008000  /* Create new databases in format 1 */
9278 #define SQLITE_FullFSync      0x00010000  /* Use full fsync on the backend */
9279 #define SQLITE_LoadExtension  0x00020000  /* Enable load_extension */
9280
9281 #define SQLITE_RecoveryMode   0x00040000  /* Ignore schema errors */
9282 #define SQLITE_SharedCache    0x00080000  /* Cache sharing is enabled */
9283 #define SQLITE_Vtab           0x00100000  /* There exists a virtual table */
9284
9285 /*
9286 ** Possible values for the sqlite.magic field.
9287 ** The numbers are obtained at random and have no special meaning, other
9288 ** than being distinct from one another.
9289 */
9290 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
9291 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
9292 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
9293 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
9294 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
9295
9296 /*
9297 ** Each SQL function is defined by an instance of the following
9298 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
9299 ** hash table.  When multiple functions have the same name, the hash table
9300 ** points to a linked list of these structures.
9301 */
9302 struct FuncDef {
9303   i16 nArg;            /* Number of arguments.  -1 means unlimited */
9304   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
9305   u8 flags;            /* Some combination of SQLITE_FUNC_* */
9306   void *pUserData;     /* User data parameter */
9307   FuncDef *pNext;      /* Next function with same name */
9308   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
9309   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
9310   void (*xFinalize)(sqlite3_context*);                /* Aggregate finializer */
9311   char *zName;         /* SQL name of the function. */
9312   FuncDef *pHash;      /* Next with a different name but the same hash */
9313 };
9314
9315 /*
9316 ** Possible values for FuncDef.flags
9317 */
9318 #define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
9319 #define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
9320 #define SQLITE_FUNC_EPHEM    0x04 /* Ephermeral.  Delete with VDBE */
9321 #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
9322
9323 /*
9324 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
9325 ** used to create the initializers for the FuncDef structures.
9326 **
9327 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
9328 **     Used to create a scalar function definition of a function zName 
9329 **     implemented by C function xFunc that accepts nArg arguments. The
9330 **     value passed as iArg is cast to a (void*) and made available
9331 **     as the user-data (sqlite3_user_data()) for the function. If 
9332 **     argument bNC is true, then the FuncDef.needCollate flag is set.
9333 **
9334 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
9335 **     Used to create an aggregate function definition implemented by
9336 **     the C functions xStep and xFinal. The first four parameters
9337 **     are interpreted in the same way as the first 4 parameters to
9338 **     FUNCTION().
9339 **
9340 **   LIKEFUNC(zName, nArg, pArg, flags)
9341 **     Used to create a scalar function definition of a function zName 
9342 **     that accepts nArg arguments and is implemented by a call to C 
9343 **     function likeFunc. Argument pArg is cast to a (void *) and made
9344 **     available as the function user-data (sqlite3_user_data()). The
9345 **     FuncDef.flags variable is set to the value passed as the flags
9346 **     parameter.
9347 */
9348 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
9349   {nArg, SQLITE_UTF8, bNC*8, SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0}
9350 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
9351   {nArg, SQLITE_UTF8, bNC*8, pArg, 0, xFunc, 0, 0, #zName, 0}
9352 #define LIKEFUNC(zName, nArg, arg, flags) \
9353   {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0}
9354 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
9355   {nArg, SQLITE_UTF8, nc*8, SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0}
9356
9357
9358 /*
9359 ** Each SQLite module (virtual table definition) is defined by an
9360 ** instance of the following structure, stored in the sqlite3.aModule
9361 ** hash table.
9362 */
9363 struct Module {
9364   const sqlite3_module *pModule;       /* Callback pointers */
9365   const char *zName;                   /* Name passed to create_module() */
9366   void *pAux;                          /* pAux passed to create_module() */
9367   void (*xDestroy)(void *);            /* Module destructor function */
9368 };
9369
9370 /*
9371 ** information about each column of an SQL table is held in an instance
9372 ** of this structure.
9373 */
9374 struct Column {
9375   char *zName;     /* Name of this column */
9376   Expr *pDflt;     /* Default value of this column */
9377   char *zType;     /* Data type for this column */
9378   char *zColl;     /* Collating sequence.  If NULL, use the default */
9379   u8 notNull;      /* True if there is a NOT NULL constraint */
9380   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
9381   char affinity;   /* One of the SQLITE_AFF_... values */
9382 #ifndef SQLITE_OMIT_VIRTUALTABLE
9383   u8 isHidden;     /* True if this column is 'hidden' */
9384 #endif
9385 };
9386
9387 /*
9388 ** A "Collating Sequence" is defined by an instance of the following
9389 ** structure. Conceptually, a collating sequence consists of a name and
9390 ** a comparison routine that defines the order of that sequence.
9391 **
9392 ** There may two seperate implementations of the collation function, one
9393 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
9394 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
9395 ** native byte order. When a collation sequence is invoked, SQLite selects
9396 ** the version that will require the least expensive encoding
9397 ** translations, if any.
9398 **
9399 ** The CollSeq.pUser member variable is an extra parameter that passed in
9400 ** as the first argument to the UTF-8 comparison function, xCmp.
9401 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
9402 ** xCmp16.
9403 **
9404 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
9405 ** collating sequence is undefined.  Indices built on an undefined
9406 ** collating sequence may not be read or written.
9407 */
9408 struct CollSeq {
9409   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
9410   u8 enc;               /* Text encoding handled by xCmp() */
9411   u8 type;              /* One of the SQLITE_COLL_... values below */
9412   void *pUser;          /* First argument to xCmp() */
9413   int (*xCmp)(void*,int, const void*, int, const void*);
9414   void (*xDel)(void*);  /* Destructor for pUser */
9415 };
9416
9417 /*
9418 ** Allowed values of CollSeq.type:
9419 */
9420 #define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
9421 #define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
9422 #define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
9423 #define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
9424
9425 /*
9426 ** A sort order can be either ASC or DESC.
9427 */
9428 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
9429 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
9430
9431 /*
9432 ** Column affinity types.
9433 **
9434 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
9435 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
9436 ** the speed a little by numbering the values consecutively.  
9437 **
9438 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
9439 ** when multiple affinity types are concatenated into a string and
9440 ** used as the P4 operand, they will be more readable.
9441 **
9442 ** Note also that the numeric types are grouped together so that testing
9443 ** for a numeric type is a single comparison.
9444 */
9445 #define SQLITE_AFF_TEXT     'a'
9446 #define SQLITE_AFF_NONE     'b'
9447 #define SQLITE_AFF_NUMERIC  'c'
9448 #define SQLITE_AFF_INTEGER  'd'
9449 #define SQLITE_AFF_REAL     'e'
9450
9451 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
9452
9453 /*
9454 ** The SQLITE_AFF_MASK values masks off the significant bits of an
9455 ** affinity value. 
9456 */
9457 #define SQLITE_AFF_MASK     0x67
9458
9459 /*
9460 ** Additional bit values that can be ORed with an affinity without
9461 ** changing the affinity.
9462 */
9463 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
9464 #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
9465
9466 /*
9467 ** Each SQL table is represented in memory by an instance of the
9468 ** following structure.
9469 **
9470 ** Table.zName is the name of the table.  The case of the original
9471 ** CREATE TABLE statement is stored, but case is not significant for
9472 ** comparisons.
9473 **
9474 ** Table.nCol is the number of columns in this table.  Table.aCol is a
9475 ** pointer to an array of Column structures, one for each column.
9476 **
9477 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
9478 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
9479 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
9480 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
9481 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
9482 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
9483 ** the table has any PRIMARY KEY, INTEGER or otherwise.
9484 **
9485 ** Table.tnum is the page number for the root BTree page of the table in the
9486 ** database file.  If Table.iDb is the index of the database table backend
9487 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
9488 ** holds temporary tables and indices.  If TF_Ephemeral is set
9489 ** then the table is stored in a file that is automatically deleted
9490 ** when the VDBE cursor to the table is closed.  In this case Table.tnum 
9491 ** refers VDBE cursor number that holds the table open, not to the root
9492 ** page number.  Transient tables are used to hold the results of a
9493 ** sub-query that appears instead of a real table name in the FROM clause 
9494 ** of a SELECT statement.
9495 */
9496 struct Table {
9497   sqlite3 *db;         /* Associated database connection.  Might be NULL. */
9498   char *zName;         /* Name of the table or view */
9499   int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
9500   int nCol;            /* Number of columns in this table */
9501   Column *aCol;        /* Information about each column */
9502   Index *pIndex;       /* List of SQL indexes on this table. */
9503   int tnum;            /* Root BTree node for this table (see note above) */
9504   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
9505   u16 nRef;            /* Number of pointers to this Table */
9506   u8 tabFlags;         /* Mask of TF_* values */
9507   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
9508   Trigger *pTrigger;   /* List of SQL triggers on this table */
9509   FKey *pFKey;         /* Linked list of all foreign keys in this table */
9510   char *zColAff;       /* String defining the affinity of each column */
9511 #ifndef SQLITE_OMIT_CHECK
9512   Expr *pCheck;        /* The AND of all CHECK constraints */
9513 #endif
9514 #ifndef SQLITE_OMIT_ALTERTABLE
9515   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
9516 #endif
9517 #ifndef SQLITE_OMIT_VIRTUALTABLE
9518   Module *pMod;        /* Pointer to the implementation of the module */
9519   sqlite3_vtab *pVtab; /* Pointer to the module instance */
9520   int nModuleArg;      /* Number of arguments to the module */
9521   char **azModuleArg;  /* Text of all module args. [0] is module name */
9522 #endif
9523   Schema *pSchema;     /* Schema that contains this table */
9524   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
9525 };
9526
9527 /*
9528 ** Allowed values for Tabe.tabFlags.
9529 */
9530 #define TF_Readonly        0x01    /* Read-only system table */
9531 #define TF_Ephemeral       0x02    /* An emphermal table */
9532 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
9533 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
9534 #define TF_Virtual         0x10    /* Is a virtual table */
9535 #define TF_NeedMetadata    0x20    /* aCol[].zType and aCol[].pColl missing */
9536
9537
9538
9539 /*
9540 ** Test to see whether or not a table is a virtual table.  This is
9541 ** done as a macro so that it will be optimized out when virtual
9542 ** table support is omitted from the build.
9543 */
9544 #ifndef SQLITE_OMIT_VIRTUALTABLE
9545 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
9546 #  define IsHiddenColumn(X) ((X)->isHidden)
9547 #else
9548 #  define IsVirtual(X)      0
9549 #  define IsHiddenColumn(X) 0
9550 #endif
9551
9552 /*
9553 ** Each foreign key constraint is an instance of the following structure.
9554 **
9555 ** A foreign key is associated with two tables.  The "from" table is
9556 ** the table that contains the REFERENCES clause that creates the foreign
9557 ** key.  The "to" table is the table that is named in the REFERENCES clause.
9558 ** Consider this example:
9559 **
9560 **     CREATE TABLE ex1(
9561 **       a INTEGER PRIMARY KEY,
9562 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
9563 **     );
9564 **
9565 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
9566 **
9567 ** Each REFERENCES clause generates an instance of the following structure
9568 ** which is attached to the from-table.  The to-table need not exist when
9569 ** the from-table is created.  The existance of the to-table is not checked
9570 ** until an attempt is made to insert data into the from-table.
9571 **
9572 ** The sqlite.aFKey hash table stores pointers to this structure
9573 ** given the name of a to-table.  For each to-table, all foreign keys
9574 ** associated with that table are on a linked list using the FKey.pNextTo
9575 ** field.
9576 */
9577 struct FKey {
9578   Table *pFrom;     /* The table that constains the REFERENCES clause */
9579   FKey *pNextFrom;  /* Next foreign key in pFrom */
9580   char *zTo;        /* Name of table that the key points to */
9581   FKey *pNextTo;    /* Next foreign key that points to zTo */
9582   int nCol;         /* Number of columns in this key */
9583   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
9584     int iFrom;         /* Index of column in pFrom */
9585     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
9586   } *aCol;          /* One entry for each of nCol column s */
9587   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
9588   u8 updateConf;    /* How to resolve conflicts that occur on UPDATE */
9589   u8 deleteConf;    /* How to resolve conflicts that occur on DELETE */
9590   u8 insertConf;    /* How to resolve conflicts that occur on INSERT */
9591 };
9592
9593 /*
9594 ** SQLite supports many different ways to resolve a constraint
9595 ** error.  ROLLBACK processing means that a constraint violation
9596 ** causes the operation in process to fail and for the current transaction
9597 ** to be rolled back.  ABORT processing means the operation in process
9598 ** fails and any prior changes from that one operation are backed out,
9599 ** but the transaction is not rolled back.  FAIL processing means that
9600 ** the operation in progress stops and returns an error code.  But prior
9601 ** changes due to the same operation are not backed out and no rollback
9602 ** occurs.  IGNORE means that the particular row that caused the constraint
9603 ** error is not inserted or updated.  Processing continues and no error
9604 ** is returned.  REPLACE means that preexisting database rows that caused
9605 ** a UNIQUE constraint violation are removed so that the new insert or
9606 ** update can proceed.  Processing continues and no error is reported.
9607 **
9608 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
9609 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
9610 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
9611 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
9612 ** referenced table row is propagated into the row that holds the
9613 ** foreign key.
9614 ** 
9615 ** The following symbolic values are used to record which type
9616 ** of action to take.
9617 */
9618 #define OE_None     0   /* There is no constraint to check */
9619 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
9620 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
9621 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
9622 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
9623 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
9624
9625 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
9626 #define OE_SetNull  7   /* Set the foreign key value to NULL */
9627 #define OE_SetDflt  8   /* Set the foreign key value to its default */
9628 #define OE_Cascade  9   /* Cascade the changes */
9629
9630 #define OE_Default  99  /* Do whatever the default action is */
9631
9632
9633 /*
9634 ** An instance of the following structure is passed as the first
9635 ** argument to sqlite3VdbeKeyCompare and is used to control the 
9636 ** comparison of the two index keys.
9637 */
9638 struct KeyInfo {
9639   sqlite3 *db;        /* The database connection */
9640   u8 enc;             /* Text encoding - one of the TEXT_Utf* values */
9641   u16 nField;         /* Number of entries in aColl[] */
9642   u8 *aSortOrder;     /* If defined an aSortOrder[i] is true, sort DESC */
9643   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
9644 };
9645
9646 /*
9647 ** An instance of the following structure holds information about a
9648 ** single index record that has already been parsed out into individual
9649 ** values.
9650 **
9651 ** A record is an object that contains one or more fields of data.
9652 ** Records are used to store the content of a table row and to store
9653 ** the key of an index.  A blob encoding of a record is created by
9654 ** the OP_MakeRecord opcode of the VDBE and is disassemblied by the
9655 ** OP_Column opcode.
9656 **
9657 ** This structure holds a record that has already been disassembled
9658 ** into its constitutent fields.
9659 */
9660 struct UnpackedRecord {
9661   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
9662   u16 nField;         /* Number of entries in apMem[] */
9663   u16 flags;          /* Boolean settings.  UNPACKED_... below */
9664   Mem *aMem;          /* Values */
9665 };
9666
9667 /*
9668 ** Allowed values of UnpackedRecord.flags
9669 */
9670 #define UNPACKED_NEED_FREE     0x0001  /* Memory is from sqlite3Malloc() */
9671 #define UNPACKED_NEED_DESTROY  0x0002  /* apMem[]s should all be destroyed */
9672 #define UNPACKED_IGNORE_ROWID  0x0004  /* Ignore trailing rowid on key1 */
9673 #define UNPACKED_INCRKEY       0x0008  /* Make this key an epsilon larger */
9674 #define UNPACKED_PREFIX_MATCH  0x0010  /* A prefix match is considered OK */
9675
9676 /*
9677 ** Each SQL index is represented in memory by an
9678 ** instance of the following structure.
9679 **
9680 ** The columns of the table that are to be indexed are described
9681 ** by the aiColumn[] field of this structure.  For example, suppose
9682 ** we have the following table and index:
9683 **
9684 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
9685 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
9686 **
9687 ** In the Table structure describing Ex1, nCol==3 because there are
9688 ** three columns in the table.  In the Index structure describing
9689 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
9690 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
9691 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
9692 ** The second column to be indexed (c1) has an index of 0 in
9693 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
9694 **
9695 ** The Index.onError field determines whether or not the indexed columns
9696 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
9697 ** it means this is not a unique index.  Otherwise it is a unique index
9698 ** and the value of Index.onError indicate the which conflict resolution 
9699 ** algorithm to employ whenever an attempt is made to insert a non-unique
9700 ** element.
9701 */
9702 struct Index {
9703   char *zName;     /* Name of this index */
9704   int nColumn;     /* Number of columns in the table used by this index */
9705   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
9706   unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
9707   Table *pTable;   /* The SQL table being indexed */
9708   int tnum;        /* Page containing root of this index in database file */
9709   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
9710   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
9711   char *zColAff;   /* String defining the affinity of each column */
9712   Index *pNext;    /* The next index associated with the same table */
9713   Schema *pSchema; /* Schema containing this index */
9714   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
9715   char **azColl;   /* Array of collation sequence names for index */
9716 };
9717
9718 /*
9719 ** Each token coming out of the lexer is an instance of
9720 ** this structure.  Tokens are also used as part of an expression.
9721 **
9722 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
9723 ** may contain random values.  Do not make any assuptions about Token.dyn
9724 ** and Token.n when Token.z==0.
9725 */
9726 struct Token {
9727   const unsigned char *z; /* Text of the token.  Not NULL-terminated! */
9728   unsigned dyn  : 1;      /* True for malloced memory, false for static */
9729   unsigned n    : 31;     /* Number of characters in this token */
9730 };
9731
9732 /*
9733 ** An instance of this structure contains information needed to generate
9734 ** code for a SELECT that contains aggregate functions.
9735 **
9736 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
9737 ** pointer to this structure.  The Expr.iColumn field is the index in
9738 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
9739 ** code for that node.
9740 **
9741 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
9742 ** original Select structure that describes the SELECT statement.  These
9743 ** fields do not need to be freed when deallocating the AggInfo structure.
9744 */
9745 struct AggInfo {
9746   u8 directMode;          /* Direct rendering mode means take data directly
9747                           ** from source tables rather than from accumulators */
9748   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
9749                           ** than the source table */
9750   int sortingIdx;         /* Cursor number of the sorting index */
9751   ExprList *pGroupBy;     /* The group by clause */
9752   int nSortingColumn;     /* Number of columns in the sorting index */
9753   struct AggInfo_col {    /* For each column used in source tables */
9754     Table *pTab;             /* Source table */
9755     int iTable;              /* Cursor number of the source table */
9756     int iColumn;             /* Column number within the source table */
9757     int iSorterColumn;       /* Column number in the sorting index */
9758     int iMem;                /* Memory location that acts as accumulator */
9759     Expr *pExpr;             /* The original expression */
9760   } *aCol;
9761   int nColumn;            /* Number of used entries in aCol[] */
9762   int nColumnAlloc;       /* Number of slots allocated for aCol[] */
9763   int nAccumulator;       /* Number of columns that show through to the output.
9764                           ** Additional columns are used only as parameters to
9765                           ** aggregate functions */
9766   struct AggInfo_func {   /* For each aggregate function */
9767     Expr *pExpr;             /* Expression encoding the function */
9768     FuncDef *pFunc;          /* The aggregate function implementation */
9769     int iMem;                /* Memory location that acts as accumulator */
9770     int iDistinct;           /* Ephermeral table used to enforce DISTINCT */
9771   } *aFunc;
9772   int nFunc;              /* Number of entries in aFunc[] */
9773   int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
9774 };
9775
9776 /*
9777 ** Each node of an expression in the parse tree is an instance
9778 ** of this structure.
9779 **
9780 ** Expr.op is the opcode.  The integer parser token codes are reused
9781 ** as opcodes here.  For example, the parser defines TK_GE to be an integer
9782 ** code representing the ">=" operator.  This same integer code is reused
9783 ** to represent the greater-than-or-equal-to operator in the expression
9784 ** tree.
9785 **
9786 ** Expr.pRight and Expr.pLeft are subexpressions.  Expr.pList is a list
9787 ** of argument if the expression is a function.
9788 **
9789 ** Expr.token is the operator token for this node.  For some expressions
9790 ** that have subexpressions, Expr.token can be the complete text that gave
9791 ** rise to the Expr.  In the latter case, the token is marked as being
9792 ** a compound token.
9793 **
9794 ** An expression of the form ID or ID.ID refers to a column in a table.
9795 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
9796 ** the integer cursor number of a VDBE cursor pointing to that table and
9797 ** Expr.iColumn is the column number for the specific column.  If the
9798 ** expression is used as a result in an aggregate SELECT, then the
9799 ** value is also stored in the Expr.iAgg column in the aggregate so that
9800 ** it can be accessed after all aggregates are computed.
9801 **
9802 ** If the expression is a function, the Expr.iTable is an integer code
9803 ** representing which function.  If the expression is an unbound variable
9804 ** marker (a question mark character '?' in the original SQL) then the
9805 ** Expr.iTable holds the index number for that variable.
9806 **
9807 ** If the expression is a subquery then Expr.iColumn holds an integer
9808 ** register number containing the result of the subquery.  If the
9809 ** subquery gives a constant result, then iTable is -1.  If the subquery
9810 ** gives a different answer at different times during statement processing
9811 ** then iTable is the address of a subroutine that computes the subquery.
9812 **
9813 ** The Expr.pSelect field points to a SELECT statement.  The SELECT might
9814 ** be the right operand of an IN operator.  Or, if a scalar SELECT appears
9815 ** in an expression the opcode is TK_SELECT and Expr.pSelect is the only
9816 ** operand.
9817 **
9818 ** If the Expr is of type OP_Column, and the table it is selecting from
9819 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
9820 ** corresponding table definition.
9821 */
9822 struct Expr {
9823   u8 op;                 /* Operation performed by this node */
9824   char affinity;         /* The affinity of the column or 0 if not a column */
9825   u16 flags;             /* Various flags.  See below */
9826   CollSeq *pColl;        /* The collation type of the column or 0 */
9827   Expr *pLeft, *pRight;  /* Left and right subnodes */
9828   ExprList *pList;       /* A list of expressions used as function arguments
9829                          ** or in "<expr> IN (<expr-list)" */
9830   Token token;           /* An operand token */
9831   Token span;            /* Complete text of the expression */
9832   int iTable, iColumn;   /* When op==TK_COLUMN, then this expr node means the
9833                          ** iColumn-th field of the iTable-th table. */
9834   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
9835   int iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
9836   int iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
9837   Select *pSelect;       /* When the expression is a sub-select.  Also the
9838                          ** right side of "<expr> IN (<select>)" */
9839   Table *pTab;           /* Table for TK_COLUMN expressions. */
9840 #if SQLITE_MAX_EXPR_DEPTH>0
9841   int nHeight;           /* Height of the tree headed by this node */
9842 #endif
9843 };
9844
9845 /*
9846 ** The following are the meanings of bits in the Expr.flags field.
9847 */
9848 #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
9849 #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
9850 #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
9851 #define EP_Error      0x0008  /* Expression contains one or more errors */
9852 #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
9853 #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
9854 #define EP_Dequoted   0x0040  /* True if the string has been dequoted */
9855 #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
9856 #define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
9857 #define EP_AnyAff     0x0200  /* Can take a cached column of any affinity */
9858 #define EP_FixedDest  0x0400  /* Result needed in a specific register */
9859 #define EP_IntValue   0x0800  /* Integer value contained in iTable */
9860 /*
9861 ** These macros can be used to test, set, or clear bits in the 
9862 ** Expr.flags field.
9863 */
9864 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
9865 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
9866 #define ExprSetProperty(E,P)     (E)->flags|=(P)
9867 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
9868
9869 /*
9870 ** A list of expressions.  Each expression may optionally have a
9871 ** name.  An expr/name combination can be used in several ways, such
9872 ** as the list of "expr AS ID" fields following a "SELECT" or in the
9873 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
9874 ** also be used as the argument to a function, in which case the a.zName
9875 ** field is not used.
9876 */
9877 struct ExprList {
9878   int nExpr;             /* Number of expressions on the list */
9879   int nAlloc;            /* Number of entries allocated below */
9880   int iECursor;          /* VDBE Cursor associated with this ExprList */
9881   struct ExprList_item {
9882     Expr *pExpr;           /* The list of expressions */
9883     char *zName;           /* Token associated with this expression */
9884     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
9885     u8 done;               /* A flag to indicate when processing is finished */
9886     u16 iCol;              /* For ORDER BY, column number in result set */
9887     u16 iAlias;            /* Index into Parse.aAlias[] for zName */
9888   } *a;                  /* One entry for each expression */
9889 };
9890
9891 /*
9892 ** An instance of this structure can hold a simple list of identifiers,
9893 ** such as the list "a,b,c" in the following statements:
9894 **
9895 **      INSERT INTO t(a,b,c) VALUES ...;
9896 **      CREATE INDEX idx ON t(a,b,c);
9897 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
9898 **
9899 ** The IdList.a.idx field is used when the IdList represents the list of
9900 ** column names after a table name in an INSERT statement.  In the statement
9901 **
9902 **     INSERT INTO t(a,b,c) ...
9903 **
9904 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
9905 */
9906 struct IdList {
9907   struct IdList_item {
9908     char *zName;      /* Name of the identifier */
9909     int idx;          /* Index in some Table.aCol[] of a column named zName */
9910   } *a;
9911   int nId;         /* Number of identifiers on the list */
9912   int nAlloc;      /* Number of entries allocated for a[] below */
9913 };
9914
9915 /*
9916 ** The bitmask datatype defined below is used for various optimizations.
9917 **
9918 ** Changing this from a 64-bit to a 32-bit type limits the number of
9919 ** tables in a join to 32 instead of 64.  But it also reduces the size
9920 ** of the library by 738 bytes on ix86.
9921 */
9922 typedef u64 Bitmask;
9923
9924 /*
9925 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
9926 */
9927 #define BMS  ((int)(sizeof(Bitmask)*8))
9928
9929 /*
9930 ** The following structure describes the FROM clause of a SELECT statement.
9931 ** Each table or subquery in the FROM clause is a separate element of
9932 ** the SrcList.a[] array.
9933 **
9934 ** With the addition of multiple database support, the following structure
9935 ** can also be used to describe a particular table such as the table that
9936 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
9937 ** such a table must be a simple name: ID.  But in SQLite, the table can
9938 ** now be identified by a database name, a dot, then the table name: ID.ID.
9939 **
9940 ** The jointype starts out showing the join type between the current table
9941 ** and the next table on the list.  The parser builds the list this way.
9942 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
9943 ** jointype expresses the join between the table and the previous table.
9944 */
9945 struct SrcList {
9946   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
9947   i16 nAlloc;      /* Number of entries allocated in a[] below */
9948   struct SrcList_item {
9949     char *zDatabase;  /* Name of database holding this table */
9950     char *zName;      /* Name of the table */
9951     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
9952     Table *pTab;      /* An SQL table corresponding to zName */
9953     Select *pSelect;  /* A SELECT statement used in place of a table name */
9954     u8 isPopulated;   /* Temporary table associated with SELECT is populated */
9955     u8 jointype;      /* Type of join between this able and the previous */
9956     int iCursor;      /* The VDBE cursor number used to access this table */
9957     Expr *pOn;        /* The ON clause of a join */
9958     IdList *pUsing;   /* The USING clause of a join */
9959     Bitmask colUsed;  /* Bit N (1<<N) set if column N or pTab is used */
9960     u8 notIndexed;    /* True if there is a NOT INDEXED clause */
9961     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
9962     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
9963   } a[1];             /* One entry for each identifier on the list */
9964 };
9965
9966 /*
9967 ** Permitted values of the SrcList.a.jointype field
9968 */
9969 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
9970 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
9971 #define JT_NATURAL   0x0004    /* True for a "natural" join */
9972 #define JT_LEFT      0x0008    /* Left outer join */
9973 #define JT_RIGHT     0x0010    /* Right outer join */
9974 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
9975 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
9976
9977 /*
9978 ** For each nested loop in a WHERE clause implementation, the WhereInfo
9979 ** structure contains a single instance of this structure.  This structure
9980 ** is intended to be private the the where.c module and should not be
9981 ** access or modified by other modules.
9982 **
9983 ** The pIdxInfo and pBestIdx fields are used to help pick the best
9984 ** index on a virtual table.  The pIdxInfo pointer contains indexing
9985 ** information for the i-th table in the FROM clause before reordering.
9986 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
9987 ** The pBestIdx pointer is a copy of pIdxInfo for the i-th table after
9988 ** FROM clause ordering.  This is a little confusing so I will repeat
9989 ** it in different words.  WhereInfo.a[i].pIdxInfo is index information 
9990 ** for WhereInfo.pTabList.a[i].  WhereInfo.a[i].pBestInfo is the
9991 ** index information for the i-th loop of the join.  pBestInfo is always
9992 ** either NULL or a copy of some pIdxInfo.  So for cleanup it is 
9993 ** sufficient to free all of the pIdxInfo pointers.
9994 ** 
9995 */
9996 struct WhereLevel {
9997   int iFrom;            /* Which entry in the FROM clause */
9998   int flags;            /* Flags associated with this level */
9999   int iMem;             /* First memory cell used by this level */
10000   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
10001   Index *pIdx;          /* Index used.  NULL if no index */
10002   int iTabCur;          /* The VDBE cursor used to access the table */
10003   int iIdxCur;          /* The VDBE cursor used to acesss pIdx */
10004   int brk;              /* Jump here to break out of the loop */
10005   int nxt;              /* Jump here to start the next IN combination */
10006   int cont;             /* Jump here to continue with the next loop cycle */
10007   int top;              /* First instruction of interior of the loop */
10008   int op, p1, p2, p5;   /* Opcode used to terminate the loop */
10009   int nEq;              /* Number of == or IN constraints on this loop */
10010   int nIn;              /* Number of IN operators constraining this loop */
10011   struct InLoop {
10012     int iCur;              /* The VDBE cursor used by this IN operator */
10013     int topAddr;           /* Top of the IN loop */
10014   } *aInLoop;           /* Information about each nested IN operator */
10015   sqlite3_index_info *pBestIdx;  /* Index information for this level */
10016
10017   /* The following field is really not part of the current level.  But
10018   ** we need a place to cache index information for each table in the
10019   ** FROM clause and the WhereLevel structure is a convenient place.
10020   */
10021   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
10022 };
10023
10024 /*
10025 ** Flags appropriate for the wflags parameter of sqlite3WhereBegin().
10026 */
10027 #define WHERE_ORDERBY_NORMAL     0   /* No-op */
10028 #define WHERE_ORDERBY_MIN        1   /* ORDER BY processing for min() func */
10029 #define WHERE_ORDERBY_MAX        2   /* ORDER BY processing for max() func */
10030 #define WHERE_ONEPASS_DESIRED    4   /* Want to do one-pass UPDATE/DELETE */
10031
10032 /*
10033 ** The WHERE clause processing routine has two halves.  The
10034 ** first part does the start of the WHERE loop and the second
10035 ** half does the tail of the WHERE loop.  An instance of
10036 ** this structure is returned by the first half and passed
10037 ** into the second half to give some continuity.
10038 */
10039 struct WhereInfo {
10040   Parse *pParse;       /* Parsing and code generating context */
10041   u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
10042   SrcList *pTabList;   /* List of tables in the join */
10043   int iTop;            /* The very beginning of the WHERE loop */
10044   int iContinue;       /* Jump here to continue with next record */
10045   int iBreak;          /* Jump here to break out of the loop */
10046   int nLevel;          /* Number of nested loop */
10047   sqlite3_index_info **apInfo;  /* Array of pointers to index info structures */
10048   WhereLevel a[1];     /* Information about each nest loop in the WHERE */
10049 };
10050
10051 /*
10052 ** A NameContext defines a context in which to resolve table and column
10053 ** names.  The context consists of a list of tables (the pSrcList) field and
10054 ** a list of named expression (pEList).  The named expression list may
10055 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
10056 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
10057 ** pEList corresponds to the result set of a SELECT and is NULL for
10058 ** other statements.
10059 **
10060 ** NameContexts can be nested.  When resolving names, the inner-most 
10061 ** context is searched first.  If no match is found, the next outer
10062 ** context is checked.  If there is still no match, the next context
10063 ** is checked.  This process continues until either a match is found
10064 ** or all contexts are check.  When a match is found, the nRef member of
10065 ** the context containing the match is incremented. 
10066 **
10067 ** Each subquery gets a new NameContext.  The pNext field points to the
10068 ** NameContext in the parent query.  Thus the process of scanning the
10069 ** NameContext list corresponds to searching through successively outer
10070 ** subqueries looking for a match.
10071 */
10072 struct NameContext {
10073   Parse *pParse;       /* The parser */
10074   SrcList *pSrcList;   /* One or more tables used to resolve names */
10075   ExprList *pEList;    /* Optional list of named expressions */
10076   int nRef;            /* Number of names resolved by this context */
10077   int nErr;            /* Number of errors encountered while resolving names */
10078   u8 allowAgg;         /* Aggregate functions allowed here */
10079   u8 hasAgg;           /* True if aggregates are seen */
10080   u8 isCheck;          /* True if resolving names in a CHECK constraint */
10081   int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
10082   AggInfo *pAggInfo;   /* Information about aggregates at this level */
10083   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
10084 };
10085
10086 /*
10087 ** An instance of the following structure contains all information
10088 ** needed to generate code for a single SELECT statement.
10089 **
10090 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
10091 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
10092 ** limit and nOffset to the value of the offset (or 0 if there is not
10093 ** offset).  But later on, nLimit and nOffset become the memory locations
10094 ** in the VDBE that record the limit and offset counters.
10095 **
10096 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
10097 ** These addresses must be stored so that we can go back and fill in
10098 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
10099 ** the number of columns in P2 can be computed at the same time
10100 ** as the OP_OpenEphm instruction is coded because not
10101 ** enough information about the compound query is known at that point.
10102 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
10103 ** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
10104 ** sequences for the ORDER BY clause.
10105 */
10106 struct Select {
10107   ExprList *pEList;      /* The fields of the result */
10108   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
10109   char affinity;         /* MakeRecord with this affinity for SRT_Set */
10110   u16 selFlags;          /* Various SF_* values */
10111   SrcList *pSrc;         /* The FROM clause */
10112   Expr *pWhere;          /* The WHERE clause */
10113   ExprList *pGroupBy;    /* The GROUP BY clause */
10114   Expr *pHaving;         /* The HAVING clause */
10115   ExprList *pOrderBy;    /* The ORDER BY clause */
10116   Select *pPrior;        /* Prior select in a compound select statement */
10117   Select *pNext;         /* Next select to the left in a compound */
10118   Select *pRightmost;    /* Right-most select in a compound select statement */
10119   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
10120   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
10121   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
10122   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
10123 };
10124
10125 /*
10126 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
10127 ** "Select Flag".
10128 */
10129 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
10130 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
10131 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
10132 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
10133 #define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
10134 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
10135
10136
10137 /*
10138 ** The results of a select can be distributed in several ways.  The
10139 ** "SRT" prefix means "SELECT Result Type".
10140 */
10141 #define SRT_Union        1  /* Store result as keys in an index */
10142 #define SRT_Except       2  /* Remove result from a UNION index */
10143 #define SRT_Exists       3  /* Store 1 if the result is not empty */
10144 #define SRT_Discard      4  /* Do not save the results anywhere */
10145
10146 /* The ORDER BY clause is ignored for all of the above */
10147 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
10148
10149 #define SRT_Output       5  /* Output each row of result */
10150 #define SRT_Mem          6  /* Store result in a memory cell */
10151 #define SRT_Set          7  /* Store results as keys in an index */
10152 #define SRT_Table        8  /* Store result as data with an automatic rowid */
10153 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
10154 #define SRT_Coroutine   10  /* Generate a single row of result */
10155
10156 /*
10157 ** A structure used to customize the behaviour of sqlite3Select(). See
10158 ** comments above sqlite3Select() for details.
10159 */
10160 typedef struct SelectDest SelectDest;
10161 struct SelectDest {
10162   u8 eDest;         /* How to dispose of the results */
10163   u8 affinity;      /* Affinity used when eDest==SRT_Set */
10164   int iParm;        /* A parameter used by the eDest disposal method */
10165   int iMem;         /* Base register where results are written */
10166   int nMem;         /* Number of registers allocated */
10167 };
10168
10169 /*
10170 ** An SQL parser context.  A copy of this structure is passed through
10171 ** the parser and down into all the parser action routine in order to
10172 ** carry around information that is global to the entire parse.
10173 **
10174 ** The structure is divided into two parts.  When the parser and code
10175 ** generate call themselves recursively, the first part of the structure
10176 ** is constant but the second part is reset at the beginning and end of
10177 ** each recursion.
10178 **
10179 ** The nTableLock and aTableLock variables are only used if the shared-cache 
10180 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
10181 ** used to store the set of table-locks required by the statement being
10182 ** compiled. Function sqlite3TableLock() is used to add entries to the
10183 ** list.
10184 */
10185 struct Parse {
10186   sqlite3 *db;         /* The main database structure */
10187   int rc;              /* Return code from execution */
10188   char *zErrMsg;       /* An error message */
10189   Vdbe *pVdbe;         /* An engine for executing database bytecode */
10190   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
10191   u8 nameClash;        /* A permanent table name clashes with temp table name */
10192   u8 checkSchema;      /* Causes schema cookie check after an error */
10193   u8 nested;           /* Number of nested calls to the parser/code generator */
10194   u8 parseError;       /* True after a parsing error.  Ticket #1794 */
10195   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
10196   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
10197   int aTempReg[8];     /* Holding area for temporary registers */
10198   int nRangeReg;       /* Size of the temporary register block */
10199   int iRangeReg;       /* First register in temporary register block */
10200   int nErr;            /* Number of errors seen */
10201   int nTab;            /* Number of previously allocated VDBE cursors */
10202   int nMem;            /* Number of memory cells used so far */
10203   int nSet;            /* Number of sets used so far */
10204   int ckBase;          /* Base register of data during check constraints */
10205   int disableColCache; /* True to disable adding to column cache */
10206   int nColCache;       /* Number of entries in the column cache */
10207   int iColCache;       /* Next entry of the cache to replace */
10208   struct yColCache {
10209     int iTable;           /* Table cursor number */
10210     int iColumn;          /* Table column number */
10211     char affChange;       /* True if this register has had an affinity change */
10212     int iReg;             /* Register holding value of this column */
10213   } aColCache[10];     /* One for each valid column cache entry */
10214   u32 writeMask;       /* Start a write transaction on these databases */
10215   u32 cookieMask;      /* Bitmask of schema verified databases */
10216   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
10217   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
10218 #ifndef SQLITE_OMIT_SHARED_CACHE
10219   int nTableLock;        /* Number of locks in aTableLock */
10220   TableLock *aTableLock; /* Required table locks for shared-cache mode */
10221 #endif
10222   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
10223   int regRoot;         /* Register holding root page number for new objects */
10224
10225   /* Above is constant between recursions.  Below is reset before and after
10226   ** each recursion */
10227
10228   int nVar;            /* Number of '?' variables seen in the SQL so far */
10229   int nVarExpr;        /* Number of used slots in apVarExpr[] */
10230   int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
10231   Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
10232   int nAlias;          /* Number of aliased result set columns */
10233   int *aAlias;         /* Register used to hold aliased result */
10234   u8 explain;          /* True if the EXPLAIN flag is found on the query */
10235   Token sErrToken;     /* The token at which the error occurred */
10236   Token sNameToken;    /* Token with unqualified schema object name */
10237   Token sLastToken;    /* The last token parsed */
10238   const char *zSql;    /* All SQL text */
10239   const char *zTail;   /* All SQL text past the last semicolon parsed */
10240   Table *pNewTable;    /* A table being constructed by CREATE TABLE */
10241   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
10242   TriggerStack *trigStack;  /* Trigger actions being coded */
10243   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
10244 #ifndef SQLITE_OMIT_VIRTUALTABLE
10245   Token sArg;                /* Complete text of a module argument */
10246   u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
10247   int nVtabLock;             /* Number of virtual tables to lock */
10248   Table **apVtabLock;        /* Pointer to virtual tables needing locking */
10249 #endif
10250   int nHeight;            /* Expression tree height of current sub-select */
10251   Table *pZombieTab;      /* List of Table objects to delete after code gen */
10252 };
10253
10254 #ifdef SQLITE_OMIT_VIRTUALTABLE
10255   #define IN_DECLARE_VTAB 0
10256 #else
10257   #define IN_DECLARE_VTAB (pParse->declareVtab)
10258 #endif
10259
10260 /*
10261 ** An instance of the following structure can be declared on a stack and used
10262 ** to save the Parse.zAuthContext value so that it can be restored later.
10263 */
10264 struct AuthContext {
10265   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
10266   Parse *pParse;              /* The Parse structure */
10267 };
10268
10269 /*
10270 ** Bitfield flags for P2 value in OP_Insert and OP_Delete
10271 */
10272 #define OPFLAG_NCHANGE   1    /* Set to update db->nChange */
10273 #define OPFLAG_LASTROWID 2    /* Set to update db->lastRowid */
10274 #define OPFLAG_ISUPDATE  4    /* This OP_Insert is an sql UPDATE */
10275 #define OPFLAG_APPEND    8    /* This is likely to be an append */
10276
10277 /*
10278  * Each trigger present in the database schema is stored as an instance of
10279  * struct Trigger. 
10280  *
10281  * Pointers to instances of struct Trigger are stored in two ways.
10282  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the 
10283  *    database). This allows Trigger structures to be retrieved by name.
10284  * 2. All triggers associated with a single table form a linked list, using the
10285  *    pNext member of struct Trigger. A pointer to the first element of the
10286  *    linked list is stored as the "pTrigger" member of the associated
10287  *    struct Table.
10288  *
10289  * The "step_list" member points to the first element of a linked list
10290  * containing the SQL statements specified as the trigger program.
10291  */
10292 struct Trigger {
10293   char *name;             /* The name of the trigger                        */
10294   char *table;            /* The table or view to which the trigger applies */
10295   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
10296   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
10297   Expr *pWhen;            /* The WHEN clause of the expresion (may be NULL) */
10298   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
10299                              the <column-list> is stored here */
10300   Token nameToken;        /* Token containing zName. Use during parsing only */
10301   Schema *pSchema;        /* Schema containing the trigger */
10302   Schema *pTabSchema;     /* Schema containing the table */
10303   TriggerStep *step_list; /* Link list of trigger program steps             */
10304   Trigger *pNext;         /* Next trigger associated with the table */
10305 };
10306
10307 /*
10308 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
10309 ** determine which. 
10310 **
10311 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
10312 ** In that cases, the constants below can be ORed together.
10313 */
10314 #define TRIGGER_BEFORE  1
10315 #define TRIGGER_AFTER   2
10316
10317 /*
10318  * An instance of struct TriggerStep is used to store a single SQL statement
10319  * that is a part of a trigger-program. 
10320  *
10321  * Instances of struct TriggerStep are stored in a singly linked list (linked
10322  * using the "pNext" member) referenced by the "step_list" member of the 
10323  * associated struct Trigger instance. The first element of the linked list is
10324  * the first step of the trigger-program.
10325  * 
10326  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
10327  * "SELECT" statement. The meanings of the other members is determined by the 
10328  * value of "op" as follows:
10329  *
10330  * (op == TK_INSERT)
10331  * orconf    -> stores the ON CONFLICT algorithm
10332  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
10333  *              this stores a pointer to the SELECT statement. Otherwise NULL.
10334  * target    -> A token holding the name of the table to insert into.
10335  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
10336  *              this stores values to be inserted. Otherwise NULL.
10337  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
10338  *              statement, then this stores the column-names to be
10339  *              inserted into.
10340  *
10341  * (op == TK_DELETE)
10342  * target    -> A token holding the name of the table to delete from.
10343  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
10344  *              Otherwise NULL.
10345  * 
10346  * (op == TK_UPDATE)
10347  * target    -> A token holding the name of the table to update rows of.
10348  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
10349  *              Otherwise NULL.
10350  * pExprList -> A list of the columns to update and the expressions to update
10351  *              them to. See sqlite3Update() documentation of "pChanges"
10352  *              argument.
10353  * 
10354  */
10355 struct TriggerStep {
10356   int op;              /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
10357   int orconf;          /* OE_Rollback etc. */
10358   Trigger *pTrig;      /* The trigger that this step is a part of */
10359
10360   Select *pSelect;     /* Valid for SELECT and sometimes 
10361                           INSERT steps (when pExprList == 0) */
10362   Token target;        /* Valid for DELETE, UPDATE, INSERT steps */
10363   Expr *pWhere;        /* Valid for DELETE, UPDATE steps */
10364   ExprList *pExprList; /* Valid for UPDATE statements and sometimes 
10365                            INSERT steps (when pSelect == 0)         */
10366   IdList *pIdList;     /* Valid for INSERT statements only */
10367   TriggerStep *pNext;  /* Next in the link-list */
10368   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
10369 };
10370
10371 /*
10372  * An instance of struct TriggerStack stores information required during code
10373  * generation of a single trigger program. While the trigger program is being
10374  * coded, its associated TriggerStack instance is pointed to by the
10375  * "pTriggerStack" member of the Parse structure.
10376  *
10377  * The pTab member points to the table that triggers are being coded on. The 
10378  * newIdx member contains the index of the vdbe cursor that points at the temp
10379  * table that stores the new.* references. If new.* references are not valid
10380  * for the trigger being coded (for example an ON DELETE trigger), then newIdx
10381  * is set to -1. The oldIdx member is analogous to newIdx, for old.* references.
10382  *
10383  * The ON CONFLICT policy to be used for the trigger program steps is stored 
10384  * as the orconf member. If this is OE_Default, then the ON CONFLICT clause 
10385  * specified for individual triggers steps is used.
10386  *
10387  * struct TriggerStack has a "pNext" member, to allow linked lists to be
10388  * constructed. When coding nested triggers (triggers fired by other triggers)
10389  * each nested trigger stores its parent trigger's TriggerStack as the "pNext" 
10390  * pointer. Once the nested trigger has been coded, the pNext value is restored
10391  * to the pTriggerStack member of the Parse stucture and coding of the parent
10392  * trigger continues.
10393  *
10394  * Before a nested trigger is coded, the linked list pointed to by the 
10395  * pTriggerStack is scanned to ensure that the trigger is not about to be coded
10396  * recursively. If this condition is detected, the nested trigger is not coded.
10397  */
10398 struct TriggerStack {
10399   Table *pTab;         /* Table that triggers are currently being coded on */
10400   int newIdx;          /* Index of vdbe cursor to "new" temp table */
10401   int oldIdx;          /* Index of vdbe cursor to "old" temp table */
10402   u32 newColMask;
10403   u32 oldColMask;
10404   int orconf;          /* Current orconf policy */
10405   int ignoreJump;      /* where to jump to for a RAISE(IGNORE) */
10406   Trigger *pTrigger;   /* The trigger currently being coded */
10407   TriggerStack *pNext; /* Next trigger down on the trigger stack */
10408 };
10409
10410 /*
10411 ** The following structure contains information used by the sqliteFix...
10412 ** routines as they walk the parse tree to make database references
10413 ** explicit.  
10414 */
10415 typedef struct DbFixer DbFixer;
10416 struct DbFixer {
10417   Parse *pParse;      /* The parsing context.  Error messages written here */
10418   const char *zDb;    /* Make sure all objects are contained in this database */
10419   const char *zType;  /* Type of the container - used for error messages */
10420   const Token *pName; /* Name of the container - used for error messages */
10421 };
10422
10423 /*
10424 ** An objected used to accumulate the text of a string where we
10425 ** do not necessarily know how big the string will be in the end.
10426 */
10427 struct StrAccum {
10428   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
10429   char *zBase;         /* A base allocation.  Not from malloc. */
10430   char *zText;         /* The string collected so far */
10431   int  nChar;          /* Length of the string so far */
10432   int  nAlloc;         /* Amount of space allocated in zText */
10433   int  mxAlloc;        /* Maximum allowed string length */
10434   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
10435   u8   useMalloc;      /* True if zText is enlargable using realloc */
10436   u8   tooBig;         /* Becomes true if string size exceeds limits */
10437 };
10438
10439 /*
10440 ** A pointer to this structure is used to communicate information
10441 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
10442 */
10443 typedef struct {
10444   sqlite3 *db;        /* The database being initialized */
10445   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
10446   char **pzErrMsg;    /* Error message stored here */
10447   int rc;             /* Result code stored here */
10448 } InitData;
10449
10450 /*
10451 ** Structure containing global configuration data for the SQLite library.
10452 **
10453 ** This structure also contains some state information.
10454 */
10455 struct Sqlite3Config {
10456   int bMemstat;                     /* True to enable memory status */
10457   int bCoreMutex;                   /* True to enable core mutexing */
10458   int bFullMutex;                   /* True to enable full mutexing */
10459   int mxStrlen;                     /* Maximum string length */
10460   int szLookaside;                  /* Default lookaside buffer size */
10461   int nLookaside;                   /* Default lookaside buffer count */
10462   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
10463   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
10464   sqlite3_pcache_methods pcache;    /* Low-level page-cache interface */
10465   void *pHeap;                      /* Heap storage space */
10466   int nHeap;                        /* Size of pHeap[] */
10467   int mnReq, mxReq;                 /* Min and max heap requests sizes */
10468   void *pScratch;                   /* Scratch memory */
10469   int szScratch;                    /* Size of each scratch buffer */
10470   int nScratch;                     /* Number of scratch buffers */
10471   void *pPage;                      /* Page cache memory */
10472   int szPage;                       /* Size of each page in pPage[] */
10473   int nPage;                        /* Number of pages in pPage[] */
10474   int isInit;                       /* True after initialization has finished */
10475   int inProgress;                   /* True while initialization in progress */
10476   int isMallocInit;                 /* True after malloc is initialized */
10477   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
10478   int nRefInitMutex;                /* Number of users of pInitMutex */
10479   int mxParserStack;                /* maximum depth of the parser stack */
10480   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
10481 };
10482
10483 /*
10484 ** Context pointer passed down through the tree-walk.
10485 */
10486 struct Walker {
10487   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
10488   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
10489   Parse *pParse;                            /* Parser context.  */
10490   union {                                   /* Extra data for callback */
10491     NameContext *pNC;                          /* Naming context */
10492     int i;                                     /* Integer value */
10493   } u;
10494 };
10495
10496 /* Forward declarations */
10497 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
10498 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
10499 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
10500 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
10501 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
10502
10503 /*
10504 ** Return code from the parse-tree walking primitives and their
10505 ** callbacks.
10506 */
10507 #define WRC_Continue    0
10508 #define WRC_Prune       1
10509 #define WRC_Abort       2
10510
10511 /*
10512 ** Assuming zIn points to the first byte of a UTF-8 character,
10513 ** advance zIn to point to the first byte of the next UTF-8 character.
10514 */
10515 #define SQLITE_SKIP_UTF8(zIn) {                        \
10516   if( (*(zIn++))>=0xc0 ){                              \
10517     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
10518   }                                                    \
10519 }
10520
10521 /*
10522 ** The SQLITE_CORRUPT_BKPT macro can be either a constant (for production
10523 ** builds) or a function call (for debugging).  If it is a function call,
10524 ** it allows the operator to set a breakpoint at the spot where database
10525 ** corruption is first detected.
10526 */
10527 #ifdef SQLITE_DEBUG
10528 SQLITE_PRIVATE   int sqlite3Corrupt(void);
10529 # define SQLITE_CORRUPT_BKPT sqlite3Corrupt()
10530 #else
10531 # define SQLITE_CORRUPT_BKPT SQLITE_CORRUPT
10532 #endif
10533
10534 /*
10535 ** Internal function prototypes
10536 */
10537 SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
10538 SQLITE_PRIVATE int sqlite3StrNICmp(const char *, const char *, int);
10539 SQLITE_PRIVATE int sqlite3IsNumber(const char*, int*, u8);
10540 SQLITE_PRIVATE int sqlite3Strlen(sqlite3*, const char*);
10541
10542 SQLITE_PRIVATE int sqlite3MallocInit(void);
10543 SQLITE_PRIVATE void sqlite3MallocEnd(void);
10544 SQLITE_PRIVATE void *sqlite3Malloc(int);
10545 SQLITE_PRIVATE void *sqlite3MallocZero(int);
10546 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
10547 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
10548 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
10549 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
10550 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
10551 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
10552 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
10553 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
10554 SQLITE_PRIVATE int sqlite3MallocSize(void*);
10555 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
10556 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
10557 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
10558 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
10559 SQLITE_PRIVATE void sqlite3PageFree(void*);
10560 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
10561 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
10562 SQLITE_PRIVATE int sqlite3MemoryAlarm(void (*)(void*, sqlite3_int64, int), void*, sqlite3_int64);
10563
10564 #ifdef SQLITE_ENABLE_MEMSYS3
10565 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
10566 #endif
10567 #ifdef SQLITE_ENABLE_MEMSYS5
10568 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
10569 #endif
10570
10571
10572 #ifndef SQLITE_MUTEX_OMIT
10573 SQLITE_PRIVATE   sqlite3_mutex_methods *sqlite3DefaultMutex(void);
10574 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
10575 SQLITE_PRIVATE   int sqlite3MutexInit(void);
10576 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
10577 #endif
10578
10579 SQLITE_PRIVATE int sqlite3StatusValue(int);
10580 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
10581 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
10582
10583 SQLITE_PRIVATE int sqlite3IsNaN(double);
10584
10585 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
10586 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
10587 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
10588 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
10589 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
10590 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
10591 #endif
10592 #if defined(SQLITE_TEST)
10593 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
10594 #endif
10595 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
10596 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
10597 SQLITE_PRIVATE void sqlite3ErrorClear(Parse*);
10598 SQLITE_PRIVATE void sqlite3Dequote(char*);
10599 SQLITE_PRIVATE void sqlite3DequoteExpr(sqlite3*, Expr*);
10600 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
10601 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
10602 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
10603 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
10604 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
10605 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
10606 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
10607 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*, int, Expr*, Expr*, const Token*);
10608 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
10609 SQLITE_PRIVATE Expr *sqlite3RegisterExpr(Parse*,Token*);
10610 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
10611 SQLITE_PRIVATE void sqlite3ExprSpan(Expr*,Token*,Token*);
10612 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
10613 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
10614 SQLITE_PRIVATE void sqlite3ExprClear(sqlite3*, Expr*);
10615 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
10616 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*,Token*);
10617 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
10618 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
10619 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
10620 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
10621 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
10622 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
10623 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
10624 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
10625 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
10626 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
10627 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
10628 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
10629 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
10630 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
10631 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
10632 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,Expr*);
10633 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
10634 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
10635
10636 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
10637 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
10638 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
10639 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32);
10640 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
10641 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
10642
10643 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
10644
10645 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
10646 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
10647 #else
10648 # define sqlite3ViewGetColumnNames(A,B) 0
10649 #endif
10650
10651 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
10652 SQLITE_PRIVATE void sqlite3DeleteTable(Table*);
10653 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
10654 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
10655 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
10656 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
10657 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
10658 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
10659 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
10660                                       Token*, Select*, Expr*, IdList*);
10661 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
10662 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
10663 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
10664 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
10665 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
10666 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
10667 SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
10668                         Token*, int, int);
10669 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
10670 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
10671 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
10672                          Expr*,ExprList*,int,Expr*,Expr*);
10673 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
10674 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
10675 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
10676 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
10677 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
10678 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
10679 #endif
10680 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
10681 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
10682 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u8);
10683 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
10684 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, int);
10685 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
10686 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
10687 SQLITE_PRIVATE void sqlite3ExprClearColumnCache(Parse*, int);
10688 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
10689 SQLITE_PRIVATE int sqlite3ExprWritableRegister(Parse*,int,int);
10690 SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse*,int,int);
10691 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
10692 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
10693 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
10694 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
10695 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
10696 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
10697 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
10698 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
10699 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
10700 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
10701 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
10702 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
10703 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
10704 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
10705 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
10706 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
10707 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
10708 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
10709 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
10710 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
10711 SQLITE_PRIVATE Expr *sqlite3CreateIdExpr(Parse *, const char*);
10712 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
10713 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
10714 SQLITE_PRIVATE void sqlite3PrngResetState(void);
10715 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
10716 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
10717 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
10718 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
10719 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
10720 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
10721 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
10722 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
10723 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
10724 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
10725 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int);
10726 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
10727 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
10728 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
10729                                      int*,int,int,int,int);
10730 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
10731 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
10732 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
10733 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*);
10734 SQLITE_PRIVATE void sqlite3TokenCopy(sqlite3*,Token*, Token*);
10735 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*);
10736 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*);
10737 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
10738 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*);
10739 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
10740 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
10741 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
10742 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
10743 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
10744 #ifdef SQLITE_DEBUG
10745 SQLITE_PRIVATE   int sqlite3SafetyOn(sqlite3*);
10746 SQLITE_PRIVATE   int sqlite3SafetyOff(sqlite3*);
10747 #else
10748 # define sqlite3SafetyOn(A) 0
10749 # define sqlite3SafetyOff(A) 0
10750 #endif
10751 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
10752 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
10753 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
10754
10755 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
10756 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
10757 #endif
10758
10759 #ifndef SQLITE_OMIT_TRIGGER
10760 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
10761                            Expr*,int, int);
10762 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
10763 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
10764 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
10765 SQLITE_PRIVATE   int sqlite3TriggersExist(Table*, int, ExprList*);
10766 SQLITE_PRIVATE   int sqlite3CodeRowTrigger(Parse*, int, ExprList*, int, Table *, int, int, 
10767                            int, int, u32*, u32*);
10768   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
10769 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
10770 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
10771 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
10772                                         ExprList*,Select*,int);
10773 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, int);
10774 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
10775 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
10776 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
10777 #else
10778 # define sqlite3TriggersExist(B,C,D,E,F) 0
10779 # define sqlite3DeleteTrigger(A,B)
10780 # define sqlite3DropTriggerPtr(A,B)
10781 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
10782 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I,J,K) 0
10783 #endif
10784
10785 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
10786 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
10787 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
10788 #ifndef SQLITE_OMIT_AUTHORIZATION
10789 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
10790 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
10791 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
10792 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
10793 #else
10794 # define sqlite3AuthRead(a,b,c,d)
10795 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
10796 # define sqlite3AuthContextPush(a,b,c)
10797 # define sqlite3AuthContextPop(a)  ((void)(a))
10798 #endif
10799 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
10800 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
10801 SQLITE_PRIVATE int sqlite3BtreeFactory(const sqlite3 *db, const char *zFilename,
10802                        int omitJournal, int nCache, int flags, Btree **ppBtree);
10803 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
10804 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
10805 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
10806 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
10807 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
10808 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
10809 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*);
10810 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
10811 SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *, int);
10812 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
10813 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
10814 SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8*, const u8**);
10815
10816 /*
10817 ** Routines to read and write variable-length integers.  These used to
10818 ** be defined locally, but now we use the varint routines in the util.c
10819 ** file.  Code should use the MACRO forms below, as the Varint32 versions
10820 ** are coded to assume the single byte case is already handled (which 
10821 ** the MACRO form does).
10822 */
10823 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
10824 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
10825 SQLITE_PRIVATE int sqlite3GetVarint(const unsigned char *, u64 *);
10826 SQLITE_PRIVATE int sqlite3GetVarint32(const unsigned char *, u32 *);
10827 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
10828
10829 /*
10830 ** The header of a record consists of a sequence variable-length integers.
10831 ** These integers are almost always small and are encoded as a single byte.
10832 ** The following macros take advantage this fact to provide a fast encode
10833 ** and decode of the integers in a record header.  It is faster for the common
10834 ** case where the integer is a single byte.  It is a little slower when the
10835 ** integer is two or more bytes.  But overall it is faster.
10836 **
10837 ** The following expressions are equivalent:
10838 **
10839 **     x = sqlite3GetVarint32( A, &B );
10840 **     x = sqlite3PutVarint32( A, B );
10841 **
10842 **     x = getVarint32( A, B );
10843 **     x = putVarint32( A, B );
10844 **
10845 */
10846 #define getVarint32(A,B)  ((*(A)<(unsigned char)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
10847 #define putVarint32(A,B)  (((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
10848 #define getVarint    sqlite3GetVarint
10849 #define putVarint    sqlite3PutVarint
10850
10851
10852 SQLITE_PRIVATE void sqlite3IndexAffinityStr(Vdbe *, Index *);
10853 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
10854 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
10855 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
10856 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
10857 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*);
10858 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
10859 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
10860 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
10861 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
10862 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
10863 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char *,int,int);
10864 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName);
10865 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
10866 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *, Token *);
10867 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
10868 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
10869 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
10870
10871 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
10872 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
10873 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, 
10874                         void(*)(void*));
10875 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
10876 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
10877 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int);
10878 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
10879 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
10880 #ifndef SQLITE_AMALGAMATION
10881 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
10882 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
10883 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
10884 #endif
10885 SQLITE_PRIVATE void sqlite3RootPageMoved(Db*, int, int);
10886 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
10887 SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3*);
10888 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
10889 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
10890 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
10891 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
10892 SQLITE_PRIVATE void sqlite3CodeSubselect(Parse *, Expr *, int, int);
10893 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
10894 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
10895 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
10896 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
10897 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int);
10898 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
10899 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
10900 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, CollSeq *, const char *, int);
10901 SQLITE_PRIVATE char sqlite3AffinityType(const Token*);
10902 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
10903 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
10904 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
10905 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
10906 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
10907 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
10908 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
10909 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
10910 SQLITE_PRIVATE void sqlite3SchemaFree(void *);
10911 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
10912 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
10913 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
10914 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
10915   void (*)(sqlite3_context*,int,sqlite3_value **),
10916   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
10917 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
10918 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
10919
10920 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
10921 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
10922 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
10923 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
10924 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
10925
10926 /*
10927 ** The interface to the LEMON-generated parser
10928 */
10929 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
10930 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
10931 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
10932 #ifdef YYTRACKMAXSTACKDEPTH
10933 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
10934 #endif
10935
10936 SQLITE_PRIVATE int sqlite3AutoLoadExtensions(sqlite3*);
10937 #ifndef SQLITE_OMIT_LOAD_EXTENSION
10938 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
10939 #else
10940 # define sqlite3CloseExtensions(X)
10941 #endif
10942
10943 #ifndef SQLITE_OMIT_SHARED_CACHE
10944 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
10945 #else
10946   #define sqlite3TableLock(v,w,x,y,z)
10947 #endif
10948
10949 #ifdef SQLITE_TEST
10950 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
10951 #endif
10952
10953 #ifdef SQLITE_OMIT_VIRTUALTABLE
10954 #  define sqlite3VtabClear(X)
10955 #  define sqlite3VtabSync(X,Y) SQLITE_OK
10956 #  define sqlite3VtabRollback(X)
10957 #  define sqlite3VtabCommit(X)
10958 #  define sqlite3VtabInSync(db) 0
10959 #else
10960 SQLITE_PRIVATE    void sqlite3VtabClear(Table*);
10961 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
10962 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
10963 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
10964 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
10965 #endif
10966 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
10967 SQLITE_PRIVATE void sqlite3VtabLock(sqlite3_vtab*);
10968 SQLITE_PRIVATE void sqlite3VtabUnlock(sqlite3*, sqlite3_vtab*);
10969 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
10970 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
10971 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
10972 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
10973 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
10974 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
10975 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
10976 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, sqlite3_vtab *);
10977 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
10978 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
10979 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
10980 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
10981 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
10982 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
10983
10984
10985 /*
10986 ** Available fault injectors.  Should be numbered beginning with 0.
10987 */
10988 #define SQLITE_FAULTINJECTOR_MALLOC     0
10989 #define SQLITE_FAULTINJECTOR_COUNT      1
10990
10991 /*
10992 ** The interface to the code in fault.c used for identifying "benign"
10993 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
10994 ** is not defined.
10995 */
10996 #ifndef SQLITE_OMIT_BUILTIN_TEST
10997 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
10998 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
10999 #else
11000   #define sqlite3BeginBenignMalloc()
11001   #define sqlite3EndBenignMalloc()
11002 #endif
11003
11004 #define IN_INDEX_ROWID           1
11005 #define IN_INDEX_EPH             2
11006 #define IN_INDEX_INDEX           3
11007 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
11008
11009 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
11010 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
11011 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
11012 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
11013 #else
11014   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
11015 #endif
11016
11017 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
11018 SQLITE_PRIVATE int sqlite3MemJournalSize();
11019 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
11020
11021 #if SQLITE_MAX_EXPR_DEPTH>0
11022 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
11023 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
11024 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
11025 #else
11026   #define sqlite3ExprSetHeight(x,y)
11027   #define sqlite3SelectExprHeight(x) 0
11028   #define sqlite3ExprCheckHeight(x,y)
11029 #endif
11030
11031 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
11032 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
11033
11034 #ifdef SQLITE_SSE
11035 #include "sseInt.h"
11036 #endif
11037
11038 #ifdef SQLITE_DEBUG
11039 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
11040 #endif
11041
11042 /*
11043 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
11044 ** sqlite3IoTrace is a pointer to a printf-like routine used to
11045 ** print I/O tracing messages. 
11046 */
11047 #ifdef SQLITE_ENABLE_IOTRACE
11048 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
11049 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
11050 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
11051 #else
11052 # define IOTRACE(A)
11053 # define sqlite3VdbeIOTraceSql(X)
11054 #endif
11055
11056 #endif
11057
11058 /************** End of sqliteInt.h *******************************************/
11059 /************** Begin file global.c ******************************************/
11060 /*
11061 ** 2008 June 13
11062 **
11063 ** The author disclaims copyright to this source code.  In place of
11064 ** a legal notice, here is a blessing:
11065 **
11066 **    May you do good and not evil.
11067 **    May you find forgiveness for yourself and forgive others.
11068 **    May you share freely, never taking more than you give.
11069 **
11070 *************************************************************************
11071 **
11072 ** This file contains definitions of global variables and contants.
11073 **
11074 ** $Id: global.c,v 1.8 2008/09/04 17:17:39 danielk1977 Exp $
11075 */
11076
11077
11078 /* An array to map all upper-case characters into their corresponding
11079 ** lower-case character. 
11080 **
11081 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
11082 ** handle case conversions for the UTF character set since the tables
11083 ** involved are nearly as big or bigger than SQLite itself.
11084 */
11085 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
11086 #ifdef SQLITE_ASCII
11087       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
11088      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
11089      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
11090      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
11091     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
11092     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
11093     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
11094     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
11095     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
11096     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
11097     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
11098     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
11099     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
11100     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
11101     252,253,254,255
11102 #endif
11103 #ifdef SQLITE_EBCDIC
11104       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
11105      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
11106      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
11107      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
11108      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
11109      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
11110      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
11111     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
11112     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
11113     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
11114     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
11115     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
11116     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
11117     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
11118     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
11119     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
11120 #endif
11121 };
11122
11123 /*
11124 ** The following singleton contains the global configuration for
11125 ** the SQLite library.
11126 */
11127 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
11128    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
11129    1,                         /* bCoreMutex */
11130    SQLITE_THREADSAFE==1,      /* bFullMutex */
11131    0x7ffffffe,                /* mxStrlen */
11132    100,                       /* szLookaside */
11133    500,                       /* nLookaside */
11134    /* Other fields all default to zero */
11135 };
11136
11137
11138 /*
11139 ** Hash table for global functions - functions common to all
11140 ** database connections.  After initialization, this table is
11141 ** read-only.
11142 */
11143 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
11144
11145 /************** End of global.c **********************************************/
11146 /************** Begin file status.c ******************************************/
11147 /*
11148 ** 2008 June 18
11149 **
11150 ** The author disclaims copyright to this source code.  In place of
11151 ** a legal notice, here is a blessing:
11152 **
11153 **    May you do good and not evil.
11154 **    May you find forgiveness for yourself and forgive others.
11155 **    May you share freely, never taking more than you give.
11156 **
11157 *************************************************************************
11158 **
11159 ** This module implements the sqlite3_status() interface and related
11160 ** functionality.
11161 **
11162 ** $Id: status.c,v 1.9 2008/09/02 00:52:52 drh Exp $
11163 */
11164
11165 /*
11166 ** Variables in which to record status information.
11167 */
11168 typedef struct sqlite3StatType sqlite3StatType;
11169 static SQLITE_WSD struct sqlite3StatType {
11170   int nowValue[9];         /* Current value */
11171   int mxValue[9];          /* Maximum value */
11172 } sqlite3Stat = { {0,}, {0,} };
11173
11174
11175 /* The "wsdStat" macro will resolve to the status information
11176 ** state vector.  If writable static data is unsupported on the target,
11177 ** we have to locate the state vector at run-time.  In the more common
11178 ** case where writable static data is supported, wsdStat can refer directly
11179 ** to the "sqlite3Stat" state vector declared above.
11180 */
11181 #ifdef SQLITE_OMIT_WSD
11182 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
11183 # define wsdStat x[0]
11184 #else
11185 # define wsdStatInit
11186 # define wsdStat sqlite3Stat
11187 #endif
11188
11189 /*
11190 ** Return the current value of a status parameter.
11191 */
11192 SQLITE_PRIVATE int sqlite3StatusValue(int op){
11193   wsdStatInit;
11194   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
11195   return wsdStat.nowValue[op];
11196 }
11197
11198 /*
11199 ** Add N to the value of a status record.  It is assumed that the
11200 ** caller holds appropriate locks.
11201 */
11202 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
11203   wsdStatInit;
11204   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
11205   wsdStat.nowValue[op] += N;
11206   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
11207     wsdStat.mxValue[op] = wsdStat.nowValue[op];
11208   }
11209 }
11210
11211 /*
11212 ** Set the value of a status to X.
11213 */
11214 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
11215   wsdStatInit;
11216   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
11217   wsdStat.nowValue[op] = X;
11218   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
11219     wsdStat.mxValue[op] = wsdStat.nowValue[op];
11220   }
11221 }
11222
11223 /*
11224 ** Query status information.
11225 **
11226 ** This implementation assumes that reading or writing an aligned
11227 ** 32-bit integer is an atomic operation.  If that assumption is not true,
11228 ** then this routine is not threadsafe.
11229 */
11230 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
11231   wsdStatInit;
11232   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
11233     return SQLITE_MISUSE;
11234   }
11235   *pCurrent = wsdStat.nowValue[op];
11236   *pHighwater = wsdStat.mxValue[op];
11237   if( resetFlag ){
11238     wsdStat.mxValue[op] = wsdStat.nowValue[op];
11239   }
11240   return SQLITE_OK;
11241 }
11242
11243 /*
11244 ** Query status information for a single database connection
11245 */
11246 SQLITE_API int sqlite3_db_status(
11247   sqlite3 *db,          /* The database connection whose status is desired */
11248   int op,               /* Status verb */
11249   int *pCurrent,        /* Write current value here */
11250   int *pHighwater,      /* Write high-water mark here */
11251   int resetFlag         /* Reset high-water mark if true */
11252 ){
11253   switch( op ){
11254     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
11255       *pCurrent = db->lookaside.nOut;
11256       *pHighwater = db->lookaside.mxOut;
11257       if( resetFlag ){
11258         db->lookaside.mxOut = db->lookaside.nOut;
11259       }
11260       break;
11261     }
11262     default: {
11263       return SQLITE_ERROR;
11264     }
11265   }
11266   return SQLITE_OK;
11267 }
11268
11269 /************** End of status.c **********************************************/
11270 /************** Begin file date.c ********************************************/
11271 /*
11272 ** 2003 October 31
11273 **
11274 ** The author disclaims copyright to this source code.  In place of
11275 ** a legal notice, here is a blessing:
11276 **
11277 **    May you do good and not evil.
11278 **    May you find forgiveness for yourself and forgive others.
11279 **    May you share freely, never taking more than you give.
11280 **
11281 *************************************************************************
11282 ** This file contains the C functions that implement date and time
11283 ** functions for SQLite.  
11284 **
11285 ** There is only one exported symbol in this file - the function
11286 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
11287 ** All other code has file scope.
11288 **
11289 ** $Id: date.c,v 1.94 2008/11/19 09:05:27 danielk1977 Exp $
11290 **
11291 ** SQLite processes all times and dates as Julian Day numbers.  The
11292 ** dates and times are stored as the number of days since noon
11293 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
11294 ** calendar system. 
11295 **
11296 ** 1970-01-01 00:00:00 is JD 2440587.5
11297 ** 2000-01-01 00:00:00 is JD 2451544.5
11298 **
11299 ** This implemention requires years to be expressed as a 4-digit number
11300 ** which means that only dates between 0000-01-01 and 9999-12-31 can
11301 ** be represented, even though julian day numbers allow a much wider
11302 ** range of dates.
11303 **
11304 ** The Gregorian calendar system is used for all dates and times,
11305 ** even those that predate the Gregorian calendar.  Historians usually
11306 ** use the Julian calendar for dates prior to 1582-10-15 and for some
11307 ** dates afterwards, depending on locale.  Beware of this difference.
11308 **
11309 ** The conversion algorithms are implemented based on descriptions
11310 ** in the following text:
11311 **
11312 **      Jean Meeus
11313 **      Astronomical Algorithms, 2nd Edition, 1998
11314 **      ISBM 0-943396-61-1
11315 **      Willmann-Bell, Inc
11316 **      Richmond, Virginia (USA)
11317 */
11318 #include <ctype.h>
11319 #include <time.h>
11320
11321 #ifndef SQLITE_OMIT_DATETIME_FUNCS
11322
11323 /*
11324 ** On recent Windows platforms, the localtime_s() function is available
11325 ** as part of the "Secure CRT". It is essentially equivalent to 
11326 ** localtime_r() available under most POSIX platforms, except that the 
11327 ** order of the parameters is reversed.
11328 **
11329 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
11330 **
11331 ** If the user has not indicated to use localtime_r() or localtime_s()
11332 ** already, check for an MSVC build environment that provides 
11333 ** localtime_s().
11334 */
11335 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
11336      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
11337 #define HAVE_LOCALTIME_S 1
11338 #endif
11339
11340 /*
11341 ** A structure for holding a single date and time.
11342 */
11343 typedef struct DateTime DateTime;
11344 struct DateTime {
11345   sqlite3_int64 iJD; /* The julian day number times 86400000 */
11346   int Y, M, D;       /* Year, month, and day */
11347   int h, m;          /* Hour and minutes */
11348   int tz;            /* Timezone offset in minutes */
11349   double s;          /* Seconds */
11350   char validYMD;     /* True if Y,M,D are valid */
11351   char validHMS;     /* True if h,m,s are valid */
11352   char validJD;      /* True if iJD is valid */
11353   char validTZ;      /* True if tz is valid */
11354 };
11355
11356
11357 /*
11358 ** Convert zDate into one or more integers.  Additional arguments
11359 ** come in groups of 5 as follows:
11360 **
11361 **       N       number of digits in the integer
11362 **       min     minimum allowed value of the integer
11363 **       max     maximum allowed value of the integer
11364 **       nextC   first character after the integer
11365 **       pVal    where to write the integers value.
11366 **
11367 ** Conversions continue until one with nextC==0 is encountered.
11368 ** The function returns the number of successful conversions.
11369 */
11370 static int getDigits(const char *zDate, ...){
11371   va_list ap;
11372   int val;
11373   int N;
11374   int min;
11375   int max;
11376   int nextC;
11377   int *pVal;
11378   int cnt = 0;
11379   va_start(ap, zDate);
11380   do{
11381     N = va_arg(ap, int);
11382     min = va_arg(ap, int);
11383     max = va_arg(ap, int);
11384     nextC = va_arg(ap, int);
11385     pVal = va_arg(ap, int*);
11386     val = 0;
11387     while( N-- ){
11388       if( !isdigit(*(u8*)zDate) ){
11389         goto end_getDigits;
11390       }
11391       val = val*10 + *zDate - '0';
11392       zDate++;
11393     }
11394     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
11395       goto end_getDigits;
11396     }
11397     *pVal = val;
11398     zDate++;
11399     cnt++;
11400   }while( nextC );
11401 end_getDigits:
11402   va_end(ap);
11403   return cnt;
11404 }
11405
11406 /*
11407 ** Read text from z[] and convert into a floating point number.  Return
11408 ** the number of digits converted.
11409 */
11410 #define getValue sqlite3AtoF
11411
11412 /*
11413 ** Parse a timezone extension on the end of a date-time.
11414 ** The extension is of the form:
11415 **
11416 **        (+/-)HH:MM
11417 **
11418 ** Or the "zulu" notation:
11419 **
11420 **        Z
11421 **
11422 ** If the parse is successful, write the number of minutes
11423 ** of change in p->tz and return 0.  If a parser error occurs,
11424 ** return non-zero.
11425 **
11426 ** A missing specifier is not considered an error.
11427 */
11428 static int parseTimezone(const char *zDate, DateTime *p){
11429   int sgn = 0;
11430   int nHr, nMn;
11431   int c;
11432   while( isspace(*(u8*)zDate) ){ zDate++; }
11433   p->tz = 0;
11434   c = *zDate;
11435   if( c=='-' ){
11436     sgn = -1;
11437   }else if( c=='+' ){
11438     sgn = +1;
11439   }else if( c=='Z' || c=='z' ){
11440     zDate++;
11441     goto zulu_time;
11442   }else{
11443     return c!=0;
11444   }
11445   zDate++;
11446   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
11447     return 1;
11448   }
11449   zDate += 5;
11450   p->tz = sgn*(nMn + nHr*60);
11451 zulu_time:
11452   while( isspace(*(u8*)zDate) ){ zDate++; }
11453   return *zDate!=0;
11454 }
11455
11456 /*
11457 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
11458 ** The HH, MM, and SS must each be exactly 2 digits.  The
11459 ** fractional seconds FFFF can be one or more digits.
11460 **
11461 ** Return 1 if there is a parsing error and 0 on success.
11462 */
11463 static int parseHhMmSs(const char *zDate, DateTime *p){
11464   int h, m, s;
11465   double ms = 0.0;
11466   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
11467     return 1;
11468   }
11469   zDate += 5;
11470   if( *zDate==':' ){
11471     zDate++;
11472     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
11473       return 1;
11474     }
11475     zDate += 2;
11476     if( *zDate=='.' && isdigit((u8)zDate[1]) ){
11477       double rScale = 1.0;
11478       zDate++;
11479       while( isdigit(*(u8*)zDate) ){
11480         ms = ms*10.0 + *zDate - '0';
11481         rScale *= 10.0;
11482         zDate++;
11483       }
11484       ms /= rScale;
11485     }
11486   }else{
11487     s = 0;
11488   }
11489   p->validJD = 0;
11490   p->validHMS = 1;
11491   p->h = h;
11492   p->m = m;
11493   p->s = s + ms;
11494   if( parseTimezone(zDate, p) ) return 1;
11495   p->validTZ = p->tz!=0;
11496   return 0;
11497 }
11498
11499 /*
11500 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
11501 ** that the YYYY-MM-DD is according to the Gregorian calendar.
11502 **
11503 ** Reference:  Meeus page 61
11504 */
11505 static void computeJD(DateTime *p){
11506   int Y, M, D, A, B, X1, X2;
11507
11508   if( p->validJD ) return;
11509   if( p->validYMD ){
11510     Y = p->Y;
11511     M = p->M;
11512     D = p->D;
11513   }else{
11514     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
11515     M = 1;
11516     D = 1;
11517   }
11518   if( M<=2 ){
11519     Y--;
11520     M += 12;
11521   }
11522   A = Y/100;
11523   B = 2 - A + (A/4);
11524   X1 = 365.25*(Y+4716);
11525   X2 = 30.6001*(M+1);
11526   p->iJD = (X1 + X2 + D + B - 1524.5)*86400000;
11527   p->validJD = 1;
11528   if( p->validHMS ){
11529     p->iJD += p->h*3600000 + p->m*60000 + p->s*1000;
11530     if( p->validTZ ){
11531       p->iJD -= p->tz*60000;
11532       p->validYMD = 0;
11533       p->validHMS = 0;
11534       p->validTZ = 0;
11535     }
11536   }
11537 }
11538
11539 /*
11540 ** Parse dates of the form
11541 **
11542 **     YYYY-MM-DD HH:MM:SS.FFF
11543 **     YYYY-MM-DD HH:MM:SS
11544 **     YYYY-MM-DD HH:MM
11545 **     YYYY-MM-DD
11546 **
11547 ** Write the result into the DateTime structure and return 0
11548 ** on success and 1 if the input string is not a well-formed
11549 ** date.
11550 */
11551 static int parseYyyyMmDd(const char *zDate, DateTime *p){
11552   int Y, M, D, neg;
11553
11554   if( zDate[0]=='-' ){
11555     zDate++;
11556     neg = 1;
11557   }else{
11558     neg = 0;
11559   }
11560   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
11561     return 1;
11562   }
11563   zDate += 10;
11564   while( isspace(*(u8*)zDate) || 'T'==*(u8*)zDate ){ zDate++; }
11565   if( parseHhMmSs(zDate, p)==0 ){
11566     /* We got the time */
11567   }else if( *zDate==0 ){
11568     p->validHMS = 0;
11569   }else{
11570     return 1;
11571   }
11572   p->validJD = 0;
11573   p->validYMD = 1;
11574   p->Y = neg ? -Y : Y;
11575   p->M = M;
11576   p->D = D;
11577   if( p->validTZ ){
11578     computeJD(p);
11579   }
11580   return 0;
11581 }
11582
11583 /*
11584 ** Set the time to the current time reported by the VFS
11585 */
11586 static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
11587   double r;
11588   sqlite3 *db = sqlite3_context_db_handle(context);
11589   sqlite3OsCurrentTime(db->pVfs, &r);
11590   p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
11591   p->validJD = 1;
11592 }
11593
11594 /*
11595 ** Attempt to parse the given string into a Julian Day Number.  Return
11596 ** the number of errors.
11597 **
11598 ** The following are acceptable forms for the input string:
11599 **
11600 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
11601 **      DDDD.DD 
11602 **      now
11603 **
11604 ** In the first form, the +/-HH:MM is always optional.  The fractional
11605 ** seconds extension (the ".FFF") is optional.  The seconds portion
11606 ** (":SS.FFF") is option.  The year and date can be omitted as long
11607 ** as there is a time string.  The time string can be omitted as long
11608 ** as there is a year and date.
11609 */
11610 static int parseDateOrTime(
11611   sqlite3_context *context, 
11612   const char *zDate, 
11613   DateTime *p
11614 ){
11615   if( parseYyyyMmDd(zDate,p)==0 ){
11616     return 0;
11617   }else if( parseHhMmSs(zDate, p)==0 ){
11618     return 0;
11619   }else if( sqlite3StrICmp(zDate,"now")==0){
11620     setDateTimeToCurrent(context, p);
11621     return 0;
11622   }else if( sqlite3IsNumber(zDate, 0, SQLITE_UTF8) ){
11623     double r;
11624     getValue(zDate, &r);
11625     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
11626     p->validJD = 1;
11627     return 0;
11628   }
11629   return 1;
11630 }
11631
11632 /*
11633 ** Compute the Year, Month, and Day from the julian day number.
11634 */
11635 static void computeYMD(DateTime *p){
11636   int Z, A, B, C, D, E, X1;
11637   if( p->validYMD ) return;
11638   if( !p->validJD ){
11639     p->Y = 2000;
11640     p->M = 1;
11641     p->D = 1;
11642   }else{
11643     Z = (p->iJD + 43200000)/86400000;
11644     A = (Z - 1867216.25)/36524.25;
11645     A = Z + 1 + A - (A/4);
11646     B = A + 1524;
11647     C = (B - 122.1)/365.25;
11648     D = 365.25*C;
11649     E = (B-D)/30.6001;
11650     X1 = 30.6001*E;
11651     p->D = B - D - X1;
11652     p->M = E<14 ? E-1 : E-13;
11653     p->Y = p->M>2 ? C - 4716 : C - 4715;
11654   }
11655   p->validYMD = 1;
11656 }
11657
11658 /*
11659 ** Compute the Hour, Minute, and Seconds from the julian day number.
11660 */
11661 static void computeHMS(DateTime *p){
11662   int s;
11663   if( p->validHMS ) return;
11664   computeJD(p);
11665   s = (p->iJD + 43200000) % 86400000;
11666   p->s = s/1000.0;
11667   s = p->s;
11668   p->s -= s;
11669   p->h = s/3600;
11670   s -= p->h*3600;
11671   p->m = s/60;
11672   p->s += s - p->m*60;
11673   p->validHMS = 1;
11674 }
11675
11676 /*
11677 ** Compute both YMD and HMS
11678 */
11679 static void computeYMD_HMS(DateTime *p){
11680   computeYMD(p);
11681   computeHMS(p);
11682 }
11683
11684 /*
11685 ** Clear the YMD and HMS and the TZ
11686 */
11687 static void clearYMD_HMS_TZ(DateTime *p){
11688   p->validYMD = 0;
11689   p->validHMS = 0;
11690   p->validTZ = 0;
11691 }
11692
11693 #ifndef SQLITE_OMIT_LOCALTIME
11694 /*
11695 ** Compute the difference (in milliseconds)
11696 ** between localtime and UTC (a.k.a. GMT)
11697 ** for the time value p where p is in UTC.
11698 */
11699 static int localtimeOffset(DateTime *p){
11700   DateTime x, y;
11701   time_t t;
11702   x = *p;
11703   computeYMD_HMS(&x);
11704   if( x.Y<1971 || x.Y>=2038 ){
11705     x.Y = 2000;
11706     x.M = 1;
11707     x.D = 1;
11708     x.h = 0;
11709     x.m = 0;
11710     x.s = 0.0;
11711   } else {
11712     int s = x.s + 0.5;
11713     x.s = s;
11714   }
11715   x.tz = 0;
11716   x.validJD = 0;
11717   computeJD(&x);
11718   t = x.iJD/1000 - 2440587.5*86400.0;
11719 #ifdef HAVE_LOCALTIME_R
11720   {
11721     struct tm sLocal;
11722     localtime_r(&t, &sLocal);
11723     y.Y = sLocal.tm_year + 1900;
11724     y.M = sLocal.tm_mon + 1;
11725     y.D = sLocal.tm_mday;
11726     y.h = sLocal.tm_hour;
11727     y.m = sLocal.tm_min;
11728     y.s = sLocal.tm_sec;
11729   }
11730 #elif defined(HAVE_LOCALTIME_S)
11731   {
11732     struct tm sLocal;
11733     localtime_s(&sLocal, &t);
11734     y.Y = sLocal.tm_year + 1900;
11735     y.M = sLocal.tm_mon + 1;
11736     y.D = sLocal.tm_mday;
11737     y.h = sLocal.tm_hour;
11738     y.m = sLocal.tm_min;
11739     y.s = sLocal.tm_sec;
11740   }
11741 #else
11742   {
11743     struct tm *pTm;
11744     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
11745     pTm = localtime(&t);
11746     y.Y = pTm->tm_year + 1900;
11747     y.M = pTm->tm_mon + 1;
11748     y.D = pTm->tm_mday;
11749     y.h = pTm->tm_hour;
11750     y.m = pTm->tm_min;
11751     y.s = pTm->tm_sec;
11752     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
11753   }
11754 #endif
11755   y.validYMD = 1;
11756   y.validHMS = 1;
11757   y.validJD = 0;
11758   y.validTZ = 0;
11759   computeJD(&y);
11760   return y.iJD - x.iJD;
11761 }
11762 #endif /* SQLITE_OMIT_LOCALTIME */
11763
11764 /*
11765 ** Process a modifier to a date-time stamp.  The modifiers are
11766 ** as follows:
11767 **
11768 **     NNN days
11769 **     NNN hours
11770 **     NNN minutes
11771 **     NNN.NNNN seconds
11772 **     NNN months
11773 **     NNN years
11774 **     start of month
11775 **     start of year
11776 **     start of week
11777 **     start of day
11778 **     weekday N
11779 **     unixepoch
11780 **     localtime
11781 **     utc
11782 **
11783 ** Return 0 on success and 1 if there is any kind of error.
11784 */
11785 static int parseModifier(const char *zMod, DateTime *p){
11786   int rc = 1;
11787   int n;
11788   double r;
11789   char *z, zBuf[30];
11790   z = zBuf;
11791   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
11792     z[n] = tolower(zMod[n]);
11793   }
11794   z[n] = 0;
11795   switch( z[0] ){
11796 #ifndef SQLITE_OMIT_LOCALTIME
11797     case 'l': {
11798       /*    localtime
11799       **
11800       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
11801       ** show local time.
11802       */
11803       if( strcmp(z, "localtime")==0 ){
11804         computeJD(p);
11805         p->iJD += localtimeOffset(p);
11806         clearYMD_HMS_TZ(p);
11807         rc = 0;
11808       }
11809       break;
11810     }
11811 #endif
11812     case 'u': {
11813       /*
11814       **    unixepoch
11815       **
11816       ** Treat the current value of p->iJD as the number of
11817       ** seconds since 1970.  Convert to a real julian day number.
11818       */
11819       if( strcmp(z, "unixepoch")==0 && p->validJD ){
11820         p->iJD = p->iJD/86400.0 + 2440587.5*86400000.0;
11821         clearYMD_HMS_TZ(p);
11822         rc = 0;
11823       }
11824 #ifndef SQLITE_OMIT_LOCALTIME
11825       else if( strcmp(z, "utc")==0 ){
11826         int c1;
11827         computeJD(p);
11828         c1 = localtimeOffset(p);
11829         p->iJD -= c1;
11830         clearYMD_HMS_TZ(p);
11831         p->iJD += c1 - localtimeOffset(p);
11832         rc = 0;
11833       }
11834 #endif
11835       break;
11836     }
11837     case 'w': {
11838       /*
11839       **    weekday N
11840       **
11841       ** Move the date to the same time on the next occurrence of
11842       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
11843       ** date is already on the appropriate weekday, this is a no-op.
11844       */
11845       if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
11846                  && (n=r)==r && n>=0 && r<7 ){
11847         sqlite3_int64 Z;
11848         computeYMD_HMS(p);
11849         p->validTZ = 0;
11850         p->validJD = 0;
11851         computeJD(p);
11852         Z = ((p->iJD + 129600000)/86400000) % 7;
11853         if( Z>n ) Z -= 7;
11854         p->iJD += (n - Z)*86400000;
11855         clearYMD_HMS_TZ(p);
11856         rc = 0;
11857       }
11858       break;
11859     }
11860     case 's': {
11861       /*
11862       **    start of TTTTT
11863       **
11864       ** Move the date backwards to the beginning of the current day,
11865       ** or month or year.
11866       */
11867       if( strncmp(z, "start of ", 9)!=0 ) break;
11868       z += 9;
11869       computeYMD(p);
11870       p->validHMS = 1;
11871       p->h = p->m = 0;
11872       p->s = 0.0;
11873       p->validTZ = 0;
11874       p->validJD = 0;
11875       if( strcmp(z,"month")==0 ){
11876         p->D = 1;
11877         rc = 0;
11878       }else if( strcmp(z,"year")==0 ){
11879         computeYMD(p);
11880         p->M = 1;
11881         p->D = 1;
11882         rc = 0;
11883       }else if( strcmp(z,"day")==0 ){
11884         rc = 0;
11885       }
11886       break;
11887     }
11888     case '+':
11889     case '-':
11890     case '0':
11891     case '1':
11892     case '2':
11893     case '3':
11894     case '4':
11895     case '5':
11896     case '6':
11897     case '7':
11898     case '8':
11899     case '9': {
11900       n = getValue(z, &r);
11901       assert( n>=1 );
11902       if( z[n]==':' ){
11903         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
11904         ** specified number of hours, minutes, seconds, and fractional seconds
11905         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
11906         ** omitted.
11907         */
11908         const char *z2 = z;
11909         DateTime tx;
11910         sqlite3_int64 day;
11911         if( !isdigit(*(u8*)z2) ) z2++;
11912         memset(&tx, 0, sizeof(tx));
11913         if( parseHhMmSs(z2, &tx) ) break;
11914         computeJD(&tx);
11915         tx.iJD -= 43200000;
11916         day = tx.iJD/86400000;
11917         tx.iJD -= day*86400000;
11918         if( z[0]=='-' ) tx.iJD = -tx.iJD;
11919         computeJD(p);
11920         clearYMD_HMS_TZ(p);
11921         p->iJD += tx.iJD;
11922         rc = 0;
11923         break;
11924       }
11925       z += n;
11926       while( isspace(*(u8*)z) ) z++;
11927       n = strlen(z);
11928       if( n>10 || n<3 ) break;
11929       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
11930       computeJD(p);
11931       rc = 0;
11932       if( n==3 && strcmp(z,"day")==0 ){
11933         p->iJD += r*86400000.0 + 0.5;
11934       }else if( n==4 && strcmp(z,"hour")==0 ){
11935         p->iJD += r*(86400000.0/24.0) + 0.5;
11936       }else if( n==6 && strcmp(z,"minute")==0 ){
11937         p->iJD += r*(86400000.0/(24.0*60.0)) + 0.5;
11938       }else if( n==6 && strcmp(z,"second")==0 ){
11939         p->iJD += r*(86400000.0/(24.0*60.0*60.0)) + 0.5;
11940       }else if( n==5 && strcmp(z,"month")==0 ){
11941         int x, y;
11942         computeYMD_HMS(p);
11943         p->M += r;
11944         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
11945         p->Y += x;
11946         p->M -= x*12;
11947         p->validJD = 0;
11948         computeJD(p);
11949         y = r;
11950         if( y!=r ){
11951           p->iJD += (r - y)*30.0*86400000.0 + 0.5;
11952         }
11953       }else if( n==4 && strcmp(z,"year")==0 ){
11954         computeYMD_HMS(p);
11955         p->Y += r;
11956         p->validJD = 0;
11957         computeJD(p);
11958       }else{
11959         rc = 1;
11960       }
11961       clearYMD_HMS_TZ(p);
11962       break;
11963     }
11964     default: {
11965       break;
11966     }
11967   }
11968   return rc;
11969 }
11970
11971 /*
11972 ** Process time function arguments.  argv[0] is a date-time stamp.
11973 ** argv[1] and following are modifiers.  Parse them all and write
11974 ** the resulting time into the DateTime structure p.  Return 0
11975 ** on success and 1 if there are any errors.
11976 **
11977 ** If there are zero parameters (if even argv[0] is undefined)
11978 ** then assume a default value of "now" for argv[0].
11979 */
11980 static int isDate(
11981   sqlite3_context *context, 
11982   int argc, 
11983   sqlite3_value **argv, 
11984   DateTime *p
11985 ){
11986   int i;
11987   const unsigned char *z;
11988   int eType;
11989   memset(p, 0, sizeof(*p));
11990   if( argc==0 ){
11991     setDateTimeToCurrent(context, p);
11992   }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
11993                    || eType==SQLITE_INTEGER ){
11994     p->iJD = sqlite3_value_double(argv[0])*86400000.0 + 0.5;
11995     p->validJD = 1;
11996   }else{
11997     z = sqlite3_value_text(argv[0]);
11998     if( !z || parseDateOrTime(context, (char*)z, p) ){
11999       return 1;
12000     }
12001   }
12002   for(i=1; i<argc; i++){
12003     if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
12004       return 1;
12005     }
12006   }
12007   return 0;
12008 }
12009
12010
12011 /*
12012 ** The following routines implement the various date and time functions
12013 ** of SQLite.
12014 */
12015
12016 /*
12017 **    julianday( TIMESTRING, MOD, MOD, ...)
12018 **
12019 ** Return the julian day number of the date specified in the arguments
12020 */
12021 static void juliandayFunc(
12022   sqlite3_context *context,
12023   int argc,
12024   sqlite3_value **argv
12025 ){
12026   DateTime x;
12027   if( isDate(context, argc, argv, &x)==0 ){
12028     computeJD(&x);
12029     sqlite3_result_double(context, x.iJD/86400000.0);
12030   }
12031 }
12032
12033 /*
12034 **    datetime( TIMESTRING, MOD, MOD, ...)
12035 **
12036 ** Return YYYY-MM-DD HH:MM:SS
12037 */
12038 static void datetimeFunc(
12039   sqlite3_context *context,
12040   int argc,
12041   sqlite3_value **argv
12042 ){
12043   DateTime x;
12044   if( isDate(context, argc, argv, &x)==0 ){
12045     char zBuf[100];
12046     computeYMD_HMS(&x);
12047     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
12048                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
12049     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12050   }
12051 }
12052
12053 /*
12054 **    time( TIMESTRING, MOD, MOD, ...)
12055 **
12056 ** Return HH:MM:SS
12057 */
12058 static void timeFunc(
12059   sqlite3_context *context,
12060   int argc,
12061   sqlite3_value **argv
12062 ){
12063   DateTime x;
12064   if( isDate(context, argc, argv, &x)==0 ){
12065     char zBuf[100];
12066     computeHMS(&x);
12067     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
12068     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12069   }
12070 }
12071
12072 /*
12073 **    date( TIMESTRING, MOD, MOD, ...)
12074 **
12075 ** Return YYYY-MM-DD
12076 */
12077 static void dateFunc(
12078   sqlite3_context *context,
12079   int argc,
12080   sqlite3_value **argv
12081 ){
12082   DateTime x;
12083   if( isDate(context, argc, argv, &x)==0 ){
12084     char zBuf[100];
12085     computeYMD(&x);
12086     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
12087     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12088   }
12089 }
12090
12091 /*
12092 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
12093 **
12094 ** Return a string described by FORMAT.  Conversions as follows:
12095 **
12096 **   %d  day of month
12097 **   %f  ** fractional seconds  SS.SSS
12098 **   %H  hour 00-24
12099 **   %j  day of year 000-366
12100 **   %J  ** Julian day number
12101 **   %m  month 01-12
12102 **   %M  minute 00-59
12103 **   %s  seconds since 1970-01-01
12104 **   %S  seconds 00-59
12105 **   %w  day of week 0-6  sunday==0
12106 **   %W  week of year 00-53
12107 **   %Y  year 0000-9999
12108 **   %%  %
12109 */
12110 static void strftimeFunc(
12111   sqlite3_context *context,
12112   int argc,
12113   sqlite3_value **argv
12114 ){
12115   DateTime x;
12116   u64 n;
12117   int i, j;
12118   char *z;
12119   sqlite3 *db;
12120   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
12121   char zBuf[100];
12122   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
12123   db = sqlite3_context_db_handle(context);
12124   for(i=0, n=1; zFmt[i]; i++, n++){
12125     if( zFmt[i]=='%' ){
12126       switch( zFmt[i+1] ){
12127         case 'd':
12128         case 'H':
12129         case 'm':
12130         case 'M':
12131         case 'S':
12132         case 'W':
12133           n++;
12134           /* fall thru */
12135         case 'w':
12136         case '%':
12137           break;
12138         case 'f':
12139           n += 8;
12140           break;
12141         case 'j':
12142           n += 3;
12143           break;
12144         case 'Y':
12145           n += 8;
12146           break;
12147         case 's':
12148         case 'J':
12149           n += 50;
12150           break;
12151         default:
12152           return;  /* ERROR.  return a NULL */
12153       }
12154       i++;
12155     }
12156   }
12157   if( n<sizeof(zBuf) ){
12158     z = zBuf;
12159   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
12160     sqlite3_result_error_toobig(context);
12161     return;
12162   }else{
12163     z = sqlite3DbMallocRaw(db, n);
12164     if( z==0 ){
12165       sqlite3_result_error_nomem(context);
12166       return;
12167     }
12168   }
12169   computeJD(&x);
12170   computeYMD_HMS(&x);
12171   for(i=j=0; zFmt[i]; i++){
12172     if( zFmt[i]!='%' ){
12173       z[j++] = zFmt[i];
12174     }else{
12175       i++;
12176       switch( zFmt[i] ){
12177         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
12178         case 'f': {
12179           double s = x.s;
12180           if( s>59.999 ) s = 59.999;
12181           sqlite3_snprintf(7, &z[j],"%06.3f", s);
12182           j += strlen(&z[j]);
12183           break;
12184         }
12185         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
12186         case 'W': /* Fall thru */
12187         case 'j': {
12188           int nDay;             /* Number of days since 1st day of year */
12189           DateTime y = x;
12190           y.validJD = 0;
12191           y.M = 1;
12192           y.D = 1;
12193           computeJD(&y);
12194           nDay = (x.iJD - y.iJD)/86400000.0 + 0.5;
12195           if( zFmt[i]=='W' ){
12196             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
12197             wd = ((x.iJD+43200000)/86400000) % 7;
12198             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
12199             j += 2;
12200           }else{
12201             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
12202             j += 3;
12203           }
12204           break;
12205         }
12206         case 'J': {
12207           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
12208           j+=strlen(&z[j]);
12209           break;
12210         }
12211         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
12212         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
12213         case 's': {
12214           sqlite3_snprintf(30,&z[j],"%d",
12215                            (int)(x.iJD/1000.0 - 210866760000.0));
12216           j += strlen(&z[j]);
12217           break;
12218         }
12219         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
12220         case 'w':  z[j++] = (((x.iJD+129600000)/86400000) % 7) + '0'; break;
12221         case 'Y':  sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=strlen(&z[j]);break;
12222         default:   z[j++] = '%'; break;
12223       }
12224     }
12225   }
12226   z[j] = 0;
12227   sqlite3_result_text(context, z, -1,
12228                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
12229 }
12230
12231 /*
12232 ** current_time()
12233 **
12234 ** This function returns the same value as time('now').
12235 */
12236 static void ctimeFunc(
12237   sqlite3_context *context,
12238   int NotUsed,
12239   sqlite3_value **NotUsed2
12240 ){
12241   UNUSED_PARAMETER2(NotUsed, NotUsed2);
12242   timeFunc(context, 0, 0);
12243 }
12244
12245 /*
12246 ** current_date()
12247 **
12248 ** This function returns the same value as date('now').
12249 */
12250 static void cdateFunc(
12251   sqlite3_context *context,
12252   int NotUsed,
12253   sqlite3_value **NotUsed2
12254 ){
12255   UNUSED_PARAMETER2(NotUsed, NotUsed2);
12256   dateFunc(context, 0, 0);
12257 }
12258
12259 /*
12260 ** current_timestamp()
12261 **
12262 ** This function returns the same value as datetime('now').
12263 */
12264 static void ctimestampFunc(
12265   sqlite3_context *context,
12266   int NotUsed,
12267   sqlite3_value **NotUsed2
12268 ){
12269   UNUSED_PARAMETER2(NotUsed, NotUsed2);
12270   datetimeFunc(context, 0, 0);
12271 }
12272 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
12273
12274 #ifdef SQLITE_OMIT_DATETIME_FUNCS
12275 /*
12276 ** If the library is compiled to omit the full-scale date and time
12277 ** handling (to get a smaller binary), the following minimal version
12278 ** of the functions current_time(), current_date() and current_timestamp()
12279 ** are included instead. This is to support column declarations that
12280 ** include "DEFAULT CURRENT_TIME" etc.
12281 **
12282 ** This function uses the C-library functions time(), gmtime()
12283 ** and strftime(). The format string to pass to strftime() is supplied
12284 ** as the user-data for the function.
12285 */
12286 static void currentTimeFunc(
12287   sqlite3_context *context,
12288   int argc,
12289   sqlite3_value **argv
12290 ){
12291   time_t t;
12292   char *zFormat = (char *)sqlite3_user_data(context);
12293   sqlite3 *db;
12294   double rT;
12295   char zBuf[20];
12296
12297   db = sqlite3_context_db_handle(context);
12298   sqlite3OsCurrentTime(db->pVfs, &rT);
12299   t = 86400.0*(rT - 2440587.5) + 0.5;
12300 #ifdef HAVE_GMTIME_R
12301   {
12302     struct tm sNow;
12303     gmtime_r(&t, &sNow);
12304     strftime(zBuf, 20, zFormat, &sNow);
12305   }
12306 #else
12307   {
12308     struct tm *pTm;
12309     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12310     pTm = gmtime(&t);
12311     strftime(zBuf, 20, zFormat, pTm);
12312     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12313   }
12314 #endif
12315
12316   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12317 }
12318 #endif
12319
12320 /*
12321 ** This function registered all of the above C functions as SQL
12322 ** functions.  This should be the only routine in this file with
12323 ** external linkage.
12324 */
12325 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
12326   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
12327 #ifndef SQLITE_OMIT_DATETIME_FUNCS
12328     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
12329     FUNCTION(date,             -1, 0, 0, dateFunc      ),
12330     FUNCTION(time,             -1, 0, 0, timeFunc      ),
12331     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
12332     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
12333     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
12334     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
12335     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
12336 #else
12337     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
12338     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d",          0, currentTimeFunc),
12339     STR_FUNCTION(current_date,      0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
12340 #endif
12341   };
12342   int i;
12343   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
12344   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
12345
12346   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
12347     sqlite3FuncDefInsert(pHash, &aFunc[i]);
12348   }
12349 }
12350
12351 /************** End of date.c ************************************************/
12352 /************** Begin file os.c **********************************************/
12353 /*
12354 ** 2005 November 29
12355 **
12356 ** The author disclaims copyright to this source code.  In place of
12357 ** a legal notice, here is a blessing:
12358 **
12359 **    May you do good and not evil.
12360 **    May you find forgiveness for yourself and forgive others.
12361 **    May you share freely, never taking more than you give.
12362 **
12363 ******************************************************************************
12364 **
12365 ** This file contains OS interface code that is common to all
12366 ** architectures.
12367 **
12368 ** $Id: os.c,v 1.124 2008/10/07 15:25:48 drh Exp $
12369 */
12370 #define _SQLITE_OS_C_ 1
12371 #undef _SQLITE_OS_C_
12372
12373 /*
12374 ** The default SQLite sqlite3_vfs implementations do not allocate
12375 ** memory (actually, os_unix.c allocates a small amount of memory
12376 ** from within OsOpen()), but some third-party implementations may.
12377 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
12378 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
12379 **
12380 ** The following functions are instrumented for malloc() failure 
12381 ** testing:
12382 **
12383 **     sqlite3OsOpen()
12384 **     sqlite3OsRead()
12385 **     sqlite3OsWrite()
12386 **     sqlite3OsSync()
12387 **     sqlite3OsLock()
12388 **
12389 */
12390 #if defined(SQLITE_TEST) && (SQLITE_OS_WIN==0)
12391   #define DO_OS_MALLOC_TEST if (1) {            \
12392     void *pTstAlloc = sqlite3Malloc(10);       \
12393     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;  \
12394     sqlite3_free(pTstAlloc);                    \
12395   }
12396 #else
12397   #define DO_OS_MALLOC_TEST
12398 #endif
12399
12400 /*
12401 ** The following routines are convenience wrappers around methods
12402 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
12403 ** of this would be completely automatic if SQLite were coded using
12404 ** C++ instead of plain old C.
12405 */
12406 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
12407   int rc = SQLITE_OK;
12408   if( pId->pMethods ){
12409     rc = pId->pMethods->xClose(pId);
12410     pId->pMethods = 0;
12411   }
12412   return rc;
12413 }
12414 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
12415   DO_OS_MALLOC_TEST;
12416   return id->pMethods->xRead(id, pBuf, amt, offset);
12417 }
12418 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
12419   DO_OS_MALLOC_TEST;
12420   return id->pMethods->xWrite(id, pBuf, amt, offset);
12421 }
12422 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
12423   return id->pMethods->xTruncate(id, size);
12424 }
12425 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
12426   DO_OS_MALLOC_TEST;
12427   return id->pMethods->xSync(id, flags);
12428 }
12429 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
12430   DO_OS_MALLOC_TEST;
12431   return id->pMethods->xFileSize(id, pSize);
12432 }
12433 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
12434   DO_OS_MALLOC_TEST;
12435   return id->pMethods->xLock(id, lockType);
12436 }
12437 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
12438   return id->pMethods->xUnlock(id, lockType);
12439 }
12440 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
12441   DO_OS_MALLOC_TEST;
12442   return id->pMethods->xCheckReservedLock(id, pResOut);
12443 }
12444 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
12445   return id->pMethods->xFileControl(id, op, pArg);
12446 }
12447 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
12448   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
12449   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
12450 }
12451 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
12452   return id->pMethods->xDeviceCharacteristics(id);
12453 }
12454
12455 /*
12456 ** The next group of routines are convenience wrappers around the
12457 ** VFS methods.
12458 */
12459 SQLITE_PRIVATE int sqlite3OsOpen(
12460   sqlite3_vfs *pVfs, 
12461   const char *zPath, 
12462   sqlite3_file *pFile, 
12463   int flags, 
12464   int *pFlagsOut
12465 ){
12466   DO_OS_MALLOC_TEST;
12467   return pVfs->xOpen(pVfs, zPath, pFile, flags, pFlagsOut);
12468 }
12469 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
12470   return pVfs->xDelete(pVfs, zPath, dirSync);
12471 }
12472 SQLITE_PRIVATE int sqlite3OsAccess(
12473   sqlite3_vfs *pVfs, 
12474   const char *zPath, 
12475   int flags, 
12476   int *pResOut
12477 ){
12478   DO_OS_MALLOC_TEST;
12479   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
12480 }
12481 SQLITE_PRIVATE int sqlite3OsFullPathname(
12482   sqlite3_vfs *pVfs, 
12483   const char *zPath, 
12484   int nPathOut, 
12485   char *zPathOut
12486 ){
12487   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
12488 }
12489 #ifndef SQLITE_OMIT_LOAD_EXTENSION
12490 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
12491   return pVfs->xDlOpen(pVfs, zPath);
12492 }
12493 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
12494   pVfs->xDlError(pVfs, nByte, zBufOut);
12495 }
12496 SQLITE_PRIVATE void *sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
12497   return pVfs->xDlSym(pVfs, pHandle, zSymbol);
12498 }
12499 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
12500   pVfs->xDlClose(pVfs, pHandle);
12501 }
12502 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
12503 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
12504   return pVfs->xRandomness(pVfs, nByte, zBufOut);
12505 }
12506 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
12507   return pVfs->xSleep(pVfs, nMicro);
12508 }
12509 SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
12510   return pVfs->xCurrentTime(pVfs, pTimeOut);
12511 }
12512
12513 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
12514   sqlite3_vfs *pVfs, 
12515   const char *zFile, 
12516   sqlite3_file **ppFile, 
12517   int flags,
12518   int *pOutFlags
12519 ){
12520   int rc = SQLITE_NOMEM;
12521   sqlite3_file *pFile;
12522   pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
12523   if( pFile ){
12524     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
12525     if( rc!=SQLITE_OK ){
12526       sqlite3_free(pFile);
12527     }else{
12528       *ppFile = pFile;
12529     }
12530   }
12531   return rc;
12532 }
12533 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
12534   int rc = SQLITE_OK;
12535   assert( pFile );
12536   rc = sqlite3OsClose(pFile);
12537   sqlite3_free(pFile);
12538   return rc;
12539 }
12540
12541 /*
12542 ** The list of all registered VFS implementations.
12543 */
12544 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
12545 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
12546
12547 /*
12548 ** Locate a VFS by name.  If no name is given, simply return the
12549 ** first VFS on the list.
12550 */
12551 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
12552   sqlite3_vfs *pVfs = 0;
12553 #if SQLITE_THREADSAFE
12554   sqlite3_mutex *mutex;
12555 #endif
12556 #ifndef SQLITE_OMIT_AUTOINIT
12557   int rc = sqlite3_initialize();
12558   if( rc ) return 0;
12559 #endif
12560 #if SQLITE_THREADSAFE
12561   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
12562 #endif
12563   sqlite3_mutex_enter(mutex);
12564   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
12565     if( zVfs==0 ) break;
12566     if( strcmp(zVfs, pVfs->zName)==0 ) break;
12567   }
12568   sqlite3_mutex_leave(mutex);
12569   return pVfs;
12570 }
12571
12572 /*
12573 ** Unlink a VFS from the linked list
12574 */
12575 static void vfsUnlink(sqlite3_vfs *pVfs){
12576   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
12577   if( pVfs==0 ){
12578     /* No-op */
12579   }else if( vfsList==pVfs ){
12580     vfsList = pVfs->pNext;
12581   }else if( vfsList ){
12582     sqlite3_vfs *p = vfsList;
12583     while( p->pNext && p->pNext!=pVfs ){
12584       p = p->pNext;
12585     }
12586     if( p->pNext==pVfs ){
12587       p->pNext = pVfs->pNext;
12588     }
12589   }
12590 }
12591
12592 /*
12593 ** Register a VFS with the system.  It is harmless to register the same
12594 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
12595 ** true.
12596 */
12597 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
12598   sqlite3_mutex *mutex = 0;
12599 #ifndef SQLITE_OMIT_AUTOINIT
12600   int rc = sqlite3_initialize();
12601   if( rc ) return rc;
12602 #endif
12603   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
12604   sqlite3_mutex_enter(mutex);
12605   vfsUnlink(pVfs);
12606   if( makeDflt || vfsList==0 ){
12607     pVfs->pNext = vfsList;
12608     vfsList = pVfs;
12609   }else{
12610     pVfs->pNext = vfsList->pNext;
12611     vfsList->pNext = pVfs;
12612   }
12613   assert(vfsList);
12614   sqlite3_mutex_leave(mutex);
12615   return SQLITE_OK;
12616 }
12617
12618 /*
12619 ** Unregister a VFS so that it is no longer accessible.
12620 */
12621 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
12622 #if SQLITE_THREADSAFE
12623   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
12624 #endif
12625   sqlite3_mutex_enter(mutex);
12626   vfsUnlink(pVfs);
12627   sqlite3_mutex_leave(mutex);
12628   return SQLITE_OK;
12629 }
12630
12631 /************** End of os.c **************************************************/
12632 /************** Begin file fault.c *******************************************/
12633 /*
12634 ** 2008 Jan 22
12635 **
12636 ** The author disclaims copyright to this source code.  In place of
12637 ** a legal notice, here is a blessing:
12638 **
12639 **    May you do good and not evil.
12640 **    May you find forgiveness for yourself and forgive others.
12641 **    May you share freely, never taking more than you give.
12642 **
12643 *************************************************************************
12644 **
12645 ** $Id: fault.c,v 1.11 2008/09/02 00:52:52 drh Exp $
12646 */
12647
12648 /*
12649 ** This file contains code to support the concept of "benign" 
12650 ** malloc failures (when the xMalloc() or xRealloc() method of the
12651 ** sqlite3_mem_methods structure fails to allocate a block of memory
12652 ** and returns 0). 
12653 **
12654 ** Most malloc failures are non-benign. After they occur, SQLite
12655 ** abandons the current operation and returns an error code (usually
12656 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
12657 ** fatal. For example, if a malloc fails while resizing a hash table, this 
12658 ** is completely recoverable simply by not carrying out the resize. The 
12659 ** hash table will continue to function normally.  So a malloc failure 
12660 ** during a hash table resize is a benign fault.
12661 */
12662
12663
12664 #ifndef SQLITE_OMIT_BUILTIN_TEST
12665
12666 /*
12667 ** Global variables.
12668 */
12669 typedef struct BenignMallocHooks BenignMallocHooks;
12670 static SQLITE_WSD struct BenignMallocHooks {
12671   void (*xBenignBegin)(void);
12672   void (*xBenignEnd)(void);
12673 } sqlite3Hooks = { 0, 0 };
12674
12675 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
12676 ** structure.  If writable static data is unsupported on the target,
12677 ** we have to locate the state vector at run-time.  In the more common
12678 ** case where writable static data is supported, wsdHooks can refer directly
12679 ** to the "sqlite3Hooks" state vector declared above.
12680 */
12681 #ifdef SQLITE_OMIT_WSD
12682 # define wsdHooksInit \
12683   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
12684 # define wsdHooks x[0]
12685 #else
12686 # define wsdHooksInit
12687 # define wsdHooks sqlite3Hooks
12688 #endif
12689
12690
12691 /*
12692 ** Register hooks to call when sqlite3BeginBenignMalloc() and
12693 ** sqlite3EndBenignMalloc() are called, respectively.
12694 */
12695 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
12696   void (*xBenignBegin)(void),
12697   void (*xBenignEnd)(void)
12698 ){
12699   wsdHooksInit;
12700   wsdHooks.xBenignBegin = xBenignBegin;
12701   wsdHooks.xBenignEnd = xBenignEnd;
12702 }
12703
12704 /*
12705 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
12706 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
12707 ** indicates that subsequent malloc failures are non-benign.
12708 */
12709 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
12710   wsdHooksInit;
12711   if( wsdHooks.xBenignBegin ){
12712     wsdHooks.xBenignBegin();
12713   }
12714 }
12715 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
12716   wsdHooksInit;
12717   if( wsdHooks.xBenignEnd ){
12718     wsdHooks.xBenignEnd();
12719   }
12720 }
12721
12722 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
12723
12724 /************** End of fault.c ***********************************************/
12725 /************** Begin file mem0.c ********************************************/
12726 /*
12727 ** 2008 October 28
12728 **
12729 ** The author disclaims copyright to this source code.  In place of
12730 ** a legal notice, here is a blessing:
12731 **
12732 **    May you do good and not evil.
12733 **    May you find forgiveness for yourself and forgive others.
12734 **    May you share freely, never taking more than you give.
12735 **
12736 *************************************************************************
12737 **
12738 ** This file contains a no-op memory allocation drivers for use when
12739 ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
12740 ** here always fail.  SQLite will not operate with these drivers.  These
12741 ** are merely placeholders.  Real drivers must be substituted using
12742 ** sqlite3_config() before SQLite will operate.
12743 **
12744 ** $Id: mem0.c,v 1.1 2008/10/28 18:58:20 drh Exp $
12745 */
12746
12747 /*
12748 ** This version of the memory allocator is the default.  It is
12749 ** used when no other memory allocator is specified using compile-time
12750 ** macros.
12751 */
12752 #ifdef SQLITE_ZERO_MALLOC
12753
12754 /*
12755 ** No-op versions of all memory allocation routines
12756 */
12757 static void *sqlite3MemMalloc(int nByte){ return 0; }
12758 static void sqlite3MemFree(void *pPrior){ return; }
12759 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
12760 static int sqlite3MemSize(void *pPrior){ return 0; }
12761 static int sqlite3MemRoundup(int n){ return n; }
12762 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
12763 static void sqlite3MemShutdown(void *NotUsed){ return; }
12764
12765 /*
12766 ** This routine is the only routine in this file with external linkage.
12767 **
12768 ** Populate the low-level memory allocation function pointers in
12769 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
12770 */
12771 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
12772   static const sqlite3_mem_methods defaultMethods = {
12773      sqlite3MemMalloc,
12774      sqlite3MemFree,
12775      sqlite3MemRealloc,
12776      sqlite3MemSize,
12777      sqlite3MemRoundup,
12778      sqlite3MemInit,
12779      sqlite3MemShutdown,
12780      0
12781   };
12782   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
12783 }
12784
12785 #endif /* SQLITE_ZERO_MALLOC */
12786
12787 /************** End of mem0.c ************************************************/
12788 /************** Begin file mem1.c ********************************************/
12789 /*
12790 ** 2007 August 14
12791 **
12792 ** The author disclaims copyright to this source code.  In place of
12793 ** a legal notice, here is a blessing:
12794 **
12795 **    May you do good and not evil.
12796 **    May you find forgiveness for yourself and forgive others.
12797 **    May you share freely, never taking more than you give.
12798 **
12799 *************************************************************************
12800 **
12801 ** This file contains low-level memory allocation drivers for when
12802 ** SQLite will use the standard C-library malloc/realloc/free interface
12803 ** to obtain the memory it needs.
12804 **
12805 ** This file contains implementations of the low-level memory allocation
12806 ** routines specified in the sqlite3_mem_methods object.
12807 **
12808 ** $Id: mem1.c,v 1.28 2008/11/19 09:05:27 danielk1977 Exp $
12809 */
12810
12811 /*
12812 ** This version of the memory allocator is the default.  It is
12813 ** used when no other memory allocator is specified using compile-time
12814 ** macros.
12815 */
12816 #ifdef SQLITE_SYSTEM_MALLOC
12817
12818 /*
12819 ** Like malloc(), but remember the size of the allocation
12820 ** so that we can find it later using sqlite3MemSize().
12821 **
12822 ** For this low-level routine, we are guaranteed that nByte>0 because
12823 ** cases of nByte<=0 will be intercepted and dealt with by higher level
12824 ** routines.
12825 */
12826 static void *sqlite3MemMalloc(int nByte){
12827   sqlite3_int64 *p;
12828   assert( nByte>0 );
12829   nByte = (nByte+7)&~7;
12830   p = malloc( nByte+8 );
12831   if( p ){
12832     p[0] = nByte;
12833     p++;
12834   }
12835   return (void *)p;
12836 }
12837
12838 /*
12839 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
12840 ** or sqlite3MemRealloc().
12841 **
12842 ** For this low-level routine, we already know that pPrior!=0 since
12843 ** cases where pPrior==0 will have been intecepted and dealt with
12844 ** by higher-level routines.
12845 */
12846 static void sqlite3MemFree(void *pPrior){
12847   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
12848   assert( pPrior!=0 );
12849   p--;
12850   free(p);
12851 }
12852
12853 /*
12854 ** Like realloc().  Resize an allocation previously obtained from
12855 ** sqlite3MemMalloc().
12856 **
12857 ** For this low-level interface, we know that pPrior!=0.  Cases where
12858 ** pPrior==0 while have been intercepted by higher-level routine and
12859 ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
12860 ** cases where nByte<=0 will have been intercepted by higher-level
12861 ** routines and redirected to xFree.
12862 */
12863 static void *sqlite3MemRealloc(void *pPrior, int nByte){
12864   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
12865   assert( pPrior!=0 && nByte>0 );
12866   nByte = (nByte+7)&~7;
12867   p = (sqlite3_int64*)pPrior;
12868   p--;
12869   p = realloc(p, nByte+8 );
12870   if( p ){
12871     p[0] = nByte;
12872     p++;
12873   }
12874   return (void*)p;
12875 }
12876
12877 /*
12878 ** Report the allocated size of a prior return from xMalloc()
12879 ** or xRealloc().
12880 */
12881 static int sqlite3MemSize(void *pPrior){
12882   sqlite3_int64 *p;
12883   if( pPrior==0 ) return 0;
12884   p = (sqlite3_int64*)pPrior;
12885   p--;
12886   return p[0];
12887 }
12888
12889 /*
12890 ** Round up a request size to the next valid allocation size.
12891 */
12892 static int sqlite3MemRoundup(int n){
12893   return (n+7) & ~7;
12894 }
12895
12896 /*
12897 ** Initialize this module.
12898 */
12899 static int sqlite3MemInit(void *NotUsed){
12900   UNUSED_PARAMETER(NotUsed);
12901   return SQLITE_OK;
12902 }
12903
12904 /*
12905 ** Deinitialize this module.
12906 */
12907 static void sqlite3MemShutdown(void *NotUsed){
12908   UNUSED_PARAMETER(NotUsed);
12909   return;
12910 }
12911
12912 /*
12913 ** This routine is the only routine in this file with external linkage.
12914 **
12915 ** Populate the low-level memory allocation function pointers in
12916 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
12917 */
12918 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
12919   static const sqlite3_mem_methods defaultMethods = {
12920      sqlite3MemMalloc,
12921      sqlite3MemFree,
12922      sqlite3MemRealloc,
12923      sqlite3MemSize,
12924      sqlite3MemRoundup,
12925      sqlite3MemInit,
12926      sqlite3MemShutdown,
12927      0
12928   };
12929   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
12930 }
12931
12932 #endif /* SQLITE_SYSTEM_MALLOC */
12933
12934 /************** End of mem1.c ************************************************/
12935 /************** Begin file mem2.c ********************************************/
12936 /*
12937 ** 2007 August 15
12938 **
12939 ** The author disclaims copyright to this source code.  In place of
12940 ** a legal notice, here is a blessing:
12941 **
12942 **    May you do good and not evil.
12943 **    May you find forgiveness for yourself and forgive others.
12944 **    May you share freely, never taking more than you give.
12945 **
12946 *************************************************************************
12947 **
12948 ** This file contains low-level memory allocation drivers for when
12949 ** SQLite will use the standard C-library malloc/realloc/free interface
12950 ** to obtain the memory it needs while adding lots of additional debugging
12951 ** information to each allocation in order to help detect and fix memory
12952 ** leaks and memory usage errors.
12953 **
12954 ** This file contains implementations of the low-level memory allocation
12955 ** routines specified in the sqlite3_mem_methods object.
12956 **
12957 ** $Id: mem2.c,v 1.40 2008/10/28 18:58:20 drh Exp $
12958 */
12959
12960 /*
12961 ** This version of the memory allocator is used only if the
12962 ** SQLITE_MEMDEBUG macro is defined
12963 */
12964 #ifdef SQLITE_MEMDEBUG
12965
12966 /*
12967 ** The backtrace functionality is only available with GLIBC
12968 */
12969 #ifdef __GLIBC__
12970   extern int backtrace(void**,int);
12971   extern void backtrace_symbols_fd(void*const*,int,int);
12972 #else
12973 # define backtrace(A,B) 1
12974 # define backtrace_symbols_fd(A,B,C)
12975 #endif
12976
12977 /*
12978 ** Each memory allocation looks like this:
12979 **
12980 **  ------------------------------------------------------------------------
12981 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
12982 **  ------------------------------------------------------------------------
12983 **
12984 ** The application code sees only a pointer to the allocation.  We have
12985 ** to back up from the allocation pointer to find the MemBlockHdr.  The
12986 ** MemBlockHdr tells us the size of the allocation and the number of
12987 ** backtrace pointers.  There is also a guard word at the end of the
12988 ** MemBlockHdr.
12989 */
12990 struct MemBlockHdr {
12991   i64 iSize;                          /* Size of this allocation */
12992   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
12993   char nBacktrace;                    /* Number of backtraces on this alloc */
12994   char nBacktraceSlots;               /* Available backtrace slots */
12995   short nTitle;                       /* Bytes of title; includes '\0' */
12996   int iForeGuard;                     /* Guard word for sanity */
12997 };
12998
12999 /*
13000 ** Guard words
13001 */
13002 #define FOREGUARD 0x80F5E153
13003 #define REARGUARD 0xE4676B53
13004
13005 /*
13006 ** Number of malloc size increments to track.
13007 */
13008 #define NCSIZE  1000
13009
13010 /*
13011 ** All of the static variables used by this module are collected
13012 ** into a single structure named "mem".  This is to keep the
13013 ** static variables organized and to reduce namespace pollution
13014 ** when this module is combined with other in the amalgamation.
13015 */
13016 static struct {
13017   
13018   /*
13019   ** Mutex to control access to the memory allocation subsystem.
13020   */
13021   sqlite3_mutex *mutex;
13022
13023   /*
13024   ** Head and tail of a linked list of all outstanding allocations
13025   */
13026   struct MemBlockHdr *pFirst;
13027   struct MemBlockHdr *pLast;
13028   
13029   /*
13030   ** The number of levels of backtrace to save in new allocations.
13031   */
13032   int nBacktrace;
13033   void (*xBacktrace)(int, int, void **);
13034
13035   /*
13036   ** Title text to insert in front of each block
13037   */
13038   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
13039   char zTitle[100];  /* The title text */
13040
13041   /* 
13042   ** sqlite3MallocDisallow() increments the following counter.
13043   ** sqlite3MallocAllow() decrements it.
13044   */
13045   int disallow; /* Do not allow memory allocation */
13046
13047   /*
13048   ** Gather statistics on the sizes of memory allocations.
13049   ** nAlloc[i] is the number of allocation attempts of i*8
13050   ** bytes.  i==NCSIZE is the number of allocation attempts for
13051   ** sizes more than NCSIZE*8 bytes.
13052   */
13053   int nAlloc[NCSIZE];      /* Total number of allocations */
13054   int nCurrent[NCSIZE];    /* Current number of allocations */
13055   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
13056
13057 } mem;
13058
13059
13060 /*
13061 ** Adjust memory usage statistics
13062 */
13063 static void adjustStats(int iSize, int increment){
13064   int i = ((iSize+7)&~7)/8;
13065   if( i>NCSIZE-1 ){
13066     i = NCSIZE - 1;
13067   }
13068   if( increment>0 ){
13069     mem.nAlloc[i]++;
13070     mem.nCurrent[i]++;
13071     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
13072       mem.mxCurrent[i] = mem.nCurrent[i];
13073     }
13074   }else{
13075     mem.nCurrent[i]--;
13076     assert( mem.nCurrent[i]>=0 );
13077   }
13078 }
13079
13080 /*
13081 ** Given an allocation, find the MemBlockHdr for that allocation.
13082 **
13083 ** This routine checks the guards at either end of the allocation and
13084 ** if they are incorrect it asserts.
13085 */
13086 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
13087   struct MemBlockHdr *p;
13088   int *pInt;
13089   u8 *pU8;
13090   int nReserve;
13091
13092   p = (struct MemBlockHdr*)pAllocation;
13093   p--;
13094   assert( p->iForeGuard==FOREGUARD );
13095   nReserve = (p->iSize+7)&~7;
13096   pInt = (int*)pAllocation;
13097   pU8 = (u8*)pAllocation;
13098   assert( pInt[nReserve/sizeof(int)]==REARGUARD );
13099   assert( (nReserve-0)<=p->iSize || pU8[nReserve-1]==0x65 );
13100   assert( (nReserve-1)<=p->iSize || pU8[nReserve-2]==0x65 );
13101   assert( (nReserve-2)<=p->iSize || pU8[nReserve-3]==0x65 );
13102   return p;
13103 }
13104
13105 /*
13106 ** Return the number of bytes currently allocated at address p.
13107 */
13108 static int sqlite3MemSize(void *p){
13109   struct MemBlockHdr *pHdr;
13110   if( !p ){
13111     return 0;
13112   }
13113   pHdr = sqlite3MemsysGetHeader(p);
13114   return pHdr->iSize;
13115 }
13116
13117 /*
13118 ** Initialize the memory allocation subsystem.
13119 */
13120 static int sqlite3MemInit(void *NotUsed){
13121   if( !sqlite3GlobalConfig.bMemstat ){
13122     /* If memory status is enabled, then the malloc.c wrapper will already
13123     ** hold the STATIC_MEM mutex when the routines here are invoked. */
13124     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
13125   }
13126   return SQLITE_OK;
13127 }
13128
13129 /*
13130 ** Deinitialize the memory allocation subsystem.
13131 */
13132 static void sqlite3MemShutdown(void *NotUsed){
13133   mem.mutex = 0;
13134 }
13135
13136 /*
13137 ** Round up a request size to the next valid allocation size.
13138 */
13139 static int sqlite3MemRoundup(int n){
13140   return (n+7) & ~7;
13141 }
13142
13143 /*
13144 ** Allocate nByte bytes of memory.
13145 */
13146 static void *sqlite3MemMalloc(int nByte){
13147   struct MemBlockHdr *pHdr;
13148   void **pBt;
13149   char *z;
13150   int *pInt;
13151   void *p = 0;
13152   int totalSize;
13153   int nReserve;
13154   sqlite3_mutex_enter(mem.mutex);
13155   assert( mem.disallow==0 );
13156   nReserve = (nByte+7)&~7;
13157   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
13158                mem.nBacktrace*sizeof(void*) + mem.nTitle;
13159   p = malloc(totalSize);
13160   if( p ){
13161     z = p;
13162     pBt = (void**)&z[mem.nTitle];
13163     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
13164     pHdr->pNext = 0;
13165     pHdr->pPrev = mem.pLast;
13166     if( mem.pLast ){
13167       mem.pLast->pNext = pHdr;
13168     }else{
13169       mem.pFirst = pHdr;
13170     }
13171     mem.pLast = pHdr;
13172     pHdr->iForeGuard = FOREGUARD;
13173     pHdr->nBacktraceSlots = mem.nBacktrace;
13174     pHdr->nTitle = mem.nTitle;
13175     if( mem.nBacktrace ){
13176       void *aAddr[40];
13177       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
13178       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
13179       if( mem.xBacktrace ){
13180         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
13181       }
13182     }else{
13183       pHdr->nBacktrace = 0;
13184     }
13185     if( mem.nTitle ){
13186       memcpy(z, mem.zTitle, mem.nTitle);
13187     }
13188     pHdr->iSize = nByte;
13189     adjustStats(nByte, +1);
13190     pInt = (int*)&pHdr[1];
13191     pInt[nReserve/sizeof(int)] = REARGUARD;
13192     memset(pInt, 0x65, nReserve);
13193     p = (void*)pInt;
13194   }
13195   sqlite3_mutex_leave(mem.mutex);
13196   return p; 
13197 }
13198
13199 /*
13200 ** Free memory.
13201 */
13202 static void sqlite3MemFree(void *pPrior){
13203   struct MemBlockHdr *pHdr;
13204   void **pBt;
13205   char *z;
13206   assert( sqlite3GlobalConfig.bMemstat || mem.mutex!=0 );
13207   pHdr = sqlite3MemsysGetHeader(pPrior);
13208   pBt = (void**)pHdr;
13209   pBt -= pHdr->nBacktraceSlots;
13210   sqlite3_mutex_enter(mem.mutex);
13211   if( pHdr->pPrev ){
13212     assert( pHdr->pPrev->pNext==pHdr );
13213     pHdr->pPrev->pNext = pHdr->pNext;
13214   }else{
13215     assert( mem.pFirst==pHdr );
13216     mem.pFirst = pHdr->pNext;
13217   }
13218   if( pHdr->pNext ){
13219     assert( pHdr->pNext->pPrev==pHdr );
13220     pHdr->pNext->pPrev = pHdr->pPrev;
13221   }else{
13222     assert( mem.pLast==pHdr );
13223     mem.pLast = pHdr->pPrev;
13224   }
13225   z = (char*)pBt;
13226   z -= pHdr->nTitle;
13227   adjustStats(pHdr->iSize, -1);
13228   memset(z, 0x2b, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
13229                   pHdr->iSize + sizeof(int) + pHdr->nTitle);
13230   free(z);
13231   sqlite3_mutex_leave(mem.mutex);  
13232 }
13233
13234 /*
13235 ** Change the size of an existing memory allocation.
13236 **
13237 ** For this debugging implementation, we *always* make a copy of the
13238 ** allocation into a new place in memory.  In this way, if the 
13239 ** higher level code is using pointer to the old allocation, it is 
13240 ** much more likely to break and we are much more liking to find
13241 ** the error.
13242 */
13243 static void *sqlite3MemRealloc(void *pPrior, int nByte){
13244   struct MemBlockHdr *pOldHdr;
13245   void *pNew;
13246   assert( mem.disallow==0 );
13247   pOldHdr = sqlite3MemsysGetHeader(pPrior);
13248   pNew = sqlite3MemMalloc(nByte);
13249   if( pNew ){
13250     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
13251     if( nByte>pOldHdr->iSize ){
13252       memset(&((char*)pNew)[pOldHdr->iSize], 0x2b, nByte - pOldHdr->iSize);
13253     }
13254     sqlite3MemFree(pPrior);
13255   }
13256   return pNew;
13257 }
13258
13259 /*
13260 ** Populate the low-level memory allocation function pointers in
13261 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
13262 */
13263 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
13264   static const sqlite3_mem_methods defaultMethods = {
13265      sqlite3MemMalloc,
13266      sqlite3MemFree,
13267      sqlite3MemRealloc,
13268      sqlite3MemSize,
13269      sqlite3MemRoundup,
13270      sqlite3MemInit,
13271      sqlite3MemShutdown,
13272      0
13273   };
13274   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
13275 }
13276
13277 /*
13278 ** Set the number of backtrace levels kept for each allocation.
13279 ** A value of zero turns off backtracing.  The number is always rounded
13280 ** up to a multiple of 2.
13281 */
13282 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
13283   if( depth<0 ){ depth = 0; }
13284   if( depth>20 ){ depth = 20; }
13285   depth = (depth+1)&0xfe;
13286   mem.nBacktrace = depth;
13287 }
13288
13289 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
13290   mem.xBacktrace = xBacktrace;
13291 }
13292
13293 /*
13294 ** Set the title string for subsequent allocations.
13295 */
13296 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
13297   int n = strlen(zTitle) + 1;
13298   sqlite3_mutex_enter(mem.mutex);
13299   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
13300   memcpy(mem.zTitle, zTitle, n);
13301   mem.zTitle[n] = 0;
13302   mem.nTitle = (n+7)&~7;
13303   sqlite3_mutex_leave(mem.mutex);
13304 }
13305
13306 SQLITE_PRIVATE void sqlite3MemdebugSync(){
13307   struct MemBlockHdr *pHdr;
13308   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
13309     void **pBt = (void**)pHdr;
13310     pBt -= pHdr->nBacktraceSlots;
13311     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
13312   }
13313 }
13314
13315 /*
13316 ** Open the file indicated and write a log of all unfreed memory 
13317 ** allocations into that log.
13318 */
13319 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
13320   FILE *out;
13321   struct MemBlockHdr *pHdr;
13322   void **pBt;
13323   int i;
13324   out = fopen(zFilename, "w");
13325   if( out==0 ){
13326     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
13327                     zFilename);
13328     return;
13329   }
13330   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
13331     char *z = (char*)pHdr;
13332     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
13333     fprintf(out, "**** %lld bytes at %p from %s ****\n", 
13334             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
13335     if( pHdr->nBacktrace ){
13336       fflush(out);
13337       pBt = (void**)pHdr;
13338       pBt -= pHdr->nBacktraceSlots;
13339       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
13340       fprintf(out, "\n");
13341     }
13342   }
13343   fprintf(out, "COUNTS:\n");
13344   for(i=0; i<NCSIZE-1; i++){
13345     if( mem.nAlloc[i] ){
13346       fprintf(out, "   %5d: %10d %10d %10d\n", 
13347             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
13348     }
13349   }
13350   if( mem.nAlloc[NCSIZE-1] ){
13351     fprintf(out, "   %5d: %10d %10d %10d\n",
13352              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
13353              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
13354   }
13355   fclose(out);
13356 }
13357
13358 /*
13359 ** Return the number of times sqlite3MemMalloc() has been called.
13360 */
13361 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
13362   int i;
13363   int nTotal = 0;
13364   for(i=0; i<NCSIZE; i++){
13365     nTotal += mem.nAlloc[i];
13366   }
13367   return nTotal;
13368 }
13369
13370
13371 #endif /* SQLITE_MEMDEBUG */
13372
13373 /************** End of mem2.c ************************************************/
13374 /************** Begin file mem3.c ********************************************/
13375 /*
13376 ** 2007 October 14
13377 **
13378 ** The author disclaims copyright to this source code.  In place of
13379 ** a legal notice, here is a blessing:
13380 **
13381 **    May you do good and not evil.
13382 **    May you find forgiveness for yourself and forgive others.
13383 **    May you share freely, never taking more than you give.
13384 **
13385 *************************************************************************
13386 ** This file contains the C functions that implement a memory
13387 ** allocation subsystem for use by SQLite. 
13388 **
13389 ** This version of the memory allocation subsystem omits all
13390 ** use of malloc(). The SQLite user supplies a block of memory
13391 ** before calling sqlite3_initialize() from which allocations
13392 ** are made and returned by the xMalloc() and xRealloc() 
13393 ** implementations. Once sqlite3_initialize() has been called,
13394 ** the amount of memory available to SQLite is fixed and cannot
13395 ** be changed.
13396 **
13397 ** This version of the memory allocation subsystem is included
13398 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
13399 **
13400 ** $Id: mem3.c,v 1.25 2008/11/19 16:52:44 danielk1977 Exp $
13401 */
13402
13403 /*
13404 ** This version of the memory allocator is only built into the library
13405 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
13406 ** mean that the library will use a memory-pool by default, just that
13407 ** it is available. The mempool allocator is activated by calling
13408 ** sqlite3_config().
13409 */
13410 #ifdef SQLITE_ENABLE_MEMSYS3
13411
13412 /*
13413 ** Maximum size (in Mem3Blocks) of a "small" chunk.
13414 */
13415 #define MX_SMALL 10
13416
13417
13418 /*
13419 ** Number of freelist hash slots
13420 */
13421 #define N_HASH  61
13422
13423 /*
13424 ** A memory allocation (also called a "chunk") consists of two or 
13425 ** more blocks where each block is 8 bytes.  The first 8 bytes are 
13426 ** a header that is not returned to the user.
13427 **
13428 ** A chunk is two or more blocks that is either checked out or
13429 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
13430 ** size of the allocation in blocks if the allocation is free.
13431 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
13432 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
13433 ** is true if the previous chunk is checked out and false if the
13434 ** previous chunk is free.  The u.hdr.prevSize field is the size of
13435 ** the previous chunk in blocks if the previous chunk is on the
13436 ** freelist. If the previous chunk is checked out, then
13437 ** u.hdr.prevSize can be part of the data for that chunk and should
13438 ** not be read or written.
13439 **
13440 ** We often identify a chunk by its index in mem3.aPool[].  When
13441 ** this is done, the chunk index refers to the second block of
13442 ** the chunk.  In this way, the first chunk has an index of 1.
13443 ** A chunk index of 0 means "no such chunk" and is the equivalent
13444 ** of a NULL pointer.
13445 **
13446 ** The second block of free chunks is of the form u.list.  The
13447 ** two fields form a double-linked list of chunks of related sizes.
13448 ** Pointers to the head of the list are stored in mem3.aiSmall[] 
13449 ** for smaller chunks and mem3.aiHash[] for larger chunks.
13450 **
13451 ** The second block of a chunk is user data if the chunk is checked 
13452 ** out.  If a chunk is checked out, the user data may extend into
13453 ** the u.hdr.prevSize value of the following chunk.
13454 */
13455 typedef struct Mem3Block Mem3Block;
13456 struct Mem3Block {
13457   union {
13458     struct {
13459       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
13460       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
13461     } hdr;
13462     struct {
13463       u32 next;       /* Index in mem3.aPool[] of next free chunk */
13464       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
13465     } list;
13466   } u;
13467 };
13468
13469 /*
13470 ** All of the static variables used by this module are collected
13471 ** into a single structure named "mem3".  This is to keep the
13472 ** static variables organized and to reduce namespace pollution
13473 ** when this module is combined with other in the amalgamation.
13474 */
13475 static SQLITE_WSD struct Mem3Global {
13476   /*
13477   ** Memory available for allocation. nPool is the size of the array
13478   ** (in Mem3Blocks) pointed to by aPool less 2.
13479   */
13480   u32 nPool;
13481   Mem3Block *aPool;
13482
13483   /*
13484   ** True if we are evaluating an out-of-memory callback.
13485   */
13486   int alarmBusy;
13487   
13488   /*
13489   ** Mutex to control access to the memory allocation subsystem.
13490   */
13491   sqlite3_mutex *mutex;
13492   
13493   /*
13494   ** The minimum amount of free space that we have seen.
13495   */
13496   u32 mnMaster;
13497
13498   /*
13499   ** iMaster is the index of the master chunk.  Most new allocations
13500   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
13501   ** of the current master.  iMaster is 0 if there is not master chunk.
13502   ** The master chunk is not in either the aiHash[] or aiSmall[].
13503   */
13504   u32 iMaster;
13505   u32 szMaster;
13506
13507   /*
13508   ** Array of lists of free blocks according to the block size 
13509   ** for smaller chunks, or a hash on the block size for larger
13510   ** chunks.
13511   */
13512   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
13513   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
13514 } mem3 = { 97535575 };
13515
13516 #define mem3 GLOBAL(struct Mem3Global, mem3)
13517
13518 /*
13519 ** Unlink the chunk at mem3.aPool[i] from list it is currently
13520 ** on.  *pRoot is the list that i is a member of.
13521 */
13522 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
13523   u32 next = mem3.aPool[i].u.list.next;
13524   u32 prev = mem3.aPool[i].u.list.prev;
13525   assert( sqlite3_mutex_held(mem3.mutex) );
13526   if( prev==0 ){
13527     *pRoot = next;
13528   }else{
13529     mem3.aPool[prev].u.list.next = next;
13530   }
13531   if( next ){
13532     mem3.aPool[next].u.list.prev = prev;
13533   }
13534   mem3.aPool[i].u.list.next = 0;
13535   mem3.aPool[i].u.list.prev = 0;
13536 }
13537
13538 /*
13539 ** Unlink the chunk at index i from 
13540 ** whatever list is currently a member of.
13541 */
13542 static void memsys3Unlink(u32 i){
13543   u32 size, hash;
13544   assert( sqlite3_mutex_held(mem3.mutex) );
13545   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
13546   assert( i>=1 );
13547   size = mem3.aPool[i-1].u.hdr.size4x/4;
13548   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
13549   assert( size>=2 );
13550   if( size <= MX_SMALL ){
13551     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
13552   }else{
13553     hash = size % N_HASH;
13554     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
13555   }
13556 }
13557
13558 /*
13559 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
13560 ** at *pRoot.
13561 */
13562 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
13563   assert( sqlite3_mutex_held(mem3.mutex) );
13564   mem3.aPool[i].u.list.next = *pRoot;
13565   mem3.aPool[i].u.list.prev = 0;
13566   if( *pRoot ){
13567     mem3.aPool[*pRoot].u.list.prev = i;
13568   }
13569   *pRoot = i;
13570 }
13571
13572 /*
13573 ** Link the chunk at index i into either the appropriate
13574 ** small chunk list, or into the large chunk hash table.
13575 */
13576 static void memsys3Link(u32 i){
13577   u32 size, hash;
13578   assert( sqlite3_mutex_held(mem3.mutex) );
13579   assert( i>=1 );
13580   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
13581   size = mem3.aPool[i-1].u.hdr.size4x/4;
13582   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
13583   assert( size>=2 );
13584   if( size <= MX_SMALL ){
13585     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
13586   }else{
13587     hash = size % N_HASH;
13588     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
13589   }
13590 }
13591
13592 /*
13593 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
13594 ** will already be held (obtained by code in malloc.c) if
13595 ** sqlite3GlobalConfig.bMemStat is true.
13596 */
13597 static void memsys3Enter(void){
13598   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
13599     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
13600   }
13601   sqlite3_mutex_enter(mem3.mutex);
13602 }
13603 static void memsys3Leave(void){
13604   sqlite3_mutex_leave(mem3.mutex);
13605 }
13606
13607 /*
13608 ** Called when we are unable to satisfy an allocation of nBytes.
13609 */
13610 static void memsys3OutOfMemory(int nByte){
13611   if( !mem3.alarmBusy ){
13612     mem3.alarmBusy = 1;
13613     assert( sqlite3_mutex_held(mem3.mutex) );
13614     sqlite3_mutex_leave(mem3.mutex);
13615     sqlite3_release_memory(nByte);
13616     sqlite3_mutex_enter(mem3.mutex);
13617     mem3.alarmBusy = 0;
13618   }
13619 }
13620
13621
13622 /*
13623 ** Chunk i is a free chunk that has been unlinked.  Adjust its 
13624 ** size parameters for check-out and return a pointer to the 
13625 ** user portion of the chunk.
13626 */
13627 static void *memsys3Checkout(u32 i, u32 nBlock){
13628   u32 x;
13629   assert( sqlite3_mutex_held(mem3.mutex) );
13630   assert( i>=1 );
13631   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
13632   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
13633   x = mem3.aPool[i-1].u.hdr.size4x;
13634   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
13635   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
13636   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
13637   return &mem3.aPool[i];
13638 }
13639
13640 /*
13641 ** Carve a piece off of the end of the mem3.iMaster free chunk.
13642 ** Return a pointer to the new allocation.  Or, if the master chunk
13643 ** is not large enough, return 0.
13644 */
13645 static void *memsys3FromMaster(u32 nBlock){
13646   assert( sqlite3_mutex_held(mem3.mutex) );
13647   assert( mem3.szMaster>=nBlock );
13648   if( nBlock>=mem3.szMaster-1 ){
13649     /* Use the entire master */
13650     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
13651     mem3.iMaster = 0;
13652     mem3.szMaster = 0;
13653     mem3.mnMaster = 0;
13654     return p;
13655   }else{
13656     /* Split the master block.  Return the tail. */
13657     u32 newi, x;
13658     newi = mem3.iMaster + mem3.szMaster - nBlock;
13659     assert( newi > mem3.iMaster+1 );
13660     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
13661     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
13662     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
13663     mem3.szMaster -= nBlock;
13664     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
13665     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
13666     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
13667     if( mem3.szMaster < mem3.mnMaster ){
13668       mem3.mnMaster = mem3.szMaster;
13669     }
13670     return (void*)&mem3.aPool[newi];
13671   }
13672 }
13673
13674 /*
13675 ** *pRoot is the head of a list of free chunks of the same size
13676 ** or same size hash.  In other words, *pRoot is an entry in either
13677 ** mem3.aiSmall[] or mem3.aiHash[].  
13678 **
13679 ** This routine examines all entries on the given list and tries
13680 ** to coalesce each entries with adjacent free chunks.  
13681 **
13682 ** If it sees a chunk that is larger than mem3.iMaster, it replaces 
13683 ** the current mem3.iMaster with the new larger chunk.  In order for
13684 ** this mem3.iMaster replacement to work, the master chunk must be
13685 ** linked into the hash tables.  That is not the normal state of
13686 ** affairs, of course.  The calling routine must link the master
13687 ** chunk before invoking this routine, then must unlink the (possibly
13688 ** changed) master chunk once this routine has finished.
13689 */
13690 static void memsys3Merge(u32 *pRoot){
13691   u32 iNext, prev, size, i, x;
13692
13693   assert( sqlite3_mutex_held(mem3.mutex) );
13694   for(i=*pRoot; i>0; i=iNext){
13695     iNext = mem3.aPool[i].u.list.next;
13696     size = mem3.aPool[i-1].u.hdr.size4x;
13697     assert( (size&1)==0 );
13698     if( (size&2)==0 ){
13699       memsys3UnlinkFromList(i, pRoot);
13700       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
13701       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
13702       if( prev==iNext ){
13703         iNext = mem3.aPool[prev].u.list.next;
13704       }
13705       memsys3Unlink(prev);
13706       size = i + size/4 - prev;
13707       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
13708       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
13709       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
13710       memsys3Link(prev);
13711       i = prev;
13712     }else{
13713       size /= 4;
13714     }
13715     if( size>mem3.szMaster ){
13716       mem3.iMaster = i;
13717       mem3.szMaster = size;
13718     }
13719   }
13720 }
13721
13722 /*
13723 ** Return a block of memory of at least nBytes in size.
13724 ** Return NULL if unable.
13725 **
13726 ** This function assumes that the necessary mutexes, if any, are
13727 ** already held by the caller. Hence "Unsafe".
13728 */
13729 static void *memsys3MallocUnsafe(int nByte){
13730   u32 i;
13731   u32 nBlock;
13732   u32 toFree;
13733
13734   assert( sqlite3_mutex_held(mem3.mutex) );
13735   assert( sizeof(Mem3Block)==8 );
13736   if( nByte<=12 ){
13737     nBlock = 2;
13738   }else{
13739     nBlock = (nByte + 11)/8;
13740   }
13741   assert( nBlock>=2 );
13742
13743   /* STEP 1:
13744   ** Look for an entry of the correct size in either the small
13745   ** chunk table or in the large chunk hash table.  This is
13746   ** successful most of the time (about 9 times out of 10).
13747   */
13748   if( nBlock <= MX_SMALL ){
13749     i = mem3.aiSmall[nBlock-2];
13750     if( i>0 ){
13751       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
13752       return memsys3Checkout(i, nBlock);
13753     }
13754   }else{
13755     int hash = nBlock % N_HASH;
13756     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
13757       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
13758         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
13759         return memsys3Checkout(i, nBlock);
13760       }
13761     }
13762   }
13763
13764   /* STEP 2:
13765   ** Try to satisfy the allocation by carving a piece off of the end
13766   ** of the master chunk.  This step usually works if step 1 fails.
13767   */
13768   if( mem3.szMaster>=nBlock ){
13769     return memsys3FromMaster(nBlock);
13770   }
13771
13772
13773   /* STEP 3:  
13774   ** Loop through the entire memory pool.  Coalesce adjacent free
13775   ** chunks.  Recompute the master chunk as the largest free chunk.
13776   ** Then try again to satisfy the allocation by carving a piece off
13777   ** of the end of the master chunk.  This step happens very
13778   ** rarely (we hope!)
13779   */
13780   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
13781     memsys3OutOfMemory(toFree);
13782     if( mem3.iMaster ){
13783       memsys3Link(mem3.iMaster);
13784       mem3.iMaster = 0;
13785       mem3.szMaster = 0;
13786     }
13787     for(i=0; i<N_HASH; i++){
13788       memsys3Merge(&mem3.aiHash[i]);
13789     }
13790     for(i=0; i<MX_SMALL-1; i++){
13791       memsys3Merge(&mem3.aiSmall[i]);
13792     }
13793     if( mem3.szMaster ){
13794       memsys3Unlink(mem3.iMaster);
13795       if( mem3.szMaster>=nBlock ){
13796         return memsys3FromMaster(nBlock);
13797       }
13798     }
13799   }
13800
13801   /* If none of the above worked, then we fail. */
13802   return 0;
13803 }
13804
13805 /*
13806 ** Free an outstanding memory allocation.
13807 **
13808 ** This function assumes that the necessary mutexes, if any, are
13809 ** already held by the caller. Hence "Unsafe".
13810 */
13811 void memsys3FreeUnsafe(void *pOld){
13812   Mem3Block *p = (Mem3Block*)pOld;
13813   int i;
13814   u32 size, x;
13815   assert( sqlite3_mutex_held(mem3.mutex) );
13816   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
13817   i = p - mem3.aPool;
13818   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
13819   size = mem3.aPool[i-1].u.hdr.size4x/4;
13820   assert( i+size<=mem3.nPool+1 );
13821   mem3.aPool[i-1].u.hdr.size4x &= ~1;
13822   mem3.aPool[i+size-1].u.hdr.prevSize = size;
13823   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
13824   memsys3Link(i);
13825
13826   /* Try to expand the master using the newly freed chunk */
13827   if( mem3.iMaster ){
13828     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
13829       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
13830       mem3.iMaster -= size;
13831       mem3.szMaster += size;
13832       memsys3Unlink(mem3.iMaster);
13833       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
13834       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
13835       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
13836     }
13837     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
13838     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
13839       memsys3Unlink(mem3.iMaster+mem3.szMaster);
13840       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
13841       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
13842       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
13843     }
13844   }
13845 }
13846
13847 /*
13848 ** Return the size of an outstanding allocation, in bytes.  The
13849 ** size returned omits the 8-byte header overhead.  This only
13850 ** works for chunks that are currently checked out.
13851 */
13852 static int memsys3Size(void *p){
13853   Mem3Block *pBlock;
13854   if( p==0 ) return 0;
13855   pBlock = (Mem3Block*)p;
13856   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
13857   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
13858 }
13859
13860 /*
13861 ** Round up a request size to the next valid allocation size.
13862 */
13863 static int memsys3Roundup(int n){
13864   if( n<=12 ){
13865     return 12;
13866   }else{
13867     return ((n+11)&~7) - 4;
13868   }
13869 }
13870
13871 /*
13872 ** Allocate nBytes of memory.
13873 */
13874 static void *memsys3Malloc(int nBytes){
13875   sqlite3_int64 *p;
13876   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
13877   memsys3Enter();
13878   p = memsys3MallocUnsafe(nBytes);
13879   memsys3Leave();
13880   return (void*)p; 
13881 }
13882
13883 /*
13884 ** Free memory.
13885 */
13886 void memsys3Free(void *pPrior){
13887   assert( pPrior );
13888   memsys3Enter();
13889   memsys3FreeUnsafe(pPrior);
13890   memsys3Leave();
13891 }
13892
13893 /*
13894 ** Change the size of an existing memory allocation
13895 */
13896 void *memsys3Realloc(void *pPrior, int nBytes){
13897   int nOld;
13898   void *p;
13899   if( pPrior==0 ){
13900     return sqlite3_malloc(nBytes);
13901   }
13902   if( nBytes<=0 ){
13903     sqlite3_free(pPrior);
13904     return 0;
13905   }
13906   nOld = memsys3Size(pPrior);
13907   if( nBytes<=nOld && nBytes>=nOld-128 ){
13908     return pPrior;
13909   }
13910   memsys3Enter();
13911   p = memsys3MallocUnsafe(nBytes);
13912   if( p ){
13913     if( nOld<nBytes ){
13914       memcpy(p, pPrior, nOld);
13915     }else{
13916       memcpy(p, pPrior, nBytes);
13917     }
13918     memsys3FreeUnsafe(pPrior);
13919   }
13920   memsys3Leave();
13921   return p;
13922 }
13923
13924 /*
13925 ** Initialize this module.
13926 */
13927 static int memsys3Init(void *NotUsed){
13928   UNUSED_PARAMETER(NotUsed);
13929   if( !sqlite3GlobalConfig.pHeap ){
13930     return SQLITE_ERROR;
13931   }
13932
13933   /* Store a pointer to the memory block in global structure mem3. */
13934   assert( sizeof(Mem3Block)==8 );
13935   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
13936   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
13937
13938   /* Initialize the master block. */
13939   mem3.szMaster = mem3.nPool;
13940   mem3.mnMaster = mem3.szMaster;
13941   mem3.iMaster = 1;
13942   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
13943   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
13944   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
13945
13946   return SQLITE_OK;
13947 }
13948
13949 /*
13950 ** Deinitialize this module.
13951 */
13952 static void memsys3Shutdown(void *NotUsed){
13953   UNUSED_PARAMETER(NotUsed);
13954   return;
13955 }
13956
13957
13958
13959 /*
13960 ** Open the file indicated and write a log of all unfreed memory 
13961 ** allocations into that log.
13962 */
13963 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
13964 #ifdef SQLITE_DEBUG
13965   FILE *out;
13966   u32 i, j;
13967   u32 size;
13968   if( zFilename==0 || zFilename[0]==0 ){
13969     out = stdout;
13970   }else{
13971     out = fopen(zFilename, "w");
13972     if( out==0 ){
13973       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
13974                       zFilename);
13975       return;
13976     }
13977   }
13978   memsys3Enter();
13979   fprintf(out, "CHUNKS:\n");
13980   for(i=1; i<=mem3.nPool; i+=size/4){
13981     size = mem3.aPool[i-1].u.hdr.size4x;
13982     if( size/4<=1 ){
13983       fprintf(out, "%p size error\n", &mem3.aPool[i]);
13984       assert( 0 );
13985       break;
13986     }
13987     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
13988       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
13989       assert( 0 );
13990       break;
13991     }
13992     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
13993       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
13994       assert( 0 );
13995       break;
13996     }
13997     if( size&1 ){
13998       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
13999     }else{
14000       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
14001                   i==mem3.iMaster ? " **master**" : "");
14002     }
14003   }
14004   for(i=0; i<MX_SMALL-1; i++){
14005     if( mem3.aiSmall[i]==0 ) continue;
14006     fprintf(out, "small(%2d):", i);
14007     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
14008       fprintf(out, " %p(%d)", &mem3.aPool[j],
14009               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
14010     }
14011     fprintf(out, "\n"); 
14012   }
14013   for(i=0; i<N_HASH; i++){
14014     if( mem3.aiHash[i]==0 ) continue;
14015     fprintf(out, "hash(%2d):", i);
14016     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
14017       fprintf(out, " %p(%d)", &mem3.aPool[j],
14018               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
14019     }
14020     fprintf(out, "\n"); 
14021   }
14022   fprintf(out, "master=%d\n", mem3.iMaster);
14023   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
14024   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
14025   sqlite3_mutex_leave(mem3.mutex);
14026   if( out==stdout ){
14027     fflush(stdout);
14028   }else{
14029     fclose(out);
14030   }
14031 #else
14032   UNUSED_PARAMETER(zFilename);
14033 #endif
14034 }
14035
14036 /*
14037 ** This routine is the only routine in this file with external 
14038 ** linkage.
14039 **
14040 ** Populate the low-level memory allocation function pointers in
14041 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
14042 ** arguments specify the block of memory to manage.
14043 **
14044 ** This routine is only called by sqlite3_config(), and therefore
14045 ** is not required to be threadsafe (it is not).
14046 */
14047 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
14048   static const sqlite3_mem_methods mempoolMethods = {
14049      memsys3Malloc,
14050      memsys3Free,
14051      memsys3Realloc,
14052      memsys3Size,
14053      memsys3Roundup,
14054      memsys3Init,
14055      memsys3Shutdown,
14056      0
14057   };
14058   return &mempoolMethods;
14059 }
14060
14061 #endif /* SQLITE_ENABLE_MEMSYS3 */
14062
14063 /************** End of mem3.c ************************************************/
14064 /************** Begin file mem5.c ********************************************/
14065 /*
14066 ** 2007 October 14
14067 **
14068 ** The author disclaims copyright to this source code.  In place of
14069 ** a legal notice, here is a blessing:
14070 **
14071 **    May you do good and not evil.
14072 **    May you find forgiveness for yourself and forgive others.
14073 **    May you share freely, never taking more than you give.
14074 **
14075 *************************************************************************
14076 ** This file contains the C functions that implement a memory
14077 ** allocation subsystem for use by SQLite. 
14078 **
14079 ** This version of the memory allocation subsystem omits all
14080 ** use of malloc(). The SQLite user supplies a block of memory
14081 ** before calling sqlite3_initialize() from which allocations
14082 ** are made and returned by the xMalloc() and xRealloc() 
14083 ** implementations. Once sqlite3_initialize() has been called,
14084 ** the amount of memory available to SQLite is fixed and cannot
14085 ** be changed.
14086 **
14087 ** This version of the memory allocation subsystem is included
14088 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
14089 **
14090 ** $Id: mem5.c,v 1.19 2008/11/19 16:52:44 danielk1977 Exp $
14091 */
14092
14093 /*
14094 ** This version of the memory allocator is used only when 
14095 ** SQLITE_ENABLE_MEMSYS5 is defined.
14096 */
14097 #ifdef SQLITE_ENABLE_MEMSYS5
14098
14099 /*
14100 ** A minimum allocation is an instance of the following structure.
14101 ** Larger allocations are an array of these structures where the
14102 ** size of the array is a power of 2.
14103 */
14104 typedef struct Mem5Link Mem5Link;
14105 struct Mem5Link {
14106   int next;       /* Index of next free chunk */
14107   int prev;       /* Index of previous free chunk */
14108 };
14109
14110 /*
14111 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.nAtom). Since
14112 ** mem5.nAtom is always at least 8, this is not really a practical
14113 ** limitation.
14114 */
14115 #define LOGMAX 30
14116
14117 /*
14118 ** Masks used for mem5.aCtrl[] elements.
14119 */
14120 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block relative to POW2_MIN */
14121 #define CTRL_FREE     0x20    /* True if not checked out */
14122
14123 /*
14124 ** All of the static variables used by this module are collected
14125 ** into a single structure named "mem5".  This is to keep the
14126 ** static variables organized and to reduce namespace pollution
14127 ** when this module is combined with other in the amalgamation.
14128 */
14129 static SQLITE_WSD struct Mem5Global {
14130   /*
14131   ** Memory available for allocation
14132   */
14133   int nAtom;       /* Smallest possible allocation in bytes */
14134   int nBlock;      /* Number of nAtom sized blocks in zPool */
14135   u8 *zPool;
14136   
14137   /*
14138   ** Mutex to control access to the memory allocation subsystem.
14139   */
14140   sqlite3_mutex *mutex;
14141
14142   /*
14143   ** Performance statistics
14144   */
14145   u64 nAlloc;         /* Total number of calls to malloc */
14146   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
14147   u64 totalExcess;    /* Total internal fragmentation */
14148   u32 currentOut;     /* Current checkout, including internal fragmentation */
14149   u32 currentCount;   /* Current number of distinct checkouts */
14150   u32 maxOut;         /* Maximum instantaneous currentOut */
14151   u32 maxCount;       /* Maximum instantaneous currentCount */
14152   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
14153   
14154   /*
14155   ** Lists of free blocks of various sizes.
14156   */
14157   int aiFreelist[LOGMAX+1];
14158
14159   /*
14160   ** Space for tracking which blocks are checked out and the size
14161   ** of each block.  One byte per block.
14162   */
14163   u8 *aCtrl;
14164
14165 } mem5 = { 19804167 };
14166
14167 #define mem5 GLOBAL(struct Mem5Global, mem5)
14168
14169 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.nAtom]))
14170
14171 /*
14172 ** Unlink the chunk at mem5.aPool[i] from list it is currently
14173 ** on.  It should be found on mem5.aiFreelist[iLogsize].
14174 */
14175 static void memsys5Unlink(int i, int iLogsize){
14176   int next, prev;
14177   assert( i>=0 && i<mem5.nBlock );
14178   assert( iLogsize>=0 && iLogsize<=LOGMAX );
14179   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
14180
14181   next = MEM5LINK(i)->next;
14182   prev = MEM5LINK(i)->prev;
14183   if( prev<0 ){
14184     mem5.aiFreelist[iLogsize] = next;
14185   }else{
14186     MEM5LINK(prev)->next = next;
14187   }
14188   if( next>=0 ){
14189     MEM5LINK(next)->prev = prev;
14190   }
14191 }
14192
14193 /*
14194 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
14195 ** free list.
14196 */
14197 static void memsys5Link(int i, int iLogsize){
14198   int x;
14199   assert( sqlite3_mutex_held(mem5.mutex) );
14200   assert( i>=0 && i<mem5.nBlock );
14201   assert( iLogsize>=0 && iLogsize<=LOGMAX );
14202   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
14203
14204   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
14205   MEM5LINK(i)->prev = -1;
14206   if( x>=0 ){
14207     assert( x<mem5.nBlock );
14208     MEM5LINK(x)->prev = i;
14209   }
14210   mem5.aiFreelist[iLogsize] = i;
14211 }
14212
14213 /*
14214 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
14215 ** will already be held (obtained by code in malloc.c) if
14216 ** sqlite3GlobalConfig.bMemStat is true.
14217 */
14218 static void memsys5Enter(void){
14219   if( sqlite3GlobalConfig.bMemstat==0 && mem5.mutex==0 ){
14220     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
14221   }
14222   sqlite3_mutex_enter(mem5.mutex);
14223 }
14224 static void memsys5Leave(void){
14225   sqlite3_mutex_leave(mem5.mutex);
14226 }
14227
14228 /*
14229 ** Return the size of an outstanding allocation, in bytes.  The
14230 ** size returned omits the 8-byte header overhead.  This only
14231 ** works for chunks that are currently checked out.
14232 */
14233 static int memsys5Size(void *p){
14234   int iSize = 0;
14235   if( p ){
14236     int i = ((u8 *)p-mem5.zPool)/mem5.nAtom;
14237     assert( i>=0 && i<mem5.nBlock );
14238     iSize = mem5.nAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
14239   }
14240   return iSize;
14241 }
14242
14243 /*
14244 ** Find the first entry on the freelist iLogsize.  Unlink that
14245 ** entry and return its index. 
14246 */
14247 static int memsys5UnlinkFirst(int iLogsize){
14248   int i;
14249   int iFirst;
14250
14251   assert( iLogsize>=0 && iLogsize<=LOGMAX );
14252   i = iFirst = mem5.aiFreelist[iLogsize];
14253   assert( iFirst>=0 );
14254   while( i>0 ){
14255     if( i<iFirst ) iFirst = i;
14256     i = MEM5LINK(i)->next;
14257   }
14258   memsys5Unlink(iFirst, iLogsize);
14259   return iFirst;
14260 }
14261
14262 /*
14263 ** Return a block of memory of at least nBytes in size.
14264 ** Return NULL if unable.
14265 */
14266 static void *memsys5MallocUnsafe(int nByte){
14267   int i;           /* Index of a mem5.aPool[] slot */
14268   int iBin;        /* Index into mem5.aiFreelist[] */
14269   int iFullSz;     /* Size of allocation rounded up to power of 2 */
14270   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
14271
14272   /* Keep track of the maximum allocation request.  Even unfulfilled
14273   ** requests are counted */
14274   if( (u32)nByte>mem5.maxRequest ){
14275     mem5.maxRequest = nByte;
14276   }
14277
14278   /* Round nByte up to the next valid power of two */
14279   for(iFullSz=mem5.nAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
14280
14281   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
14282   ** block.  If not, then split a block of the next larger power of
14283   ** two in order to create a new free block of size iLogsize.
14284   */
14285   for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
14286   if( iBin>LOGMAX ) return 0;
14287   i = memsys5UnlinkFirst(iBin);
14288   while( iBin>iLogsize ){
14289     int newSize;
14290
14291     iBin--;
14292     newSize = 1 << iBin;
14293     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
14294     memsys5Link(i+newSize, iBin);
14295   }
14296   mem5.aCtrl[i] = iLogsize;
14297
14298   /* Update allocator performance statistics. */
14299   mem5.nAlloc++;
14300   mem5.totalAlloc += iFullSz;
14301   mem5.totalExcess += iFullSz - nByte;
14302   mem5.currentCount++;
14303   mem5.currentOut += iFullSz;
14304   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
14305   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
14306
14307   /* Return a pointer to the allocated memory. */
14308   return (void*)&mem5.zPool[i*mem5.nAtom];
14309 }
14310
14311 /*
14312 ** Free an outstanding memory allocation.
14313 */
14314 static void memsys5FreeUnsafe(void *pOld){
14315   u32 size, iLogsize;
14316   int iBlock;             
14317
14318   /* Set iBlock to the index of the block pointed to by pOld in 
14319   ** the array of mem5.nAtom byte blocks pointed to by mem5.zPool.
14320   */
14321   iBlock = ((u8 *)pOld-mem5.zPool)/mem5.nAtom;
14322
14323   /* Check that the pointer pOld points to a valid, non-free block. */
14324   assert( iBlock>=0 && iBlock<mem5.nBlock );
14325   assert( ((u8 *)pOld-mem5.zPool)%mem5.nAtom==0 );
14326   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
14327
14328   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
14329   size = 1<<iLogsize;
14330   assert( iBlock+size-1<(u32)mem5.nBlock );
14331
14332   mem5.aCtrl[iBlock] |= CTRL_FREE;
14333   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
14334   assert( mem5.currentCount>0 );
14335   assert( mem5.currentOut>=(size*mem5.nAtom) );
14336   mem5.currentCount--;
14337   mem5.currentOut -= size*mem5.nAtom;
14338   assert( mem5.currentOut>0 || mem5.currentCount==0 );
14339   assert( mem5.currentCount>0 || mem5.currentOut==0 );
14340
14341   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
14342   while( iLogsize<LOGMAX ){
14343     int iBuddy;
14344     if( (iBlock>>iLogsize) & 1 ){
14345       iBuddy = iBlock - size;
14346     }else{
14347       iBuddy = iBlock + size;
14348     }
14349     assert( iBuddy>=0 );
14350     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
14351     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
14352     memsys5Unlink(iBuddy, iLogsize);
14353     iLogsize++;
14354     if( iBuddy<iBlock ){
14355       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
14356       mem5.aCtrl[iBlock] = 0;
14357       iBlock = iBuddy;
14358     }else{
14359       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
14360       mem5.aCtrl[iBuddy] = 0;
14361     }
14362     size *= 2;
14363   }
14364   memsys5Link(iBlock, iLogsize);
14365 }
14366
14367 /*
14368 ** Allocate nBytes of memory
14369 */
14370 static void *memsys5Malloc(int nBytes){
14371   sqlite3_int64 *p = 0;
14372   if( nBytes>0 ){
14373     memsys5Enter();
14374     p = memsys5MallocUnsafe(nBytes);
14375     memsys5Leave();
14376   }
14377   return (void*)p; 
14378 }
14379
14380 /*
14381 ** Free memory.
14382 */
14383 static void memsys5Free(void *pPrior){
14384   if( pPrior==0 ){
14385 assert(0);
14386     return;
14387   }
14388   memsys5Enter();
14389   memsys5FreeUnsafe(pPrior);
14390   memsys5Leave();  
14391 }
14392
14393 /*
14394 ** Change the size of an existing memory allocation
14395 */
14396 static void *memsys5Realloc(void *pPrior, int nBytes){
14397   int nOld;
14398   void *p;
14399   if( pPrior==0 ){
14400     return memsys5Malloc(nBytes);
14401   }
14402   if( nBytes<=0 ){
14403     memsys5Free(pPrior);
14404     return 0;
14405   }
14406   nOld = memsys5Size(pPrior);
14407   if( nBytes<=nOld ){
14408     return pPrior;
14409   }
14410   memsys5Enter();
14411   p = memsys5MallocUnsafe(nBytes);
14412   if( p ){
14413     memcpy(p, pPrior, nOld);
14414     memsys5FreeUnsafe(pPrior);
14415   }
14416   memsys5Leave();
14417   return p;
14418 }
14419
14420 /*
14421 ** Round up a request size to the next valid allocation size.
14422 */
14423 static int memsys5Roundup(int n){
14424   int iFullSz;
14425   for(iFullSz=mem5.nAtom; iFullSz<n; iFullSz *= 2);
14426   return iFullSz;
14427 }
14428
14429 static int memsys5Log(int iValue){
14430   int iLog;
14431   for(iLog=0; (1<<iLog)<iValue; iLog++);
14432   return iLog;
14433 }
14434
14435 /*
14436 ** Initialize this module.
14437 */
14438 static int memsys5Init(void *NotUsed){
14439   int ii;
14440   int nByte = sqlite3GlobalConfig.nHeap;
14441   u8 *zByte = (u8 *)sqlite3GlobalConfig.pHeap;
14442   int nMinLog;                 /* Log of minimum allocation size in bytes*/
14443   int iOffset;
14444
14445   UNUSED_PARAMETER(NotUsed);
14446
14447   if( !zByte ){
14448     return SQLITE_ERROR;
14449   }
14450
14451   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
14452   mem5.nAtom = (1<<nMinLog);
14453   while( (int)sizeof(Mem5Link)>mem5.nAtom ){
14454     mem5.nAtom = mem5.nAtom << 1;
14455   }
14456
14457   mem5.nBlock = (nByte / (mem5.nAtom+sizeof(u8)));
14458   mem5.zPool = zByte;
14459   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.nAtom];
14460
14461   for(ii=0; ii<=LOGMAX; ii++){
14462     mem5.aiFreelist[ii] = -1;
14463   }
14464
14465   iOffset = 0;
14466   for(ii=LOGMAX; ii>=0; ii--){
14467     int nAlloc = (1<<ii);
14468     if( (iOffset+nAlloc)<=mem5.nBlock ){
14469       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
14470       memsys5Link(iOffset, ii);
14471       iOffset += nAlloc;
14472     }
14473     assert((iOffset+nAlloc)>mem5.nBlock);
14474   }
14475
14476   return SQLITE_OK;
14477 }
14478
14479 /*
14480 ** Deinitialize this module.
14481 */
14482 static void memsys5Shutdown(void *NotUsed){
14483   UNUSED_PARAMETER(NotUsed);
14484   return;
14485 }
14486
14487 /*
14488 ** Open the file indicated and write a log of all unfreed memory 
14489 ** allocations into that log.
14490 */
14491 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
14492 #ifdef SQLITE_DEBUG
14493   FILE *out;
14494   int i, j, n;
14495   int nMinLog;
14496
14497   if( zFilename==0 || zFilename[0]==0 ){
14498     out = stdout;
14499   }else{
14500     out = fopen(zFilename, "w");
14501     if( out==0 ){
14502       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
14503                       zFilename);
14504       return;
14505     }
14506   }
14507   memsys5Enter();
14508   nMinLog = memsys5Log(mem5.nAtom);
14509   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
14510     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
14511     fprintf(out, "freelist items of size %d: %d\n", mem5.nAtom << i, n);
14512   }
14513   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
14514   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
14515   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
14516   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
14517   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
14518   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
14519   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
14520   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
14521   memsys5Leave();
14522   if( out==stdout ){
14523     fflush(stdout);
14524   }else{
14525     fclose(out);
14526   }
14527 #else
14528   UNUSED_PARAMETER(zFilename);
14529 #endif
14530 }
14531
14532 /*
14533 ** This routine is the only routine in this file with external 
14534 ** linkage. It returns a pointer to a static sqlite3_mem_methods
14535 ** struct populated with the memsys5 methods.
14536 */
14537 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
14538   static const sqlite3_mem_methods memsys5Methods = {
14539      memsys5Malloc,
14540      memsys5Free,
14541      memsys5Realloc,
14542      memsys5Size,
14543      memsys5Roundup,
14544      memsys5Init,
14545      memsys5Shutdown,
14546      0
14547   };
14548   return &memsys5Methods;
14549 }
14550
14551 #endif /* SQLITE_ENABLE_MEMSYS5 */
14552
14553 /************** End of mem5.c ************************************************/
14554 /************** Begin file mutex.c *******************************************/
14555 /*
14556 ** 2007 August 14
14557 **
14558 ** The author disclaims copyright to this source code.  In place of
14559 ** a legal notice, here is a blessing:
14560 **
14561 **    May you do good and not evil.
14562 **    May you find forgiveness for yourself and forgive others.
14563 **    May you share freely, never taking more than you give.
14564 **
14565 *************************************************************************
14566 ** This file contains the C functions that implement mutexes.
14567 **
14568 ** This file contains code that is common across all mutex implementations.
14569
14570 **
14571 ** $Id: mutex.c,v 1.29 2008/10/07 15:25:48 drh Exp $
14572 */
14573
14574 #ifndef SQLITE_MUTEX_OMIT
14575 /*
14576 ** Initialize the mutex system.
14577 */
14578 SQLITE_PRIVATE int sqlite3MutexInit(void){ 
14579   int rc = SQLITE_OK;
14580   if( sqlite3GlobalConfig.bCoreMutex ){
14581     if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
14582       /* If the xMutexAlloc method has not been set, then the user did not
14583       ** install a mutex implementation via sqlite3_config() prior to 
14584       ** sqlite3_initialize() being called. This block copies pointers to
14585       ** the default implementation into the sqlite3GlobalConfig structure.
14586       **
14587       ** The danger is that although sqlite3_config() is not a threadsafe
14588       ** API, sqlite3_initialize() is, and so multiple threads may be
14589       ** attempting to run this function simultaneously. To guard write
14590       ** access to the sqlite3GlobalConfig structure, the 'MASTER' static mutex
14591       ** is obtained before modifying it.
14592       */
14593       sqlite3_mutex_methods *p = sqlite3DefaultMutex();
14594       sqlite3_mutex *pMaster = 0;
14595   
14596       rc = p->xMutexInit();
14597       if( rc==SQLITE_OK ){
14598         pMaster = p->xMutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14599         assert(pMaster);
14600         p->xMutexEnter(pMaster);
14601         assert( sqlite3GlobalConfig.mutex.xMutexAlloc==0 
14602              || sqlite3GlobalConfig.mutex.xMutexAlloc==p->xMutexAlloc
14603         );
14604         if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
14605           sqlite3GlobalConfig.mutex = *p;
14606         }
14607         p->xMutexLeave(pMaster);
14608       }
14609     }else{
14610       rc = sqlite3GlobalConfig.mutex.xMutexInit();
14611     }
14612   }
14613
14614   return rc;
14615 }
14616
14617 /*
14618 ** Shutdown the mutex system. This call frees resources allocated by
14619 ** sqlite3MutexInit().
14620 */
14621 SQLITE_PRIVATE int sqlite3MutexEnd(void){
14622   int rc = SQLITE_OK;
14623   rc = sqlite3GlobalConfig.mutex.xMutexEnd();
14624   return rc;
14625 }
14626
14627 /*
14628 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
14629 */
14630 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
14631 #ifndef SQLITE_OMIT_AUTOINIT
14632   if( sqlite3_initialize() ) return 0;
14633 #endif
14634   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
14635 }
14636
14637 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
14638   if( !sqlite3GlobalConfig.bCoreMutex ){
14639     return 0;
14640   }
14641   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
14642 }
14643
14644 /*
14645 ** Free a dynamic mutex.
14646 */
14647 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
14648   if( p ){
14649     sqlite3GlobalConfig.mutex.xMutexFree(p);
14650   }
14651 }
14652
14653 /*
14654 ** Obtain the mutex p. If some other thread already has the mutex, block
14655 ** until it can be obtained.
14656 */
14657 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
14658   if( p ){
14659     sqlite3GlobalConfig.mutex.xMutexEnter(p);
14660   }
14661 }
14662
14663 /*
14664 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
14665 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
14666 */
14667 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
14668   int rc = SQLITE_OK;
14669   if( p ){
14670     return sqlite3GlobalConfig.mutex.xMutexTry(p);
14671   }
14672   return rc;
14673 }
14674
14675 /*
14676 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
14677 ** entered by the same thread.  The behavior is undefined if the mutex 
14678 ** is not currently entered. If a NULL pointer is passed as an argument
14679 ** this function is a no-op.
14680 */
14681 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
14682   if( p ){
14683     sqlite3GlobalConfig.mutex.xMutexLeave(p);
14684   }
14685 }
14686
14687 #ifndef NDEBUG
14688 /*
14689 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
14690 ** intended for use inside assert() statements.
14691 */
14692 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
14693   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
14694 }
14695 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
14696   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
14697 }
14698 #endif
14699
14700 #endif /* SQLITE_OMIT_MUTEX */
14701
14702 /************** End of mutex.c ***********************************************/
14703 /************** Begin file mutex_noop.c **************************************/
14704 /*
14705 ** 2008 October 07
14706 **
14707 ** The author disclaims copyright to this source code.  In place of
14708 ** a legal notice, here is a blessing:
14709 **
14710 **    May you do good and not evil.
14711 **    May you find forgiveness for yourself and forgive others.
14712 **    May you share freely, never taking more than you give.
14713 **
14714 *************************************************************************
14715 ** This file contains the C functions that implement mutexes.
14716 **
14717 ** This implementation in this file does not provide any mutual
14718 ** exclusion and is thus suitable for use only in applications
14719 ** that use SQLite in a single thread.  The routines defined
14720 ** here are place-holders.  Applications can substitute working
14721 ** mutex routines at start-time using the
14722 **
14723 **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
14724 **
14725 ** interface.
14726 **
14727 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
14728 ** that does error checking on mutexes to make sure they are being
14729 ** called correctly.
14730 **
14731 ** $Id: mutex_noop.c,v 1.2 2008/10/15 19:03:03 drh Exp $
14732 */
14733
14734
14735 #if defined(SQLITE_MUTEX_NOOP) && !defined(SQLITE_DEBUG)
14736 /*
14737 ** Stub routines for all mutex methods.
14738 **
14739 ** This routines provide no mutual exclusion or error checking.
14740 */
14741 static int noopMutexHeld(sqlite3_mutex *p){ return 1; }
14742 static int noopMutexNotheld(sqlite3_mutex *p){ return 1; }
14743 static int noopMutexInit(void){ return SQLITE_OK; }
14744 static int noopMutexEnd(void){ return SQLITE_OK; }
14745 static sqlite3_mutex *noopMutexAlloc(int id){ return (sqlite3_mutex*)8; }
14746 static void noopMutexFree(sqlite3_mutex *p){ return; }
14747 static void noopMutexEnter(sqlite3_mutex *p){ return; }
14748 static int noopMutexTry(sqlite3_mutex *p){ return SQLITE_OK; }
14749 static void noopMutexLeave(sqlite3_mutex *p){ return; }
14750
14751 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
14752   static sqlite3_mutex_methods sMutex = {
14753     noopMutexInit,
14754     noopMutexEnd,
14755     noopMutexAlloc,
14756     noopMutexFree,
14757     noopMutexEnter,
14758     noopMutexTry,
14759     noopMutexLeave,
14760
14761     noopMutexHeld,
14762     noopMutexNotheld
14763   };
14764
14765   return &sMutex;
14766 }
14767 #endif /* defined(SQLITE_MUTEX_NOOP) && !defined(SQLITE_DEBUG) */
14768
14769 #if defined(SQLITE_MUTEX_NOOP) && defined(SQLITE_DEBUG)
14770 /*
14771 ** In this implementation, error checking is provided for testing
14772 ** and debugging purposes.  The mutexes still do not provide any
14773 ** mutual exclusion.
14774 */
14775
14776 /*
14777 ** The mutex object
14778 */
14779 struct sqlite3_mutex {
14780   int id;     /* The mutex type */
14781   int cnt;    /* Number of entries without a matching leave */
14782 };
14783
14784 /*
14785 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
14786 ** intended for use inside assert() statements.
14787 */
14788 static int debugMutexHeld(sqlite3_mutex *p){
14789   return p==0 || p->cnt>0;
14790 }
14791 static int debugMutexNotheld(sqlite3_mutex *p){
14792   return p==0 || p->cnt==0;
14793 }
14794
14795 /*
14796 ** Initialize and deinitialize the mutex subsystem.
14797 */
14798 static int debugMutexInit(void){ return SQLITE_OK; }
14799 static int debugMutexEnd(void){ return SQLITE_OK; }
14800
14801 /*
14802 ** The sqlite3_mutex_alloc() routine allocates a new
14803 ** mutex and returns a pointer to it.  If it returns NULL
14804 ** that means that a mutex could not be allocated. 
14805 */
14806 static sqlite3_mutex *debugMutexAlloc(int id){
14807   static sqlite3_mutex aStatic[6];
14808   sqlite3_mutex *pNew = 0;
14809   switch( id ){
14810     case SQLITE_MUTEX_FAST:
14811     case SQLITE_MUTEX_RECURSIVE: {
14812       pNew = sqlite3Malloc(sizeof(*pNew));
14813       if( pNew ){
14814         pNew->id = id;
14815         pNew->cnt = 0;
14816       }
14817       break;
14818     }
14819     default: {
14820       assert( id-2 >= 0 );
14821       assert( id-2 < sizeof(aStatic)/sizeof(aStatic[0]) );
14822       pNew = &aStatic[id-2];
14823       pNew->id = id;
14824       break;
14825     }
14826   }
14827   return pNew;
14828 }
14829
14830 /*
14831 ** This routine deallocates a previously allocated mutex.
14832 */
14833 static void debugMutexFree(sqlite3_mutex *p){
14834   assert( p->cnt==0 );
14835   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
14836   sqlite3_free(p);
14837 }
14838
14839 /*
14840 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
14841 ** to enter a mutex.  If another thread is already within the mutex,
14842 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
14843 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
14844 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
14845 ** be entered multiple times by the same thread.  In such cases the,
14846 ** mutex must be exited an equal number of times before another thread
14847 ** can enter.  If the same thread tries to enter any other kind of mutex
14848 ** more than once, the behavior is undefined.
14849 */
14850 static void debugMutexEnter(sqlite3_mutex *p){
14851   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
14852   p->cnt++;
14853 }
14854 static int debugMutexTry(sqlite3_mutex *p){
14855   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
14856   p->cnt++;
14857   return SQLITE_OK;
14858 }
14859
14860 /*
14861 ** The sqlite3_mutex_leave() routine exits a mutex that was
14862 ** previously entered by the same thread.  The behavior
14863 ** is undefined if the mutex is not currently entered or
14864 ** is not currently allocated.  SQLite will never do either.
14865 */
14866 static void debugMutexLeave(sqlite3_mutex *p){
14867   assert( debugMutexHeld(p) );
14868   p->cnt--;
14869   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
14870 }
14871
14872 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
14873   static sqlite3_mutex_methods sMutex = {
14874     debugMutexInit,
14875     debugMutexEnd,
14876     debugMutexAlloc,
14877     debugMutexFree,
14878     debugMutexEnter,
14879     debugMutexTry,
14880     debugMutexLeave,
14881
14882     debugMutexHeld,
14883     debugMutexNotheld
14884   };
14885
14886   return &sMutex;
14887 }
14888 #endif /* defined(SQLITE_MUTEX_NOOP) && defined(SQLITE_DEBUG) */
14889
14890 /************** End of mutex_noop.c ******************************************/
14891 /************** Begin file mutex_os2.c ***************************************/
14892 /*
14893 ** 2007 August 28
14894 **
14895 ** The author disclaims copyright to this source code.  In place of
14896 ** a legal notice, here is a blessing:
14897 **
14898 **    May you do good and not evil.
14899 **    May you find forgiveness for yourself and forgive others.
14900 **    May you share freely, never taking more than you give.
14901 **
14902 *************************************************************************
14903 ** This file contains the C functions that implement mutexes for OS/2
14904 **
14905 ** $Id: mutex_os2.c,v 1.10 2008/06/23 22:13:28 pweilbacher Exp $
14906 */
14907
14908 /*
14909 ** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
14910 ** See the mutex.h file for details.
14911 */
14912 #ifdef SQLITE_MUTEX_OS2
14913
14914 /********************** OS/2 Mutex Implementation **********************
14915 **
14916 ** This implementation of mutexes is built using the OS/2 API.
14917 */
14918
14919 /*
14920 ** The mutex object
14921 ** Each recursive mutex is an instance of the following structure.
14922 */
14923 struct sqlite3_mutex {
14924   HMTX mutex;       /* Mutex controlling the lock */
14925   int  id;          /* Mutex type */
14926   int  nRef;        /* Number of references */
14927   TID  owner;       /* Thread holding this mutex */
14928 };
14929
14930 #define OS2_MUTEX_INITIALIZER   0,0,0,0
14931
14932 /*
14933 ** Initialize and deinitialize the mutex subsystem.
14934 */
14935 static int os2MutexInit(void){ return SQLITE_OK; }
14936 static int os2MutexEnd(void){ return SQLITE_OK; }
14937
14938 /*
14939 ** The sqlite3_mutex_alloc() routine allocates a new
14940 ** mutex and returns a pointer to it.  If it returns NULL
14941 ** that means that a mutex could not be allocated. 
14942 ** SQLite will unwind its stack and return an error.  The argument
14943 ** to sqlite3_mutex_alloc() is one of these integer constants:
14944 **
14945 ** <ul>
14946 ** <li>  SQLITE_MUTEX_FAST               0
14947 ** <li>  SQLITE_MUTEX_RECURSIVE          1
14948 ** <li>  SQLITE_MUTEX_STATIC_MASTER      2
14949 ** <li>  SQLITE_MUTEX_STATIC_MEM         3
14950 ** <li>  SQLITE_MUTEX_STATIC_PRNG        4
14951 ** </ul>
14952 **
14953 ** The first two constants cause sqlite3_mutex_alloc() to create
14954 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
14955 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
14956 ** The mutex implementation does not need to make a distinction
14957 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
14958 ** not want to.  But SQLite will only request a recursive mutex in
14959 ** cases where it really needs one.  If a faster non-recursive mutex
14960 ** implementation is available on the host platform, the mutex subsystem
14961 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
14962 **
14963 ** The other allowed parameters to sqlite3_mutex_alloc() each return
14964 ** a pointer to a static preexisting mutex.  Three static mutexes are
14965 ** used by the current version of SQLite.  Future versions of SQLite
14966 ** may add additional static mutexes.  Static mutexes are for internal
14967 ** use by SQLite only.  Applications that use SQLite mutexes should
14968 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
14969 ** SQLITE_MUTEX_RECURSIVE.
14970 **
14971 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
14972 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
14973 ** returns a different mutex on every call.  But for the static
14974 ** mutex types, the same mutex is returned on every call that has
14975 ** the same type number.
14976 */
14977 static sqlite3_mutex *os2MutexAlloc(int iType){
14978   sqlite3_mutex *p = NULL;
14979   switch( iType ){
14980     case SQLITE_MUTEX_FAST:
14981     case SQLITE_MUTEX_RECURSIVE: {
14982       p = sqlite3MallocZero( sizeof(*p) );
14983       if( p ){
14984         p->id = iType;
14985         if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
14986           sqlite3_free( p );
14987           p = NULL;
14988         }
14989       }
14990       break;
14991     }
14992     default: {
14993       static volatile int isInit = 0;
14994       static sqlite3_mutex staticMutexes[] = {
14995         { OS2_MUTEX_INITIALIZER, },
14996         { OS2_MUTEX_INITIALIZER, },
14997         { OS2_MUTEX_INITIALIZER, },
14998         { OS2_MUTEX_INITIALIZER, },
14999         { OS2_MUTEX_INITIALIZER, },
15000         { OS2_MUTEX_INITIALIZER, },
15001       };
15002       if ( !isInit ){
15003         APIRET rc;
15004         PTIB ptib;
15005         PPIB ppib;
15006         HMTX mutex;
15007         char name[32];
15008         DosGetInfoBlocks( &ptib, &ppib );
15009         sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
15010                           ppib->pib_ulpid );
15011         while( !isInit ){
15012           mutex = 0;
15013           rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
15014           if( rc == NO_ERROR ){
15015             int i;
15016             if( !isInit ){
15017               for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
15018                 DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
15019               }
15020               isInit = 1;
15021             }
15022             DosCloseMutexSem( mutex );
15023           }else if( rc == ERROR_DUPLICATE_NAME ){
15024             DosSleep( 1 );
15025           }else{
15026             return p;
15027           }
15028         }
15029       }
15030       assert( iType-2 >= 0 );
15031       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
15032       p = &staticMutexes[iType-2];
15033       p->id = iType;
15034       break;
15035     }
15036   }
15037   return p;
15038 }
15039
15040
15041 /*
15042 ** This routine deallocates a previously allocated mutex.
15043 ** SQLite is careful to deallocate every mutex that it allocates.
15044 */
15045 static void os2MutexFree(sqlite3_mutex *p){
15046   if( p==0 ) return;
15047   assert( p->nRef==0 );
15048   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15049   DosCloseMutexSem( p->mutex );
15050   sqlite3_free( p );
15051 }
15052
15053 /*
15054 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15055 ** to enter a mutex.  If another thread is already within the mutex,
15056 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15057 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15058 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15059 ** be entered multiple times by the same thread.  In such cases the,
15060 ** mutex must be exited an equal number of times before another thread
15061 ** can enter.  If the same thread tries to enter any other kind of mutex
15062 ** more than once, the behavior is undefined.
15063 */
15064 static void os2MutexEnter(sqlite3_mutex *p){
15065   TID tid;
15066   PID holder1;
15067   ULONG holder2;
15068   if( p==0 ) return;
15069   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
15070   DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
15071   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
15072   p->owner = tid;
15073   p->nRef++;
15074 }
15075 static int os2MutexTry(sqlite3_mutex *p){
15076   int rc;
15077   TID tid;
15078   PID holder1;
15079   ULONG holder2;
15080   if( p==0 ) return SQLITE_OK;
15081   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
15082   if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR) {
15083     DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
15084     p->owner = tid;
15085     p->nRef++;
15086     rc = SQLITE_OK;
15087   } else {
15088     rc = SQLITE_BUSY;
15089   }
15090
15091   return rc;
15092 }
15093
15094 /*
15095 ** The sqlite3_mutex_leave() routine exits a mutex that was
15096 ** previously entered by the same thread.  The behavior
15097 ** is undefined if the mutex is not currently entered or
15098 ** is not currently allocated.  SQLite will never do either.
15099 */
15100 static void os2MutexLeave(sqlite3_mutex *p){
15101   TID tid;
15102   PID holder1;
15103   ULONG holder2;
15104   if( p==0 ) return;
15105   assert( p->nRef>0 );
15106   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
15107   assert( p->owner==tid );
15108   p->nRef--;
15109   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
15110   DosReleaseMutexSem(p->mutex);
15111 }
15112
15113 #ifdef SQLITE_DEBUG
15114 /*
15115 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15116 ** intended for use inside assert() statements.
15117 */
15118 static int os2MutexHeld(sqlite3_mutex *p){
15119   TID tid;
15120   PID pid;
15121   ULONG ulCount;
15122   PTIB ptib;
15123   if( p!=0 ) {
15124     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
15125   } else {
15126     DosGetInfoBlocks(&ptib, NULL);
15127     tid = ptib->tib_ptib2->tib2_ultid;
15128   }
15129   return p==0 || (p->nRef!=0 && p->owner==tid);
15130 }
15131 static int os2MutexNotheld(sqlite3_mutex *p){
15132   TID tid;
15133   PID pid;
15134   ULONG ulCount;
15135   PTIB ptib;
15136   if( p!= 0 ) {
15137     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
15138   } else {
15139     DosGetInfoBlocks(&ptib, NULL);
15140     tid = ptib->tib_ptib2->tib2_ultid;
15141   }
15142   return p==0 || p->nRef==0 || p->owner!=tid;
15143 }
15144 #endif
15145
15146 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15147   static sqlite3_mutex_methods sMutex = {
15148     os2MutexInit,
15149     os2MutexEnd,
15150     os2MutexAlloc,
15151     os2MutexFree,
15152     os2MutexEnter,
15153     os2MutexTry,
15154     os2MutexLeave,
15155 #ifdef SQLITE_DEBUG
15156     os2MutexHeld,
15157     os2MutexNotheld
15158 #endif
15159   };
15160
15161   return &sMutex;
15162 }
15163 #endif /* SQLITE_MUTEX_OS2 */
15164
15165 /************** End of mutex_os2.c *******************************************/
15166 /************** Begin file mutex_unix.c **************************************/
15167 /*
15168 ** 2007 August 28
15169 **
15170 ** The author disclaims copyright to this source code.  In place of
15171 ** a legal notice, here is a blessing:
15172 **
15173 **    May you do good and not evil.
15174 **    May you find forgiveness for yourself and forgive others.
15175 **    May you share freely, never taking more than you give.
15176 **
15177 *************************************************************************
15178 ** This file contains the C functions that implement mutexes for pthreads
15179 **
15180 ** $Id: mutex_unix.c,v 1.15 2008/11/17 19:18:55 danielk1977 Exp $
15181 */
15182
15183 /*
15184 ** The code in this file is only used if we are compiling threadsafe
15185 ** under unix with pthreads.
15186 **
15187 ** Note that this implementation requires a version of pthreads that
15188 ** supports recursive mutexes.
15189 */
15190 #ifdef SQLITE_MUTEX_PTHREADS
15191
15192 #include <pthread.h>
15193
15194
15195 /*
15196 ** Each recursive mutex is an instance of the following structure.
15197 */
15198 struct sqlite3_mutex {
15199   pthread_mutex_t mutex;     /* Mutex controlling the lock */
15200   int id;                    /* Mutex type */
15201   int nRef;                  /* Number of entrances */
15202   pthread_t owner;           /* Thread that is within this mutex */
15203 #ifdef SQLITE_DEBUG
15204   int trace;                 /* True to trace changes */
15205 #endif
15206 };
15207 #ifdef SQLITE_DEBUG
15208 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
15209 #else
15210 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0 }
15211 #endif
15212
15213 /*
15214 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15215 ** intended for use only inside assert() statements.  On some platforms,
15216 ** there might be race conditions that can cause these routines to
15217 ** deliver incorrect results.  In particular, if pthread_equal() is
15218 ** not an atomic operation, then these routines might delivery
15219 ** incorrect results.  On most platforms, pthread_equal() is a 
15220 ** comparison of two integers and is therefore atomic.  But we are
15221 ** told that HPUX is not such a platform.  If so, then these routines
15222 ** will not always work correctly on HPUX.
15223 **
15224 ** On those platforms where pthread_equal() is not atomic, SQLite
15225 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
15226 ** make sure no assert() statements are evaluated and hence these
15227 ** routines are never called.
15228 */
15229 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
15230 static int pthreadMutexHeld(sqlite3_mutex *p){
15231   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
15232 }
15233 static int pthreadMutexNotheld(sqlite3_mutex *p){
15234   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
15235 }
15236 #endif
15237
15238 /*
15239 ** Initialize and deinitialize the mutex subsystem.
15240 */
15241 static int pthreadMutexInit(void){ return SQLITE_OK; }
15242 static int pthreadMutexEnd(void){ return SQLITE_OK; }
15243
15244 /*
15245 ** The sqlite3_mutex_alloc() routine allocates a new
15246 ** mutex and returns a pointer to it.  If it returns NULL
15247 ** that means that a mutex could not be allocated.  SQLite
15248 ** will unwind its stack and return an error.  The argument
15249 ** to sqlite3_mutex_alloc() is one of these integer constants:
15250 **
15251 ** <ul>
15252 ** <li>  SQLITE_MUTEX_FAST
15253 ** <li>  SQLITE_MUTEX_RECURSIVE
15254 ** <li>  SQLITE_MUTEX_STATIC_MASTER
15255 ** <li>  SQLITE_MUTEX_STATIC_MEM
15256 ** <li>  SQLITE_MUTEX_STATIC_MEM2
15257 ** <li>  SQLITE_MUTEX_STATIC_PRNG
15258 ** <li>  SQLITE_MUTEX_STATIC_LRU
15259 ** </ul>
15260 **
15261 ** The first two constants cause sqlite3_mutex_alloc() to create
15262 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15263 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15264 ** The mutex implementation does not need to make a distinction
15265 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15266 ** not want to.  But SQLite will only request a recursive mutex in
15267 ** cases where it really needs one.  If a faster non-recursive mutex
15268 ** implementation is available on the host platform, the mutex subsystem
15269 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
15270 **
15271 ** The other allowed parameters to sqlite3_mutex_alloc() each return
15272 ** a pointer to a static preexisting mutex.  Three static mutexes are
15273 ** used by the current version of SQLite.  Future versions of SQLite
15274 ** may add additional static mutexes.  Static mutexes are for internal
15275 ** use by SQLite only.  Applications that use SQLite mutexes should
15276 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15277 ** SQLITE_MUTEX_RECURSIVE.
15278 **
15279 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15280 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15281 ** returns a different mutex on every call.  But for the static 
15282 ** mutex types, the same mutex is returned on every call that has
15283 ** the same type number.
15284 */
15285 static sqlite3_mutex *pthreadMutexAlloc(int iType){
15286   static sqlite3_mutex staticMutexes[] = {
15287     SQLITE3_MUTEX_INITIALIZER,
15288     SQLITE3_MUTEX_INITIALIZER,
15289     SQLITE3_MUTEX_INITIALIZER,
15290     SQLITE3_MUTEX_INITIALIZER,
15291     SQLITE3_MUTEX_INITIALIZER,
15292     SQLITE3_MUTEX_INITIALIZER
15293   };
15294   sqlite3_mutex *p;
15295   switch( iType ){
15296     case SQLITE_MUTEX_RECURSIVE: {
15297       p = sqlite3MallocZero( sizeof(*p) );
15298       if( p ){
15299 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15300         /* If recursive mutexes are not available, we will have to
15301         ** build our own.  See below. */
15302         pthread_mutex_init(&p->mutex, 0);
15303 #else
15304         /* Use a recursive mutex if it is available */
15305         pthread_mutexattr_t recursiveAttr;
15306         pthread_mutexattr_init(&recursiveAttr);
15307         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
15308         pthread_mutex_init(&p->mutex, &recursiveAttr);
15309         pthread_mutexattr_destroy(&recursiveAttr);
15310 #endif
15311         p->id = iType;
15312       }
15313       break;
15314     }
15315     case SQLITE_MUTEX_FAST: {
15316       p = sqlite3MallocZero( sizeof(*p) );
15317       if( p ){
15318         p->id = iType;
15319         pthread_mutex_init(&p->mutex, 0);
15320       }
15321       break;
15322     }
15323     default: {
15324       assert( iType-2 >= 0 );
15325       assert( iType-2 < ArraySize(staticMutexes) );
15326       p = &staticMutexes[iType-2];
15327       p->id = iType;
15328       break;
15329     }
15330   }
15331   return p;
15332 }
15333
15334
15335 /*
15336 ** This routine deallocates a previously
15337 ** allocated mutex.  SQLite is careful to deallocate every
15338 ** mutex that it allocates.
15339 */
15340 static void pthreadMutexFree(sqlite3_mutex *p){
15341   assert( p->nRef==0 );
15342   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15343   pthread_mutex_destroy(&p->mutex);
15344   sqlite3_free(p);
15345 }
15346
15347 /*
15348 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15349 ** to enter a mutex.  If another thread is already within the mutex,
15350 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15351 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15352 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15353 ** be entered multiple times by the same thread.  In such cases the,
15354 ** mutex must be exited an equal number of times before another thread
15355 ** can enter.  If the same thread tries to enter any other kind of mutex
15356 ** more than once, the behavior is undefined.
15357 */
15358 static void pthreadMutexEnter(sqlite3_mutex *p){
15359   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
15360
15361 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15362   /* If recursive mutexes are not available, then we have to grow
15363   ** our own.  This implementation assumes that pthread_equal()
15364   ** is atomic - that it cannot be deceived into thinking self
15365   ** and p->owner are equal if p->owner changes between two values
15366   ** that are not equal to self while the comparison is taking place.
15367   ** This implementation also assumes a coherent cache - that 
15368   ** separate processes cannot read different values from the same
15369   ** address at the same time.  If either of these two conditions
15370   ** are not met, then the mutexes will fail and problems will result.
15371   */
15372   {
15373     pthread_t self = pthread_self();
15374     if( p->nRef>0 && pthread_equal(p->owner, self) ){
15375       p->nRef++;
15376     }else{
15377       pthread_mutex_lock(&p->mutex);
15378       assert( p->nRef==0 );
15379       p->owner = self;
15380       p->nRef = 1;
15381     }
15382   }
15383 #else
15384   /* Use the built-in recursive mutexes if they are available.
15385   */
15386   pthread_mutex_lock(&p->mutex);
15387   p->owner = pthread_self();
15388   p->nRef++;
15389 #endif
15390
15391 #ifdef SQLITE_DEBUG
15392   if( p->trace ){
15393     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15394   }
15395 #endif
15396 }
15397 static int pthreadMutexTry(sqlite3_mutex *p){
15398   int rc;
15399   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
15400
15401 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15402   /* If recursive mutexes are not available, then we have to grow
15403   ** our own.  This implementation assumes that pthread_equal()
15404   ** is atomic - that it cannot be deceived into thinking self
15405   ** and p->owner are equal if p->owner changes between two values
15406   ** that are not equal to self while the comparison is taking place.
15407   ** This implementation also assumes a coherent cache - that 
15408   ** separate processes cannot read different values from the same
15409   ** address at the same time.  If either of these two conditions
15410   ** are not met, then the mutexes will fail and problems will result.
15411   */
15412   {
15413     pthread_t self = pthread_self();
15414     if( p->nRef>0 && pthread_equal(p->owner, self) ){
15415       p->nRef++;
15416       rc = SQLITE_OK;
15417     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
15418       assert( p->nRef==0 );
15419       p->owner = self;
15420       p->nRef = 1;
15421       rc = SQLITE_OK;
15422     }else{
15423       rc = SQLITE_BUSY;
15424     }
15425   }
15426 #else
15427   /* Use the built-in recursive mutexes if they are available.
15428   */
15429   if( pthread_mutex_trylock(&p->mutex)==0 ){
15430     p->owner = pthread_self();
15431     p->nRef++;
15432     rc = SQLITE_OK;
15433   }else{
15434     rc = SQLITE_BUSY;
15435   }
15436 #endif
15437
15438 #ifdef SQLITE_DEBUG
15439   if( rc==SQLITE_OK && p->trace ){
15440     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15441   }
15442 #endif
15443   return rc;
15444 }
15445
15446 /*
15447 ** The sqlite3_mutex_leave() routine exits a mutex that was
15448 ** previously entered by the same thread.  The behavior
15449 ** is undefined if the mutex is not currently entered or
15450 ** is not currently allocated.  SQLite will never do either.
15451 */
15452 static void pthreadMutexLeave(sqlite3_mutex *p){
15453   assert( pthreadMutexHeld(p) );
15454   p->nRef--;
15455   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
15456
15457 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15458   if( p->nRef==0 ){
15459     pthread_mutex_unlock(&p->mutex);
15460   }
15461 #else
15462   pthread_mutex_unlock(&p->mutex);
15463 #endif
15464
15465 #ifdef SQLITE_DEBUG
15466   if( p->trace ){
15467     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15468   }
15469 #endif
15470 }
15471
15472 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15473   static sqlite3_mutex_methods sMutex = {
15474     pthreadMutexInit,
15475     pthreadMutexEnd,
15476     pthreadMutexAlloc,
15477     pthreadMutexFree,
15478     pthreadMutexEnter,
15479     pthreadMutexTry,
15480     pthreadMutexLeave,
15481 #ifdef SQLITE_DEBUG
15482     pthreadMutexHeld,
15483     pthreadMutexNotheld
15484 #endif
15485   };
15486
15487   return &sMutex;
15488 }
15489
15490 #endif /* SQLITE_MUTEX_PTHREAD */
15491
15492 /************** End of mutex_unix.c ******************************************/
15493 /************** Begin file mutex_w32.c ***************************************/
15494 /*
15495 ** 2007 August 14
15496 **
15497 ** The author disclaims copyright to this source code.  In place of
15498 ** a legal notice, here is a blessing:
15499 **
15500 **    May you do good and not evil.
15501 **    May you find forgiveness for yourself and forgive others.
15502 **    May you share freely, never taking more than you give.
15503 **
15504 *************************************************************************
15505 ** This file contains the C functions that implement mutexes for win32
15506 **
15507 ** $Id: mutex_w32.c,v 1.12 2008/11/10 20:01:41 shane Exp $
15508 */
15509
15510 /*
15511 ** The code in this file is only used if we are compiling multithreaded
15512 ** on a win32 system.
15513 */
15514 #ifdef SQLITE_MUTEX_W32
15515
15516 /*
15517 ** Each recursive mutex is an instance of the following structure.
15518 */
15519 struct sqlite3_mutex {
15520   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
15521   int id;                    /* Mutex type */
15522   int nRef;                  /* Number of enterances */
15523   DWORD owner;               /* Thread holding this mutex */
15524 };
15525
15526 /*
15527 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
15528 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
15529 **
15530 ** Here is an interesting observation:  Win95, Win98, and WinME lack
15531 ** the LockFileEx() API.  But we can still statically link against that
15532 ** API as long as we don't call it win running Win95/98/ME.  A call to
15533 ** this routine is used to determine if the host is Win95/98/ME or
15534 ** WinNT/2K/XP so that we will know whether or not we can safely call
15535 ** the LockFileEx() API.
15536 **
15537 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
15538 ** which is only available if your application was compiled with 
15539 ** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
15540 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef 
15541 ** this out as well.
15542 */
15543 #if 0
15544 #if SQLITE_OS_WINCE
15545 # define mutexIsNT()  (1)
15546 #else
15547   static int mutexIsNT(void){
15548     static int osType = 0;
15549     if( osType==0 ){
15550       OSVERSIONINFO sInfo;
15551       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
15552       GetVersionEx(&sInfo);
15553       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
15554     }
15555     return osType==2;
15556   }
15557 #endif /* SQLITE_OS_WINCE */
15558 #endif
15559
15560 #ifdef SQLITE_DEBUG
15561 /*
15562 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15563 ** intended for use only inside assert() statements.
15564 */
15565 static int winMutexHeld(sqlite3_mutex *p){
15566   return p->nRef!=0 && p->owner==GetCurrentThreadId();
15567 }
15568 static int winMutexNotheld(sqlite3_mutex *p){
15569   return p->nRef==0 || p->owner!=GetCurrentThreadId();
15570 }
15571 #endif
15572
15573
15574 /*
15575 ** Initialize and deinitialize the mutex subsystem.
15576 */
15577 static int winMutexInit(void){ return SQLITE_OK; }
15578 static int winMutexEnd(void){ return SQLITE_OK; }
15579
15580 /*
15581 ** The sqlite3_mutex_alloc() routine allocates a new
15582 ** mutex and returns a pointer to it.  If it returns NULL
15583 ** that means that a mutex could not be allocated.  SQLite
15584 ** will unwind its stack and return an error.  The argument
15585 ** to sqlite3_mutex_alloc() is one of these integer constants:
15586 **
15587 ** <ul>
15588 ** <li>  SQLITE_MUTEX_FAST               0
15589 ** <li>  SQLITE_MUTEX_RECURSIVE          1
15590 ** <li>  SQLITE_MUTEX_STATIC_MASTER      2
15591 ** <li>  SQLITE_MUTEX_STATIC_MEM         3
15592 ** <li>  SQLITE_MUTEX_STATIC_PRNG        4
15593 ** </ul>
15594 **
15595 ** The first two constants cause sqlite3_mutex_alloc() to create
15596 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15597 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15598 ** The mutex implementation does not need to make a distinction
15599 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15600 ** not want to.  But SQLite will only request a recursive mutex in
15601 ** cases where it really needs one.  If a faster non-recursive mutex
15602 ** implementation is available on the host platform, the mutex subsystem
15603 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
15604 **
15605 ** The other allowed parameters to sqlite3_mutex_alloc() each return
15606 ** a pointer to a static preexisting mutex.  Three static mutexes are
15607 ** used by the current version of SQLite.  Future versions of SQLite
15608 ** may add additional static mutexes.  Static mutexes are for internal
15609 ** use by SQLite only.  Applications that use SQLite mutexes should
15610 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15611 ** SQLITE_MUTEX_RECURSIVE.
15612 **
15613 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15614 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15615 ** returns a different mutex on every call.  But for the static 
15616 ** mutex types, the same mutex is returned on every call that has
15617 ** the same type number.
15618 */
15619 static sqlite3_mutex *winMutexAlloc(int iType){
15620   sqlite3_mutex *p;
15621
15622   switch( iType ){
15623     case SQLITE_MUTEX_FAST:
15624     case SQLITE_MUTEX_RECURSIVE: {
15625       p = sqlite3MallocZero( sizeof(*p) );
15626       if( p ){
15627         p->id = iType;
15628         InitializeCriticalSection(&p->mutex);
15629       }
15630       break;
15631     }
15632     default: {
15633       static sqlite3_mutex staticMutexes[6];
15634       static int isInit = 0;
15635       while( !isInit ){
15636         static long lock = 0;
15637         if( InterlockedIncrement(&lock)==1 ){
15638           int i;
15639           for(i=0; i<sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++){
15640             InitializeCriticalSection(&staticMutexes[i].mutex);
15641           }
15642           isInit = 1;
15643         }else{
15644           Sleep(1);
15645         }
15646       }
15647       assert( iType-2 >= 0 );
15648       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
15649       p = &staticMutexes[iType-2];
15650       p->id = iType;
15651       break;
15652     }
15653   }
15654   return p;
15655 }
15656
15657
15658 /*
15659 ** This routine deallocates a previously
15660 ** allocated mutex.  SQLite is careful to deallocate every
15661 ** mutex that it allocates.
15662 */
15663 static void winMutexFree(sqlite3_mutex *p){
15664   assert( p );
15665   assert( p->nRef==0 );
15666   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15667   DeleteCriticalSection(&p->mutex);
15668   sqlite3_free(p);
15669 }
15670
15671 /*
15672 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15673 ** to enter a mutex.  If another thread is already within the mutex,
15674 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15675 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15676 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15677 ** be entered multiple times by the same thread.  In such cases the,
15678 ** mutex must be exited an equal number of times before another thread
15679 ** can enter.  If the same thread tries to enter any other kind of mutex
15680 ** more than once, the behavior is undefined.
15681 */
15682 static void winMutexEnter(sqlite3_mutex *p){
15683   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) );
15684   EnterCriticalSection(&p->mutex);
15685   p->owner = GetCurrentThreadId(); 
15686   p->nRef++;
15687 }
15688 static int winMutexTry(sqlite3_mutex *p){
15689   int rc = SQLITE_BUSY;
15690   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) );
15691   /*
15692   ** The sqlite3_mutex_try() routine is very rarely used, and when it
15693   ** is used it is merely an optimization.  So it is OK for it to always
15694   ** fail.  
15695   **
15696   ** The TryEnterCriticalSection() interface is only available on WinNT.
15697   ** And some windows compilers complain if you try to use it without
15698   ** first doing some #defines that prevent SQLite from building on Win98.
15699   ** For that reason, we will omit this optimization for now.  See
15700   ** ticket #2685.
15701   */
15702 #if 0
15703   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
15704     p->owner = GetCurrentThreadId();
15705     p->nRef++;
15706     rc = SQLITE_OK;
15707   }
15708 #endif
15709   return rc;
15710 }
15711
15712 /*
15713 ** The sqlite3_mutex_leave() routine exits a mutex that was
15714 ** previously entered by the same thread.  The behavior
15715 ** is undefined if the mutex is not currently entered or
15716 ** is not currently allocated.  SQLite will never do either.
15717 */
15718 static void winMutexLeave(sqlite3_mutex *p){
15719   assert( p->nRef>0 );
15720   assert( p->owner==GetCurrentThreadId() );
15721   p->nRef--;
15722   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
15723   LeaveCriticalSection(&p->mutex);
15724 }
15725
15726 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15727   static sqlite3_mutex_methods sMutex = {
15728     winMutexInit,
15729     winMutexEnd,
15730     winMutexAlloc,
15731     winMutexFree,
15732     winMutexEnter,
15733     winMutexTry,
15734     winMutexLeave,
15735 #ifdef SQLITE_DEBUG
15736     winMutexHeld,
15737     winMutexNotheld
15738 #endif
15739   };
15740
15741   return &sMutex;
15742 }
15743 #endif /* SQLITE_MUTEX_W32 */
15744
15745 /************** End of mutex_w32.c *******************************************/
15746 /************** Begin file malloc.c ******************************************/
15747 /*
15748 ** 2001 September 15
15749 **
15750 ** The author disclaims copyright to this source code.  In place of
15751 ** a legal notice, here is a blessing:
15752 **
15753 **    May you do good and not evil.
15754 **    May you find forgiveness for yourself and forgive others.
15755 **    May you share freely, never taking more than you give.
15756 **
15757 *************************************************************************
15758 **
15759 ** Memory allocation functions used throughout sqlite.
15760 **
15761 ** $Id: malloc.c,v 1.48 2008/11/19 09:05:27 danielk1977 Exp $
15762 */
15763
15764 /*
15765 ** This routine runs when the memory allocator sees that the
15766 ** total memory allocation is about to exceed the soft heap
15767 ** limit.
15768 */
15769 static void softHeapLimitEnforcer(
15770   void *NotUsed, 
15771   sqlite3_int64 NotUsed2,
15772   int allocSize
15773 ){
15774   UNUSED_PARAMETER2(NotUsed, NotUsed2);
15775   sqlite3_release_memory(allocSize);
15776 }
15777
15778 /*
15779 ** Set the soft heap-size limit for the library. Passing a zero or 
15780 ** negative value indicates no limit.
15781 */
15782 SQLITE_API void sqlite3_soft_heap_limit(int n){
15783   sqlite3_uint64 iLimit;
15784   int overage;
15785   if( n<0 ){
15786     iLimit = 0;
15787   }else{
15788     iLimit = n;
15789   }
15790   sqlite3_initialize();
15791   if( iLimit>0 ){
15792     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, iLimit);
15793   }else{
15794     sqlite3MemoryAlarm(0, 0, 0);
15795   }
15796   overage = sqlite3_memory_used() - n;
15797   if( overage>0 ){
15798     sqlite3_release_memory(overage);
15799   }
15800 }
15801
15802 /*
15803 ** Attempt to release up to n bytes of non-essential memory currently
15804 ** held by SQLite. An example of non-essential memory is memory used to
15805 ** cache database pages that are not currently in use.
15806 */
15807 SQLITE_API int sqlite3_release_memory(int n){
15808 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
15809   int nRet = 0;
15810 #if 0
15811   nRet += sqlite3VdbeReleaseMemory(n);
15812 #endif
15813   nRet += sqlite3PcacheReleaseMemory(n-nRet);
15814   return nRet;
15815 #else
15816   UNUSED_PARAMETER(n);
15817   return SQLITE_OK;
15818 #endif
15819 }
15820
15821 /*
15822 ** State information local to the memory allocation subsystem.
15823 */
15824 static SQLITE_WSD struct Mem0Global {
15825   /* Number of free pages for scratch and page-cache memory */
15826   u32 nScratchFree;
15827   u32 nPageFree;
15828
15829   sqlite3_mutex *mutex;         /* Mutex to serialize access */
15830
15831   /*
15832   ** The alarm callback and its arguments.  The mem0.mutex lock will
15833   ** be held while the callback is running.  Recursive calls into
15834   ** the memory subsystem are allowed, but no new callbacks will be
15835   ** issued.  The alarmBusy variable is set to prevent recursive
15836   ** callbacks.
15837   */
15838   sqlite3_int64 alarmThreshold;
15839   void (*alarmCallback)(void*, sqlite3_int64,int);
15840   void *alarmArg;
15841   int alarmBusy;
15842
15843   /*
15844   ** Pointers to the end of sqlite3GlobalConfig.pScratch and
15845   ** sqlite3GlobalConfig.pPage to a block of memory that records
15846   ** which pages are available.
15847   */
15848   u32 *aScratchFree;
15849   u32 *aPageFree;
15850 } mem0 = { 62560955, 0, 0, 0, 0, 0, 0, 0, 0 };
15851
15852 #define mem0 GLOBAL(struct Mem0Global, mem0)
15853
15854 /*
15855 ** Initialize the memory allocation subsystem.
15856 */
15857 SQLITE_PRIVATE int sqlite3MallocInit(void){
15858   if( sqlite3GlobalConfig.m.xMalloc==0 ){
15859     sqlite3MemSetDefault();
15860   }
15861   memset(&mem0, 0, sizeof(mem0));
15862   if( sqlite3GlobalConfig.bCoreMutex ){
15863     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15864   }
15865   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
15866       && sqlite3GlobalConfig.nScratch>=0 ){
15867     int i;
15868     sqlite3GlobalConfig.szScratch -= 4;
15869     mem0.aScratchFree = (u32*)&((char*)sqlite3GlobalConfig.pScratch)
15870                   [sqlite3GlobalConfig.szScratch*sqlite3GlobalConfig.nScratch];
15871     for(i=0; i<sqlite3GlobalConfig.nScratch; i++){ mem0.aScratchFree[i] = i; }
15872     mem0.nScratchFree = sqlite3GlobalConfig.nScratch;
15873   }else{
15874     sqlite3GlobalConfig.pScratch = 0;
15875     sqlite3GlobalConfig.szScratch = 0;
15876   }
15877   if( sqlite3GlobalConfig.pPage && sqlite3GlobalConfig.szPage>=512
15878       && sqlite3GlobalConfig.nPage>=1 ){
15879     int i;
15880     int overhead;
15881     int sz = sqlite3GlobalConfig.szPage;
15882     int n = sqlite3GlobalConfig.nPage;
15883     overhead = (4*n + sz - 1)/sz;
15884     sqlite3GlobalConfig.nPage -= overhead;
15885     mem0.aPageFree = (u32*)&((char*)sqlite3GlobalConfig.pPage)
15886                   [sqlite3GlobalConfig.szPage*sqlite3GlobalConfig.nPage];
15887     for(i=0; i<sqlite3GlobalConfig.nPage; i++){ mem0.aPageFree[i] = i; }
15888     mem0.nPageFree = sqlite3GlobalConfig.nPage;
15889   }else{
15890     sqlite3GlobalConfig.pPage = 0;
15891     sqlite3GlobalConfig.szPage = 0;
15892   }
15893   return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
15894 }
15895
15896 /*
15897 ** Deinitialize the memory allocation subsystem.
15898 */
15899 SQLITE_PRIVATE void sqlite3MallocEnd(void){
15900   sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
15901   memset(&mem0, 0, sizeof(mem0));
15902 }
15903
15904 /*
15905 ** Return the amount of memory currently checked out.
15906 */
15907 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
15908   int n, mx;
15909   sqlite3_int64 res;
15910   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
15911   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
15912   return res;
15913 }
15914
15915 /*
15916 ** Return the maximum amount of memory that has ever been
15917 ** checked out since either the beginning of this process
15918 ** or since the most recent reset.
15919 */
15920 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
15921   int n, mx;
15922   sqlite3_int64 res;
15923   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
15924   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
15925   return res;
15926 }
15927
15928 /*
15929 ** Change the alarm callback
15930 */
15931 SQLITE_PRIVATE int sqlite3MemoryAlarm(
15932   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
15933   void *pArg,
15934   sqlite3_int64 iThreshold
15935 ){
15936   sqlite3_mutex_enter(mem0.mutex);
15937   mem0.alarmCallback = xCallback;
15938   mem0.alarmArg = pArg;
15939   mem0.alarmThreshold = iThreshold;
15940   sqlite3_mutex_leave(mem0.mutex);
15941   return SQLITE_OK;
15942 }
15943
15944 #ifndef SQLITE_OMIT_DEPRECATED
15945 /*
15946 ** Deprecated external interface.  Internal/core SQLite code
15947 ** should call sqlite3MemoryAlarm.
15948 */
15949 SQLITE_API int sqlite3_memory_alarm(
15950   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
15951   void *pArg,
15952   sqlite3_int64 iThreshold
15953 ){
15954   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
15955 }
15956 #endif
15957
15958 /*
15959 ** Trigger the alarm 
15960 */
15961 static void sqlite3MallocAlarm(int nByte){
15962   void (*xCallback)(void*,sqlite3_int64,int);
15963   sqlite3_int64 nowUsed;
15964   void *pArg;
15965   if( mem0.alarmCallback==0 || mem0.alarmBusy  ) return;
15966   mem0.alarmBusy = 1;
15967   xCallback = mem0.alarmCallback;
15968   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
15969   pArg = mem0.alarmArg;
15970   sqlite3_mutex_leave(mem0.mutex);
15971   xCallback(pArg, nowUsed, nByte);
15972   sqlite3_mutex_enter(mem0.mutex);
15973   mem0.alarmBusy = 0;
15974 }
15975
15976 /*
15977 ** Do a memory allocation with statistics and alarms.  Assume the
15978 ** lock is already held.
15979 */
15980 static int mallocWithAlarm(int n, void **pp){
15981   int nFull;
15982   void *p;
15983   assert( sqlite3_mutex_held(mem0.mutex) );
15984   nFull = sqlite3GlobalConfig.m.xRoundup(n);
15985   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
15986   if( mem0.alarmCallback!=0 ){
15987     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
15988     if( nUsed+nFull >= mem0.alarmThreshold ){
15989       sqlite3MallocAlarm(nFull);
15990     }
15991   }
15992   p = sqlite3GlobalConfig.m.xMalloc(nFull);
15993   if( p==0 && mem0.alarmCallback ){
15994     sqlite3MallocAlarm(nFull);
15995     p = sqlite3GlobalConfig.m.xMalloc(nFull);
15996   }
15997   if( p ){
15998     nFull = sqlite3MallocSize(p);
15999     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
16000   }
16001   *pp = p;
16002   return nFull;
16003 }
16004
16005 /*
16006 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
16007 ** assumes the memory subsystem has already been initialized.
16008 */
16009 SQLITE_PRIVATE void *sqlite3Malloc(int n){
16010   void *p;
16011   if( n<=0 ){
16012     p = 0;
16013   }else if( sqlite3GlobalConfig.bMemstat ){
16014     sqlite3_mutex_enter(mem0.mutex);
16015     mallocWithAlarm(n, &p);
16016     sqlite3_mutex_leave(mem0.mutex);
16017   }else{
16018     p = sqlite3GlobalConfig.m.xMalloc(n);
16019   }
16020   return p;
16021 }
16022
16023 /*
16024 ** This version of the memory allocation is for use by the application.
16025 ** First make sure the memory subsystem is initialized, then do the
16026 ** allocation.
16027 */
16028 SQLITE_API void *sqlite3_malloc(int n){
16029 #ifndef SQLITE_OMIT_AUTOINIT
16030   if( sqlite3_initialize() ) return 0;
16031 #endif
16032   return sqlite3Malloc(n);
16033 }
16034
16035 /*
16036 ** Each thread may only have a single outstanding allocation from
16037 ** xScratchMalloc().  We verify this constraint in the single-threaded
16038 ** case by setting scratchAllocOut to 1 when an allocation
16039 ** is outstanding clearing it when the allocation is freed.
16040 */
16041 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16042 static int scratchAllocOut = 0;
16043 #endif
16044
16045
16046 /*
16047 ** Allocate memory that is to be used and released right away.
16048 ** This routine is similar to alloca() in that it is not intended
16049 ** for situations where the memory might be held long-term.  This
16050 ** routine is intended to get memory to old large transient data
16051 ** structures that would not normally fit on the stack of an
16052 ** embedded processor.
16053 */
16054 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
16055   void *p;
16056   assert( n>0 );
16057
16058 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16059   /* Verify that no more than one scratch allocation per thread
16060   ** is outstanding at one time.  (This is only checked in the
16061   ** single-threaded case since checking in the multi-threaded case
16062   ** would be much more complicated.) */
16063   assert( scratchAllocOut==0 );
16064 #endif
16065
16066   if( sqlite3GlobalConfig.szScratch<n ){
16067     goto scratch_overflow;
16068   }else{  
16069     sqlite3_mutex_enter(mem0.mutex);
16070     if( mem0.nScratchFree==0 ){
16071       sqlite3_mutex_leave(mem0.mutex);
16072       goto scratch_overflow;
16073     }else{
16074       int i;
16075       i = mem0.aScratchFree[--mem0.nScratchFree];
16076       i *= sqlite3GlobalConfig.szScratch;
16077       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
16078       sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
16079       sqlite3_mutex_leave(mem0.mutex);
16080       p = (void*)&((char*)sqlite3GlobalConfig.pScratch)[i];
16081     }
16082   }
16083 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16084   scratchAllocOut = p!=0;
16085 #endif
16086
16087   return p;
16088
16089 scratch_overflow:
16090   if( sqlite3GlobalConfig.bMemstat ){
16091     sqlite3_mutex_enter(mem0.mutex);
16092     sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
16093     n = mallocWithAlarm(n, &p);
16094     if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
16095     sqlite3_mutex_leave(mem0.mutex);
16096   }else{
16097     p = sqlite3GlobalConfig.m.xMalloc(n);
16098   }
16099 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16100   scratchAllocOut = p!=0;
16101 #endif
16102   return p;    
16103 }
16104 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
16105   if( p ){
16106
16107 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16108     /* Verify that no more than one scratch allocation per thread
16109     ** is outstanding at one time.  (This is only checked in the
16110     ** single-threaded case since checking in the multi-threaded case
16111     ** would be much more complicated.) */
16112     assert( scratchAllocOut==1 );
16113     scratchAllocOut = 0;
16114 #endif
16115
16116     if( sqlite3GlobalConfig.pScratch==0
16117            || p<sqlite3GlobalConfig.pScratch
16118            || p>=(void*)mem0.aScratchFree ){
16119       if( sqlite3GlobalConfig.bMemstat ){
16120         int iSize = sqlite3MallocSize(p);
16121         sqlite3_mutex_enter(mem0.mutex);
16122         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
16123         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
16124         sqlite3GlobalConfig.m.xFree(p);
16125         sqlite3_mutex_leave(mem0.mutex);
16126       }else{
16127         sqlite3GlobalConfig.m.xFree(p);
16128       }
16129     }else{
16130       int i;
16131       i = (u8 *)p - (u8 *)sqlite3GlobalConfig.pScratch;
16132       i /= sqlite3GlobalConfig.szScratch;
16133       assert( i>=0 && i<sqlite3GlobalConfig.nScratch );
16134       sqlite3_mutex_enter(mem0.mutex);
16135       assert( mem0.nScratchFree<(u32)sqlite3GlobalConfig.nScratch );
16136       mem0.aScratchFree[mem0.nScratchFree++] = i;
16137       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
16138       sqlite3_mutex_leave(mem0.mutex);
16139     }
16140   }
16141 }
16142
16143 /*
16144 ** Allocate memory to be used by the page cache.  Make use of the
16145 ** memory buffer provided by SQLITE_CONFIG_PAGECACHE if there is one
16146 ** and that memory is of the right size and is not completely
16147 ** consumed.  Otherwise, failover to sqlite3Malloc().
16148 */
16149 #if 0
16150 SQLITE_PRIVATE void *sqlite3PageMalloc(int n){
16151   void *p;
16152   assert( n>0 );
16153   assert( (n & (n-1))==0 );
16154   assert( n>=512 && n<=32768 );
16155
16156   if( sqlite3GlobalConfig.szPage<n ){
16157     goto page_overflow;
16158   }else{  
16159     sqlite3_mutex_enter(mem0.mutex);
16160     if( mem0.nPageFree==0 ){
16161       sqlite3_mutex_leave(mem0.mutex);
16162       goto page_overflow;
16163     }else{
16164       int i;
16165       i = mem0.aPageFree[--mem0.nPageFree];
16166       sqlite3_mutex_leave(mem0.mutex);
16167       i *= sqlite3GlobalConfig.szPage;
16168       sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, n);
16169       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
16170       p = (void*)&((char*)sqlite3GlobalConfig.pPage)[i];
16171     }
16172   }
16173   return p;
16174
16175 page_overflow:
16176   if( sqlite3GlobalConfig.bMemstat ){
16177     sqlite3_mutex_enter(mem0.mutex);
16178     sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, n);
16179     n = mallocWithAlarm(n, &p);
16180     if( p ) sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, n);
16181     sqlite3_mutex_leave(mem0.mutex);
16182   }else{
16183     p = sqlite3GlobalConfig.m.xMalloc(n);
16184   }
16185   return p;    
16186 }
16187 SQLITE_PRIVATE void sqlite3PageFree(void *p){
16188   if( p ){
16189     if( sqlite3GlobalConfig.pPage==0
16190            || p<sqlite3GlobalConfig.pPage
16191            || p>=(void*)mem0.aPageFree ){
16192       /* In this case, the page allocation was obtained from a regular 
16193       ** call to sqlite3_mem_methods.xMalloc() (a page-cache-memory 
16194       ** "overflow"). Free the block with sqlite3_mem_methods.xFree().
16195       */
16196       if( sqlite3GlobalConfig.bMemstat ){
16197         int iSize = sqlite3MallocSize(p);
16198         sqlite3_mutex_enter(mem0.mutex);
16199         sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
16200         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
16201         sqlite3GlobalConfig.m.xFree(p);
16202         sqlite3_mutex_leave(mem0.mutex);
16203       }else{
16204         sqlite3GlobalConfig.m.xFree(p);
16205       }
16206     }else{
16207       /* The page allocation was allocated from the sqlite3GlobalConfig.pPage
16208       ** buffer. In this case all that is add the index of the page in
16209       ** the sqlite3GlobalConfig.pPage array to the set of free indexes stored
16210       ** in the mem0.aPageFree[] array.
16211       */
16212       int i;
16213       i = (u8 *)p - (u8 *)sqlite3GlobalConfig.pPage;
16214       i /= sqlite3GlobalConfig.szPage;
16215       assert( i>=0 && i<sqlite3GlobalConfig.nPage );
16216       sqlite3_mutex_enter(mem0.mutex);
16217       assert( mem0.nPageFree<sqlite3GlobalConfig.nPage );
16218       mem0.aPageFree[mem0.nPageFree++] = i;
16219       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
16220       sqlite3_mutex_leave(mem0.mutex);
16221 #if !defined(NDEBUG) && 0
16222       /* Assert that a duplicate was not just inserted into aPageFree[]. */
16223       for(i=0; i<mem0.nPageFree-1; i++){
16224         assert( mem0.aPageFree[i]!=mem0.aPageFree[mem0.nPageFree-1] );
16225       }
16226 #endif
16227     }
16228   }
16229 }
16230 #endif
16231
16232 /*
16233 ** TRUE if p is a lookaside memory allocation from db
16234 */
16235 #ifndef SQLITE_OMIT_LOOKASIDE
16236 static int isLookaside(sqlite3 *db, void *p){
16237   return db && p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
16238 }
16239 #else
16240 #define isLookaside(A,B) 0
16241 #endif
16242
16243 /*
16244 ** Return the size of a memory allocation previously obtained from
16245 ** sqlite3Malloc() or sqlite3_malloc().
16246 */
16247 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
16248   return sqlite3GlobalConfig.m.xSize(p);
16249 }
16250 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
16251   if( isLookaside(db, p) ){
16252     return db->lookaside.sz;
16253   }else{
16254     return sqlite3GlobalConfig.m.xSize(p);
16255   }
16256 }
16257
16258 /*
16259 ** Free memory previously obtained from sqlite3Malloc().
16260 */
16261 SQLITE_API void sqlite3_free(void *p){
16262   if( p==0 ) return;
16263   if( sqlite3GlobalConfig.bMemstat ){
16264     sqlite3_mutex_enter(mem0.mutex);
16265     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
16266     sqlite3GlobalConfig.m.xFree(p);
16267     sqlite3_mutex_leave(mem0.mutex);
16268   }else{
16269     sqlite3GlobalConfig.m.xFree(p);
16270   }
16271 }
16272
16273 /*
16274 ** Free memory that might be associated with a particular database
16275 ** connection.
16276 */
16277 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
16278   if( isLookaside(db, p) ){
16279     LookasideSlot *pBuf = (LookasideSlot*)p;
16280     pBuf->pNext = db->lookaside.pFree;
16281     db->lookaside.pFree = pBuf;
16282     db->lookaside.nOut--;
16283   }else{
16284     sqlite3_free(p);
16285   }
16286 }
16287
16288 /*
16289 ** Change the size of an existing memory allocation
16290 */
16291 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
16292   int nOld, nNew;
16293   void *pNew;
16294   if( pOld==0 ){
16295     return sqlite3Malloc(nBytes);
16296   }
16297   if( nBytes<=0 ){
16298     sqlite3_free(pOld);
16299     return 0;
16300   }
16301   nOld = sqlite3MallocSize(pOld);
16302   if( sqlite3GlobalConfig.bMemstat ){
16303     sqlite3_mutex_enter(mem0.mutex);
16304     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
16305     nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
16306     if( nOld==nNew ){
16307       pNew = pOld;
16308     }else{
16309       if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >= 
16310             mem0.alarmThreshold ){
16311         sqlite3MallocAlarm(nNew-nOld);
16312       }
16313       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
16314       if( pNew==0 && mem0.alarmCallback ){
16315         sqlite3MallocAlarm(nBytes);
16316         pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
16317       }
16318       if( pNew ){
16319         nNew = sqlite3MallocSize(pNew);
16320         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
16321       }
16322     }
16323     sqlite3_mutex_leave(mem0.mutex);
16324   }else{
16325     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nBytes);
16326   }
16327   return pNew;
16328 }
16329
16330 /*
16331 ** The public interface to sqlite3Realloc.  Make sure that the memory
16332 ** subsystem is initialized prior to invoking sqliteRealloc.
16333 */
16334 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
16335 #ifndef SQLITE_OMIT_AUTOINIT
16336   if( sqlite3_initialize() ) return 0;
16337 #endif
16338   return sqlite3Realloc(pOld, n);
16339 }
16340
16341
16342 /*
16343 ** Allocate and zero memory.
16344 */ 
16345 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
16346   void *p = sqlite3Malloc(n);
16347   if( p ){
16348     memset(p, 0, n);
16349   }
16350   return p;
16351 }
16352
16353 /*
16354 ** Allocate and zero memory.  If the allocation fails, make
16355 ** the mallocFailed flag in the connection pointer.
16356 */
16357 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
16358   void *p = sqlite3DbMallocRaw(db, n);
16359   if( p ){
16360     memset(p, 0, n);
16361   }
16362   return p;
16363 }
16364
16365 /*
16366 ** Allocate and zero memory.  If the allocation fails, make
16367 ** the mallocFailed flag in the connection pointer.
16368 **
16369 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
16370 ** failure on the same database connection) then always return 0.
16371 ** Hence for a particular database connection, once malloc starts
16372 ** failing, it fails consistently until mallocFailed is reset.
16373 ** This is an important assumption.  There are many places in the
16374 ** code that do things like this:
16375 **
16376 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
16377 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
16378 **         if( b ) a[10] = 9;
16379 **
16380 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
16381 ** that all prior mallocs (ex: "a") worked too.
16382 */
16383 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
16384   void *p;
16385 #ifndef SQLITE_OMIT_LOOKASIDE
16386   if( db ){
16387     LookasideSlot *pBuf;
16388     if( db->mallocFailed ){
16389       return 0;
16390     }
16391     if( db->lookaside.bEnabled && n<=db->lookaside.sz
16392          && (pBuf = db->lookaside.pFree)!=0 ){
16393       db->lookaside.pFree = pBuf->pNext;
16394       db->lookaside.nOut++;
16395       if( db->lookaside.nOut>db->lookaside.mxOut ){
16396         db->lookaside.mxOut = db->lookaside.nOut;
16397       }
16398       return (void*)pBuf;
16399     }
16400   }
16401 #else
16402   if( db && db->mallocFailed ){
16403     return 0;
16404   }
16405 #endif
16406   p = sqlite3Malloc(n);
16407   if( !p && db ){
16408     db->mallocFailed = 1;
16409   }
16410   return p;
16411 }
16412
16413 /*
16414 ** Resize the block of memory pointed to by p to n bytes. If the
16415 ** resize fails, set the mallocFailed flag in the connection object.
16416 */
16417 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
16418   void *pNew = 0;
16419   if( db->mallocFailed==0 ){
16420     if( p==0 ){
16421       return sqlite3DbMallocRaw(db, n);
16422     }
16423     if( isLookaside(db, p) ){
16424       if( n<=db->lookaside.sz ){
16425         return p;
16426       }
16427       pNew = sqlite3DbMallocRaw(db, n);
16428       if( pNew ){
16429         memcpy(pNew, p, db->lookaside.sz);
16430         sqlite3DbFree(db, p);
16431       }
16432     }else{
16433       pNew = sqlite3_realloc(p, n);
16434       if( !pNew ){
16435         db->mallocFailed = 1;
16436       }
16437     }
16438   }
16439   return pNew;
16440 }
16441
16442 /*
16443 ** Attempt to reallocate p.  If the reallocation fails, then free p
16444 ** and set the mallocFailed flag in the database connection.
16445 */
16446 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
16447   void *pNew;
16448   pNew = sqlite3DbRealloc(db, p, n);
16449   if( !pNew ){
16450     sqlite3DbFree(db, p);
16451   }
16452   return pNew;
16453 }
16454
16455 /*
16456 ** Make a copy of a string in memory obtained from sqliteMalloc(). These 
16457 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
16458 ** is because when memory debugging is turned on, these two functions are 
16459 ** called via macros that record the current file and line number in the
16460 ** ThreadData structure.
16461 */
16462 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
16463   char *zNew;
16464   size_t n;
16465   if( z==0 ){
16466     return 0;
16467   }
16468   n = strlen(z)+1;
16469   assert( (n&0x7fffffff)==n );
16470   zNew = sqlite3DbMallocRaw(db, (int)n);
16471   if( zNew ){
16472     memcpy(zNew, z, n);
16473   }
16474   return zNew;
16475 }
16476 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
16477   char *zNew;
16478   if( z==0 ){
16479     return 0;
16480   }
16481   assert( (n&0x7fffffff)==n );
16482   zNew = sqlite3DbMallocRaw(db, n+1);
16483   if( zNew ){
16484     memcpy(zNew, z, n);
16485     zNew[n] = 0;
16486   }
16487   return zNew;
16488 }
16489
16490 /*
16491 ** Create a string from the zFromat argument and the va_list that follows.
16492 ** Store the string in memory obtained from sqliteMalloc() and make *pz
16493 ** point to that string.
16494 */
16495 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
16496   va_list ap;
16497   char *z;
16498
16499   va_start(ap, zFormat);
16500   z = sqlite3VMPrintf(db, zFormat, ap);
16501   va_end(ap);
16502   sqlite3DbFree(db, *pz);
16503   *pz = z;
16504 }
16505
16506
16507 /*
16508 ** This function must be called before exiting any API function (i.e. 
16509 ** returning control to the user) that has called sqlite3_malloc or
16510 ** sqlite3_realloc.
16511 **
16512 ** The returned value is normally a copy of the second argument to this
16513 ** function. However, if a malloc() failure has occured since the previous
16514 ** invocation SQLITE_NOMEM is returned instead. 
16515 **
16516 ** If the first argument, db, is not NULL and a malloc() error has occured,
16517 ** then the connection error-code (the value returned by sqlite3_errcode())
16518 ** is set to SQLITE_NOMEM.
16519 */
16520 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
16521   /* If the db handle is not NULL, then we must hold the connection handle
16522   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
16523   ** is unsafe, as is the call to sqlite3Error().
16524   */
16525   assert( !db || sqlite3_mutex_held(db->mutex) );
16526   if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
16527     sqlite3Error(db, SQLITE_NOMEM, 0);
16528     db->mallocFailed = 0;
16529     rc = SQLITE_NOMEM;
16530   }
16531   return rc & (db ? db->errMask : 0xff);
16532 }
16533
16534 /************** End of malloc.c **********************************************/
16535 /************** Begin file printf.c ******************************************/
16536 /*
16537 ** The "printf" code that follows dates from the 1980's.  It is in
16538 ** the public domain.  The original comments are included here for
16539 ** completeness.  They are very out-of-date but might be useful as
16540 ** an historical reference.  Most of the "enhancements" have been backed
16541 ** out so that the functionality is now the same as standard printf().
16542 **
16543 ** $Id: printf.c,v 1.96 2008/11/20 18:20:28 drh Exp $
16544 **
16545 **************************************************************************
16546 **
16547 ** The following modules is an enhanced replacement for the "printf" subroutines
16548 ** found in the standard C library.  The following enhancements are
16549 ** supported:
16550 **
16551 **      +  Additional functions.  The standard set of "printf" functions
16552 **         includes printf, fprintf, sprintf, vprintf, vfprintf, and
16553 **         vsprintf.  This module adds the following:
16554 **
16555 **           *  snprintf -- Works like sprintf, but has an extra argument
16556 **                          which is the size of the buffer written to.
16557 **
16558 **           *  mprintf --  Similar to sprintf.  Writes output to memory
16559 **                          obtained from malloc.
16560 **
16561 **           *  xprintf --  Calls a function to dispose of output.
16562 **
16563 **           *  nprintf --  No output, but returns the number of characters
16564 **                          that would have been output by printf.
16565 **
16566 **           *  A v- version (ex: vsnprintf) of every function is also
16567 **              supplied.
16568 **
16569 **      +  A few extensions to the formatting notation are supported:
16570 **
16571 **           *  The "=" flag (similar to "-") causes the output to be
16572 **              be centered in the appropriately sized field.
16573 **
16574 **           *  The %b field outputs an integer in binary notation.
16575 **
16576 **           *  The %c field now accepts a precision.  The character output
16577 **              is repeated by the number of times the precision specifies.
16578 **
16579 **           *  The %' field works like %c, but takes as its character the
16580 **              next character of the format string, instead of the next
16581 **              argument.  For example,  printf("%.78'-")  prints 78 minus
16582 **              signs, the same as  printf("%.78c",'-').
16583 **
16584 **      +  When compiled using GCC on a SPARC, this version of printf is
16585 **         faster than the library printf for SUN OS 4.1.
16586 **
16587 **      +  All functions are fully reentrant.
16588 **
16589 */
16590
16591 /*
16592 ** Conversion types fall into various categories as defined by the
16593 ** following enumeration.
16594 */
16595 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
16596 #define etFLOAT       2 /* Floating point.  %f */
16597 #define etEXP         3 /* Exponentional notation. %e and %E */
16598 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
16599 #define etSIZE        5 /* Return number of characters processed so far. %n */
16600 #define etSTRING      6 /* Strings. %s */
16601 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
16602 #define etPERCENT     8 /* Percent symbol. %% */
16603 #define etCHARX       9 /* Characters. %c */
16604 /* The rest are extensions, not normally found in printf() */
16605 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
16606 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
16607                           NULL pointers replaced by SQL NULL.  %Q */
16608 #define etTOKEN      12 /* a pointer to a Token structure */
16609 #define etSRCLIST    13 /* a pointer to a SrcList */
16610 #define etPOINTER    14 /* The %p conversion */
16611 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
16612 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
16613
16614
16615 /*
16616 ** An "etByte" is an 8-bit unsigned value.
16617 */
16618 typedef unsigned char etByte;
16619
16620 /*
16621 ** Each builtin conversion character (ex: the 'd' in "%d") is described
16622 ** by an instance of the following structure
16623 */
16624 typedef struct et_info {   /* Information about each format field */
16625   char fmttype;            /* The format field code letter */
16626   etByte base;             /* The base for radix conversion */
16627   etByte flags;            /* One or more of FLAG_ constants below */
16628   etByte type;             /* Conversion paradigm */
16629   etByte charset;          /* Offset into aDigits[] of the digits string */
16630   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
16631 } et_info;
16632
16633 /*
16634 ** Allowed values for et_info.flags
16635 */
16636 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
16637 #define FLAG_INTERN  2     /* True if for internal use only */
16638 #define FLAG_STRING  4     /* Allow infinity precision */
16639
16640
16641 /*
16642 ** The following table is searched linearly, so it is good to put the
16643 ** most frequently used conversion types first.
16644 */
16645 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
16646 static const char aPrefix[] = "-x0\000X0";
16647 static const et_info fmtinfo[] = {
16648   {  'd', 10, 1, etRADIX,      0,  0 },
16649   {  's',  0, 4, etSTRING,     0,  0 },
16650   {  'g',  0, 1, etGENERIC,    30, 0 },
16651   {  'z',  0, 4, etDYNSTRING,  0,  0 },
16652   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
16653   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
16654   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
16655   {  'c',  0, 0, etCHARX,      0,  0 },
16656   {  'o',  8, 0, etRADIX,      0,  2 },
16657   {  'u', 10, 0, etRADIX,      0,  0 },
16658   {  'x', 16, 0, etRADIX,      16, 1 },
16659   {  'X', 16, 0, etRADIX,      0,  4 },
16660 #ifndef SQLITE_OMIT_FLOATING_POINT
16661   {  'f',  0, 1, etFLOAT,      0,  0 },
16662   {  'e',  0, 1, etEXP,        30, 0 },
16663   {  'E',  0, 1, etEXP,        14, 0 },
16664   {  'G',  0, 1, etGENERIC,    14, 0 },
16665 #endif
16666   {  'i', 10, 1, etRADIX,      0,  0 },
16667   {  'n',  0, 0, etSIZE,       0,  0 },
16668   {  '%',  0, 0, etPERCENT,    0,  0 },
16669   {  'p', 16, 0, etPOINTER,    0,  1 },
16670   {  'T',  0, 2, etTOKEN,      0,  0 },
16671   {  'S',  0, 2, etSRCLIST,    0,  0 },
16672   {  'r', 10, 3, etORDINAL,    0,  0 },
16673 };
16674
16675 /*
16676 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
16677 ** conversions will work.
16678 */
16679 #ifndef SQLITE_OMIT_FLOATING_POINT
16680 /*
16681 ** "*val" is a double such that 0.1 <= *val < 10.0
16682 ** Return the ascii code for the leading digit of *val, then
16683 ** multiply "*val" by 10.0 to renormalize.
16684 **
16685 ** Example:
16686 **     input:     *val = 3.14159
16687 **     output:    *val = 1.4159    function return = '3'
16688 **
16689 ** The counter *cnt is incremented each time.  After counter exceeds
16690 ** 16 (the number of significant digits in a 64-bit float) '0' is
16691 ** always returned.
16692 */
16693 static int et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
16694   int digit;
16695   LONGDOUBLE_TYPE d;
16696   if( (*cnt)++ >= 16 ) return '0';
16697   digit = (int)*val;
16698   d = digit;
16699   digit += '0';
16700   *val = (*val - d)*10.0;
16701   return digit;
16702 }
16703 #endif /* SQLITE_OMIT_FLOATING_POINT */
16704
16705 /*
16706 ** Append N space characters to the given string buffer.
16707 */
16708 static void appendSpace(StrAccum *pAccum, int N){
16709   static const char zSpaces[] = "                             ";
16710   while( N>=(int)sizeof(zSpaces)-1 ){
16711     sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
16712     N -= sizeof(zSpaces)-1;
16713   }
16714   if( N>0 ){
16715     sqlite3StrAccumAppend(pAccum, zSpaces, N);
16716   }
16717 }
16718
16719 /*
16720 ** On machines with a small stack size, you can redefine the
16721 ** SQLITE_PRINT_BUF_SIZE to be less than 350.  But beware - for
16722 ** smaller values some %f conversions may go into an infinite loop.
16723 */
16724 #ifndef SQLITE_PRINT_BUF_SIZE
16725 # define SQLITE_PRINT_BUF_SIZE 350
16726 #endif
16727 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
16728
16729 /*
16730 ** The root program.  All variations call this core.
16731 **
16732 ** INPUTS:
16733 **   func   This is a pointer to a function taking three arguments
16734 **            1. A pointer to anything.  Same as the "arg" parameter.
16735 **            2. A pointer to the list of characters to be output
16736 **               (Note, this list is NOT null terminated.)
16737 **            3. An integer number of characters to be output.
16738 **               (Note: This number might be zero.)
16739 **
16740 **   arg    This is the pointer to anything which will be passed as the
16741 **          first argument to "func".  Use it for whatever you like.
16742 **
16743 **   fmt    This is the format string, as in the usual print.
16744 **
16745 **   ap     This is a pointer to a list of arguments.  Same as in
16746 **          vfprint.
16747 **
16748 ** OUTPUTS:
16749 **          The return value is the total number of characters sent to
16750 **          the function "func".  Returns -1 on a error.
16751 **
16752 ** Note that the order in which automatic variables are declared below
16753 ** seems to make a big difference in determining how fast this beast
16754 ** will run.
16755 */
16756 SQLITE_PRIVATE void sqlite3VXPrintf(
16757   StrAccum *pAccum,                  /* Accumulate results here */
16758   int useExtended,                   /* Allow extended %-conversions */
16759   const char *fmt,                   /* Format string */
16760   va_list ap                         /* arguments */
16761 ){
16762   int c;                     /* Next character in the format string */
16763   char *bufpt;               /* Pointer to the conversion buffer */
16764   int precision;             /* Precision of the current field */
16765   int length;                /* Length of the field */
16766   int idx;                   /* A general purpose loop counter */
16767   int width;                 /* Width of the current field */
16768   etByte flag_leftjustify;   /* True if "-" flag is present */
16769   etByte flag_plussign;      /* True if "+" flag is present */
16770   etByte flag_blanksign;     /* True if " " flag is present */
16771   etByte flag_alternateform; /* True if "#" flag is present */
16772   etByte flag_altform2;      /* True if "!" flag is present */
16773   etByte flag_zeropad;       /* True if field width constant starts with zero */
16774   etByte flag_long;          /* True if "l" flag is present */
16775   etByte flag_longlong;      /* True if the "ll" flag is present */
16776   etByte done;               /* Loop termination flag */
16777   sqlite_uint64 longvalue;   /* Value for integer types */
16778   LONGDOUBLE_TYPE realvalue; /* Value for real types */
16779   const et_info *infop;      /* Pointer to the appropriate info structure */
16780   char buf[etBUFSIZE];       /* Conversion buffer */
16781   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
16782   etByte xtype;              /* Conversion paradigm */
16783   char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
16784 #ifndef SQLITE_OMIT_FLOATING_POINT
16785   int  exp, e2;              /* exponent of real numbers */
16786   double rounder;            /* Used for rounding floating point values */
16787   etByte flag_dp;            /* True if decimal point should be shown */
16788   etByte flag_rtz;           /* True if trailing zeros should be removed */
16789   etByte flag_exp;           /* True to force display of the exponent */
16790   int nsd;                   /* Number of significant digits returned */
16791 #endif
16792
16793   length = 0;
16794   bufpt = 0;
16795   for(; (c=(*fmt))!=0; ++fmt){
16796     if( c!='%' ){
16797       int amt;
16798       bufpt = (char *)fmt;
16799       amt = 1;
16800       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
16801       sqlite3StrAccumAppend(pAccum, bufpt, amt);
16802       if( c==0 ) break;
16803     }
16804     if( (c=(*++fmt))==0 ){
16805       sqlite3StrAccumAppend(pAccum, "%", 1);
16806       break;
16807     }
16808     /* Find out what flags are present */
16809     flag_leftjustify = flag_plussign = flag_blanksign = 
16810      flag_alternateform = flag_altform2 = flag_zeropad = 0;
16811     done = 0;
16812     do{
16813       switch( c ){
16814         case '-':   flag_leftjustify = 1;     break;
16815         case '+':   flag_plussign = 1;        break;
16816         case ' ':   flag_blanksign = 1;       break;
16817         case '#':   flag_alternateform = 1;   break;
16818         case '!':   flag_altform2 = 1;        break;
16819         case '0':   flag_zeropad = 1;         break;
16820         default:    done = 1;                 break;
16821       }
16822     }while( !done && (c=(*++fmt))!=0 );
16823     /* Get the field width */
16824     width = 0;
16825     if( c=='*' ){
16826       width = va_arg(ap,int);
16827       if( width<0 ){
16828         flag_leftjustify = 1;
16829         width = -width;
16830       }
16831       c = *++fmt;
16832     }else{
16833       while( c>='0' && c<='9' ){
16834         width = width*10 + c - '0';
16835         c = *++fmt;
16836       }
16837     }
16838     if( width > etBUFSIZE-10 ){
16839       width = etBUFSIZE-10;
16840     }
16841     /* Get the precision */
16842     if( c=='.' ){
16843       precision = 0;
16844       c = *++fmt;
16845       if( c=='*' ){
16846         precision = va_arg(ap,int);
16847         if( precision<0 ) precision = -precision;
16848         c = *++fmt;
16849       }else{
16850         while( c>='0' && c<='9' ){
16851           precision = precision*10 + c - '0';
16852           c = *++fmt;
16853         }
16854       }
16855     }else{
16856       precision = -1;
16857     }
16858     /* Get the conversion type modifier */
16859     if( c=='l' ){
16860       flag_long = 1;
16861       c = *++fmt;
16862       if( c=='l' ){
16863         flag_longlong = 1;
16864         c = *++fmt;
16865       }else{
16866         flag_longlong = 0;
16867       }
16868     }else{
16869       flag_long = flag_longlong = 0;
16870     }
16871     /* Fetch the info entry for the field */
16872     infop = 0;
16873     for(idx=0; idx<ArraySize(fmtinfo); idx++){
16874       if( c==fmtinfo[idx].fmttype ){
16875         infop = &fmtinfo[idx];
16876         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
16877           xtype = infop->type;
16878         }else{
16879           return;
16880         }
16881         break;
16882       }
16883     }
16884     zExtra = 0;
16885     if( infop==0 ){
16886       return;
16887     }
16888
16889
16890     /* Limit the precision to prevent overflowing buf[] during conversion */
16891     if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
16892       precision = etBUFSIZE-40;
16893     }
16894
16895     /*
16896     ** At this point, variables are initialized as follows:
16897     **
16898     **   flag_alternateform          TRUE if a '#' is present.
16899     **   flag_altform2               TRUE if a '!' is present.
16900     **   flag_plussign               TRUE if a '+' is present.
16901     **   flag_leftjustify            TRUE if a '-' is present or if the
16902     **                               field width was negative.
16903     **   flag_zeropad                TRUE if the width began with 0.
16904     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
16905     **                               the conversion character.
16906     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
16907     **                               the conversion character.
16908     **   flag_blanksign              TRUE if a ' ' is present.
16909     **   width                       The specified field width.  This is
16910     **                               always non-negative.  Zero is the default.
16911     **   precision                   The specified precision.  The default
16912     **                               is -1.
16913     **   xtype                       The class of the conversion.
16914     **   infop                       Pointer to the appropriate info struct.
16915     */
16916     switch( xtype ){
16917       case etPOINTER:
16918         flag_longlong = sizeof(char*)==sizeof(i64);
16919         flag_long = sizeof(char*)==sizeof(long int);
16920         /* Fall through into the next case */
16921       case etORDINAL:
16922       case etRADIX:
16923         if( infop->flags & FLAG_SIGNED ){
16924           i64 v;
16925           if( flag_longlong )   v = va_arg(ap,i64);
16926           else if( flag_long )  v = va_arg(ap,long int);
16927           else                  v = va_arg(ap,int);
16928           if( v<0 ){
16929             longvalue = -v;
16930             prefix = '-';
16931           }else{
16932             longvalue = v;
16933             if( flag_plussign )        prefix = '+';
16934             else if( flag_blanksign )  prefix = ' ';
16935             else                       prefix = 0;
16936           }
16937         }else{
16938           if( flag_longlong )   longvalue = va_arg(ap,u64);
16939           else if( flag_long )  longvalue = va_arg(ap,unsigned long int);
16940           else                  longvalue = va_arg(ap,unsigned int);
16941           prefix = 0;
16942         }
16943         if( longvalue==0 ) flag_alternateform = 0;
16944         if( flag_zeropad && precision<width-(prefix!=0) ){
16945           precision = width-(prefix!=0);
16946         }
16947         bufpt = &buf[etBUFSIZE-1];
16948         if( xtype==etORDINAL ){
16949           static const char zOrd[] = "thstndrd";
16950           int x = longvalue % 10;
16951           if( x>=4 || (longvalue/10)%10==1 ){
16952             x = 0;
16953           }
16954           buf[etBUFSIZE-3] = zOrd[x*2];
16955           buf[etBUFSIZE-2] = zOrd[x*2+1];
16956           bufpt -= 2;
16957         }
16958         {
16959           register const char *cset;      /* Use registers for speed */
16960           register int base;
16961           cset = &aDigits[infop->charset];
16962           base = infop->base;
16963           do{                                           /* Convert to ascii */
16964             *(--bufpt) = cset[longvalue%base];
16965             longvalue = longvalue/base;
16966           }while( longvalue>0 );
16967         }
16968         length = &buf[etBUFSIZE-1]-bufpt;
16969         for(idx=precision-length; idx>0; idx--){
16970           *(--bufpt) = '0';                             /* Zero pad */
16971         }
16972         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
16973         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
16974           const char *pre;
16975           char x;
16976           pre = &aPrefix[infop->prefix];
16977           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
16978         }
16979         length = &buf[etBUFSIZE-1]-bufpt;
16980         break;
16981       case etFLOAT:
16982       case etEXP:
16983       case etGENERIC:
16984         realvalue = va_arg(ap,double);
16985 #ifndef SQLITE_OMIT_FLOATING_POINT
16986         if( precision<0 ) precision = 6;         /* Set default precision */
16987         if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
16988         if( realvalue<0.0 ){
16989           realvalue = -realvalue;
16990           prefix = '-';
16991         }else{
16992           if( flag_plussign )          prefix = '+';
16993           else if( flag_blanksign )    prefix = ' ';
16994           else                         prefix = 0;
16995         }
16996         if( xtype==etGENERIC && precision>0 ) precision--;
16997 #if 0
16998         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
16999         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
17000 #else
17001         /* It makes more sense to use 0.5 */
17002         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
17003 #endif
17004         if( xtype==etFLOAT ) realvalue += rounder;
17005         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
17006         exp = 0;
17007         if( sqlite3IsNaN(realvalue) ){
17008           bufpt = "NaN";
17009           length = 3;
17010           break;
17011         }
17012         if( realvalue>0.0 ){
17013           while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
17014           while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
17015           while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
17016           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
17017           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
17018           if( exp>350 ){
17019             if( prefix=='-' ){
17020               bufpt = "-Inf";
17021             }else if( prefix=='+' ){
17022               bufpt = "+Inf";
17023             }else{
17024               bufpt = "Inf";
17025             }
17026             length = strlen(bufpt);
17027             break;
17028           }
17029         }
17030         bufpt = buf;
17031         /*
17032         ** If the field type is etGENERIC, then convert to either etEXP
17033         ** or etFLOAT, as appropriate.
17034         */
17035         flag_exp = xtype==etEXP;
17036         if( xtype!=etFLOAT ){
17037           realvalue += rounder;
17038           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
17039         }
17040         if( xtype==etGENERIC ){
17041           flag_rtz = !flag_alternateform;
17042           if( exp<-4 || exp>precision ){
17043             xtype = etEXP;
17044           }else{
17045             precision = precision - exp;
17046             xtype = etFLOAT;
17047           }
17048         }else{
17049           flag_rtz = 0;
17050         }
17051         if( xtype==etEXP ){
17052           e2 = 0;
17053         }else{
17054           e2 = exp;
17055         }
17056         nsd = 0;
17057         flag_dp = (precision>0) | flag_alternateform | flag_altform2;
17058         /* The sign in front of the number */
17059         if( prefix ){
17060           *(bufpt++) = prefix;
17061         }
17062         /* Digits prior to the decimal point */
17063         if( e2<0 ){
17064           *(bufpt++) = '0';
17065         }else{
17066           for(; e2>=0; e2--){
17067             *(bufpt++) = et_getdigit(&realvalue,&nsd);
17068           }
17069         }
17070         /* The decimal point */
17071         if( flag_dp ){
17072           *(bufpt++) = '.';
17073         }
17074         /* "0" digits after the decimal point but before the first
17075         ** significant digit of the number */
17076         for(e2++; e2<0; precision--, e2++){
17077           assert( precision>0 );
17078           *(bufpt++) = '0';
17079         }
17080         /* Significant digits after the decimal point */
17081         while( (precision--)>0 ){
17082           *(bufpt++) = et_getdigit(&realvalue,&nsd);
17083         }
17084         /* Remove trailing zeros and the "." if no digits follow the "." */
17085         if( flag_rtz && flag_dp ){
17086           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
17087           assert( bufpt>buf );
17088           if( bufpt[-1]=='.' ){
17089             if( flag_altform2 ){
17090               *(bufpt++) = '0';
17091             }else{
17092               *(--bufpt) = 0;
17093             }
17094           }
17095         }
17096         /* Add the "eNNN" suffix */
17097         if( flag_exp || xtype==etEXP ){
17098           *(bufpt++) = aDigits[infop->charset];
17099           if( exp<0 ){
17100             *(bufpt++) = '-'; exp = -exp;
17101           }else{
17102             *(bufpt++) = '+';
17103           }
17104           if( exp>=100 ){
17105             *(bufpt++) = (exp/100)+'0';                /* 100's digit */
17106             exp %= 100;
17107           }
17108           *(bufpt++) = exp/10+'0';                     /* 10's digit */
17109           *(bufpt++) = exp%10+'0';                     /* 1's digit */
17110         }
17111         *bufpt = 0;
17112
17113         /* The converted number is in buf[] and zero terminated. Output it.
17114         ** Note that the number is in the usual order, not reversed as with
17115         ** integer conversions. */
17116         length = bufpt-buf;
17117         bufpt = buf;
17118
17119         /* Special case:  Add leading zeros if the flag_zeropad flag is
17120         ** set and we are not left justified */
17121         if( flag_zeropad && !flag_leftjustify && length < width){
17122           int i;
17123           int nPad = width - length;
17124           for(i=width; i>=nPad; i--){
17125             bufpt[i] = bufpt[i-nPad];
17126           }
17127           i = prefix!=0;
17128           while( nPad-- ) bufpt[i++] = '0';
17129           length = width;
17130         }
17131 #endif
17132         break;
17133       case etSIZE:
17134         *(va_arg(ap,int*)) = pAccum->nChar;
17135         length = width = 0;
17136         break;
17137       case etPERCENT:
17138         buf[0] = '%';
17139         bufpt = buf;
17140         length = 1;
17141         break;
17142       case etCHARX:
17143         c = buf[0] = va_arg(ap,int);
17144         if( precision>=0 ){
17145           for(idx=1; idx<precision; idx++) buf[idx] = c;
17146           length = precision;
17147         }else{
17148           length =1;
17149         }
17150         bufpt = buf;
17151         break;
17152       case etSTRING:
17153       case etDYNSTRING:
17154         bufpt = va_arg(ap,char*);
17155         if( bufpt==0 ){
17156           bufpt = "";
17157         }else if( xtype==etDYNSTRING ){
17158           zExtra = bufpt;
17159         }
17160         if( precision>=0 ){
17161           for(length=0; length<precision && bufpt[length]; length++){}
17162         }else{
17163           length = strlen(bufpt);
17164         }
17165         break;
17166       case etSQLESCAPE:
17167       case etSQLESCAPE2:
17168       case etSQLESCAPE3: {
17169         int i, j, n, ch, isnull;
17170         int needQuote;
17171         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
17172         char *escarg = va_arg(ap,char*);
17173         isnull = escarg==0;
17174         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
17175         for(i=n=0; (ch=escarg[i])!=0; i++){
17176           if( ch==q )  n++;
17177         }
17178         needQuote = !isnull && xtype==etSQLESCAPE2;
17179         n += i + 1 + needQuote*2;
17180         if( n>etBUFSIZE ){
17181           bufpt = zExtra = sqlite3Malloc( n );
17182           if( bufpt==0 ){
17183             pAccum->mallocFailed = 1;
17184             return;
17185           }
17186         }else{
17187           bufpt = buf;
17188         }
17189         j = 0;
17190         if( needQuote ) bufpt[j++] = q;
17191         for(i=0; (ch=escarg[i])!=0; i++){
17192           bufpt[j++] = ch;
17193           if( ch==q ) bufpt[j++] = ch;
17194         }
17195         if( needQuote ) bufpt[j++] = q;
17196         bufpt[j] = 0;
17197         length = j;
17198         /* The precision is ignored on %q and %Q */
17199         /* if( precision>=0 && precision<length ) length = precision; */
17200         break;
17201       }
17202       case etTOKEN: {
17203         Token *pToken = va_arg(ap, Token*);
17204         if( pToken ){
17205           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
17206         }
17207         length = width = 0;
17208         break;
17209       }
17210       case etSRCLIST: {
17211         SrcList *pSrc = va_arg(ap, SrcList*);
17212         int k = va_arg(ap, int);
17213         struct SrcList_item *pItem = &pSrc->a[k];
17214         assert( k>=0 && k<pSrc->nSrc );
17215         if( pItem->zDatabase ){
17216           sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
17217           sqlite3StrAccumAppend(pAccum, ".", 1);
17218         }
17219         sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
17220         length = width = 0;
17221         break;
17222       }
17223     }/* End switch over the format type */
17224     /*
17225     ** The text of the conversion is pointed to by "bufpt" and is
17226     ** "length" characters long.  The field width is "width".  Do
17227     ** the output.
17228     */
17229     if( !flag_leftjustify ){
17230       register int nspace;
17231       nspace = width-length;
17232       if( nspace>0 ){
17233         appendSpace(pAccum, nspace);
17234       }
17235     }
17236     if( length>0 ){
17237       sqlite3StrAccumAppend(pAccum, bufpt, length);
17238     }
17239     if( flag_leftjustify ){
17240       register int nspace;
17241       nspace = width-length;
17242       if( nspace>0 ){
17243         appendSpace(pAccum, nspace);
17244       }
17245     }
17246     if( zExtra ){
17247       sqlite3_free(zExtra);
17248     }
17249   }/* End for loop over the format string */
17250 } /* End of function */
17251
17252 /*
17253 ** Append N bytes of text from z to the StrAccum object.
17254 */
17255 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
17256   if( p->tooBig | p->mallocFailed ){
17257     return;
17258   }
17259   if( N<0 ){
17260     N = strlen(z);
17261   }
17262   if( N==0 ){
17263     return;
17264   }
17265   if( p->nChar+N >= p->nAlloc ){
17266     char *zNew;
17267     if( !p->useMalloc ){
17268       p->tooBig = 1;
17269       N = p->nAlloc - p->nChar - 1;
17270       if( N<=0 ){
17271         return;
17272       }
17273     }else{
17274       i64 szNew = p->nChar;
17275       szNew += N + 1;
17276       if( szNew > p->mxAlloc ){
17277         sqlite3StrAccumReset(p);
17278         p->tooBig = 1;
17279         return;
17280       }else{
17281         p->nAlloc = szNew;
17282       }
17283       zNew = sqlite3DbMallocRaw(p->db, p->nAlloc );
17284       if( zNew ){
17285         memcpy(zNew, p->zText, p->nChar);
17286         sqlite3StrAccumReset(p);
17287         p->zText = zNew;
17288       }else{
17289         p->mallocFailed = 1;
17290         sqlite3StrAccumReset(p);
17291         return;
17292       }
17293     }
17294   }
17295   memcpy(&p->zText[p->nChar], z, N);
17296   p->nChar += N;
17297 }
17298
17299 /*
17300 ** Finish off a string by making sure it is zero-terminated.
17301 ** Return a pointer to the resulting string.  Return a NULL
17302 ** pointer if any kind of error was encountered.
17303 */
17304 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
17305   if( p->zText ){
17306     p->zText[p->nChar] = 0;
17307     if( p->useMalloc && p->zText==p->zBase ){
17308       p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
17309       if( p->zText ){
17310         memcpy(p->zText, p->zBase, p->nChar+1);
17311       }else{
17312         p->mallocFailed = 1;
17313       }
17314     }
17315   }
17316   return p->zText;
17317 }
17318
17319 /*
17320 ** Reset an StrAccum string.  Reclaim all malloced memory.
17321 */
17322 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
17323   if( p->zText!=p->zBase ){
17324     sqlite3DbFree(p->db, p->zText);
17325   }
17326   p->zText = 0;
17327 }
17328
17329 /*
17330 ** Initialize a string accumulator
17331 */
17332 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
17333   p->zText = p->zBase = zBase;
17334   p->db = 0;
17335   p->nChar = 0;
17336   p->nAlloc = n;
17337   p->mxAlloc = mx;
17338   p->useMalloc = 1;
17339   p->tooBig = 0;
17340   p->mallocFailed = 0;
17341 }
17342
17343 /*
17344 ** Print into memory obtained from sqliteMalloc().  Use the internal
17345 ** %-conversion extensions.
17346 */
17347 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
17348   char *z;
17349   char zBase[SQLITE_PRINT_BUF_SIZE];
17350   StrAccum acc;
17351   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
17352                       db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH);
17353   acc.db = db;
17354   sqlite3VXPrintf(&acc, 1, zFormat, ap);
17355   z = sqlite3StrAccumFinish(&acc);
17356   if( acc.mallocFailed && db ){
17357     db->mallocFailed = 1;
17358   }
17359   return z;
17360 }
17361
17362 /*
17363 ** Print into memory obtained from sqliteMalloc().  Use the internal
17364 ** %-conversion extensions.
17365 */
17366 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
17367   va_list ap;
17368   char *z;
17369   va_start(ap, zFormat);
17370   z = sqlite3VMPrintf(db, zFormat, ap);
17371   va_end(ap);
17372   return z;
17373 }
17374
17375 /*
17376 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
17377 ** the string and before returnning.  This routine is intended to be used
17378 ** to modify an existing string.  For example:
17379 **
17380 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
17381 **
17382 */
17383 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
17384   va_list ap;
17385   char *z;
17386   va_start(ap, zFormat);
17387   z = sqlite3VMPrintf(db, zFormat, ap);
17388   va_end(ap);
17389   sqlite3DbFree(db, zStr);
17390   return z;
17391 }
17392
17393 /*
17394 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
17395 ** %-conversion extensions.
17396 */
17397 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
17398   char *z;
17399   char zBase[SQLITE_PRINT_BUF_SIZE];
17400   StrAccum acc;
17401 #ifndef SQLITE_OMIT_AUTOINIT
17402   if( sqlite3_initialize() ) return 0;
17403 #endif
17404   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
17405   sqlite3VXPrintf(&acc, 0, zFormat, ap);
17406   z = sqlite3StrAccumFinish(&acc);
17407   return z;
17408 }
17409
17410 /*
17411 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
17412 ** %-conversion extensions.
17413 */
17414 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
17415   va_list ap;
17416   char *z;
17417 #ifndef SQLITE_OMIT_AUTOINIT
17418   if( sqlite3_initialize() ) return 0;
17419 #endif
17420   va_start(ap, zFormat);
17421   z = sqlite3_vmprintf(zFormat, ap);
17422   va_end(ap);
17423   return z;
17424 }
17425
17426 /*
17427 ** sqlite3_snprintf() works like snprintf() except that it ignores the
17428 ** current locale settings.  This is important for SQLite because we
17429 ** are not able to use a "," as the decimal point in place of "." as
17430 ** specified by some locales.
17431 */
17432 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
17433   char *z;
17434   va_list ap;
17435   StrAccum acc;
17436
17437   if( n<=0 ){
17438     return zBuf;
17439   }
17440   sqlite3StrAccumInit(&acc, zBuf, n, 0);
17441   acc.useMalloc = 0;
17442   va_start(ap,zFormat);
17443   sqlite3VXPrintf(&acc, 0, zFormat, ap);
17444   va_end(ap);
17445   z = sqlite3StrAccumFinish(&acc);
17446   return z;
17447 }
17448
17449 #if defined(SQLITE_DEBUG)
17450 /*
17451 ** A version of printf() that understands %lld.  Used for debugging.
17452 ** The printf() built into some versions of windows does not understand %lld
17453 ** and segfaults if you give it a long long int.
17454 */
17455 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
17456   va_list ap;
17457   StrAccum acc;
17458   char zBuf[500];
17459   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
17460   acc.useMalloc = 0;
17461   va_start(ap,zFormat);
17462   sqlite3VXPrintf(&acc, 0, zFormat, ap);
17463   va_end(ap);
17464   sqlite3StrAccumFinish(&acc);
17465   fprintf(stdout,"%s", zBuf);
17466   fflush(stdout);
17467 }
17468 #endif
17469
17470 /************** End of printf.c **********************************************/
17471 /************** Begin file random.c ******************************************/
17472 /*
17473 ** 2001 September 15
17474 **
17475 ** The author disclaims copyright to this source code.  In place of
17476 ** a legal notice, here is a blessing:
17477 **
17478 **    May you do good and not evil.
17479 **    May you find forgiveness for yourself and forgive others.
17480 **    May you share freely, never taking more than you give.
17481 **
17482 *************************************************************************
17483 ** This file contains code to implement a pseudo-random number
17484 ** generator (PRNG) for SQLite.
17485 **
17486 ** Random numbers are used by some of the database backends in order
17487 ** to generate random integer keys for tables or random filenames.
17488 **
17489 ** $Id: random.c,v 1.27 2008/10/07 15:25:48 drh Exp $
17490 */
17491
17492
17493 /* All threads share a single random number generator.
17494 ** This structure is the current state of the generator.
17495 */
17496 static SQLITE_WSD struct sqlite3PrngType {
17497   unsigned char isInit;          /* True if initialized */
17498   unsigned char i, j;            /* State variables */
17499   unsigned char s[256];          /* State variables */
17500 } sqlite3Prng = { 0, };
17501
17502 /*
17503 ** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
17504 ** must be held while executing this routine.
17505 **
17506 ** Why not just use a library random generator like lrand48() for this?
17507 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
17508 ** good source of random numbers.  The lrand48() library function may
17509 ** well be good enough.  But maybe not.  Or maybe lrand48() has some
17510 ** subtle problems on some systems that could cause problems.  It is hard
17511 ** to know.  To minimize the risk of problems due to bad lrand48()
17512 ** implementations, SQLite uses this random number generator based
17513 ** on RC4, which we know works very well.
17514 **
17515 ** (Later):  Actually, OP_NewRowid does not depend on a good source of
17516 ** randomness any more.  But we will leave this code in all the same.
17517 */
17518 static int randomByte(void){
17519   unsigned char t;
17520
17521
17522   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
17523   ** state vector.  If writable static data is unsupported on the target,
17524   ** we have to locate the state vector at run-time.  In the more common
17525   ** case where writable static data is supported, wsdPrng can refer directly
17526   ** to the "sqlite3Prng" state vector declared above.
17527   */
17528 #ifdef SQLITE_OMIT_WSD
17529   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
17530 # define wsdPrng p[0]
17531 #else
17532 # define wsdPrng sqlite3Prng
17533 #endif
17534
17535
17536   /* Initialize the state of the random number generator once,
17537   ** the first time this routine is called.  The seed value does
17538   ** not need to contain a lot of randomness since we are not
17539   ** trying to do secure encryption or anything like that...
17540   **
17541   ** Nothing in this file or anywhere else in SQLite does any kind of
17542   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
17543   ** number generator) not as an encryption device.
17544   */
17545   if( !wsdPrng.isInit ){
17546     int i;
17547     char k[256];
17548     wsdPrng.j = 0;
17549     wsdPrng.i = 0;
17550     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
17551     for(i=0; i<256; i++){
17552       wsdPrng.s[i] = i;
17553     }
17554     for(i=0; i<256; i++){
17555       wsdPrng.j += wsdPrng.s[i] + k[i];
17556       t = wsdPrng.s[wsdPrng.j];
17557       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
17558       wsdPrng.s[i] = t;
17559     }
17560     wsdPrng.isInit = 1;
17561   }
17562
17563   /* Generate and return single random byte
17564   */
17565   wsdPrng.i++;
17566   t = wsdPrng.s[wsdPrng.i];
17567   wsdPrng.j += t;
17568   wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
17569   wsdPrng.s[wsdPrng.j] = t;
17570   t += wsdPrng.s[wsdPrng.i];
17571   return wsdPrng.s[t];
17572 }
17573
17574 /*
17575 ** Return N random bytes.
17576 */
17577 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
17578   unsigned char *zBuf = pBuf;
17579 #if SQLITE_THREADSAFE
17580   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
17581 #endif
17582   sqlite3_mutex_enter(mutex);
17583   while( N-- ){
17584     *(zBuf++) = randomByte();
17585   }
17586   sqlite3_mutex_leave(mutex);
17587 }
17588
17589 #ifndef SQLITE_OMIT_BUILTIN_TEST
17590 /*
17591 ** For testing purposes, we sometimes want to preserve the state of
17592 ** PRNG and restore the PRNG to its saved state at a later time, or
17593 ** to reset the PRNG to its initial state.  These routines accomplish
17594 ** those tasks.
17595 **
17596 ** The sqlite3_test_control() interface calls these routines to
17597 ** control the PRNG.
17598 */
17599 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng = { 0, };
17600 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
17601   memcpy(
17602     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
17603     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
17604     sizeof(sqlite3Prng)
17605   );
17606 }
17607 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
17608   memcpy(
17609     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
17610     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
17611     sizeof(sqlite3Prng)
17612   );
17613 }
17614 SQLITE_PRIVATE void sqlite3PrngResetState(void){
17615   GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
17616 }
17617 #endif /* SQLITE_OMIT_BUILTIN_TEST */
17618
17619 /************** End of random.c **********************************************/
17620 /************** Begin file utf.c *********************************************/
17621 /*
17622 ** 2004 April 13
17623 **
17624 ** The author disclaims copyright to this source code.  In place of
17625 ** a legal notice, here is a blessing:
17626 **
17627 **    May you do good and not evil.
17628 **    May you find forgiveness for yourself and forgive others.
17629 **    May you share freely, never taking more than you give.
17630 **
17631 *************************************************************************
17632 ** This file contains routines used to translate between UTF-8, 
17633 ** UTF-16, UTF-16BE, and UTF-16LE.
17634 **
17635 ** $Id: utf.c,v 1.66 2008/11/07 03:29:34 drh Exp $
17636 **
17637 ** Notes on UTF-8:
17638 **
17639 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
17640 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
17641 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
17642 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
17643 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
17644 **
17645 **
17646 ** Notes on UTF-16:  (with wwww+1==uuuuu)
17647 **
17648 **      Word-0               Word-1          Value
17649 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
17650 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
17651 **
17652 **
17653 ** BOM or Byte Order Mark:
17654 **     0xff 0xfe   little-endian utf-16 follows
17655 **     0xfe 0xff   big-endian utf-16 follows
17656 **
17657 */
17658 /************** Include vdbeInt.h in the middle of utf.c *********************/
17659 /************** Begin file vdbeInt.h *****************************************/
17660 /*
17661 ** 2003 September 6
17662 **
17663 ** The author disclaims copyright to this source code.  In place of
17664 ** a legal notice, here is a blessing:
17665 **
17666 **    May you do good and not evil.
17667 **    May you find forgiveness for yourself and forgive others.
17668 **    May you share freely, never taking more than you give.
17669 **
17670 *************************************************************************
17671 ** This is the header file for information that is private to the
17672 ** VDBE.  This information used to all be at the top of the single
17673 ** source code file "vdbe.c".  When that file became too big (over
17674 ** 6000 lines long) it was split up into several smaller files and
17675 ** this header information was factored out.
17676 **
17677 ** $Id: vdbeInt.h,v 1.158 2008/11/17 15:31:48 danielk1977 Exp $
17678 */
17679 #ifndef _VDBEINT_H_
17680 #define _VDBEINT_H_
17681
17682 /*
17683 ** intToKey() and keyToInt() used to transform the rowid.  But with
17684 ** the latest versions of the design they are no-ops.
17685 */
17686 #define keyToInt(X)   (X)
17687 #define intToKey(X)   (X)
17688
17689
17690 /*
17691 ** SQL is translated into a sequence of instructions to be
17692 ** executed by a virtual machine.  Each instruction is an instance
17693 ** of the following structure.
17694 */
17695 typedef struct VdbeOp Op;
17696
17697 /*
17698 ** Boolean values
17699 */
17700 typedef unsigned char Bool;
17701
17702 /*
17703 ** A cursor is a pointer into a single BTree within a database file.
17704 ** The cursor can seek to a BTree entry with a particular key, or
17705 ** loop over all entries of the Btree.  You can also insert new BTree
17706 ** entries or retrieve the key or data from the entry that the cursor
17707 ** is currently pointing to.
17708 ** 
17709 ** Every cursor that the virtual machine has open is represented by an
17710 ** instance of the following structure.
17711 **
17712 ** If the VdbeCursor.isTriggerRow flag is set it means that this cursor is
17713 ** really a single row that represents the NEW or OLD pseudo-table of
17714 ** a row trigger.  The data for the row is stored in VdbeCursor.pData and
17715 ** the rowid is in VdbeCursor.iKey.
17716 */
17717 struct VdbeCursor {
17718   BtCursor *pCursor;    /* The cursor structure of the backend */
17719   int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
17720   i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
17721   i64 nextRowid;        /* Next rowid returned by OP_NewRowid */
17722   Bool zeroed;          /* True if zeroed out and ready for reuse */
17723   Bool rowidIsValid;    /* True if lastRowid is valid */
17724   Bool atFirst;         /* True if pointing to first entry */
17725   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
17726   Bool nullRow;         /* True if pointing to a row with no data */
17727   Bool nextRowidValid;  /* True if the nextRowid field is valid */
17728   Bool pseudoTable;     /* This is a NEW or OLD pseudo-tables of a trigger */
17729   Bool ephemPseudoTable;
17730   Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
17731   Bool isTable;         /* True if a table requiring integer keys */
17732   Bool isIndex;         /* True if an index containing keys only - no data */
17733   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
17734   Btree *pBt;           /* Separate file holding temporary table */
17735   int nData;            /* Number of bytes in pData */
17736   char *pData;          /* Data for a NEW or OLD pseudo-table */
17737   i64 iKey;             /* Key for the NEW or OLD pseudo-table row */
17738   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
17739   int nField;           /* Number of fields in the header */
17740   i64 seqCount;         /* Sequence counter */
17741   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
17742   const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
17743
17744   /* Cached information about the header for the data record that the
17745   ** cursor is currently pointing to.  Only valid if cacheValid is true.
17746   ** aRow might point to (ephemeral) data for the current row, or it might
17747   ** be NULL.
17748   */
17749   int cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
17750   int payloadSize;      /* Total number of bytes in the record */
17751   u32 *aType;           /* Type values for all entries in the record */
17752   u32 *aOffset;         /* Cached offsets to the start of each columns data */
17753   u8 *aRow;             /* Data for the current row, if all on one page */
17754 };
17755 typedef struct VdbeCursor VdbeCursor;
17756
17757 /*
17758 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
17759 */
17760 #define CACHE_STALE 0
17761
17762 /*
17763 ** Internally, the vdbe manipulates nearly all SQL values as Mem
17764 ** structures. Each Mem struct may cache multiple representations (string,
17765 ** integer etc.) of the same value.  A value (and therefore Mem structure)
17766 ** has the following properties:
17767 **
17768 ** Each value has a manifest type. The manifest type of the value stored
17769 ** in a Mem struct is returned by the MemType(Mem*) macro. The type is
17770 ** one of SQLITE_NULL, SQLITE_INTEGER, SQLITE_REAL, SQLITE_TEXT or
17771 ** SQLITE_BLOB.
17772 */
17773 struct Mem {
17774   union {
17775     i64 i;              /* Integer value. Or FuncDef* when flags==MEM_Agg */
17776     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
17777   } u;
17778   double r;           /* Real value */
17779   sqlite3 *db;        /* The associated database connection */
17780   char *z;            /* String or BLOB value */
17781   int n;              /* Number of characters in string value, excluding '\0' */
17782   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
17783   u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
17784   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
17785   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
17786   char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
17787 };
17788
17789 /* One or more of the following flags are set to indicate the validOK
17790 ** representations of the value stored in the Mem struct.
17791 **
17792 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
17793 ** No other flags may be set in this case.
17794 **
17795 ** If the MEM_Str flag is set then Mem.z points at a string representation.
17796 ** Usually this is encoded in the same unicode encoding as the main
17797 ** database (see below for exceptions). If the MEM_Term flag is also
17798 ** set, then the string is nul terminated. The MEM_Int and MEM_Real 
17799 ** flags may coexist with the MEM_Str flag.
17800 **
17801 ** Multiple of these values can appear in Mem.flags.  But only one
17802 ** at a time can appear in Mem.type.
17803 */
17804 #define MEM_Null      0x0001   /* Value is NULL */
17805 #define MEM_Str       0x0002   /* Value is a string */
17806 #define MEM_Int       0x0004   /* Value is an integer */
17807 #define MEM_Real      0x0008   /* Value is a real number */
17808 #define MEM_Blob      0x0010   /* Value is a BLOB */
17809
17810 #define MemSetTypeFlag(p, f) \
17811   ((p)->flags = ((p)->flags&~(MEM_Int|MEM_Real|MEM_Null|MEM_Blob|MEM_Str))|f)
17812
17813 /* Whenever Mem contains a valid string or blob representation, one of
17814 ** the following flags must be set to determine the memory management
17815 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
17816 ** string is \000 or \u0000 terminated
17817 */
17818 #define MEM_Term      0x0020   /* String rep is nul terminated */
17819 #define MEM_Dyn       0x0040   /* Need to call sqliteFree() on Mem.z */
17820 #define MEM_Static    0x0080   /* Mem.z points to a static string */
17821 #define MEM_Ephem     0x0100   /* Mem.z points to an ephemeral string */
17822 #define MEM_Agg       0x0400   /* Mem.z points to an agg function context */
17823 #define MEM_Zero      0x0800   /* Mem.i contains count of 0s appended to blob */
17824
17825 #ifdef SQLITE_OMIT_INCRBLOB
17826   #undef MEM_Zero
17827   #define MEM_Zero 0x0000
17828 #endif
17829
17830
17831 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
17832 ** additional information about auxiliary information bound to arguments
17833 ** of the function.  This is used to implement the sqlite3_get_auxdata()
17834 ** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
17835 ** that can be associated with a constant argument to a function.  This
17836 ** allows functions such as "regexp" to compile their constant regular
17837 ** expression argument once and reused the compiled code for multiple
17838 ** invocations.
17839 */
17840 struct VdbeFunc {
17841   FuncDef *pFunc;               /* The definition of the function */
17842   int nAux;                     /* Number of entries allocated for apAux[] */
17843   struct AuxData {
17844     void *pAux;                   /* Aux data for the i-th argument */
17845     void (*xDelete)(void *);      /* Destructor for the aux data */
17846   } apAux[1];                   /* One slot for each function argument */
17847 };
17848
17849 /*
17850 ** The "context" argument for a installable function.  A pointer to an
17851 ** instance of this structure is the first argument to the routines used
17852 ** implement the SQL functions.
17853 **
17854 ** There is a typedef for this structure in sqlite.h.  So all routines,
17855 ** even the public interface to SQLite, can use a pointer to this structure.
17856 ** But this file is the only place where the internal details of this
17857 ** structure are known.
17858 **
17859 ** This structure is defined inside of vdbeInt.h because it uses substructures
17860 ** (Mem) which are only defined there.
17861 */
17862 struct sqlite3_context {
17863   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
17864   VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
17865   Mem s;                /* The return value is stored here */
17866   Mem *pMem;            /* Memory cell used to store aggregate context */
17867   int isError;          /* Error code returned by the function. */
17868   CollSeq *pColl;       /* Collating sequence */
17869 };
17870
17871 /*
17872 ** A Set structure is used for quick testing to see if a value
17873 ** is part of a small set.  Sets are used to implement code like
17874 ** this:
17875 **            x.y IN ('hi','hoo','hum')
17876 */
17877 typedef struct Set Set;
17878 struct Set {
17879   Hash hash;             /* A set is just a hash table */
17880   HashElem *prev;        /* Previously accessed hash elemen */
17881 };
17882
17883 /*
17884 ** A FifoPage structure holds a single page of valves.  Pages are arranged
17885 ** in a list.
17886 */
17887 typedef struct FifoPage FifoPage;
17888 struct FifoPage {
17889   int nSlot;         /* Number of entries aSlot[] */
17890   int iWrite;        /* Push the next value into this entry in aSlot[] */
17891   int iRead;         /* Read the next value from this entry in aSlot[] */
17892   FifoPage *pNext;   /* Next page in the fifo */
17893   i64 aSlot[1];      /* One or more slots for rowid values */
17894 };
17895
17896 /*
17897 ** The Fifo structure is typedef-ed in vdbeInt.h.  But the implementation
17898 ** of that structure is private to this file.
17899 **
17900 ** The Fifo structure describes the entire fifo.  
17901 */
17902 typedef struct Fifo Fifo;
17903 struct Fifo {
17904   int nEntry;         /* Total number of entries */
17905   sqlite3 *db;        /* The associated database connection */
17906   FifoPage *pFirst;   /* First page on the list */
17907   FifoPage *pLast;    /* Last page on the list */
17908 };
17909
17910 /*
17911 ** A Context stores the last insert rowid, the last statement change count,
17912 ** and the current statement change count (i.e. changes since last statement).
17913 ** The current keylist is also stored in the context.
17914 ** Elements of Context structure type make up the ContextStack, which is
17915 ** updated by the ContextPush and ContextPop opcodes (used by triggers).
17916 ** The context is pushed before executing a trigger a popped when the
17917 ** trigger finishes.
17918 */
17919 typedef struct Context Context;
17920 struct Context {
17921   i64 lastRowid;    /* Last insert rowid (sqlite3.lastRowid) */
17922   int nChange;      /* Statement changes (Vdbe.nChanges)     */
17923   Fifo sFifo;       /* Records that will participate in a DELETE or UPDATE */
17924 };
17925
17926 /*
17927 ** An instance of the virtual machine.  This structure contains the complete
17928 ** state of the virtual machine.
17929 **
17930 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_compile()
17931 ** is really a pointer to an instance of this structure.
17932 **
17933 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
17934 ** any virtual table method invocations made by the vdbe program. It is
17935 ** set to 2 for xDestroy method calls and 1 for all other methods. This
17936 ** variable is used for two purposes: to allow xDestroy methods to execute
17937 ** "DROP TABLE" statements and to prevent some nasty side effects of
17938 ** malloc failure when SQLite is invoked recursively by a virtual table 
17939 ** method function.
17940 */
17941 struct Vdbe {
17942   sqlite3 *db;        /* The whole database */
17943   Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
17944   int nOp;            /* Number of instructions in the program */
17945   int nOpAlloc;       /* Number of slots allocated for aOp[] */
17946   Op *aOp;            /* Space to hold the virtual machine's program */
17947   int nLabel;         /* Number of labels used */
17948   int nLabelAlloc;    /* Number of slots allocated in aLabel[] */
17949   int *aLabel;        /* Space to hold the labels */
17950   Mem **apArg;        /* Arguments to currently executing user function */
17951   Mem *aColName;      /* Column names to return */
17952   int nCursor;        /* Number of slots in apCsr[] */
17953   VdbeCursor **apCsr; /* One element of this array for each open cursor */
17954   int nVar;           /* Number of entries in aVar[] */
17955   Mem *aVar;          /* Values for the OP_Variable opcode. */
17956   char **azVar;       /* Name of variables */
17957   int okVar;          /* True if azVar[] has been initialized */
17958   u32 magic;              /* Magic number for sanity checking */
17959   int nMem;               /* Number of memory locations currently allocated */
17960   Mem *aMem;              /* The memory locations */
17961   int nCallback;          /* Number of callbacks invoked so far */
17962   int cacheCtr;           /* VdbeCursor row cache generation counter */
17963   Fifo sFifo;             /* A list of ROWIDs */
17964   int contextStackTop;    /* Index of top element in the context stack */
17965   int contextStackDepth;  /* The size of the "context" stack */
17966   Context *contextStack;  /* Stack used by opcodes ContextPush & ContextPop*/
17967   int pc;                 /* The program counter */
17968   int rc;                 /* Value to return */
17969   unsigned uniqueCnt;     /* Used by OP_MakeRecord when P2!=0 */
17970   int errorAction;        /* Recovery action to do in case of an error */
17971   int inTempTrans;        /* True if temp database is transactioned */
17972   int nResColumn;         /* Number of columns in one row of the result set */
17973   char **azResColumn;     /* Values for one row of result */ 
17974   char *zErrMsg;          /* Error message written here */
17975   Mem *pResultSet;        /* Pointer to an array of results */
17976   u8 explain;             /* True if EXPLAIN present on SQL command */
17977   u8 changeCntOn;         /* True to update the change-counter */
17978   u8 expired;             /* True if the VM needs to be recompiled */
17979   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
17980   u8 inVtabMethod;        /* See comments above */
17981   u8 usesStmtJournal;     /* True if uses a statement journal */
17982   u8 readOnly;            /* True for read-only statements */
17983   int nChange;            /* Number of db changes made since last reset */
17984   i64 startTime;          /* Time when query started - used for profiling */
17985   int btreeMask;          /* Bitmask of db->aDb[] entries referenced */
17986   BtreeMutexArray aMutex; /* An array of Btree used here and needing locks */
17987   int aCounter[2];        /* Counters used by sqlite3_stmt_status() */
17988   int nSql;             /* Number of bytes in zSql */
17989   char *zSql;           /* Text of the SQL statement that generated this */
17990 #ifdef SQLITE_DEBUG
17991   FILE *trace;          /* Write an execution trace here, if not NULL */
17992 #endif
17993   int openedStatement;  /* True if this VM has opened a statement journal */
17994 #ifdef SQLITE_SSE
17995   int fetchId;          /* Statement number used by sqlite3_fetch_statement */
17996   int lru;              /* Counter used for LRU cache replacement */
17997 #endif
17998 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
17999   Vdbe *pLruPrev;
18000   Vdbe *pLruNext;
18001 #endif
18002 };
18003
18004 /*
18005 ** The following are allowed values for Vdbe.magic
18006 */
18007 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
18008 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
18009 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
18010 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
18011
18012 /*
18013 ** Function prototypes
18014 */
18015 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
18016 void sqliteVdbePopStack(Vdbe*,int);
18017 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
18018 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
18019 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
18020 #endif
18021 SQLITE_PRIVATE int sqlite3VdbeSerialTypeLen(u32);
18022 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
18023 SQLITE_PRIVATE int sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
18024 SQLITE_PRIVATE int sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
18025 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
18026
18027 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
18028 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
18029 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(BtCursor *, i64 *);
18030 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
18031 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
18032 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
18033 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
18034 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
18035 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
18036 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
18037 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
18038 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
18039 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
18040 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
18041 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
18042 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
18043 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
18044 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
18045 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
18046 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
18047 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
18048 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
18049 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
18050 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
18051 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
18052 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
18053 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
18054 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
18055 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
18056 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
18057 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
18058 SQLITE_PRIVATE int sqlite3VdbeOpcodeHasProperty(int, int);
18059 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
18060 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
18061 SQLITE_PRIVATE int sqlite3VdbeReleaseBuffers(Vdbe *p);
18062 #endif
18063
18064 #ifndef NDEBUG
18065 SQLITE_PRIVATE   void sqlite3VdbeMemSanity(Mem*);
18066 #endif
18067 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
18068 #ifdef SQLITE_DEBUG
18069 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
18070 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
18071 #endif
18072 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
18073 SQLITE_PRIVATE void sqlite3VdbeFifoInit(Fifo*, sqlite3*);
18074 SQLITE_PRIVATE int sqlite3VdbeFifoPush(Fifo*, i64);
18075 SQLITE_PRIVATE int sqlite3VdbeFifoPop(Fifo*, i64*);
18076 SQLITE_PRIVATE void sqlite3VdbeFifoClear(Fifo*);
18077
18078 #ifndef SQLITE_OMIT_INCRBLOB
18079 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
18080 #else
18081   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
18082 #endif
18083
18084 #endif /* !defined(_VDBEINT_H_) */
18085
18086 /************** End of vdbeInt.h *********************************************/
18087 /************** Continuing where we left off in utf.c ************************/
18088
18089 /*
18090 ** The following constant value is used by the SQLITE_BIGENDIAN and
18091 ** SQLITE_LITTLEENDIAN macros.
18092 */
18093 SQLITE_PRIVATE const int sqlite3one = 1;
18094
18095 /*
18096 ** This lookup table is used to help decode the first byte of
18097 ** a multi-byte UTF8 character.
18098 */
18099 static const unsigned char sqlite3UtfTrans1[] = {
18100   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
18101   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
18102   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
18103   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
18104   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
18105   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
18106   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
18107   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
18108 };
18109
18110
18111 #define WRITE_UTF8(zOut, c) {                          \
18112   if( c<0x00080 ){                                     \
18113     *zOut++ = (c&0xFF);                                \
18114   }                                                    \
18115   else if( c<0x00800 ){                                \
18116     *zOut++ = 0xC0 + ((c>>6)&0x1F);                    \
18117     *zOut++ = 0x80 + (c & 0x3F);                       \
18118   }                                                    \
18119   else if( c<0x10000 ){                                \
18120     *zOut++ = 0xE0 + ((c>>12)&0x0F);                   \
18121     *zOut++ = 0x80 + ((c>>6) & 0x3F);                  \
18122     *zOut++ = 0x80 + (c & 0x3F);                       \
18123   }else{                                               \
18124     *zOut++ = 0xF0 + ((c>>18) & 0x07);                 \
18125     *zOut++ = 0x80 + ((c>>12) & 0x3F);                 \
18126     *zOut++ = 0x80 + ((c>>6) & 0x3F);                  \
18127     *zOut++ = 0x80 + (c & 0x3F);                       \
18128   }                                                    \
18129 }
18130
18131 #define WRITE_UTF16LE(zOut, c) {                                \
18132   if( c<=0xFFFF ){                                              \
18133     *zOut++ = (c&0x00FF);                                       \
18134     *zOut++ = ((c>>8)&0x00FF);                                  \
18135   }else{                                                        \
18136     *zOut++ = (((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
18137     *zOut++ = (0x00D8 + (((c-0x10000)>>18)&0x03));              \
18138     *zOut++ = (c&0x00FF);                                       \
18139     *zOut++ = (0x00DC + ((c>>8)&0x03));                         \
18140   }                                                             \
18141 }
18142
18143 #define WRITE_UTF16BE(zOut, c) {                                \
18144   if( c<=0xFFFF ){                                              \
18145     *zOut++ = ((c>>8)&0x00FF);                                  \
18146     *zOut++ = (c&0x00FF);                                       \
18147   }else{                                                        \
18148     *zOut++ = (0x00D8 + (((c-0x10000)>>18)&0x03));              \
18149     *zOut++ = (((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
18150     *zOut++ = (0x00DC + ((c>>8)&0x03));                         \
18151     *zOut++ = (c&0x00FF);                                       \
18152   }                                                             \
18153 }
18154
18155 #define READ_UTF16LE(zIn, c){                                         \
18156   c = (*zIn++);                                                       \
18157   c += ((*zIn++)<<8);                                                 \
18158   if( c>=0xD800 && c<0xE000 ){                                       \
18159     int c2 = (*zIn++);                                                \
18160     c2 += ((*zIn++)<<8);                                              \
18161     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
18162     if( (c & 0xFFFF0000)==0 ) c = 0xFFFD;                             \
18163   }                                                                   \
18164 }
18165
18166 #define READ_UTF16BE(zIn, c){                                         \
18167   c = ((*zIn++)<<8);                                                  \
18168   c += (*zIn++);                                                      \
18169   if( c>=0xD800 && c<0xE000 ){                                       \
18170     int c2 = ((*zIn++)<<8);                                           \
18171     c2 += (*zIn++);                                                   \
18172     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
18173     if( (c & 0xFFFF0000)==0 ) c = 0xFFFD;                             \
18174   }                                                                   \
18175 }
18176
18177 /*
18178 ** Translate a single UTF-8 character.  Return the unicode value.
18179 **
18180 ** During translation, assume that the byte that zTerm points
18181 ** is a 0x00.
18182 **
18183 ** Write a pointer to the next unread byte back into *pzNext.
18184 **
18185 ** Notes On Invalid UTF-8:
18186 **
18187 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
18188 **     be encoded as a multi-byte character.  Any multi-byte character that
18189 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
18190 **
18191 **  *  This routine never allows a UTF16 surrogate value to be encoded.
18192 **     If a multi-byte character attempts to encode a value between
18193 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
18194 **
18195 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
18196 **     byte of a character are interpreted as single-byte characters
18197 **     and rendered as themselves even though they are technically
18198 **     invalid characters.
18199 **
18200 **  *  This routine accepts an infinite number of different UTF8 encodings
18201 **     for unicode values 0x80 and greater.  It do not change over-length
18202 **     encodings to 0xfffd as some systems recommend.
18203 */
18204 #define READ_UTF8(zIn, zTerm, c)                           \
18205   c = *(zIn++);                                            \
18206   if( c>=0xc0 ){                                           \
18207     c = sqlite3UtfTrans1[c-0xc0];                          \
18208     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
18209       c = (c<<6) + (0x3f & *(zIn++));                      \
18210     }                                                      \
18211     if( c<0x80                                             \
18212         || (c&0xFFFFF800)==0xD800                          \
18213         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
18214   }
18215 SQLITE_PRIVATE int sqlite3Utf8Read(
18216   const unsigned char *z,         /* First byte of UTF-8 character */
18217   const unsigned char *zTerm,     /* Pretend this byte is 0x00 */
18218   const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
18219 ){
18220   int c;
18221   READ_UTF8(z, zTerm, c);
18222   *pzNext = z;
18223   return c;
18224 }
18225
18226
18227
18228
18229 /*
18230 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
18231 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
18232 */ 
18233 /* #define TRANSLATE_TRACE 1 */
18234
18235 #ifndef SQLITE_OMIT_UTF16
18236 /*
18237 ** This routine transforms the internal text encoding used by pMem to
18238 ** desiredEnc. It is an error if the string is already of the desired
18239 ** encoding, or if *pMem does not contain a string value.
18240 */
18241 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
18242   int len;                    /* Maximum length of output string in bytes */
18243   unsigned char *zOut;                  /* Output buffer */
18244   unsigned char *zIn;                   /* Input iterator */
18245   unsigned char *zTerm;                 /* End of input */
18246   unsigned char *z;                     /* Output iterator */
18247   unsigned int c;
18248
18249   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
18250   assert( pMem->flags&MEM_Str );
18251   assert( pMem->enc!=desiredEnc );
18252   assert( pMem->enc!=0 );
18253   assert( pMem->n>=0 );
18254
18255 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
18256   {
18257     char zBuf[100];
18258     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
18259     fprintf(stderr, "INPUT:  %s\n", zBuf);
18260   }
18261 #endif
18262
18263   /* If the translation is between UTF-16 little and big endian, then 
18264   ** all that is required is to swap the byte order. This case is handled
18265   ** differently from the others.
18266   */
18267   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
18268     u8 temp;
18269     int rc;
18270     rc = sqlite3VdbeMemMakeWriteable(pMem);
18271     if( rc!=SQLITE_OK ){
18272       assert( rc==SQLITE_NOMEM );
18273       return SQLITE_NOMEM;
18274     }
18275     zIn = (u8*)pMem->z;
18276     zTerm = &zIn[pMem->n&~1];
18277     while( zIn<zTerm ){
18278       temp = *zIn;
18279       *zIn = *(zIn+1);
18280       zIn++;
18281       *zIn++ = temp;
18282     }
18283     pMem->enc = desiredEnc;
18284     goto translate_out;
18285   }
18286
18287   /* Set len to the maximum number of bytes required in the output buffer. */
18288   if( desiredEnc==SQLITE_UTF8 ){
18289     /* When converting from UTF-16, the maximum growth results from
18290     ** translating a 2-byte character to a 4-byte UTF-8 character.
18291     ** A single byte is required for the output string
18292     ** nul-terminator.
18293     */
18294     pMem->n &= ~1;
18295     len = pMem->n * 2 + 1;
18296   }else{
18297     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
18298     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
18299     ** character. Two bytes are required in the output buffer for the
18300     ** nul-terminator.
18301     */
18302     len = pMem->n * 2 + 2;
18303   }
18304
18305   /* Set zIn to point at the start of the input buffer and zTerm to point 1
18306   ** byte past the end.
18307   **
18308   ** Variable zOut is set to point at the output buffer, space obtained
18309   ** from sqlite3_malloc().
18310   */
18311   zIn = (u8*)pMem->z;
18312   zTerm = &zIn[pMem->n];
18313   zOut = sqlite3DbMallocRaw(pMem->db, len);
18314   if( !zOut ){
18315     return SQLITE_NOMEM;
18316   }
18317   z = zOut;
18318
18319   if( pMem->enc==SQLITE_UTF8 ){
18320     if( desiredEnc==SQLITE_UTF16LE ){
18321       /* UTF-8 -> UTF-16 Little-endian */
18322       while( zIn<zTerm ){
18323         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
18324         READ_UTF8(zIn, zTerm, c);
18325         WRITE_UTF16LE(z, c);
18326       }
18327     }else{
18328       assert( desiredEnc==SQLITE_UTF16BE );
18329       /* UTF-8 -> UTF-16 Big-endian */
18330       while( zIn<zTerm ){
18331         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
18332         READ_UTF8(zIn, zTerm, c);
18333         WRITE_UTF16BE(z, c);
18334       }
18335     }
18336     pMem->n = z - zOut;
18337     *z++ = 0;
18338   }else{
18339     assert( desiredEnc==SQLITE_UTF8 );
18340     if( pMem->enc==SQLITE_UTF16LE ){
18341       /* UTF-16 Little-endian -> UTF-8 */
18342       while( zIn<zTerm ){
18343         READ_UTF16LE(zIn, c); 
18344         WRITE_UTF8(z, c);
18345       }
18346     }else{
18347       /* UTF-16 Big-endian -> UTF-8 */
18348       while( zIn<zTerm ){
18349         READ_UTF16BE(zIn, c); 
18350         WRITE_UTF8(z, c);
18351       }
18352     }
18353     pMem->n = z - zOut;
18354   }
18355   *z = 0;
18356   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
18357
18358   sqlite3VdbeMemRelease(pMem);
18359   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
18360   pMem->enc = desiredEnc;
18361   pMem->flags |= (MEM_Term|MEM_Dyn);
18362   pMem->z = (char*)zOut;
18363   pMem->zMalloc = pMem->z;
18364
18365 translate_out:
18366 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
18367   {
18368     char zBuf[100];
18369     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
18370     fprintf(stderr, "OUTPUT: %s\n", zBuf);
18371   }
18372 #endif
18373   return SQLITE_OK;
18374 }
18375
18376 /*
18377 ** This routine checks for a byte-order mark at the beginning of the 
18378 ** UTF-16 string stored in *pMem. If one is present, it is removed and
18379 ** the encoding of the Mem adjusted. This routine does not do any
18380 ** byte-swapping, it just sets Mem.enc appropriately.
18381 **
18382 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
18383 ** changed by this function.
18384 */
18385 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
18386   int rc = SQLITE_OK;
18387   u8 bom = 0;
18388
18389   if( pMem->n<0 || pMem->n>1 ){
18390     u8 b1 = *(u8 *)pMem->z;
18391     u8 b2 = *(((u8 *)pMem->z) + 1);
18392     if( b1==0xFE && b2==0xFF ){
18393       bom = SQLITE_UTF16BE;
18394     }
18395     if( b1==0xFF && b2==0xFE ){
18396       bom = SQLITE_UTF16LE;
18397     }
18398   }
18399   
18400   if( bom ){
18401     rc = sqlite3VdbeMemMakeWriteable(pMem);
18402     if( rc==SQLITE_OK ){
18403       pMem->n -= 2;
18404       memmove(pMem->z, &pMem->z[2], pMem->n);
18405       pMem->z[pMem->n] = '\0';
18406       pMem->z[pMem->n+1] = '\0';
18407       pMem->flags |= MEM_Term;
18408       pMem->enc = bom;
18409     }
18410   }
18411   return rc;
18412 }
18413 #endif /* SQLITE_OMIT_UTF16 */
18414
18415 /*
18416 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
18417 ** return the number of unicode characters in pZ up to (but not including)
18418 ** the first 0x00 byte. If nByte is not less than zero, return the
18419 ** number of unicode characters in the first nByte of pZ (or up to 
18420 ** the first 0x00, whichever comes first).
18421 */
18422 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
18423   int r = 0;
18424   const u8 *z = (const u8*)zIn;
18425   const u8 *zTerm;
18426   if( nByte>=0 ){
18427     zTerm = &z[nByte];
18428   }else{
18429     zTerm = (const u8*)(-1);
18430   }
18431   assert( z<=zTerm );
18432   while( *z!=0 && z<zTerm ){
18433     SQLITE_SKIP_UTF8(z);
18434     r++;
18435   }
18436   return r;
18437 }
18438
18439 /* This test function is not currently used by the automated test-suite. 
18440 ** Hence it is only available in debug builds.
18441 */
18442 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
18443 /*
18444 ** Translate UTF-8 to UTF-8.
18445 **
18446 ** This has the effect of making sure that the string is well-formed
18447 ** UTF-8.  Miscoded characters are removed.
18448 **
18449 ** The translation is done in-place (since it is impossible for the
18450 ** correct UTF-8 encoding to be longer than a malformed encoding).
18451 */
18452 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
18453   unsigned char *zOut = zIn;
18454   unsigned char *zStart = zIn;
18455   unsigned char *zTerm = &zIn[strlen((char *)zIn)];
18456   u32 c;
18457
18458   while( zIn[0] ){
18459     c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn);
18460     if( c!=0xfffd ){
18461       WRITE_UTF8(zOut, c);
18462     }
18463   }
18464   *zOut = 0;
18465   return zOut - zStart;
18466 }
18467 #endif
18468
18469 #ifndef SQLITE_OMIT_UTF16
18470 /*
18471 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
18472 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
18473 ** be freed by the calling function.
18474 **
18475 ** NULL is returned if there is an allocation error.
18476 */
18477 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte){
18478   Mem m;
18479   memset(&m, 0, sizeof(m));
18480   m.db = db;
18481   sqlite3VdbeMemSetStr(&m, z, nByte, SQLITE_UTF16NATIVE, SQLITE_STATIC);
18482   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
18483   if( db->mallocFailed ){
18484     sqlite3VdbeMemRelease(&m);
18485     m.z = 0;
18486   }
18487   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
18488   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
18489   return (m.flags & MEM_Dyn)!=0 ? m.z : sqlite3DbStrDup(db, m.z);
18490 }
18491
18492 /*
18493 ** pZ is a UTF-16 encoded unicode string. If nChar is less than zero,
18494 ** return the number of bytes up to (but not including), the first pair
18495 ** of consecutive 0x00 bytes in pZ. If nChar is not less than zero,
18496 ** then return the number of bytes in the first nChar unicode characters
18497 ** in pZ (or up until the first pair of 0x00 bytes, whichever comes first).
18498 */
18499 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
18500   unsigned int c = 1;
18501   char const *z = zIn;
18502   int n = 0;
18503   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
18504     /* Using an "if (SQLITE_UTF16NATIVE==SQLITE_UTF16BE)" construct here
18505     ** and in other parts of this file means that at one branch will
18506     ** not be covered by coverage testing on any single host. But coverage
18507     ** will be complete if the tests are run on both a little-endian and 
18508     ** big-endian host. Because both the UTF16NATIVE and SQLITE_UTF16BE
18509     ** macros are constant at compile time the compiler can determine
18510     ** which branch will be followed. It is therefore assumed that no runtime
18511     ** penalty is paid for this "if" statement.
18512     */
18513     while( c && ((nChar<0) || n<nChar) ){
18514       READ_UTF16BE(z, c);
18515       n++;
18516     }
18517   }else{
18518     while( c && ((nChar<0) || n<nChar) ){
18519       READ_UTF16LE(z, c);
18520       n++;
18521     }
18522   }
18523   return (z-(char const *)zIn)-((c==0)?2:0);
18524 }
18525
18526 #if defined(SQLITE_TEST)
18527 /*
18528 ** This routine is called from the TCL test function "translate_selftest".
18529 ** It checks that the primitives for serializing and deserializing
18530 ** characters in each encoding are inverses of each other.
18531 */
18532 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
18533   unsigned int i, t;
18534   unsigned char zBuf[20];
18535   unsigned char *z;
18536   unsigned char *zTerm;
18537   int n;
18538   unsigned int c;
18539
18540   for(i=0; i<0x00110000; i++){
18541     z = zBuf;
18542     WRITE_UTF8(z, i);
18543     n = z-zBuf;
18544     z[0] = 0;
18545     zTerm = z;
18546     z = zBuf;
18547     c = sqlite3Utf8Read(z, zTerm, (const u8**)&z);
18548     t = i;
18549     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
18550     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
18551     assert( c==t );
18552     assert( (z-zBuf)==n );
18553   }
18554   for(i=0; i<0x00110000; i++){
18555     if( i>=0xD800 && i<0xE000 ) continue;
18556     z = zBuf;
18557     WRITE_UTF16LE(z, i);
18558     n = z-zBuf;
18559     z[0] = 0;
18560     z = zBuf;
18561     READ_UTF16LE(z, c);
18562     assert( c==i );
18563     assert( (z-zBuf)==n );
18564   }
18565   for(i=0; i<0x00110000; i++){
18566     if( i>=0xD800 && i<0xE000 ) continue;
18567     z = zBuf;
18568     WRITE_UTF16BE(z, i);
18569     n = z-zBuf;
18570     z[0] = 0;
18571     z = zBuf;
18572     READ_UTF16BE(z, c);
18573     assert( c==i );
18574     assert( (z-zBuf)==n );
18575   }
18576 }
18577 #endif /* SQLITE_TEST */
18578 #endif /* SQLITE_OMIT_UTF16 */
18579
18580 /************** End of utf.c *************************************************/
18581 /************** Begin file util.c ********************************************/
18582 /*
18583 ** 2001 September 15
18584 **
18585 ** The author disclaims copyright to this source code.  In place of
18586 ** a legal notice, here is a blessing:
18587 **
18588 **    May you do good and not evil.
18589 **    May you find forgiveness for yourself and forgive others.
18590 **    May you share freely, never taking more than you give.
18591 **
18592 *************************************************************************
18593 ** Utility functions used throughout sqlite.
18594 **
18595 ** This file contains functions for allocating memory, comparing
18596 ** strings, and stuff like that.
18597 **
18598 ** $Id: util.c,v 1.242 2008/11/17 19:18:55 danielk1977 Exp $
18599 */
18600
18601
18602 /*
18603 ** Return true if the floating point value is Not a Number (NaN).
18604 */
18605 SQLITE_PRIVATE int sqlite3IsNaN(double x){
18606   /* This NaN test sometimes fails if compiled on GCC with -ffast-math.
18607   ** On the other hand, the use of -ffast-math comes with the following
18608   ** warning:
18609   **
18610   **      This option [-ffast-math] should never be turned on by any
18611   **      -O option since it can result in incorrect output for programs
18612   **      which depend on an exact implementation of IEEE or ISO 
18613   **      rules/specifications for math functions.
18614   **
18615   ** Under MSVC, this NaN test may fail if compiled with a floating-
18616   ** point precision mode other than /fp:precise.  From the MSDN 
18617   ** documentation:
18618   **
18619   **      The compiler [with /fp:precise] will properly handle comparisons 
18620   **      involving NaN. For example, x != x evaluates to true if x is NaN 
18621   **      ...
18622   */
18623 #ifdef __FAST_MATH__
18624 # error SQLite will not work correctly with the -ffast-math option of GCC.
18625 #endif
18626   volatile double y = x;
18627   volatile double z = y;
18628   return y!=z;
18629 }
18630
18631 /*
18632 ** Return the length of a string, except do not allow the string length
18633 ** to exceed the SQLITE_LIMIT_LENGTH setting.
18634 */
18635 SQLITE_PRIVATE int sqlite3Strlen(sqlite3 *db, const char *z){
18636   const char *z2 = z;
18637   int len;
18638   int x;
18639   while( *z2 ){ z2++; }
18640   x = z2 - z;
18641   len = 0x7fffffff & x;
18642   if( len!=x || len > db->aLimit[SQLITE_LIMIT_LENGTH] ){
18643     return db->aLimit[SQLITE_LIMIT_LENGTH];
18644   }else{
18645     return len;
18646   }
18647 }
18648
18649 /*
18650 ** Set the most recent error code and error string for the sqlite
18651 ** handle "db". The error code is set to "err_code".
18652 **
18653 ** If it is not NULL, string zFormat specifies the format of the
18654 ** error string in the style of the printf functions: The following
18655 ** format characters are allowed:
18656 **
18657 **      %s      Insert a string
18658 **      %z      A string that should be freed after use
18659 **      %d      Insert an integer
18660 **      %T      Insert a token
18661 **      %S      Insert the first element of a SrcList
18662 **
18663 ** zFormat and any string tokens that follow it are assumed to be
18664 ** encoded in UTF-8.
18665 **
18666 ** To clear the most recent error for sqlite handle "db", sqlite3Error
18667 ** should be called with err_code set to SQLITE_OK and zFormat set
18668 ** to NULL.
18669 */
18670 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
18671   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
18672     db->errCode = err_code;
18673     if( zFormat ){
18674       char *z;
18675       va_list ap;
18676       va_start(ap, zFormat);
18677       z = sqlite3VMPrintf(db, zFormat, ap);
18678       va_end(ap);
18679       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
18680     }else{
18681       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
18682     }
18683   }
18684 }
18685
18686 /*
18687 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
18688 ** The following formatting characters are allowed:
18689 **
18690 **      %s      Insert a string
18691 **      %z      A string that should be freed after use
18692 **      %d      Insert an integer
18693 **      %T      Insert a token
18694 **      %S      Insert the first element of a SrcList
18695 **
18696 ** This function should be used to report any error that occurs whilst
18697 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
18698 ** last thing the sqlite3_prepare() function does is copy the error
18699 ** stored by this function into the database handle using sqlite3Error().
18700 ** Function sqlite3Error() should be used during statement execution
18701 ** (sqlite3_step() etc.).
18702 */
18703 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
18704   va_list ap;
18705   sqlite3 *db = pParse->db;
18706   pParse->nErr++;
18707   sqlite3DbFree(db, pParse->zErrMsg);
18708   va_start(ap, zFormat);
18709   pParse->zErrMsg = sqlite3VMPrintf(db, zFormat, ap);
18710   va_end(ap);
18711   if( pParse->rc==SQLITE_OK ){
18712     pParse->rc = SQLITE_ERROR;
18713   }
18714 }
18715
18716 /*
18717 ** Clear the error message in pParse, if any
18718 */
18719 SQLITE_PRIVATE void sqlite3ErrorClear(Parse *pParse){
18720   sqlite3DbFree(pParse->db, pParse->zErrMsg);
18721   pParse->zErrMsg = 0;
18722   pParse->nErr = 0;
18723 }
18724
18725 /*
18726 ** Convert an SQL-style quoted string into a normal string by removing
18727 ** the quote characters.  The conversion is done in-place.  If the
18728 ** input does not begin with a quote character, then this routine
18729 ** is a no-op.
18730 **
18731 ** 2002-Feb-14: This routine is extended to remove MS-Access style
18732 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
18733 ** "a-b-c".
18734 */
18735 SQLITE_PRIVATE void sqlite3Dequote(char *z){
18736   int quote;
18737   int i, j;
18738   if( z==0 ) return;
18739   quote = z[0];
18740   switch( quote ){
18741     case '\'':  break;
18742     case '"':   break;
18743     case '`':   break;                /* For MySQL compatibility */
18744     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
18745     default:    return;
18746   }
18747   for(i=1, j=0; z[i]; i++){
18748     if( z[i]==quote ){
18749       if( z[i+1]==quote ){
18750         z[j++] = quote;
18751         i++;
18752       }else{
18753         z[j++] = 0;
18754         break;
18755       }
18756     }else{
18757       z[j++] = z[i];
18758     }
18759   }
18760 }
18761
18762 /* Convenient short-hand */
18763 #define UpperToLower sqlite3UpperToLower
18764
18765 /*
18766 ** Some systems have stricmp().  Others have strcasecmp().  Because
18767 ** there is no consistency, we will define our own.
18768 */
18769 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
18770   register unsigned char *a, *b;
18771   a = (unsigned char *)zLeft;
18772   b = (unsigned char *)zRight;
18773   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
18774   return UpperToLower[*a] - UpperToLower[*b];
18775 }
18776 SQLITE_PRIVATE int sqlite3StrNICmp(const char *zLeft, const char *zRight, int N){
18777   register unsigned char *a, *b;
18778   a = (unsigned char *)zLeft;
18779   b = (unsigned char *)zRight;
18780   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
18781   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
18782 }
18783
18784 /*
18785 ** Return TRUE if z is a pure numeric string.  Return FALSE if the
18786 ** string contains any character which is not part of a number. If
18787 ** the string is numeric and contains the '.' character, set *realnum
18788 ** to TRUE (otherwise FALSE).
18789 **
18790 ** An empty string is considered non-numeric.
18791 */
18792 SQLITE_PRIVATE int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
18793   int incr = (enc==SQLITE_UTF8?1:2);
18794   if( enc==SQLITE_UTF16BE ) z++;
18795   if( *z=='-' || *z=='+' ) z += incr;
18796   if( !isdigit(*(u8*)z) ){
18797     return 0;
18798   }
18799   z += incr;
18800   if( realnum ) *realnum = 0;
18801   while( isdigit(*(u8*)z) ){ z += incr; }
18802   if( *z=='.' ){
18803     z += incr;
18804     if( !isdigit(*(u8*)z) ) return 0;
18805     while( isdigit(*(u8*)z) ){ z += incr; }
18806     if( realnum ) *realnum = 1;
18807   }
18808   if( *z=='e' || *z=='E' ){
18809     z += incr;
18810     if( *z=='+' || *z=='-' ) z += incr;
18811     if( !isdigit(*(u8*)z) ) return 0;
18812     while( isdigit(*(u8*)z) ){ z += incr; }
18813     if( realnum ) *realnum = 1;
18814   }
18815   return *z==0;
18816 }
18817
18818 /*
18819 ** The string z[] is an ascii representation of a real number.
18820 ** Convert this string to a double.
18821 **
18822 ** This routine assumes that z[] really is a valid number.  If it
18823 ** is not, the result is undefined.
18824 **
18825 ** This routine is used instead of the library atof() function because
18826 ** the library atof() might want to use "," as the decimal point instead
18827 ** of "." depending on how locale is set.  But that would cause problems
18828 ** for SQL.  So this routine always uses "." regardless of locale.
18829 */
18830 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult){
18831 #ifndef SQLITE_OMIT_FLOATING_POINT
18832   int sign = 1;
18833   const char *zBegin = z;
18834   LONGDOUBLE_TYPE v1 = 0.0;
18835   int nSignificant = 0;
18836   while( isspace(*(u8*)z) ) z++;
18837   if( *z=='-' ){
18838     sign = -1;
18839     z++;
18840   }else if( *z=='+' ){
18841     z++;
18842   }
18843   while( z[0]=='0' ){
18844     z++;
18845   }
18846   while( isdigit(*(u8*)z) ){
18847     v1 = v1*10.0 + (*z - '0');
18848     z++;
18849     nSignificant++;
18850   }
18851   if( *z=='.' ){
18852     LONGDOUBLE_TYPE divisor = 1.0;
18853     z++;
18854     if( nSignificant==0 ){
18855       while( z[0]=='0' ){
18856         divisor *= 10.0;
18857         z++;
18858       }
18859     }
18860     while( isdigit(*(u8*)z) ){
18861       if( nSignificant<18 ){
18862         v1 = v1*10.0 + (*z - '0');
18863         divisor *= 10.0;
18864         nSignificant++;
18865       }
18866       z++;
18867     }
18868     v1 /= divisor;
18869   }
18870   if( *z=='e' || *z=='E' ){
18871     int esign = 1;
18872     int eval = 0;
18873     LONGDOUBLE_TYPE scale = 1.0;
18874     z++;
18875     if( *z=='-' ){
18876       esign = -1;
18877       z++;
18878     }else if( *z=='+' ){
18879       z++;
18880     }
18881     while( isdigit(*(u8*)z) ){
18882       eval = eval*10 + *z - '0';
18883       z++;
18884     }
18885     while( eval>=64 ){ scale *= 1.0e+64; eval -= 64; }
18886     while( eval>=16 ){ scale *= 1.0e+16; eval -= 16; }
18887     while( eval>=4 ){ scale *= 1.0e+4; eval -= 4; }
18888     while( eval>=1 ){ scale *= 1.0e+1; eval -= 1; }
18889     if( esign<0 ){
18890       v1 /= scale;
18891     }else{
18892       v1 *= scale;
18893     }
18894   }
18895   *pResult = sign<0 ? -v1 : v1;
18896   return z - zBegin;
18897 #else
18898   return sqlite3Atoi64(z, pResult);
18899 #endif /* SQLITE_OMIT_FLOATING_POINT */
18900 }
18901
18902 /*
18903 ** Compare the 19-character string zNum against the text representation
18904 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
18905 ** if zNum is less than, equal to, or greater than the string.
18906 **
18907 ** Unlike memcmp() this routine is guaranteed to return the difference
18908 ** in the values of the last digit if the only difference is in the
18909 ** last digit.  So, for example,
18910 **
18911 **      compare2pow63("9223372036854775800")
18912 **
18913 ** will return -8.
18914 */
18915 static int compare2pow63(const char *zNum){
18916   int c;
18917   c = memcmp(zNum,"922337203685477580",18);
18918   if( c==0 ){
18919     c = zNum[18] - '8';
18920   }
18921   return c;
18922 }
18923
18924
18925 /*
18926 ** Return TRUE if zNum is a 64-bit signed integer and write
18927 ** the value of the integer into *pNum.  If zNum is not an integer
18928 ** or is an integer that is too large to be expressed with 64 bits,
18929 ** then return false.
18930 **
18931 ** When this routine was originally written it dealt with only
18932 ** 32-bit numbers.  At that time, it was much faster than the
18933 ** atoi() library routine in RedHat 7.2.
18934 */
18935 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum){
18936   i64 v = 0;
18937   int neg;
18938   int i, c;
18939   const char *zStart;
18940   while( isspace(*(u8*)zNum) ) zNum++;
18941   if( *zNum=='-' ){
18942     neg = 1;
18943     zNum++;
18944   }else if( *zNum=='+' ){
18945     neg = 0;
18946     zNum++;
18947   }else{
18948     neg = 0;
18949   }
18950   zStart = zNum;
18951   while( zNum[0]=='0' ){ zNum++; } /* Skip over leading zeros. Ticket #2454 */
18952   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
18953     v = v*10 + c - '0';
18954   }
18955   *pNum = neg ? -v : v;
18956   if( c!=0 || (i==0 && zStart==zNum) || i>19 ){
18957     /* zNum is empty or contains non-numeric text or is longer
18958     ** than 19 digits (thus guaranting that it is too large) */
18959     return 0;
18960   }else if( i<19 ){
18961     /* Less than 19 digits, so we know that it fits in 64 bits */
18962     return 1;
18963   }else{
18964     /* 19-digit numbers must be no larger than 9223372036854775807 if positive
18965     ** or 9223372036854775808 if negative.  Note that 9223372036854665808
18966     ** is 2^63. */
18967     return compare2pow63(zNum)<neg;
18968   }
18969 }
18970
18971 /*
18972 ** The string zNum represents an integer.  There might be some other
18973 ** information following the integer too, but that part is ignored.
18974 ** If the integer that the prefix of zNum represents will fit in a
18975 ** 64-bit signed integer, return TRUE.  Otherwise return FALSE.
18976 **
18977 ** This routine returns FALSE for the string -9223372036854775808 even that
18978 ** that number will, in theory fit in a 64-bit integer.  Positive
18979 ** 9223373036854775808 will not fit in 64 bits.  So it seems safer to return
18980 ** false.
18981 */
18982 SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *zNum, int negFlag){
18983   int i, c;
18984   int neg = 0;
18985   if( *zNum=='-' ){
18986     neg = 1;
18987     zNum++;
18988   }else if( *zNum=='+' ){
18989     zNum++;
18990   }
18991   if( negFlag ) neg = 1-neg;
18992   while( *zNum=='0' ){
18993     zNum++;   /* Skip leading zeros.  Ticket #2454 */
18994   }
18995   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
18996   if( i<19 ){
18997     /* Guaranteed to fit if less than 19 digits */
18998     return 1;
18999   }else if( i>19 ){
19000     /* Guaranteed to be too big if greater than 19 digits */
19001     return 0;
19002   }else{
19003     /* Compare against 2^63. */
19004     return compare2pow63(zNum)<neg;
19005   }
19006 }
19007
19008 /*
19009 ** If zNum represents an integer that will fit in 32-bits, then set
19010 ** *pValue to that integer and return true.  Otherwise return false.
19011 **
19012 ** Any non-numeric characters that following zNum are ignored.
19013 ** This is different from sqlite3Atoi64() which requires the
19014 ** input number to be zero-terminated.
19015 */
19016 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
19017   sqlite_int64 v = 0;
19018   int i, c;
19019   int neg = 0;
19020   if( zNum[0]=='-' ){
19021     neg = 1;
19022     zNum++;
19023   }else if( zNum[0]=='+' ){
19024     zNum++;
19025   }
19026   while( zNum[0]=='0' ) zNum++;
19027   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
19028     v = v*10 + c;
19029   }
19030
19031   /* The longest decimal representation of a 32 bit integer is 10 digits:
19032   **
19033   **             1234567890
19034   **     2^31 -> 2147483648
19035   */
19036   if( i>10 ){
19037     return 0;
19038   }
19039   if( v-neg>2147483647 ){
19040     return 0;
19041   }
19042   if( neg ){
19043     v = -v;
19044   }
19045   *pValue = (int)v;
19046   return 1;
19047 }
19048
19049 /*
19050 ** The variable-length integer encoding is as follows:
19051 **
19052 ** KEY:
19053 **         A = 0xxxxxxx    7 bits of data and one flag bit
19054 **         B = 1xxxxxxx    7 bits of data and one flag bit
19055 **         C = xxxxxxxx    8 bits of data
19056 **
19057 **  7 bits - A
19058 ** 14 bits - BA
19059 ** 21 bits - BBA
19060 ** 28 bits - BBBA
19061 ** 35 bits - BBBBA
19062 ** 42 bits - BBBBBA
19063 ** 49 bits - BBBBBBA
19064 ** 56 bits - BBBBBBBA
19065 ** 64 bits - BBBBBBBBC
19066 */
19067
19068 /*
19069 ** Write a 64-bit variable-length integer to memory starting at p[0].
19070 ** The length of data write will be between 1 and 9 bytes.  The number
19071 ** of bytes written is returned.
19072 **
19073 ** A variable-length integer consists of the lower 7 bits of each byte
19074 ** for all bytes that have the 8th bit set and one byte with the 8th
19075 ** bit clear.  Except, if we get to the 9th byte, it stores the full
19076 ** 8 bits and is the last byte.
19077 */
19078 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
19079   int i, j, n;
19080   u8 buf[10];
19081   if( v & (((u64)0xff000000)<<32) ){
19082     p[8] = v;
19083     v >>= 8;
19084     for(i=7; i>=0; i--){
19085       p[i] = (v & 0x7f) | 0x80;
19086       v >>= 7;
19087     }
19088     return 9;
19089   }    
19090   n = 0;
19091   do{
19092     buf[n++] = (v & 0x7f) | 0x80;
19093     v >>= 7;
19094   }while( v!=0 );
19095   buf[0] &= 0x7f;
19096   assert( n<=9 );
19097   for(i=0, j=n-1; j>=0; j--, i++){
19098     p[i] = buf[j];
19099   }
19100   return n;
19101 }
19102
19103 /*
19104 ** This routine is a faster version of sqlite3PutVarint() that only
19105 ** works for 32-bit positive integers and which is optimized for
19106 ** the common case of small integers.  A MACRO version, putVarint32,
19107 ** is provided which inlines the single-byte case.  All code should use
19108 ** the MACRO version as this function assumes the single-byte case has
19109 ** already been handled.
19110 */
19111 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
19112 #ifndef putVarint32
19113   if( (v & ~0x7f)==0 ){
19114     p[0] = v;
19115     return 1;
19116   }
19117 #endif
19118   if( (v & ~0x3fff)==0 ){
19119     p[0] = (v>>7) | 0x80;
19120     p[1] = v & 0x7f;
19121     return 2;
19122   }
19123   return sqlite3PutVarint(p, v);
19124 }
19125
19126 /*
19127 ** Read a 64-bit variable-length integer from memory starting at p[0].
19128 ** Return the number of bytes read.  The value is stored in *v.
19129 */
19130 SQLITE_PRIVATE int sqlite3GetVarint(const unsigned char *p, u64 *v){
19131   u32 a,b,s;
19132
19133   a = *p;
19134   /* a: p0 (unmasked) */
19135   if (!(a&0x80))
19136   {
19137     *v = a;
19138     return 1;
19139   }
19140
19141   p++;
19142   b = *p;
19143   /* b: p1 (unmasked) */
19144   if (!(b&0x80))
19145   {
19146     a &= 0x7f;
19147     a = a<<7;
19148     a |= b;
19149     *v = a;
19150     return 2;
19151   }
19152
19153   p++;
19154   a = a<<14;
19155   a |= *p;
19156   /* a: p0<<14 | p2 (unmasked) */
19157   if (!(a&0x80))
19158   {
19159     a &= (0x7f<<14)|(0x7f);
19160     b &= 0x7f;
19161     b = b<<7;
19162     a |= b;
19163     *v = a;
19164     return 3;
19165   }
19166
19167   /* CSE1 from below */
19168   a &= (0x7f<<14)|(0x7f);
19169   p++;
19170   b = b<<14;
19171   b |= *p;
19172   /* b: p1<<14 | p3 (unmasked) */
19173   if (!(b&0x80))
19174   {
19175     b &= (0x7f<<14)|(0x7f);
19176     /* moved CSE1 up */
19177     /* a &= (0x7f<<14)|(0x7f); */
19178     a = a<<7;
19179     a |= b;
19180     *v = a;
19181     return 4;
19182   }
19183
19184   /* a: p0<<14 | p2 (masked) */
19185   /* b: p1<<14 | p3 (unmasked) */
19186   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
19187   /* moved CSE1 up */
19188   /* a &= (0x7f<<14)|(0x7f); */
19189   b &= (0x7f<<14)|(0x7f);
19190   s = a;
19191   /* s: p0<<14 | p2 (masked) */
19192
19193   p++;
19194   a = a<<14;
19195   a |= *p;
19196   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
19197   if (!(a&0x80))
19198   {
19199     /* we can skip these cause they were (effectively) done above in calc'ing s */
19200     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
19201     /* b &= (0x7f<<14)|(0x7f); */
19202     b = b<<7;
19203     a |= b;
19204     s = s>>18;
19205     *v = ((u64)s)<<32 | a;
19206     return 5;
19207   }
19208
19209   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
19210   s = s<<7;
19211   s |= b;
19212   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
19213
19214   p++;
19215   b = b<<14;
19216   b |= *p;
19217   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
19218   if (!(b&0x80))
19219   {
19220     /* we can skip this cause it was (effectively) done above in calc'ing s */
19221     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
19222     a &= (0x7f<<14)|(0x7f);
19223     a = a<<7;
19224     a |= b;
19225     s = s>>18;
19226     *v = ((u64)s)<<32 | a;
19227     return 6;
19228   }
19229
19230   p++;
19231   a = a<<14;
19232   a |= *p;
19233   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
19234   if (!(a&0x80))
19235   {
19236     a &= (0x7f<<28)|(0x7f<<14)|(0x7f);
19237     b &= (0x7f<<14)|(0x7f);
19238     b = b<<7;
19239     a |= b;
19240     s = s>>11;
19241     *v = ((u64)s)<<32 | a;
19242     return 7;
19243   }
19244
19245   /* CSE2 from below */
19246   a &= (0x7f<<14)|(0x7f);
19247   p++;
19248   b = b<<14;
19249   b |= *p;
19250   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
19251   if (!(b&0x80))
19252   {
19253     b &= (0x7f<<28)|(0x7f<<14)|(0x7f);
19254     /* moved CSE2 up */
19255     /* a &= (0x7f<<14)|(0x7f); */
19256     a = a<<7;
19257     a |= b;
19258     s = s>>4;
19259     *v = ((u64)s)<<32 | a;
19260     return 8;
19261   }
19262
19263   p++;
19264   a = a<<15;
19265   a |= *p;
19266   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
19267
19268   /* moved CSE2 up */
19269   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
19270   b &= (0x7f<<14)|(0x7f);
19271   b = b<<8;
19272   a |= b;
19273
19274   s = s<<4;
19275   b = p[-4];
19276   b &= 0x7f;
19277   b = b>>3;
19278   s |= b;
19279
19280   *v = ((u64)s)<<32 | a;
19281
19282   return 9;
19283 }
19284
19285 /*
19286 ** Read a 32-bit variable-length integer from memory starting at p[0].
19287 ** Return the number of bytes read.  The value is stored in *v.
19288 ** A MACRO version, getVarint32, is provided which inlines the 
19289 ** single-byte case.  All code should use the MACRO version as 
19290 ** this function assumes the single-byte case has already been handled.
19291 */
19292 SQLITE_PRIVATE int sqlite3GetVarint32(const unsigned char *p, u32 *v){
19293   u32 a,b;
19294
19295   a = *p;
19296   /* a: p0 (unmasked) */
19297 #ifndef getVarint32
19298   if (!(a&0x80))
19299   {
19300     *v = a;
19301     return 1;
19302   }
19303 #endif
19304
19305   p++;
19306   b = *p;
19307   /* b: p1 (unmasked) */
19308   if (!(b&0x80))
19309   {
19310     a &= 0x7f;
19311     a = a<<7;
19312     *v = a | b;
19313     return 2;
19314   }
19315
19316   p++;
19317   a = a<<14;
19318   a |= *p;
19319   /* a: p0<<14 | p2 (unmasked) */
19320   if (!(a&0x80))
19321   {
19322     a &= (0x7f<<14)|(0x7f);
19323     b &= 0x7f;
19324     b = b<<7;
19325     *v = a | b;
19326     return 3;
19327   }
19328
19329   p++;
19330   b = b<<14;
19331   b |= *p;
19332   /* b: p1<<14 | p3 (unmasked) */
19333   if (!(b&0x80))
19334   {
19335     b &= (0x7f<<14)|(0x7f);
19336     a &= (0x7f<<14)|(0x7f);
19337     a = a<<7;
19338     *v = a | b;
19339     return 4;
19340   }
19341
19342   p++;
19343   a = a<<14;
19344   a |= *p;
19345   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
19346   if (!(a&0x80))
19347   {
19348     a &= (0x7f<<28)|(0x7f<<14)|(0x7f);
19349     b &= (0x7f<<28)|(0x7f<<14)|(0x7f);
19350     b = b<<7;
19351     *v = a | b;
19352     return 5;
19353   }
19354
19355   /* We can only reach this point when reading a corrupt database
19356   ** file.  In that case we are not in any hurry.  Use the (relatively
19357   ** slow) general-purpose sqlite3GetVarint() routine to extract the
19358   ** value. */
19359   {
19360     u64 v64;
19361     int n;
19362
19363     p -= 4;
19364     n = sqlite3GetVarint(p, &v64);
19365     assert( n>5 && n<=9 );
19366     *v = (u32)v64;
19367     return n;
19368   }
19369 }
19370
19371 /*
19372 ** Return the number of bytes that will be needed to store the given
19373 ** 64-bit integer.
19374 */
19375 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
19376   int i = 0;
19377   do{
19378     i++;
19379     v >>= 7;
19380   }while( v!=0 && i<9 );
19381   return i;
19382 }
19383
19384
19385 /*
19386 ** Read or write a four-byte big-endian integer value.
19387 */
19388 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
19389   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
19390 }
19391 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
19392   p[0] = v>>24;
19393   p[1] = v>>16;
19394   p[2] = v>>8;
19395   p[3] = v;
19396 }
19397
19398
19399
19400 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
19401 /*
19402 ** Translate a single byte of Hex into an integer.
19403 ** This routinen only works if h really is a valid hexadecimal
19404 ** character:  0..9a..fA..F
19405 */
19406 static int hexToInt(int h){
19407   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
19408 #ifdef SQLITE_ASCII
19409   h += 9*(1&(h>>6));
19410 #endif
19411 #ifdef SQLITE_EBCDIC
19412   h += 9*(1&~(h>>4));
19413 #endif
19414   return h & 0xf;
19415 }
19416 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
19417
19418 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
19419 /*
19420 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
19421 ** value.  Return a pointer to its binary value.  Space to hold the
19422 ** binary value has been obtained from malloc and must be freed by
19423 ** the calling routine.
19424 */
19425 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
19426   char *zBlob;
19427   int i;
19428
19429   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
19430   n--;
19431   if( zBlob ){
19432     for(i=0; i<n; i+=2){
19433       zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
19434     }
19435     zBlob[i/2] = 0;
19436   }
19437   return zBlob;
19438 }
19439 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
19440
19441
19442 /*
19443 ** Change the sqlite.magic from SQLITE_MAGIC_OPEN to SQLITE_MAGIC_BUSY.
19444 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_OPEN
19445 ** when this routine is called.
19446 **
19447 ** This routine is called when entering an SQLite API.  The SQLITE_MAGIC_OPEN
19448 ** value indicates that the database connection passed into the API is
19449 ** open and is not being used by another thread.  By changing the value
19450 ** to SQLITE_MAGIC_BUSY we indicate that the connection is in use.
19451 ** sqlite3SafetyOff() below will change the value back to SQLITE_MAGIC_OPEN
19452 ** when the API exits. 
19453 **
19454 ** This routine is a attempt to detect if two threads use the
19455 ** same sqlite* pointer at the same time.  There is a race 
19456 ** condition so it is possible that the error is not detected.
19457 ** But usually the problem will be seen.  The result will be an
19458 ** error which can be used to debug the application that is
19459 ** using SQLite incorrectly.
19460 **
19461 ** Ticket #202:  If db->magic is not a valid open value, take care not
19462 ** to modify the db structure at all.  It could be that db is a stale
19463 ** pointer.  In other words, it could be that there has been a prior
19464 ** call to sqlite3_close(db) and db has been deallocated.  And we do
19465 ** not want to write into deallocated memory.
19466 */
19467 #ifdef SQLITE_DEBUG
19468 SQLITE_PRIVATE int sqlite3SafetyOn(sqlite3 *db){
19469   if( db->magic==SQLITE_MAGIC_OPEN ){
19470     db->magic = SQLITE_MAGIC_BUSY;
19471     assert( sqlite3_mutex_held(db->mutex) );
19472     return 0;
19473   }else if( db->magic==SQLITE_MAGIC_BUSY ){
19474     db->magic = SQLITE_MAGIC_ERROR;
19475     db->u1.isInterrupted = 1;
19476   }
19477   return 1;
19478 }
19479 #endif
19480
19481 /*
19482 ** Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN.
19483 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY
19484 ** when this routine is called.
19485 */
19486 #ifdef SQLITE_DEBUG
19487 SQLITE_PRIVATE int sqlite3SafetyOff(sqlite3 *db){
19488   if( db->magic==SQLITE_MAGIC_BUSY ){
19489     db->magic = SQLITE_MAGIC_OPEN;
19490     assert( sqlite3_mutex_held(db->mutex) );
19491     return 0;
19492   }else{
19493     db->magic = SQLITE_MAGIC_ERROR;
19494     db->u1.isInterrupted = 1;
19495     return 1;
19496   }
19497 }
19498 #endif
19499
19500 /*
19501 ** Check to make sure we have a valid db pointer.  This test is not
19502 ** foolproof but it does provide some measure of protection against
19503 ** misuse of the interface such as passing in db pointers that are
19504 ** NULL or which have been previously closed.  If this routine returns
19505 ** 1 it means that the db pointer is valid and 0 if it should not be
19506 ** dereferenced for any reason.  The calling function should invoke
19507 ** SQLITE_MISUSE immediately.
19508 **
19509 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
19510 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
19511 ** open properly and is not fit for general use but which can be
19512 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
19513 */
19514 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
19515   u32 magic;
19516   if( db==0 ) return 0;
19517   magic = db->magic;
19518   if( magic!=SQLITE_MAGIC_OPEN &&
19519       magic!=SQLITE_MAGIC_BUSY ) return 0;
19520   return 1;
19521 }
19522 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
19523   u32 magic;
19524   if( db==0 ) return 0;
19525   magic = db->magic;
19526   if( magic!=SQLITE_MAGIC_SICK &&
19527       magic!=SQLITE_MAGIC_OPEN &&
19528       magic!=SQLITE_MAGIC_BUSY ) return 0;
19529   return 1;
19530 }
19531
19532 /************** End of util.c ************************************************/
19533 /************** Begin file hash.c ********************************************/
19534 /*
19535 ** 2001 September 22
19536 **
19537 ** The author disclaims copyright to this source code.  In place of
19538 ** a legal notice, here is a blessing:
19539 **
19540 **    May you do good and not evil.
19541 **    May you find forgiveness for yourself and forgive others.
19542 **    May you share freely, never taking more than you give.
19543 **
19544 *************************************************************************
19545 ** This is the implementation of generic hash-tables
19546 ** used in SQLite.
19547 **
19548 ** $Id: hash.c,v 1.31 2008/10/10 17:41:29 drh Exp $
19549 */
19550
19551 /* Turn bulk memory into a hash table object by initializing the
19552 ** fields of the Hash structure.
19553 **
19554 ** "pNew" is a pointer to the hash table that is to be initialized.
19555 ** "copyKey" is true if the hash table should make its own private
19556 ** copy of keys and false if it should just use the supplied pointer.
19557 */
19558 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew, int copyKey){
19559   assert( pNew!=0 );
19560   pNew->copyKey = copyKey!=0;
19561   pNew->first = 0;
19562   pNew->count = 0;
19563   pNew->htsize = 0;
19564   pNew->ht = 0;
19565 }
19566
19567 /* Remove all entries from a hash table.  Reclaim all memory.
19568 ** Call this routine to delete a hash table or to reset a hash table
19569 ** to the empty state.
19570 */
19571 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
19572   HashElem *elem;         /* For looping over all elements of the table */
19573
19574   assert( pH!=0 );
19575   elem = pH->first;
19576   pH->first = 0;
19577   sqlite3_free(pH->ht);
19578   pH->ht = 0;
19579   pH->htsize = 0;
19580   while( elem ){
19581     HashElem *next_elem = elem->next;
19582     if( pH->copyKey && elem->pKey ){
19583       sqlite3_free(elem->pKey);
19584     }
19585     sqlite3_free(elem);
19586     elem = next_elem;
19587   }
19588   pH->count = 0;
19589 }
19590
19591 /*
19592 ** Hash and comparison functions when the mode is SQLITE_HASH_STRING
19593 */
19594 static int strHash(const void *pKey, int nKey){
19595   const char *z = (const char *)pKey;
19596   int h = 0;
19597   if( nKey<=0 ) nKey = strlen(z);
19598   while( nKey > 0  ){
19599     h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
19600     nKey--;
19601   }
19602   return h & 0x7fffffff;
19603 }
19604 static int strCompare(const void *pKey1, int n1, const void *pKey2, int n2){
19605   if( n1!=n2 ) return 1;
19606   return sqlite3StrNICmp((const char*)pKey1,(const char*)pKey2,n1);
19607 }
19608
19609
19610 /* Link an element into the hash table
19611 */
19612 static void insertElement(
19613   Hash *pH,              /* The complete hash table */
19614   struct _ht *pEntry,    /* The entry into which pNew is inserted */
19615   HashElem *pNew         /* The element to be inserted */
19616 ){
19617   HashElem *pHead;       /* First element already in pEntry */
19618   pHead = pEntry->chain;
19619   if( pHead ){
19620     pNew->next = pHead;
19621     pNew->prev = pHead->prev;
19622     if( pHead->prev ){ pHead->prev->next = pNew; }
19623     else             { pH->first = pNew; }
19624     pHead->prev = pNew;
19625   }else{
19626     pNew->next = pH->first;
19627     if( pH->first ){ pH->first->prev = pNew; }
19628     pNew->prev = 0;
19629     pH->first = pNew;
19630   }
19631   pEntry->count++;
19632   pEntry->chain = pNew;
19633 }
19634
19635
19636 /* Resize the hash table so that it cantains "new_size" buckets.
19637 ** "new_size" must be a power of 2.  The hash table might fail 
19638 ** to resize if sqlite3_malloc() fails.
19639 */
19640 static void rehash(Hash *pH, int new_size){
19641   struct _ht *new_ht;            /* The new hash table */
19642   HashElem *elem, *next_elem;    /* For looping over existing elements */
19643
19644 #ifdef SQLITE_MALLOC_SOFT_LIMIT
19645   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
19646     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
19647   }
19648   if( new_size==pH->htsize ) return;
19649 #endif
19650
19651   /* There is a call to sqlite3_malloc() inside rehash(). If there is
19652   ** already an allocation at pH->ht, then if this malloc() fails it
19653   ** is benign (since failing to resize a hash table is a performance
19654   ** hit only, not a fatal error).
19655   */
19656   if( pH->htsize>0 ) sqlite3BeginBenignMalloc();
19657   new_ht = (struct _ht *)sqlite3MallocZero( new_size*sizeof(struct _ht) );
19658   if( pH->htsize>0 ) sqlite3EndBenignMalloc();
19659
19660   if( new_ht==0 ) return;
19661   sqlite3_free(pH->ht);
19662   pH->ht = new_ht;
19663   pH->htsize = new_size;
19664   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
19665     int h = strHash(elem->pKey, elem->nKey) & (new_size-1);
19666     next_elem = elem->next;
19667     insertElement(pH, &new_ht[h], elem);
19668   }
19669 }
19670
19671 /* This function (for internal use only) locates an element in an
19672 ** hash table that matches the given key.  The hash for this key has
19673 ** already been computed and is passed as the 4th parameter.
19674 */
19675 static HashElem *findElementGivenHash(
19676   const Hash *pH,     /* The pH to be searched */
19677   const void *pKey,   /* The key we are searching for */
19678   int nKey,
19679   int h               /* The hash for this key. */
19680 ){
19681   HashElem *elem;                /* Used to loop thru the element list */
19682   int count;                     /* Number of elements left to test */
19683
19684   if( pH->ht ){
19685     struct _ht *pEntry = &pH->ht[h];
19686     elem = pEntry->chain;
19687     count = pEntry->count;
19688     while( count-- && elem ){
19689       if( strCompare(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
19690         return elem;
19691       }
19692       elem = elem->next;
19693     }
19694   }
19695   return 0;
19696 }
19697
19698 /* Remove a single entry from the hash table given a pointer to that
19699 ** element and a hash on the element's key.
19700 */
19701 static void removeElementGivenHash(
19702   Hash *pH,         /* The pH containing "elem" */
19703   HashElem* elem,   /* The element to be removed from the pH */
19704   int h             /* Hash value for the element */
19705 ){
19706   struct _ht *pEntry;
19707   if( elem->prev ){
19708     elem->prev->next = elem->next; 
19709   }else{
19710     pH->first = elem->next;
19711   }
19712   if( elem->next ){
19713     elem->next->prev = elem->prev;
19714   }
19715   pEntry = &pH->ht[h];
19716   if( pEntry->chain==elem ){
19717     pEntry->chain = elem->next;
19718   }
19719   pEntry->count--;
19720   if( pEntry->count<=0 ){
19721     pEntry->chain = 0;
19722   }
19723   if( pH->copyKey ){
19724     sqlite3_free(elem->pKey);
19725   }
19726   sqlite3_free( elem );
19727   pH->count--;
19728   if( pH->count<=0 ){
19729     assert( pH->first==0 );
19730     assert( pH->count==0 );
19731     sqlite3HashClear(pH);
19732   }
19733 }
19734
19735 /* Attempt to locate an element of the hash table pH with a key
19736 ** that matches pKey,nKey.  Return a pointer to the corresponding 
19737 ** HashElem structure for this element if it is found, or NULL
19738 ** otherwise.
19739 */
19740 SQLITE_PRIVATE HashElem *sqlite3HashFindElem(const Hash *pH, const void *pKey, int nKey){
19741   int h;             /* A hash on key */
19742   HashElem *elem;    /* The element that matches key */
19743
19744   if( pH==0 || pH->ht==0 ) return 0;
19745   h = strHash(pKey,nKey);
19746   elem = findElementGivenHash(pH,pKey,nKey, h % pH->htsize);
19747   return elem;
19748 }
19749
19750 /* Attempt to locate an element of the hash table pH with a key
19751 ** that matches pKey,nKey.  Return the data for this element if it is
19752 ** found, or NULL if there is no match.
19753 */
19754 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const void *pKey, int nKey){
19755   HashElem *elem;    /* The element that matches key */
19756   elem = sqlite3HashFindElem(pH, pKey, nKey);
19757   return elem ? elem->data : 0;
19758 }
19759
19760 /* Insert an element into the hash table pH.  The key is pKey,nKey
19761 ** and the data is "data".
19762 **
19763 ** If no element exists with a matching key, then a new
19764 ** element is created.  A copy of the key is made if the copyKey
19765 ** flag is set.  NULL is returned.
19766 **
19767 ** If another element already exists with the same key, then the
19768 ** new data replaces the old data and the old data is returned.
19769 ** The key is not copied in this instance.  If a malloc fails, then
19770 ** the new data is returned and the hash table is unchanged.
19771 **
19772 ** If the "data" parameter to this function is NULL, then the
19773 ** element corresponding to "key" is removed from the hash table.
19774 */
19775 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const void *pKey, int nKey, void *data){
19776   int hraw;             /* Raw hash value of the key */
19777   int h;                /* the hash of the key modulo hash table size */
19778   HashElem *elem;       /* Used to loop thru the element list */
19779   HashElem *new_elem;   /* New element added to the pH */
19780
19781   assert( pH!=0 );
19782   hraw = strHash(pKey, nKey);
19783   if( pH->htsize ){
19784     h = hraw % pH->htsize;
19785     elem = findElementGivenHash(pH,pKey,nKey,h);
19786     if( elem ){
19787       void *old_data = elem->data;
19788       if( data==0 ){
19789         removeElementGivenHash(pH,elem,h);
19790       }else{
19791         elem->data = data;
19792         if( !pH->copyKey ){
19793           elem->pKey = (void *)pKey;
19794         }
19795         assert(nKey==elem->nKey);
19796       }
19797       return old_data;
19798     }
19799   }
19800   if( data==0 ) return 0;
19801   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
19802   if( new_elem==0 ) return data;
19803   if( pH->copyKey && pKey!=0 ){
19804     new_elem->pKey = sqlite3Malloc( nKey );
19805     if( new_elem->pKey==0 ){
19806       sqlite3_free(new_elem);
19807       return data;
19808     }
19809     memcpy((void*)new_elem->pKey, pKey, nKey);
19810   }else{
19811     new_elem->pKey = (void*)pKey;
19812   }
19813   new_elem->nKey = nKey;
19814   pH->count++;
19815   if( pH->htsize==0 ){
19816     rehash(pH, 128/sizeof(pH->ht[0]));
19817     if( pH->htsize==0 ){
19818       pH->count = 0;
19819       if( pH->copyKey ){
19820         sqlite3_free(new_elem->pKey);
19821       }
19822       sqlite3_free(new_elem);
19823       return data;
19824     }
19825   }
19826   if( pH->count > pH->htsize ){
19827     rehash(pH,pH->htsize*2);
19828   }
19829   assert( pH->htsize>0 );
19830   h = hraw % pH->htsize;
19831   insertElement(pH, &pH->ht[h], new_elem);
19832   new_elem->data = data;
19833   return 0;
19834 }
19835
19836 /************** End of hash.c ************************************************/
19837 /************** Begin file opcodes.c *****************************************/
19838 /* Automatically generated.  Do not edit */
19839 /* See the mkopcodec.awk script for details. */
19840 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
19841 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
19842  static const char *const azName[] = { "?",
19843      /*   1 */ "VNext",
19844      /*   2 */ "Affinity",
19845      /*   3 */ "Column",
19846      /*   4 */ "SetCookie",
19847      /*   5 */ "Sequence",
19848      /*   6 */ "MoveGt",
19849      /*   7 */ "RowKey",
19850      /*   8 */ "SCopy",
19851      /*   9 */ "OpenWrite",
19852      /*  10 */ "If",
19853      /*  11 */ "VRowid",
19854      /*  12 */ "CollSeq",
19855      /*  13 */ "OpenRead",
19856      /*  14 */ "Expire",
19857      /*  15 */ "AutoCommit",
19858      /*  16 */ "Not",
19859      /*  17 */ "Pagecount",
19860      /*  18 */ "IntegrityCk",
19861      /*  19 */ "Sort",
19862      /*  20 */ "Copy",
19863      /*  21 */ "Trace",
19864      /*  22 */ "Function",
19865      /*  23 */ "IfNeg",
19866      /*  24 */ "Noop",
19867      /*  25 */ "Return",
19868      /*  26 */ "NewRowid",
19869      /*  27 */ "Variable",
19870      /*  28 */ "String",
19871      /*  29 */ "RealAffinity",
19872      /*  30 */ "VRename",
19873      /*  31 */ "ParseSchema",
19874      /*  32 */ "VOpen",
19875      /*  33 */ "Close",
19876      /*  34 */ "CreateIndex",
19877      /*  35 */ "IsUnique",
19878      /*  36 */ "NotFound",
19879      /*  37 */ "Int64",
19880      /*  38 */ "MustBeInt",
19881      /*  39 */ "Halt",
19882      /*  40 */ "Rowid",
19883      /*  41 */ "IdxLT",
19884      /*  42 */ "AddImm",
19885      /*  43 */ "Statement",
19886      /*  44 */ "RowData",
19887      /*  45 */ "MemMax",
19888      /*  46 */ "NotExists",
19889      /*  47 */ "Gosub",
19890      /*  48 */ "Integer",
19891      /*  49 */ "Prev",
19892      /*  50 */ "VColumn",
19893      /*  51 */ "CreateTable",
19894      /*  52 */ "Last",
19895      /*  53 */ "IncrVacuum",
19896      /*  54 */ "IdxRowid",
19897      /*  55 */ "ResetCount",
19898      /*  56 */ "FifoWrite",
19899      /*  57 */ "ContextPush",
19900      /*  58 */ "Yield",
19901      /*  59 */ "DropTrigger",
19902      /*  60 */ "Or",
19903      /*  61 */ "And",
19904      /*  62 */ "DropIndex",
19905      /*  63 */ "IdxGE",
19906      /*  64 */ "IdxDelete",
19907      /*  65 */ "IsNull",
19908      /*  66 */ "NotNull",
19909      /*  67 */ "Ne",
19910      /*  68 */ "Eq",
19911      /*  69 */ "Gt",
19912      /*  70 */ "Le",
19913      /*  71 */ "Lt",
19914      /*  72 */ "Ge",
19915      /*  73 */ "Vacuum",
19916      /*  74 */ "BitAnd",
19917      /*  75 */ "BitOr",
19918      /*  76 */ "ShiftLeft",
19919      /*  77 */ "ShiftRight",
19920      /*  78 */ "Add",
19921      /*  79 */ "Subtract",
19922      /*  80 */ "Multiply",
19923      /*  81 */ "Divide",
19924      /*  82 */ "Remainder",
19925      /*  83 */ "Concat",
19926      /*  84 */ "MoveLe",
19927      /*  85 */ "IfNot",
19928      /*  86 */ "DropTable",
19929      /*  87 */ "BitNot",
19930      /*  88 */ "String8",
19931      /*  89 */ "MakeRecord",
19932      /*  90 */ "ResultRow",
19933      /*  91 */ "Delete",
19934      /*  92 */ "AggFinal",
19935      /*  93 */ "Compare",
19936      /*  94 */ "Goto",
19937      /*  95 */ "TableLock",
19938      /*  96 */ "FifoRead",
19939      /*  97 */ "Clear",
19940      /*  98 */ "MoveLt",
19941      /*  99 */ "VerifyCookie",
19942      /* 100 */ "AggStep",
19943      /* 101 */ "SetNumColumns",
19944      /* 102 */ "Transaction",
19945      /* 103 */ "VFilter",
19946      /* 104 */ "VDestroy",
19947      /* 105 */ "ContextPop",
19948      /* 106 */ "Next",
19949      /* 107 */ "IdxInsert",
19950      /* 108 */ "Insert",
19951      /* 109 */ "Destroy",
19952      /* 110 */ "ReadCookie",
19953      /* 111 */ "ForceInt",
19954      /* 112 */ "LoadAnalysis",
19955      /* 113 */ "Explain",
19956      /* 114 */ "OpenPseudo",
19957      /* 115 */ "OpenEphemeral",
19958      /* 116 */ "Null",
19959      /* 117 */ "Move",
19960      /* 118 */ "Blob",
19961      /* 119 */ "Rewind",
19962      /* 120 */ "MoveGe",
19963      /* 121 */ "VBegin",
19964      /* 122 */ "VUpdate",
19965      /* 123 */ "IfZero",
19966      /* 124 */ "VCreate",
19967      /* 125 */ "Found",
19968      /* 126 */ "Real",
19969      /* 127 */ "IfPos",
19970      /* 128 */ "NullRow",
19971      /* 129 */ "Jump",
19972      /* 130 */ "Permutation",
19973      /* 131 */ "NotUsed_131",
19974      /* 132 */ "NotUsed_132",
19975      /* 133 */ "NotUsed_133",
19976      /* 134 */ "NotUsed_134",
19977      /* 135 */ "NotUsed_135",
19978      /* 136 */ "NotUsed_136",
19979      /* 137 */ "NotUsed_137",
19980      /* 138 */ "NotUsed_138",
19981      /* 139 */ "ToText",
19982      /* 140 */ "ToBlob",
19983      /* 141 */ "ToNumeric",
19984      /* 142 */ "ToInt",
19985      /* 143 */ "ToReal",
19986   };
19987   return azName[i];
19988 }
19989 #endif
19990
19991 /************** End of opcodes.c *********************************************/
19992 /************** Begin file os_os2.c ******************************************/
19993 /*
19994 ** 2006 Feb 14
19995 **
19996 ** The author disclaims copyright to this source code.  In place of
19997 ** a legal notice, here is a blessing:
19998 **
19999 **    May you do good and not evil.
20000 **    May you find forgiveness for yourself and forgive others.
20001 **    May you share freely, never taking more than you give.
20002 **
20003 ******************************************************************************
20004 **
20005 ** This file contains code that is specific to OS/2.
20006 **
20007 ** $Id: os_os2.c,v 1.59 2008/11/18 23:03:40 pweilbacher Exp $
20008 */
20009
20010
20011 #if SQLITE_OS_OS2
20012
20013 /*
20014 ** A Note About Memory Allocation:
20015 **
20016 ** This driver uses malloc()/free() directly rather than going through
20017 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
20018 ** are designed for use on embedded systems where memory is scarce and
20019 ** malloc failures happen frequently.  OS/2 does not typically run on
20020 ** embedded systems, and when it does the developers normally have bigger
20021 ** problems to worry about than running out of memory.  So there is not
20022 ** a compelling need to use the wrappers.
20023 **
20024 ** But there is a good reason to not use the wrappers.  If we use the
20025 ** wrappers then we will get simulated malloc() failures within this
20026 ** driver.  And that causes all kinds of problems for our tests.  We
20027 ** could enhance SQLite to deal with simulated malloc failures within
20028 ** the OS driver, but the code to deal with those failure would not
20029 ** be exercised on Linux (which does not need to malloc() in the driver)
20030 ** and so we would have difficulty writing coverage tests for that
20031 ** code.  Better to leave the code out, we think.
20032 **
20033 ** The point of this discussion is as follows:  When creating a new
20034 ** OS layer for an embedded system, if you use this file as an example,
20035 ** avoid the use of malloc()/free().  Those routines work ok on OS/2
20036 ** desktops but not so well in embedded systems.
20037 */
20038
20039 /*
20040 ** Macros used to determine whether or not to use threads.
20041 */
20042 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
20043 # define SQLITE_OS2_THREADS 1
20044 #endif
20045
20046 /*
20047 ** Include code that is common to all os_*.c files
20048 */
20049 /************** Include os_common.h in the middle of os_os2.c ****************/
20050 /************** Begin file os_common.h ***************************************/
20051 /*
20052 ** 2004 May 22
20053 **
20054 ** The author disclaims copyright to this source code.  In place of
20055 ** a legal notice, here is a blessing:
20056 **
20057 **    May you do good and not evil.
20058 **    May you find forgiveness for yourself and forgive others.
20059 **    May you share freely, never taking more than you give.
20060 **
20061 ******************************************************************************
20062 **
20063 ** This file contains macros and a little bit of code that is common to
20064 ** all of the platform-specific files (os_*.c) and is #included into those
20065 ** files.
20066 **
20067 ** This file should be #included by the os_*.c files only.  It is not a
20068 ** general purpose header file.
20069 **
20070 ** $Id: os_common.h,v 1.37 2008/05/29 20:22:37 shane Exp $
20071 */
20072 #ifndef _OS_COMMON_H_
20073 #define _OS_COMMON_H_
20074
20075 /*
20076 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
20077 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
20078 ** switch.  The following code should catch this problem at compile-time.
20079 */
20080 #ifdef MEMORY_DEBUG
20081 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
20082 #endif
20083
20084
20085 /*
20086  * When testing, this global variable stores the location of the
20087  * pending-byte in the database file.
20088  */
20089 #ifdef SQLITE_TEST
20090 SQLITE_API unsigned int sqlite3_pending_byte = 0x40000000;
20091 #endif
20092
20093 #ifdef SQLITE_DEBUG
20094 SQLITE_PRIVATE int sqlite3OSTrace = 0;
20095 #define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
20096 #define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
20097 #define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
20098 #define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
20099 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
20100 #define OSTRACE6(X,Y,Z,A,B,C) \
20101     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
20102 #define OSTRACE7(X,Y,Z,A,B,C,D) \
20103     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
20104 #else
20105 #define OSTRACE1(X)
20106 #define OSTRACE2(X,Y)
20107 #define OSTRACE3(X,Y,Z)
20108 #define OSTRACE4(X,Y,Z,A)
20109 #define OSTRACE5(X,Y,Z,A,B)
20110 #define OSTRACE6(X,Y,Z,A,B,C)
20111 #define OSTRACE7(X,Y,Z,A,B,C,D)
20112 #endif
20113
20114 /*
20115 ** Macros for performance tracing.  Normally turned off.  Only works
20116 ** on i486 hardware.
20117 */
20118 #ifdef SQLITE_PERFORMANCE_TRACE
20119
20120 /* 
20121 ** hwtime.h contains inline assembler code for implementing 
20122 ** high-performance timing routines.
20123 */
20124 /************** Include hwtime.h in the middle of os_common.h ****************/
20125 /************** Begin file hwtime.h ******************************************/
20126 /*
20127 ** 2008 May 27
20128 **
20129 ** The author disclaims copyright to this source code.  In place of
20130 ** a legal notice, here is a blessing:
20131 **
20132 **    May you do good and not evil.
20133 **    May you find forgiveness for yourself and forgive others.
20134 **    May you share freely, never taking more than you give.
20135 **
20136 ******************************************************************************
20137 **
20138 ** This file contains inline asm code for retrieving "high-performance"
20139 ** counters for x86 class CPUs.
20140 **
20141 ** $Id: hwtime.h,v 1.3 2008/08/01 14:33:15 shane Exp $
20142 */
20143 #ifndef _HWTIME_H_
20144 #define _HWTIME_H_
20145
20146 /*
20147 ** The following routine only works on pentium-class (or newer) processors.
20148 ** It uses the RDTSC opcode to read the cycle count value out of the
20149 ** processor and returns that value.  This can be used for high-res
20150 ** profiling.
20151 */
20152 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
20153       (defined(i386) || defined(__i386__) || defined(_M_IX86))
20154
20155   #if defined(__GNUC__)
20156
20157   __inline__ sqlite_uint64 sqlite3Hwtime(void){
20158      unsigned int lo, hi;
20159      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
20160      return (sqlite_uint64)hi << 32 | lo;
20161   }
20162
20163   #elif defined(_MSC_VER)
20164
20165   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
20166      __asm {
20167         rdtsc
20168         ret       ; return value at EDX:EAX
20169      }
20170   }
20171
20172   #endif
20173
20174 #elif (defined(__GNUC__) && defined(__x86_64__))
20175
20176   __inline__ sqlite_uint64 sqlite3Hwtime(void){
20177       unsigned long val;
20178       __asm__ __volatile__ ("rdtsc" : "=A" (val));
20179       return val;
20180   }
20181  
20182 #elif (defined(__GNUC__) && defined(__ppc__))
20183
20184   __inline__ sqlite_uint64 sqlite3Hwtime(void){
20185       unsigned long long retval;
20186       unsigned long junk;
20187       __asm__ __volatile__ ("\n\
20188           1:      mftbu   %1\n\
20189                   mftb    %L0\n\
20190                   mftbu   %0\n\
20191                   cmpw    %0,%1\n\
20192                   bne     1b"
20193                   : "=r" (retval), "=r" (junk));
20194       return retval;
20195   }
20196
20197 #else
20198
20199   #error Need implementation of sqlite3Hwtime() for your platform.
20200
20201   /*
20202   ** To compile without implementing sqlite3Hwtime() for your platform,
20203   ** you can remove the above #error and use the following
20204   ** stub function.  You will lose timing support for many
20205   ** of the debugging and testing utilities, but it should at
20206   ** least compile and run.
20207   */
20208 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
20209
20210 #endif
20211
20212 #endif /* !defined(_HWTIME_H_) */
20213
20214 /************** End of hwtime.h **********************************************/
20215 /************** Continuing where we left off in os_common.h ******************/
20216
20217 static sqlite_uint64 g_start;
20218 static sqlite_uint64 g_elapsed;
20219 #define TIMER_START       g_start=sqlite3Hwtime()
20220 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
20221 #define TIMER_ELAPSED     g_elapsed
20222 #else
20223 #define TIMER_START
20224 #define TIMER_END
20225 #define TIMER_ELAPSED     ((sqlite_uint64)0)
20226 #endif
20227
20228 /*
20229 ** If we compile with the SQLITE_TEST macro set, then the following block
20230 ** of code will give us the ability to simulate a disk I/O error.  This
20231 ** is used for testing the I/O recovery logic.
20232 */
20233 #ifdef SQLITE_TEST
20234 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
20235 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
20236 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
20237 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
20238 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
20239 SQLITE_API int sqlite3_diskfull_pending = 0;
20240 SQLITE_API int sqlite3_diskfull = 0;
20241 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
20242 #define SimulateIOError(CODE)  \
20243   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
20244        || sqlite3_io_error_pending-- == 1 )  \
20245               { local_ioerr(); CODE; }
20246 static void local_ioerr(){
20247   IOTRACE(("IOERR\n"));
20248   sqlite3_io_error_hit++;
20249   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
20250 }
20251 #define SimulateDiskfullError(CODE) \
20252    if( sqlite3_diskfull_pending ){ \
20253      if( sqlite3_diskfull_pending == 1 ){ \
20254        local_ioerr(); \
20255        sqlite3_diskfull = 1; \
20256        sqlite3_io_error_hit = 1; \
20257        CODE; \
20258      }else{ \
20259        sqlite3_diskfull_pending--; \
20260      } \
20261    }
20262 #else
20263 #define SimulateIOErrorBenign(X)
20264 #define SimulateIOError(A)
20265 #define SimulateDiskfullError(A)
20266 #endif
20267
20268 /*
20269 ** When testing, keep a count of the number of open files.
20270 */
20271 #ifdef SQLITE_TEST
20272 SQLITE_API int sqlite3_open_file_count = 0;
20273 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
20274 #else
20275 #define OpenCounter(X)
20276 #endif
20277
20278 #endif /* !defined(_OS_COMMON_H_) */
20279
20280 /************** End of os_common.h *******************************************/
20281 /************** Continuing where we left off in os_os2.c *********************/
20282
20283 /*
20284 ** The os2File structure is subclass of sqlite3_file specific for the OS/2
20285 ** protability layer.
20286 */
20287 typedef struct os2File os2File;
20288 struct os2File {
20289   const sqlite3_io_methods *pMethod;  /* Always the first entry */
20290   HFILE h;                  /* Handle for accessing the file */
20291   char* pathToDel;          /* Name of file to delete on close, NULL if not */
20292   unsigned char locktype;   /* Type of lock currently held on this file */
20293 };
20294
20295 #define LOCK_TIMEOUT 10L /* the default locking timeout */
20296
20297 /*****************************************************************************
20298 ** The next group of routines implement the I/O methods specified
20299 ** by the sqlite3_io_methods object.
20300 ******************************************************************************/
20301
20302 /*
20303 ** Close a file.
20304 */
20305 static int os2Close( sqlite3_file *id ){
20306   APIRET rc = NO_ERROR;
20307   os2File *pFile;
20308   if( id && (pFile = (os2File*)id) != 0 ){
20309     OSTRACE2( "CLOSE %d\n", pFile->h );
20310     rc = DosClose( pFile->h );
20311     pFile->locktype = NO_LOCK;
20312     if( pFile->pathToDel != NULL ){
20313       rc = DosForceDelete( (PSZ)pFile->pathToDel );
20314       free( pFile->pathToDel );
20315       pFile->pathToDel = NULL;
20316     }
20317     id = 0;
20318     OpenCounter( -1 );
20319   }
20320
20321   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
20322 }
20323
20324 /*
20325 ** Read data from a file into a buffer.  Return SQLITE_OK if all
20326 ** bytes were read successfully and SQLITE_IOERR if anything goes
20327 ** wrong.
20328 */
20329 static int os2Read(
20330   sqlite3_file *id,               /* File to read from */
20331   void *pBuf,                     /* Write content into this buffer */
20332   int amt,                        /* Number of bytes to read */
20333   sqlite3_int64 offset            /* Begin reading at this offset */
20334 ){
20335   ULONG fileLocation = 0L;
20336   ULONG got;
20337   os2File *pFile = (os2File*)id;
20338   assert( id!=0 );
20339   SimulateIOError( return SQLITE_IOERR_READ );
20340   OSTRACE3( "READ %d lock=%d\n", pFile->h, pFile->locktype );
20341   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
20342     return SQLITE_IOERR;
20343   }
20344   if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
20345     return SQLITE_IOERR_READ;
20346   }
20347   if( got == (ULONG)amt )
20348     return SQLITE_OK;
20349   else {
20350     /* Unread portions of the input buffer must be zero-filled */
20351     memset(&((char*)pBuf)[got], 0, amt-got);
20352     return SQLITE_IOERR_SHORT_READ;
20353   }
20354 }
20355
20356 /*
20357 ** Write data from a buffer into a file.  Return SQLITE_OK on success
20358 ** or some other error code on failure.
20359 */
20360 static int os2Write(
20361   sqlite3_file *id,               /* File to write into */
20362   const void *pBuf,               /* The bytes to be written */
20363   int amt,                        /* Number of bytes to write */
20364   sqlite3_int64 offset            /* Offset into the file to begin writing at */
20365 ){
20366   ULONG fileLocation = 0L;
20367   APIRET rc = NO_ERROR;
20368   ULONG wrote;
20369   os2File *pFile = (os2File*)id;
20370   assert( id!=0 );
20371   SimulateIOError( return SQLITE_IOERR_WRITE );
20372   SimulateDiskfullError( return SQLITE_FULL );
20373   OSTRACE3( "WRITE %d lock=%d\n", pFile->h, pFile->locktype );
20374   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
20375     return SQLITE_IOERR;
20376   }
20377   assert( amt>0 );
20378   while( amt > 0 &&
20379          ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
20380          wrote > 0
20381   ){
20382     amt -= wrote;
20383     pBuf = &((char*)pBuf)[wrote];
20384   }
20385
20386   return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
20387 }
20388
20389 /*
20390 ** Truncate an open file to a specified size
20391 */
20392 static int os2Truncate( sqlite3_file *id, i64 nByte ){
20393   APIRET rc = NO_ERROR;
20394   os2File *pFile = (os2File*)id;
20395   OSTRACE3( "TRUNCATE %d %lld\n", pFile->h, nByte );
20396   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
20397   rc = DosSetFileSize( pFile->h, nByte );
20398   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
20399 }
20400
20401 #ifdef SQLITE_TEST
20402 /*
20403 ** Count the number of fullsyncs and normal syncs.  This is used to test
20404 ** that syncs and fullsyncs are occuring at the right times.
20405 */
20406 SQLITE_API int sqlite3_sync_count = 0;
20407 SQLITE_API int sqlite3_fullsync_count = 0;
20408 #endif
20409
20410 /*
20411 ** Make sure all writes to a particular file are committed to disk.
20412 */
20413 static int os2Sync( sqlite3_file *id, int flags ){
20414   os2File *pFile = (os2File*)id;
20415   OSTRACE3( "SYNC %d lock=%d\n", pFile->h, pFile->locktype );
20416 #ifdef SQLITE_TEST
20417   if( flags & SQLITE_SYNC_FULL){
20418     sqlite3_fullsync_count++;
20419   }
20420   sqlite3_sync_count++;
20421 #endif
20422   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
20423   ** no-op
20424   */
20425 #ifdef SQLITE_NO_SYNC
20426   return SQLITE_OK;
20427 #else
20428   return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
20429 #endif
20430 }
20431
20432 /*
20433 ** Determine the current size of a file in bytes
20434 */
20435 static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
20436   APIRET rc = NO_ERROR;
20437   FILESTATUS3 fsts3FileInfo;
20438   memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
20439   assert( id!=0 );
20440   SimulateIOError( return SQLITE_IOERR_FSTAT );
20441   rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
20442   if( rc == NO_ERROR ){
20443     *pSize = fsts3FileInfo.cbFile;
20444     return SQLITE_OK;
20445   }else{
20446     return SQLITE_IOERR_FSTAT;
20447   }
20448 }
20449
20450 /*
20451 ** Acquire a reader lock.
20452 */
20453 static int getReadLock( os2File *pFile ){
20454   FILELOCK  LockArea,
20455             UnlockArea;
20456   APIRET res;
20457   memset(&LockArea, 0, sizeof(LockArea));
20458   memset(&UnlockArea, 0, sizeof(UnlockArea));
20459   LockArea.lOffset = SHARED_FIRST;
20460   LockArea.lRange = SHARED_SIZE;
20461   UnlockArea.lOffset = 0L;
20462   UnlockArea.lRange = 0L;
20463   res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
20464   OSTRACE3( "GETREADLOCK %d res=%d\n", pFile->h, res );
20465   return res;
20466 }
20467
20468 /*
20469 ** Undo a readlock
20470 */
20471 static int unlockReadLock( os2File *id ){
20472   FILELOCK  LockArea,
20473             UnlockArea;
20474   APIRET res;
20475   memset(&LockArea, 0, sizeof(LockArea));
20476   memset(&UnlockArea, 0, sizeof(UnlockArea));
20477   LockArea.lOffset = 0L;
20478   LockArea.lRange = 0L;
20479   UnlockArea.lOffset = SHARED_FIRST;
20480   UnlockArea.lRange = SHARED_SIZE;
20481   res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
20482   OSTRACE3( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res );
20483   return res;
20484 }
20485
20486 /*
20487 ** Lock the file with the lock specified by parameter locktype - one
20488 ** of the following:
20489 **
20490 **     (1) SHARED_LOCK
20491 **     (2) RESERVED_LOCK
20492 **     (3) PENDING_LOCK
20493 **     (4) EXCLUSIVE_LOCK
20494 **
20495 ** Sometimes when requesting one lock state, additional lock states
20496 ** are inserted in between.  The locking might fail on one of the later
20497 ** transitions leaving the lock state different from what it started but
20498 ** still short of its goal.  The following chart shows the allowed
20499 ** transitions and the inserted intermediate states:
20500 **
20501 **    UNLOCKED -> SHARED
20502 **    SHARED -> RESERVED
20503 **    SHARED -> (PENDING) -> EXCLUSIVE
20504 **    RESERVED -> (PENDING) -> EXCLUSIVE
20505 **    PENDING -> EXCLUSIVE
20506 **
20507 ** This routine will only increase a lock.  The os2Unlock() routine
20508 ** erases all locks at once and returns us immediately to locking level 0.
20509 ** It is not possible to lower the locking level one step at a time.  You
20510 ** must go straight to locking level 0.
20511 */
20512 static int os2Lock( sqlite3_file *id, int locktype ){
20513   int rc = SQLITE_OK;       /* Return code from subroutines */
20514   APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
20515   int newLocktype;       /* Set pFile->locktype to this value before exiting */
20516   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
20517   FILELOCK  LockArea,
20518             UnlockArea;
20519   os2File *pFile = (os2File*)id;
20520   memset(&LockArea, 0, sizeof(LockArea));
20521   memset(&UnlockArea, 0, sizeof(UnlockArea));
20522   assert( pFile!=0 );
20523   OSTRACE4( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype );
20524
20525   /* If there is already a lock of this type or more restrictive on the
20526   ** os2File, do nothing. Don't use the end_lock: exit path, as
20527   ** sqlite3_mutex_enter() hasn't been called yet.
20528   */
20529   if( pFile->locktype>=locktype ){
20530     OSTRACE3( "LOCK %d %d ok (already held)\n", pFile->h, locktype );
20531     return SQLITE_OK;
20532   }
20533
20534   /* Make sure the locking sequence is correct
20535   */
20536   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
20537   assert( locktype!=PENDING_LOCK );
20538   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
20539
20540   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
20541   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
20542   ** the PENDING_LOCK byte is temporary.
20543   */
20544   newLocktype = pFile->locktype;
20545   if( pFile->locktype==NO_LOCK
20546       || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
20547   ){
20548     LockArea.lOffset = PENDING_BYTE;
20549     LockArea.lRange = 1L;
20550     UnlockArea.lOffset = 0L;
20551     UnlockArea.lRange = 0L;
20552
20553     /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
20554     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
20555     if( res == NO_ERROR ){
20556       gotPendingLock = 1;
20557       OSTRACE3( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res );
20558     }
20559   }
20560
20561   /* Acquire a shared lock
20562   */
20563   if( locktype==SHARED_LOCK && res == NO_ERROR ){
20564     assert( pFile->locktype==NO_LOCK );
20565     res = getReadLock(pFile);
20566     if( res == NO_ERROR ){
20567       newLocktype = SHARED_LOCK;
20568     }
20569     OSTRACE3( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res );
20570   }
20571
20572   /* Acquire a RESERVED lock
20573   */
20574   if( locktype==RESERVED_LOCK && res == NO_ERROR ){
20575     assert( pFile->locktype==SHARED_LOCK );
20576     LockArea.lOffset = RESERVED_BYTE;
20577     LockArea.lRange = 1L;
20578     UnlockArea.lOffset = 0L;
20579     UnlockArea.lRange = 0L;
20580     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20581     if( res == NO_ERROR ){
20582       newLocktype = RESERVED_LOCK;
20583     }
20584     OSTRACE3( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res );
20585   }
20586
20587   /* Acquire a PENDING lock
20588   */
20589   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
20590     newLocktype = PENDING_LOCK;
20591     gotPendingLock = 0;
20592     OSTRACE2( "LOCK %d acquire pending lock. pending lock boolean unset.\n", pFile->h );
20593   }
20594
20595   /* Acquire an EXCLUSIVE lock
20596   */
20597   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
20598     assert( pFile->locktype>=SHARED_LOCK );
20599     res = unlockReadLock(pFile);
20600     OSTRACE2( "unreadlock = %d\n", res );
20601     LockArea.lOffset = SHARED_FIRST;
20602     LockArea.lRange = SHARED_SIZE;
20603     UnlockArea.lOffset = 0L;
20604     UnlockArea.lRange = 0L;
20605     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20606     if( res == NO_ERROR ){
20607       newLocktype = EXCLUSIVE_LOCK;
20608     }else{
20609       OSTRACE2( "OS/2 error-code = %d\n", res );
20610       getReadLock(pFile);
20611     }
20612     OSTRACE3( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res );
20613   }
20614
20615   /* If we are holding a PENDING lock that ought to be released, then
20616   ** release it now.
20617   */
20618   if( gotPendingLock && locktype==SHARED_LOCK ){
20619     int r;
20620     LockArea.lOffset = 0L;
20621     LockArea.lRange = 0L;
20622     UnlockArea.lOffset = PENDING_BYTE;
20623     UnlockArea.lRange = 1L;
20624     r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20625     OSTRACE3( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r );
20626   }
20627
20628   /* Update the state of the lock has held in the file descriptor then
20629   ** return the appropriate result code.
20630   */
20631   if( res == NO_ERROR ){
20632     rc = SQLITE_OK;
20633   }else{
20634     OSTRACE4( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
20635               locktype, newLocktype );
20636     rc = SQLITE_BUSY;
20637   }
20638   pFile->locktype = newLocktype;
20639   OSTRACE3( "LOCK %d now %d\n", pFile->h, pFile->locktype );
20640   return rc;
20641 }
20642
20643 /*
20644 ** This routine checks if there is a RESERVED lock held on the specified
20645 ** file by this or any other process. If such a lock is held, return
20646 ** non-zero, otherwise zero.
20647 */
20648 static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
20649   int r = 0;
20650   os2File *pFile = (os2File*)id;
20651   assert( pFile!=0 );
20652   if( pFile->locktype>=RESERVED_LOCK ){
20653     r = 1;
20654     OSTRACE3( "TEST WR-LOCK %d %d (local)\n", pFile->h, r );
20655   }else{
20656     FILELOCK  LockArea,
20657               UnlockArea;
20658     APIRET rc = NO_ERROR;
20659     memset(&LockArea, 0, sizeof(LockArea));
20660     memset(&UnlockArea, 0, sizeof(UnlockArea));
20661     LockArea.lOffset = RESERVED_BYTE;
20662     LockArea.lRange = 1L;
20663     UnlockArea.lOffset = 0L;
20664     UnlockArea.lRange = 0L;
20665     rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20666     OSTRACE3( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc );
20667     if( rc == NO_ERROR ){
20668       APIRET rcu = NO_ERROR; /* return code for unlocking */
20669       LockArea.lOffset = 0L;
20670       LockArea.lRange = 0L;
20671       UnlockArea.lOffset = RESERVED_BYTE;
20672       UnlockArea.lRange = 1L;
20673       rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20674       OSTRACE3( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu );
20675     }
20676     r = !(rc == NO_ERROR);
20677     OSTRACE3( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r );
20678   }
20679   *pOut = r;
20680   return SQLITE_OK;
20681 }
20682
20683 /*
20684 ** Lower the locking level on file descriptor id to locktype.  locktype
20685 ** must be either NO_LOCK or SHARED_LOCK.
20686 **
20687 ** If the locking level of the file descriptor is already at or below
20688 ** the requested locking level, this routine is a no-op.
20689 **
20690 ** It is not possible for this routine to fail if the second argument
20691 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
20692 ** might return SQLITE_IOERR;
20693 */
20694 static int os2Unlock( sqlite3_file *id, int locktype ){
20695   int type;
20696   os2File *pFile = (os2File*)id;
20697   APIRET rc = SQLITE_OK;
20698   APIRET res = NO_ERROR;
20699   FILELOCK  LockArea,
20700             UnlockArea;
20701   memset(&LockArea, 0, sizeof(LockArea));
20702   memset(&UnlockArea, 0, sizeof(UnlockArea));
20703   assert( pFile!=0 );
20704   assert( locktype<=SHARED_LOCK );
20705   OSTRACE4( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype );
20706   type = pFile->locktype;
20707   if( type>=EXCLUSIVE_LOCK ){
20708     LockArea.lOffset = 0L;
20709     LockArea.lRange = 0L;
20710     UnlockArea.lOffset = SHARED_FIRST;
20711     UnlockArea.lRange = SHARED_SIZE;
20712     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20713     OSTRACE3( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res );
20714     if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
20715       /* This should never happen.  We should always be able to
20716       ** reacquire the read lock */
20717       OSTRACE3( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype );
20718       rc = SQLITE_IOERR_UNLOCK;
20719     }
20720   }
20721   if( type>=RESERVED_LOCK ){
20722     LockArea.lOffset = 0L;
20723     LockArea.lRange = 0L;
20724     UnlockArea.lOffset = RESERVED_BYTE;
20725     UnlockArea.lRange = 1L;
20726     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20727     OSTRACE3( "UNLOCK %d reserved res=%d\n", pFile->h, res );
20728   }
20729   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
20730     res = unlockReadLock(pFile);
20731     OSTRACE5( "UNLOCK %d is %d want %d res=%d\n", pFile->h, type, locktype, res );
20732   }
20733   if( type>=PENDING_LOCK ){
20734     LockArea.lOffset = 0L;
20735     LockArea.lRange = 0L;
20736     UnlockArea.lOffset = PENDING_BYTE;
20737     UnlockArea.lRange = 1L;
20738     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20739     OSTRACE3( "UNLOCK %d pending res=%d\n", pFile->h, res );
20740   }
20741   pFile->locktype = locktype;
20742   OSTRACE3( "UNLOCK %d now %d\n", pFile->h, pFile->locktype );
20743   return rc;
20744 }
20745
20746 /*
20747 ** Control and query of the open file handle.
20748 */
20749 static int os2FileControl(sqlite3_file *id, int op, void *pArg){
20750   switch( op ){
20751     case SQLITE_FCNTL_LOCKSTATE: {
20752       *(int*)pArg = ((os2File*)id)->locktype;
20753       OSTRACE3( "FCNTL_LOCKSTATE %d lock=%d\n", ((os2File*)id)->h, ((os2File*)id)->locktype );
20754       return SQLITE_OK;
20755     }
20756   }
20757   return SQLITE_ERROR;
20758 }
20759
20760 /*
20761 ** Return the sector size in bytes of the underlying block device for
20762 ** the specified file. This is almost always 512 bytes, but may be
20763 ** larger for some devices.
20764 **
20765 ** SQLite code assumes this function cannot fail. It also assumes that
20766 ** if two files are created in the same file-system directory (i.e.
20767 ** a database and its journal file) that the sector size will be the
20768 ** same for both.
20769 */
20770 static int os2SectorSize(sqlite3_file *id){
20771   return SQLITE_DEFAULT_SECTOR_SIZE;
20772 }
20773
20774 /*
20775 ** Return a vector of device characteristics.
20776 */
20777 static int os2DeviceCharacteristics(sqlite3_file *id){
20778   return 0;
20779 }
20780
20781
20782 /*
20783 ** Character set conversion objects used by conversion routines.
20784 */
20785 static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
20786 static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */
20787
20788 /*
20789 ** Helper function to initialize the conversion objects from and to UTF-8.
20790 */
20791 static void initUconvObjects( void ){
20792   if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
20793     ucUtf8 = NULL;
20794   if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
20795     uclCp = NULL;
20796 }
20797
20798 /*
20799 ** Helper function to free the conversion objects from and to UTF-8.
20800 */
20801 static void freeUconvObjects( void ){
20802   if ( ucUtf8 )
20803     UniFreeUconvObject( ucUtf8 );
20804   if ( uclCp )
20805     UniFreeUconvObject( uclCp );
20806   ucUtf8 = NULL;
20807   uclCp = NULL;
20808 }
20809
20810 /*
20811 ** Helper function to convert UTF-8 filenames to local OS/2 codepage.
20812 ** The two-step process: first convert the incoming UTF-8 string
20813 ** into UCS-2 and then from UCS-2 to the current codepage.
20814 ** The returned char pointer has to be freed.
20815 */
20816 static char *convertUtf8PathToCp( const char *in ){
20817   UniChar tempPath[CCHMAXPATH];
20818   char *out = (char *)calloc( CCHMAXPATH, 1 );
20819
20820   if( !out )
20821     return NULL;
20822
20823   if( !ucUtf8 || !uclCp )
20824     initUconvObjects();
20825
20826   /* determine string for the conversion of UTF-8 which is CP1208 */
20827   if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
20828     return out; /* if conversion fails, return the empty string */
20829
20830   /* conversion for current codepage which can be used for paths */
20831   UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
20832
20833   return out;
20834 }
20835
20836 /*
20837 ** Helper function to convert filenames from local codepage to UTF-8.
20838 ** The two-step process: first convert the incoming codepage-specific
20839 ** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
20840 ** The returned char pointer has to be freed.
20841 **
20842 ** This function is non-static to be able to use this in shell.c and
20843 ** similar applications that take command line arguments.
20844 */
20845 char *convertCpPathToUtf8( const char *in ){
20846   UniChar tempPath[CCHMAXPATH];
20847   char *out = (char *)calloc( CCHMAXPATH, 1 );
20848
20849   if( !out )
20850     return NULL;
20851
20852   if( !ucUtf8 || !uclCp )
20853     initUconvObjects();
20854
20855   /* conversion for current codepage which can be used for paths */
20856   if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
20857     return out; /* if conversion fails, return the empty string */
20858
20859   /* determine string for the conversion of UTF-8 which is CP1208 */
20860   UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
20861
20862   return out;
20863 }
20864
20865 /*
20866 ** This vector defines all the methods that can operate on an
20867 ** sqlite3_file for os2.
20868 */
20869 static const sqlite3_io_methods os2IoMethod = {
20870   1,                        /* iVersion */
20871   os2Close,
20872   os2Read,
20873   os2Write,
20874   os2Truncate,
20875   os2Sync,
20876   os2FileSize,
20877   os2Lock,
20878   os2Unlock,
20879   os2CheckReservedLock,
20880   os2FileControl,
20881   os2SectorSize,
20882   os2DeviceCharacteristics
20883 };
20884
20885 /***************************************************************************
20886 ** Here ends the I/O methods that form the sqlite3_io_methods object.
20887 **
20888 ** The next block of code implements the VFS methods.
20889 ****************************************************************************/
20890
20891 /*
20892 ** Create a temporary file name in zBuf.  zBuf must be big enough to
20893 ** hold at pVfs->mxPathname characters.
20894 */
20895 static int getTempname(int nBuf, char *zBuf ){
20896   static const unsigned char zChars[] =
20897     "abcdefghijklmnopqrstuvwxyz"
20898     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
20899     "0123456789";
20900   int i, j;
20901   char zTempPathBuf[3];
20902   PSZ zTempPath = (PSZ)&zTempPathBuf;
20903   if( sqlite3_temp_directory ){
20904     zTempPath = sqlite3_temp_directory;
20905   }else{
20906     if( DosScanEnv( (PSZ)"TEMP", &zTempPath ) ){
20907       if( DosScanEnv( (PSZ)"TMP", &zTempPath ) ){
20908         if( DosScanEnv( (PSZ)"TMPDIR", &zTempPath ) ){
20909            ULONG ulDriveNum = 0, ulDriveMap = 0;
20910            DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
20911            sprintf( (char*)zTempPath, "%c:", (char)( 'A' + ulDriveNum - 1 ) );
20912         }
20913       }
20914     }
20915   }
20916   /* Strip off a trailing slashes or backslashes, otherwise we would get *
20917    * multiple (back)slashes which causes DosOpen() to fail.              *
20918    * Trailing spaces are not allowed, either.                            */
20919   j = strlen(zTempPath);
20920   while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/'
20921                     || zTempPath[j-1] == ' ' ) ){
20922     j--;
20923   }
20924   zTempPath[j] = '\0';
20925   if( !sqlite3_temp_directory ){
20926     char *zTempPathUTF = convertCpPathToUtf8( zTempPath );
20927     sqlite3_snprintf( nBuf-30, zBuf,
20928                       "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPathUTF );
20929     free( zTempPathUTF );
20930   }else{
20931     sqlite3_snprintf( nBuf-30, zBuf,
20932                       "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath );
20933   }
20934   j = strlen( zBuf );
20935   sqlite3_randomness( 20, &zBuf[j] );
20936   for( i = 0; i < 20; i++, j++ ){
20937     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
20938   }
20939   zBuf[j] = 0;
20940   OSTRACE2( "TEMP FILENAME: %s\n", zBuf );
20941   return SQLITE_OK;
20942 }
20943
20944
20945 /*
20946 ** Turn a relative pathname into a full pathname.  Write the full
20947 ** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
20948 ** bytes in size.
20949 */
20950 static int os2FullPathname(
20951   sqlite3_vfs *pVfs,          /* Pointer to vfs object */
20952   const char *zRelative,      /* Possibly relative input path */
20953   int nFull,                  /* Size of output buffer in bytes */
20954   char *zFull                 /* Output buffer */
20955 ){
20956   char *zRelativeCp = convertUtf8PathToCp( zRelative );
20957   char zFullCp[CCHMAXPATH] = "\0";
20958   char *zFullUTF;
20959   APIRET rc = DosQueryPathInfo( zRelativeCp, FIL_QUERYFULLNAME, zFullCp,
20960                                 CCHMAXPATH );
20961   free( zRelativeCp );
20962   zFullUTF = convertCpPathToUtf8( zFullCp );
20963   sqlite3_snprintf( nFull, zFull, zFullUTF );
20964   free( zFullUTF );
20965   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
20966 }
20967
20968
20969 /*
20970 ** Open a file.
20971 */
20972 static int os2Open(
20973   sqlite3_vfs *pVfs,            /* Not used */
20974   const char *zName,            /* Name of the file */
20975   sqlite3_file *id,             /* Write the SQLite file handle here */
20976   int flags,                    /* Open mode flags */
20977   int *pOutFlags                /* Status return flags */
20978 ){
20979   HFILE h;
20980   ULONG ulFileAttribute = FILE_NORMAL;
20981   ULONG ulOpenFlags = 0;
20982   ULONG ulOpenMode = 0;
20983   os2File *pFile = (os2File*)id;
20984   APIRET rc = NO_ERROR;
20985   ULONG ulAction;
20986   char *zNameCp;
20987   char zTmpname[CCHMAXPATH+1];    /* Buffer to hold name of temp file */
20988
20989   /* If the second argument to this function is NULL, generate a 
20990   ** temporary file name to use 
20991   */
20992   if( !zName ){
20993     int rc = getTempname(CCHMAXPATH+1, zTmpname);
20994     if( rc!=SQLITE_OK ){
20995       return rc;
20996     }
20997     zName = zTmpname;
20998   }
20999
21000
21001   memset( pFile, 0, sizeof(*pFile) );
21002
21003   OSTRACE2( "OPEN want %d\n", flags );
21004
21005   if( flags & SQLITE_OPEN_READWRITE ){
21006     ulOpenMode |= OPEN_ACCESS_READWRITE;
21007     OSTRACE1( "OPEN read/write\n" );
21008   }else{
21009     ulOpenMode |= OPEN_ACCESS_READONLY;
21010     OSTRACE1( "OPEN read only\n" );
21011   }
21012
21013   if( flags & SQLITE_OPEN_CREATE ){
21014     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW;
21015     OSTRACE1( "OPEN open new/create\n" );
21016   }else{
21017     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW;
21018     OSTRACE1( "OPEN open existing\n" );
21019   }
21020
21021   if( flags & SQLITE_OPEN_MAIN_DB ){
21022     ulOpenMode |= OPEN_SHARE_DENYNONE;
21023     OSTRACE1( "OPEN share read/write\n" );
21024   }else{
21025     ulOpenMode |= OPEN_SHARE_DENYWRITE;
21026     OSTRACE1( "OPEN share read only\n" );
21027   }
21028
21029   if( flags & SQLITE_OPEN_DELETEONCLOSE ){
21030     char pathUtf8[CCHMAXPATH];
21031 #ifdef NDEBUG /* when debugging we want to make sure it is deleted */
21032     ulFileAttribute = FILE_HIDDEN;
21033 #endif
21034     os2FullPathname( pVfs, zName, CCHMAXPATH, pathUtf8 );
21035     pFile->pathToDel = convertUtf8PathToCp( pathUtf8 );
21036     OSTRACE1( "OPEN hidden/delete on close file attributes\n" );
21037   }else{
21038     pFile->pathToDel = NULL;
21039     OSTRACE1( "OPEN normal file attribute\n" );
21040   }
21041
21042   /* always open in random access mode for possibly better speed */
21043   ulOpenMode |= OPEN_FLAGS_RANDOM;
21044   ulOpenMode |= OPEN_FLAGS_FAIL_ON_ERROR;
21045   ulOpenMode |= OPEN_FLAGS_NOINHERIT;
21046
21047   zNameCp = convertUtf8PathToCp( zName );
21048   rc = DosOpen( (PSZ)zNameCp,
21049                 &h,
21050                 &ulAction,
21051                 0L,
21052                 ulFileAttribute,
21053                 ulOpenFlags,
21054                 ulOpenMode,
21055                 (PEAOP2)NULL );
21056   free( zNameCp );
21057   if( rc != NO_ERROR ){
21058     OSTRACE7( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulAttr=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
21059               rc, zName, ulAction, ulFileAttribute, ulOpenFlags, ulOpenMode );
21060     if( pFile->pathToDel )
21061       free( pFile->pathToDel );
21062     pFile->pathToDel = NULL;
21063     if( flags & SQLITE_OPEN_READWRITE ){
21064       OSTRACE2( "OPEN %d Invalid handle\n", ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE) );
21065       return os2Open( pVfs, zName, id,
21066                       ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE),
21067                       pOutFlags );
21068     }else{
21069       return SQLITE_CANTOPEN;
21070     }
21071   }
21072
21073   if( pOutFlags ){
21074     *pOutFlags = flags & SQLITE_OPEN_READWRITE ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
21075   }
21076
21077   pFile->pMethod = &os2IoMethod;
21078   pFile->h = h;
21079   OpenCounter(+1);
21080   OSTRACE3( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags );
21081   return SQLITE_OK;
21082 }
21083
21084 /*
21085 ** Delete the named file.
21086 */
21087 static int os2Delete(
21088   sqlite3_vfs *pVfs,                     /* Not used on os2 */
21089   const char *zFilename,                 /* Name of file to delete */
21090   int syncDir                            /* Not used on os2 */
21091 ){
21092   APIRET rc = NO_ERROR;
21093   char *zFilenameCp = convertUtf8PathToCp( zFilename );
21094   SimulateIOError( return SQLITE_IOERR_DELETE );
21095   rc = DosDelete( (PSZ)zFilenameCp );
21096   free( zFilenameCp );
21097   OSTRACE2( "DELETE \"%s\"\n", zFilename );
21098   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_DELETE;
21099 }
21100
21101 /*
21102 ** Check the existance and status of a file.
21103 */
21104 static int os2Access(
21105   sqlite3_vfs *pVfs,        /* Not used on os2 */
21106   const char *zFilename,    /* Name of file to check */
21107   int flags,                /* Type of test to make on this file */
21108   int *pOut                 /* Write results here */
21109 ){
21110   FILESTATUS3 fsts3ConfigInfo;
21111   APIRET rc = NO_ERROR;
21112   char *zFilenameCp = convertUtf8PathToCp( zFilename );
21113
21114   memset( &fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo) );
21115   rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
21116                          &fsts3ConfigInfo, sizeof(FILESTATUS3) );
21117   free( zFilenameCp );
21118   OSTRACE4( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
21119             fsts3ConfigInfo.attrFile, flags, rc );
21120   switch( flags ){
21121     case SQLITE_ACCESS_READ:
21122     case SQLITE_ACCESS_EXISTS:
21123       rc = (rc == NO_ERROR);
21124       OSTRACE3( "ACCESS %s access of read and exists  rc=%d\n", zFilename, rc );
21125       break;
21126     case SQLITE_ACCESS_READWRITE:
21127       rc = (rc == NO_ERROR) && ( (fsts3ConfigInfo.attrFile & FILE_READONLY) == 0 );
21128       OSTRACE3( "ACCESS %s access of read/write  rc=%d\n", zFilename, rc );
21129       break;
21130     default:
21131       assert( !"Invalid flags argument" );
21132   }
21133   *pOut = rc;
21134   return SQLITE_OK;
21135 }
21136
21137
21138 #ifndef SQLITE_OMIT_LOAD_EXTENSION
21139 /*
21140 ** Interfaces for opening a shared library, finding entry points
21141 ** within the shared library, and closing the shared library.
21142 */
21143 /*
21144 ** Interfaces for opening a shared library, finding entry points
21145 ** within the shared library, and closing the shared library.
21146 */
21147 static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
21148   UCHAR loadErr[256];
21149   HMODULE hmod;
21150   APIRET rc;
21151   char *zFilenameCp = convertUtf8PathToCp(zFilename);
21152   rc = DosLoadModule((PSZ)loadErr, sizeof(loadErr), zFilenameCp, &hmod);
21153   free(zFilenameCp);
21154   return rc != NO_ERROR ? 0 : (void*)hmod;
21155 }
21156 /*
21157 ** A no-op since the error code is returned on the DosLoadModule call.
21158 ** os2Dlopen returns zero if DosLoadModule is not successful.
21159 */
21160 static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
21161 /* no-op */
21162 }
21163 static void *os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
21164   PFN pfn;
21165   APIRET rc;
21166   rc = DosQueryProcAddr((HMODULE)pHandle, 0L, zSymbol, &pfn);
21167   if( rc != NO_ERROR ){
21168     /* if the symbol itself was not found, search again for the same
21169      * symbol with an extra underscore, that might be needed depending
21170      * on the calling convention */
21171     char _zSymbol[256] = "_";
21172     strncat(_zSymbol, zSymbol, 255);
21173     rc = DosQueryProcAddr((HMODULE)pHandle, 0L, _zSymbol, &pfn);
21174   }
21175   return rc != NO_ERROR ? 0 : (void*)pfn;
21176 }
21177 static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
21178   DosFreeModule((HMODULE)pHandle);
21179 }
21180 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
21181   #define os2DlOpen 0
21182   #define os2DlError 0
21183   #define os2DlSym 0
21184   #define os2DlClose 0
21185 #endif
21186
21187
21188 /*
21189 ** Write up to nBuf bytes of randomness into zBuf.
21190 */
21191 static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
21192   ULONG sizeofULong = sizeof(ULONG);
21193   int n = 0;
21194   if( sizeof(DATETIME) <= nBuf - n ){
21195     DATETIME x;
21196     DosGetDateTime(&x);
21197     memcpy(&zBuf[n], &x, sizeof(x));
21198     n += sizeof(x);
21199   }
21200
21201   if( sizeofULong <= nBuf - n ){
21202     PPIB ppib;
21203     DosGetInfoBlocks(NULL, &ppib);
21204     memcpy(&zBuf[n], &ppib->pib_ulpid, sizeofULong);
21205     n += sizeofULong;
21206   }
21207
21208   if( sizeofULong <= nBuf - n ){
21209     PTIB ptib;
21210     DosGetInfoBlocks(&ptib, NULL);
21211     memcpy(&zBuf[n], &ptib->tib_ptib2->tib2_ultid, sizeofULong);
21212     n += sizeofULong;
21213   }
21214
21215   /* if we still haven't filled the buffer yet the following will */
21216   /* grab everything once instead of making several calls for a single item */
21217   if( sizeofULong <= nBuf - n ){
21218     ULONG ulSysInfo[QSV_MAX];
21219     DosQuerySysInfo(1L, QSV_MAX, ulSysInfo, sizeofULong * QSV_MAX);
21220
21221     memcpy(&zBuf[n], &ulSysInfo[QSV_MS_COUNT - 1], sizeofULong);
21222     n += sizeofULong;
21223
21224     if( sizeofULong <= nBuf - n ){
21225       memcpy(&zBuf[n], &ulSysInfo[QSV_TIMER_INTERVAL - 1], sizeofULong);
21226       n += sizeofULong;
21227     }
21228     if( sizeofULong <= nBuf - n ){
21229       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_LOW - 1], sizeofULong);
21230       n += sizeofULong;
21231     }
21232     if( sizeofULong <= nBuf - n ){
21233       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_HIGH - 1], sizeofULong);
21234       n += sizeofULong;
21235     }
21236     if( sizeofULong <= nBuf - n ){
21237       memcpy(&zBuf[n], &ulSysInfo[QSV_TOTAVAILMEM - 1], sizeofULong);
21238       n += sizeofULong;
21239     }
21240   }
21241
21242   return n;
21243 }
21244
21245 /*
21246 ** Sleep for a little while.  Return the amount of time slept.
21247 ** The argument is the number of microseconds we want to sleep.
21248 ** The return value is the number of microseconds of sleep actually
21249 ** requested from the underlying operating system, a number which
21250 ** might be greater than or equal to the argument, but not less
21251 ** than the argument.
21252 */
21253 static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
21254   DosSleep( (microsec/1000) );
21255   return microsec;
21256 }
21257
21258 /*
21259 ** The following variable, if set to a non-zero value, becomes the result
21260 ** returned from sqlite3OsCurrentTime().  This is used for testing.
21261 */
21262 #ifdef SQLITE_TEST
21263 SQLITE_API int sqlite3_current_time = 0;
21264 #endif
21265
21266 /*
21267 ** Find the current time (in Universal Coordinated Time).  Write the
21268 ** current time and date as a Julian Day number into *prNow and
21269 ** return 0.  Return 1 if the time and date cannot be found.
21270 */
21271 int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
21272   double now;
21273   SHORT minute; /* needs to be able to cope with negative timezone offset */
21274   USHORT second, hour,
21275          day, month, year;
21276   DATETIME dt;
21277   DosGetDateTime( &dt );
21278   second = (USHORT)dt.seconds;
21279   minute = (SHORT)dt.minutes + dt.timezone;
21280   hour = (USHORT)dt.hours;
21281   day = (USHORT)dt.day;
21282   month = (USHORT)dt.month;
21283   year = (USHORT)dt.year;
21284
21285   /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
21286      http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c */
21287   /* Calculate the Julian days */
21288   now = day - 32076 +
21289     1461*(year + 4800 + (month - 14)/12)/4 +
21290     367*(month - 2 - (month - 14)/12*12)/12 -
21291     3*((year + 4900 + (month - 14)/12)/100)/4;
21292
21293   /* Add the fractional hours, mins and seconds */
21294   now += (hour + 12.0)/24.0;
21295   now += minute/1440.0;
21296   now += second/86400.0;
21297   *prNow = now;
21298 #ifdef SQLITE_TEST
21299   if( sqlite3_current_time ){
21300     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
21301   }
21302 #endif
21303   return 0;
21304 }
21305
21306 static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
21307   return 0;
21308 }
21309
21310 /*
21311 ** Initialize and deinitialize the operating system interface.
21312 */
21313 SQLITE_API int sqlite3_os_init(void){
21314   static sqlite3_vfs os2Vfs = {
21315     1,                 /* iVersion */
21316     sizeof(os2File),   /* szOsFile */
21317     CCHMAXPATH,        /* mxPathname */
21318     0,                 /* pNext */
21319     "os2",             /* zName */
21320     0,                 /* pAppData */
21321
21322     os2Open,           /* xOpen */
21323     os2Delete,         /* xDelete */
21324     os2Access,         /* xAccess */
21325     os2FullPathname,   /* xFullPathname */
21326     os2DlOpen,         /* xDlOpen */
21327     os2DlError,        /* xDlError */
21328     os2DlSym,          /* xDlSym */
21329     os2DlClose,        /* xDlClose */
21330     os2Randomness,     /* xRandomness */
21331     os2Sleep,          /* xSleep */
21332     os2CurrentTime,    /* xCurrentTime */
21333     os2GetLastError    /* xGetLastError */
21334   };
21335   sqlite3_vfs_register(&os2Vfs, 1);
21336   initUconvObjects();
21337   return SQLITE_OK;
21338 }
21339 SQLITE_API int sqlite3_os_end(void){
21340   freeUconvObjects();
21341   return SQLITE_OK;
21342 }
21343
21344 #endif /* SQLITE_OS_OS2 */
21345
21346 /************** End of os_os2.c **********************************************/
21347 /************** Begin file os_unix.c *****************************************/
21348 /*
21349 ** 2004 May 22
21350 **
21351 ** The author disclaims copyright to this source code.  In place of
21352 ** a legal notice, here is a blessing:
21353 **
21354 **    May you do good and not evil.
21355 **    May you find forgiveness for yourself and forgive others.
21356 **    May you share freely, never taking more than you give.
21357 **
21358 ******************************************************************************
21359 **
21360 ** This file contains code that is specific to Unix systems.
21361 **
21362 ** $Id: os_unix.c,v 1.216 2008/11/19 16:52:44 danielk1977 Exp $
21363 */
21364 #if SQLITE_OS_UNIX              /* This file is used on unix only */
21365
21366 /*
21367 ** If SQLITE_ENABLE_LOCKING_STYLE is defined and is non-zero, then several
21368 ** alternative locking implementations are provided:
21369 **
21370 **   * POSIX locking (the default),
21371 **   * No locking,
21372 **   * Dot-file locking,
21373 **   * flock() locking,
21374 **   * AFP locking (OSX only),
21375 **   * Named POSIX semaphores (VXWorks only).
21376 **
21377 ** SQLITE_ENABLE_LOCKING_STYLE only works on a Mac. It is turned on by
21378 ** default on a Mac and disabled on all other posix platforms.
21379 */
21380 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
21381 #  if defined(__DARWIN__)
21382 #    define SQLITE_ENABLE_LOCKING_STYLE 1
21383 #  else
21384 #    define SQLITE_ENABLE_LOCKING_STYLE 0
21385 #  endif
21386 #endif
21387
21388 /*
21389 ** Define the IS_VXWORKS pre-processor macro to 1 if building on 
21390 ** vxworks, or 0 otherwise.
21391 */
21392 #if defined(__RTP__) || defined(_WRS_KERNEL)
21393 #  define IS_VXWORKS 1
21394 #else
21395 #  define IS_VXWORKS 0
21396 #endif
21397
21398 /*
21399 ** These #defines should enable >2GB file support on Posix if the
21400 ** underlying operating system supports it.  If the OS lacks
21401 ** large file support, these should be no-ops.
21402 **
21403 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
21404 ** on the compiler command line.  This is necessary if you are compiling
21405 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
21406 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
21407 ** without this option, LFS is enable.  But LFS does not exist in the kernel
21408 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
21409 ** portability you should omit LFS.
21410 */
21411 #ifndef SQLITE_DISABLE_LFS
21412 # define _LARGE_FILE       1
21413 # ifndef _FILE_OFFSET_BITS
21414 #   define _FILE_OFFSET_BITS 64
21415 # endif
21416 # define _LARGEFILE_SOURCE 1
21417 #endif
21418
21419 /*
21420 ** standard include files.
21421 */
21422 #include <sys/types.h>
21423 #include <sys/stat.h>
21424 #include <fcntl.h>
21425 #include <unistd.h>
21426 #include <sys/time.h>
21427 #include <errno.h>
21428
21429 #if SQLITE_ENABLE_LOCKING_STYLE
21430 # include <sys/ioctl.h>
21431 # if IS_VXWORKS
21432 #  define lstat stat
21433 #  include <semaphore.h>
21434 #  include <limits.h>
21435 # else
21436 #  include <sys/param.h>
21437 #  include <sys/mount.h>
21438 # endif
21439 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
21440
21441 /*
21442 ** If we are to be thread-safe, include the pthreads header and define
21443 ** the SQLITE_UNIX_THREADS macro.
21444 */
21445 #if SQLITE_THREADSAFE
21446 # define SQLITE_UNIX_THREADS 1
21447 #endif
21448
21449 /*
21450 ** Default permissions when creating a new file
21451 */
21452 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
21453 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
21454 #endif
21455
21456 /*
21457 ** Maximum supported path-length.
21458 */
21459 #define MAX_PATHNAME 512
21460
21461
21462 /*
21463 ** The unixFile structure is subclass of sqlite3_file specific for the unix
21464 ** protability layer.
21465 */
21466 typedef struct unixFile unixFile;
21467 struct unixFile {
21468   sqlite3_io_methods const *pMethod;  /* Always the first entry */
21469 #ifdef SQLITE_TEST
21470   /* In test mode, increase the size of this structure a bit so that 
21471   ** it is larger than the struct CrashFile defined in test6.c.
21472   */
21473   char aPadding[32];
21474 #endif
21475   struct openCnt *pOpen;    /* Info about all open fd's on this inode */
21476   struct lockInfo *pLock;   /* Info about locks on this inode */
21477 #if SQLITE_ENABLE_LOCKING_STYLE
21478   void *lockingContext;     /* Locking style specific state */
21479 #endif
21480   int h;                    /* The file descriptor */
21481   unsigned char locktype;   /* The type of lock held on this fd */
21482   int dirfd;                /* File descriptor for the directory */
21483 #if SQLITE_THREADSAFE
21484   pthread_t tid;            /* The thread that "owns" this unixFile */
21485 #endif
21486   int lastErrno;            /* The unix errno from the last I/O error */
21487 #if IS_VXWORKS
21488   int isDelete;             /* Delete on close if true */
21489   char *zRealpath;
21490 #endif
21491 };
21492
21493 /*
21494 ** Include code that is common to all os_*.c files
21495 */
21496 /************** Include os_common.h in the middle of os_unix.c ***************/
21497 /************** Begin file os_common.h ***************************************/
21498 /*
21499 ** 2004 May 22
21500 **
21501 ** The author disclaims copyright to this source code.  In place of
21502 ** a legal notice, here is a blessing:
21503 **
21504 **    May you do good and not evil.
21505 **    May you find forgiveness for yourself and forgive others.
21506 **    May you share freely, never taking more than you give.
21507 **
21508 ******************************************************************************
21509 **
21510 ** This file contains macros and a little bit of code that is common to
21511 ** all of the platform-specific files (os_*.c) and is #included into those
21512 ** files.
21513 **
21514 ** This file should be #included by the os_*.c files only.  It is not a
21515 ** general purpose header file.
21516 **
21517 ** $Id: os_common.h,v 1.37 2008/05/29 20:22:37 shane Exp $
21518 */
21519 #ifndef _OS_COMMON_H_
21520 #define _OS_COMMON_H_
21521
21522 /*
21523 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
21524 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
21525 ** switch.  The following code should catch this problem at compile-time.
21526 */
21527 #ifdef MEMORY_DEBUG
21528 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
21529 #endif
21530
21531
21532 /*
21533  * When testing, this global variable stores the location of the
21534  * pending-byte in the database file.
21535  */
21536 #ifdef SQLITE_TEST
21537 SQLITE_API unsigned int sqlite3_pending_byte = 0x40000000;
21538 #endif
21539
21540 #ifdef SQLITE_DEBUG
21541 SQLITE_PRIVATE int sqlite3OSTrace = 0;
21542 #define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
21543 #define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
21544 #define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
21545 #define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
21546 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
21547 #define OSTRACE6(X,Y,Z,A,B,C) \
21548     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
21549 #define OSTRACE7(X,Y,Z,A,B,C,D) \
21550     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
21551 #else
21552 #define OSTRACE1(X)
21553 #define OSTRACE2(X,Y)
21554 #define OSTRACE3(X,Y,Z)
21555 #define OSTRACE4(X,Y,Z,A)
21556 #define OSTRACE5(X,Y,Z,A,B)
21557 #define OSTRACE6(X,Y,Z,A,B,C)
21558 #define OSTRACE7(X,Y,Z,A,B,C,D)
21559 #endif
21560
21561 /*
21562 ** Macros for performance tracing.  Normally turned off.  Only works
21563 ** on i486 hardware.
21564 */
21565 #ifdef SQLITE_PERFORMANCE_TRACE
21566
21567 /* 
21568 ** hwtime.h contains inline assembler code for implementing 
21569 ** high-performance timing routines.
21570 */
21571 /************** Include hwtime.h in the middle of os_common.h ****************/
21572 /************** Begin file hwtime.h ******************************************/
21573 /*
21574 ** 2008 May 27
21575 **
21576 ** The author disclaims copyright to this source code.  In place of
21577 ** a legal notice, here is a blessing:
21578 **
21579 **    May you do good and not evil.
21580 **    May you find forgiveness for yourself and forgive others.
21581 **    May you share freely, never taking more than you give.
21582 **
21583 ******************************************************************************
21584 **
21585 ** This file contains inline asm code for retrieving "high-performance"
21586 ** counters for x86 class CPUs.
21587 **
21588 ** $Id: hwtime.h,v 1.3 2008/08/01 14:33:15 shane Exp $
21589 */
21590 #ifndef _HWTIME_H_
21591 #define _HWTIME_H_
21592
21593 /*
21594 ** The following routine only works on pentium-class (or newer) processors.
21595 ** It uses the RDTSC opcode to read the cycle count value out of the
21596 ** processor and returns that value.  This can be used for high-res
21597 ** profiling.
21598 */
21599 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
21600       (defined(i386) || defined(__i386__) || defined(_M_IX86))
21601
21602   #if defined(__GNUC__)
21603
21604   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21605      unsigned int lo, hi;
21606      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
21607      return (sqlite_uint64)hi << 32 | lo;
21608   }
21609
21610   #elif defined(_MSC_VER)
21611
21612   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
21613      __asm {
21614         rdtsc
21615         ret       ; return value at EDX:EAX
21616      }
21617   }
21618
21619   #endif
21620
21621 #elif (defined(__GNUC__) && defined(__x86_64__))
21622
21623   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21624       unsigned long val;
21625       __asm__ __volatile__ ("rdtsc" : "=A" (val));
21626       return val;
21627   }
21628  
21629 #elif (defined(__GNUC__) && defined(__ppc__))
21630
21631   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21632       unsigned long long retval;
21633       unsigned long junk;
21634       __asm__ __volatile__ ("\n\
21635           1:      mftbu   %1\n\
21636                   mftb    %L0\n\
21637                   mftbu   %0\n\
21638                   cmpw    %0,%1\n\
21639                   bne     1b"
21640                   : "=r" (retval), "=r" (junk));
21641       return retval;
21642   }
21643
21644 #else
21645
21646   #error Need implementation of sqlite3Hwtime() for your platform.
21647
21648   /*
21649   ** To compile without implementing sqlite3Hwtime() for your platform,
21650   ** you can remove the above #error and use the following
21651   ** stub function.  You will lose timing support for many
21652   ** of the debugging and testing utilities, but it should at
21653   ** least compile and run.
21654   */
21655 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
21656
21657 #endif
21658
21659 #endif /* !defined(_HWTIME_H_) */
21660
21661 /************** End of hwtime.h **********************************************/
21662 /************** Continuing where we left off in os_common.h ******************/
21663
21664 static sqlite_uint64 g_start;
21665 static sqlite_uint64 g_elapsed;
21666 #define TIMER_START       g_start=sqlite3Hwtime()
21667 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
21668 #define TIMER_ELAPSED     g_elapsed
21669 #else
21670 #define TIMER_START
21671 #define TIMER_END
21672 #define TIMER_ELAPSED     ((sqlite_uint64)0)
21673 #endif
21674
21675 /*
21676 ** If we compile with the SQLITE_TEST macro set, then the following block
21677 ** of code will give us the ability to simulate a disk I/O error.  This
21678 ** is used for testing the I/O recovery logic.
21679 */
21680 #ifdef SQLITE_TEST
21681 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
21682 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
21683 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
21684 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
21685 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
21686 SQLITE_API int sqlite3_diskfull_pending = 0;
21687 SQLITE_API int sqlite3_diskfull = 0;
21688 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
21689 #define SimulateIOError(CODE)  \
21690   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
21691        || sqlite3_io_error_pending-- == 1 )  \
21692               { local_ioerr(); CODE; }
21693 static void local_ioerr(){
21694   IOTRACE(("IOERR\n"));
21695   sqlite3_io_error_hit++;
21696   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
21697 }
21698 #define SimulateDiskfullError(CODE) \
21699    if( sqlite3_diskfull_pending ){ \
21700      if( sqlite3_diskfull_pending == 1 ){ \
21701        local_ioerr(); \
21702        sqlite3_diskfull = 1; \
21703        sqlite3_io_error_hit = 1; \
21704        CODE; \
21705      }else{ \
21706        sqlite3_diskfull_pending--; \
21707      } \
21708    }
21709 #else
21710 #define SimulateIOErrorBenign(X)
21711 #define SimulateIOError(A)
21712 #define SimulateDiskfullError(A)
21713 #endif
21714
21715 /*
21716 ** When testing, keep a count of the number of open files.
21717 */
21718 #ifdef SQLITE_TEST
21719 SQLITE_API int sqlite3_open_file_count = 0;
21720 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
21721 #else
21722 #define OpenCounter(X)
21723 #endif
21724
21725 #endif /* !defined(_OS_COMMON_H_) */
21726
21727 /************** End of os_common.h *******************************************/
21728 /************** Continuing where we left off in os_unix.c ********************/
21729
21730 /*
21731 ** Define various macros that are missing from some systems.
21732 */
21733 #ifndef O_LARGEFILE
21734 # define O_LARGEFILE 0
21735 #endif
21736 #ifdef SQLITE_DISABLE_LFS
21737 # undef O_LARGEFILE
21738 # define O_LARGEFILE 0
21739 #endif
21740 #ifndef O_NOFOLLOW
21741 # define O_NOFOLLOW 0
21742 #endif
21743 #ifndef O_BINARY
21744 # define O_BINARY 0
21745 #endif
21746
21747 /*
21748 ** The DJGPP compiler environment looks mostly like Unix, but it
21749 ** lacks the fcntl() system call.  So redefine fcntl() to be something
21750 ** that always succeeds.  This means that locking does not occur under
21751 ** DJGPP.  But it is DOS - what did you expect?
21752 */
21753 #ifdef __DJGPP__
21754 # define fcntl(A,B,C) 0
21755 #endif
21756
21757 /*
21758 ** The threadid macro resolves to the thread-id or to 0.  Used for
21759 ** testing and debugging only.
21760 */
21761 #if SQLITE_THREADSAFE
21762 #define threadid pthread_self()
21763 #else
21764 #define threadid 0
21765 #endif
21766
21767 /*
21768 ** Set or check the unixFile.tid field.  This field is set when an unixFile
21769 ** is first opened.  All subsequent uses of the unixFile verify that the
21770 ** same thread is operating on the unixFile.  Some operating systems do
21771 ** not allow locks to be overridden by other threads and that restriction
21772 ** means that sqlite3* database handles cannot be moved from one thread
21773 ** to another.  This logic makes sure a user does not try to do that
21774 ** by mistake.
21775 **
21776 ** Version 3.3.1 (2006-01-15):  unixFile can be moved from one thread to
21777 ** another as long as we are running on a system that supports threads
21778 ** overriding each others locks (which now the most common behavior)
21779 ** or if no locks are held.  But the unixFile.pLock field needs to be
21780 ** recomputed because its key includes the thread-id.  See the 
21781 ** transferOwnership() function below for additional information
21782 */
21783 #if SQLITE_THREADSAFE
21784 # define SET_THREADID(X)   (X)->tid = pthread_self()
21785 # define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
21786                             !pthread_equal((X)->tid, pthread_self()))
21787 #else
21788 # define SET_THREADID(X)
21789 # define CHECK_THREADID(X) 0
21790 #endif
21791
21792 /*
21793 ** Here is the dirt on POSIX advisory locks:  ANSI STD 1003.1 (1996)
21794 ** section 6.5.2.2 lines 483 through 490 specify that when a process
21795 ** sets or clears a lock, that operation overrides any prior locks set
21796 ** by the same process.  It does not explicitly say so, but this implies
21797 ** that it overrides locks set by the same process using a different
21798 ** file descriptor.  Consider this test case:
21799 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
21800 **
21801 ** Suppose ./file1 and ./file2 are really the same file (because
21802 ** one is a hard or symbolic link to the other) then if you set
21803 ** an exclusive lock on fd1, then try to get an exclusive lock
21804 ** on fd2, it works.  I would have expected the second lock to
21805 ** fail since there was already a lock on the file due to fd1.
21806 ** But not so.  Since both locks came from the same process, the
21807 ** second overrides the first, even though they were on different
21808 ** file descriptors opened on different file names.
21809 **
21810 ** Bummer.  If you ask me, this is broken.  Badly broken.  It means
21811 ** that we cannot use POSIX locks to synchronize file access among
21812 ** competing threads of the same process.  POSIX locks will work fine
21813 ** to synchronize access for threads in separate processes, but not
21814 ** threads within the same process.
21815 **
21816 ** To work around the problem, SQLite has to manage file locks internally
21817 ** on its own.  Whenever a new database is opened, we have to find the
21818 ** specific inode of the database file (the inode is determined by the
21819 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
21820 ** and check for locks already existing on that inode.  When locks are
21821 ** created or removed, we have to look at our own internal record of the
21822 ** locks to see if another thread has previously set a lock on that same
21823 ** inode.
21824 **
21825 ** The sqlite3_file structure for POSIX is no longer just an integer file
21826 ** descriptor.  It is now a structure that holds the integer file
21827 ** descriptor and a pointer to a structure that describes the internal
21828 ** locks on the corresponding inode.  There is one locking structure
21829 ** per inode, so if the same inode is opened twice, both unixFile structures
21830 ** point to the same locking structure.  The locking structure keeps
21831 ** a reference count (so we will know when to delete it) and a "cnt"
21832 ** field that tells us its internal lock status.  cnt==0 means the
21833 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
21834 ** cnt>0 means there are cnt shared locks on the file.
21835 **
21836 ** Any attempt to lock or unlock a file first checks the locking
21837 ** structure.  The fcntl() system call is only invoked to set a 
21838 ** POSIX lock if the internal lock structure transitions between
21839 ** a locked and an unlocked state.
21840 **
21841 ** 2004-Jan-11:
21842 ** More recent discoveries about POSIX advisory locks.  (The more
21843 ** I discover, the more I realize the a POSIX advisory locks are
21844 ** an abomination.)
21845 **
21846 ** If you close a file descriptor that points to a file that has locks,
21847 ** all locks on that file that are owned by the current process are
21848 ** released.  To work around this problem, each unixFile structure contains
21849 ** a pointer to an openCnt structure.  There is one openCnt structure
21850 ** per open inode, which means that multiple unixFile can point to a single
21851 ** openCnt.  When an attempt is made to close an unixFile, if there are
21852 ** other unixFile open on the same inode that are holding locks, the call
21853 ** to close() the file descriptor is deferred until all of the locks clear.
21854 ** The openCnt structure keeps a list of file descriptors that need to
21855 ** be closed and that list is walked (and cleared) when the last lock
21856 ** clears.
21857 **
21858 ** First, under Linux threads, because each thread has a separate
21859 ** process ID, lock operations in one thread do not override locks
21860 ** to the same file in other threads.  Linux threads behave like
21861 ** separate processes in this respect.  But, if you close a file
21862 ** descriptor in linux threads, all locks are cleared, even locks
21863 ** on other threads and even though the other threads have different
21864 ** process IDs.  Linux threads is inconsistent in this respect.
21865 ** (I'm beginning to think that linux threads is an abomination too.)
21866 ** The consequence of this all is that the hash table for the lockInfo
21867 ** structure has to include the process id as part of its key because
21868 ** locks in different threads are treated as distinct.  But the 
21869 ** openCnt structure should not include the process id in its
21870 ** key because close() clears lock on all threads, not just the current
21871 ** thread.  Were it not for this goofiness in linux threads, we could
21872 ** combine the lockInfo and openCnt structures into a single structure.
21873 **
21874 ** 2004-Jun-28:
21875 ** On some versions of linux, threads can override each others locks.
21876 ** On others not.  Sometimes you can change the behavior on the same
21877 ** system by setting the LD_ASSUME_KERNEL environment variable.  The
21878 ** POSIX standard is silent as to which behavior is correct, as far
21879 ** as I can tell, so other versions of unix might show the same
21880 ** inconsistency.  There is no little doubt in my mind that posix
21881 ** advisory locks and linux threads are profoundly broken.
21882 **
21883 ** To work around the inconsistencies, we have to test at runtime 
21884 ** whether or not threads can override each others locks.  This test
21885 ** is run once, the first time any lock is attempted.  A static 
21886 ** variable is set to record the results of this test for future
21887 ** use.
21888 */
21889
21890 /*
21891 ** An instance of the following structure serves as the key used
21892 ** to locate a particular lockInfo structure given its inode.
21893 **
21894 ** If threads cannot override each others locks, then we set the
21895 ** lockKey.tid field to the thread ID.  If threads can override
21896 ** each others locks then tid is always set to zero.  tid is omitted
21897 ** if we compile without threading support.
21898 */
21899 struct lockKey {
21900   dev_t dev;       /* Device number */
21901 #if IS_VXWORKS
21902   void *rnam;      /* Realname since inode unusable */
21903 #else
21904   ino_t ino;       /* Inode number */
21905 #endif
21906 #if SQLITE_THREADSAFE
21907   pthread_t tid;   /* Thread ID or zero if threads can override each other */
21908 #endif
21909 };
21910
21911 /*
21912 ** An instance of the following structure is allocated for each open
21913 ** inode on each thread with a different process ID.  (Threads have
21914 ** different process IDs on linux, but not on most other unixes.)
21915 **
21916 ** A single inode can have multiple file descriptors, so each unixFile
21917 ** structure contains a pointer to an instance of this object and this
21918 ** object keeps a count of the number of unixFile pointing to it.
21919 */
21920 struct lockInfo {
21921   struct lockKey key;  /* The lookup key */
21922   int cnt;             /* Number of SHARED locks held */
21923   int locktype;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
21924   int nRef;            /* Number of pointers to this structure */
21925   struct lockInfo *pNext, *pPrev;   /* List of all lockInfo objects */
21926 };
21927
21928 /*
21929 ** An instance of the following structure serves as the key used
21930 ** to locate a particular openCnt structure given its inode.  This
21931 ** is the same as the lockKey except that the thread ID is omitted.
21932 */
21933 struct openKey {
21934   dev_t dev;   /* Device number */
21935 #if IS_VXWORKS
21936   void *rnam;  /* Realname since inode unusable */
21937 #else
21938   ino_t ino;   /* Inode number */
21939 #endif
21940 };
21941
21942 /*
21943 ** An instance of the following structure is allocated for each open
21944 ** inode.  This structure keeps track of the number of locks on that
21945 ** inode.  If a close is attempted against an inode that is holding
21946 ** locks, the close is deferred until all locks clear by adding the
21947 ** file descriptor to be closed to the pending list.
21948 */
21949 struct openCnt {
21950   struct openKey key;   /* The lookup key */
21951   int nRef;             /* Number of pointers to this structure */
21952   int nLock;            /* Number of outstanding locks */
21953   int nPending;         /* Number of pending close() operations */
21954   int *aPending;        /* Malloced space holding fd's awaiting a close() */
21955 #if IS_VXWORKS
21956   sem_t *pSem;          /* Named POSIX semaphore */
21957   char aSemName[MAX_PATHNAME+1];   /* Name of that semaphore */
21958 #endif
21959   struct openCnt *pNext, *pPrev;   /* List of all openCnt objects */
21960 };
21961
21962 /*
21963 ** List of all lockInfo and openCnt objects.  This used to be a hash
21964 ** table.  But the number of objects is rarely more than a dozen and
21965 ** never exceeds a few thousand.  And lookup is not on a critical
21966 ** path oo a simple linked list will suffice.
21967 */
21968 static struct lockInfo *lockList = 0;
21969 static struct openCnt *openList = 0;
21970
21971 #if IS_VXWORKS
21972 /*
21973 ** This hash table is used to bind the canonical file name to a
21974 ** unixFile structure and use the hash key (= canonical name)
21975 ** instead of the Inode number of the file to find the matching
21976 ** lockInfo and openCnt structures. It also helps to make the
21977 ** name of the semaphore when LOCKING_STYLE_NAMEDSEM is used
21978 ** for the file.
21979 */
21980 static Hash nameHash;
21981 #endif
21982
21983 /*
21984 ** The locking styles are associated with the different file locking
21985 ** capabilities supported by different file systems.  
21986 **
21987 ** POSIX locking style fully supports shared and exclusive byte-range locks 
21988 ** AFP locking only supports exclusive byte-range locks
21989 ** FLOCK only supports a single file-global exclusive lock
21990 ** DOTLOCK isn't a true locking style, it refers to the use of a special
21991 **   file named the same as the database file with a '.lock' extension, this
21992 **   can be used on file systems that do not offer any reliable file locking
21993 ** NO locking means that no locking will be attempted, this is only used for
21994 **   read-only file systems currently
21995 ** NAMEDSEM is similar to DOTLOCK but uses a named semaphore instead of an
21996 **   indicator file.
21997 ** UNSUPPORTED means that no locking will be attempted, this is only used for
21998 **   file systems that are known to be unsupported
21999 */
22000 #define LOCKING_STYLE_POSIX        1
22001 #define LOCKING_STYLE_NONE         2
22002 #define LOCKING_STYLE_DOTFILE      3
22003 #define LOCKING_STYLE_FLOCK        4
22004 #define LOCKING_STYLE_AFP          5
22005 #define LOCKING_STYLE_NAMEDSEM     6
22006
22007 /*
22008 ** Only set the lastErrno if the error code is a real error and not 
22009 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
22010 */
22011 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
22012
22013 /*
22014 ** Helper functions to obtain and relinquish the global mutex.
22015 */
22016 static void enterMutex(void){
22017   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22018 }
22019 static void leaveMutex(void){
22020   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22021 }
22022
22023 #if SQLITE_THREADSAFE
22024 /*
22025 ** This variable records whether or not threads can override each others
22026 ** locks.
22027 **
22028 **    0:  No.  Threads cannot override each others locks.
22029 **    1:  Yes.  Threads can override each others locks.
22030 **   -1:  We don't know yet.
22031 **
22032 ** On some systems, we know at compile-time if threads can override each
22033 ** others locks.  On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
22034 ** will be set appropriately.  On other systems, we have to check at
22035 ** runtime.  On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
22036 ** undefined.
22037 **
22038 ** This variable normally has file scope only.  But during testing, we make
22039 ** it a global so that the test code can change its value in order to verify
22040 ** that the right stuff happens in either case.
22041 */
22042 #ifndef SQLITE_THREAD_OVERRIDE_LOCK
22043 # define SQLITE_THREAD_OVERRIDE_LOCK -1
22044 #endif
22045 #ifdef SQLITE_TEST
22046 int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
22047 #else
22048 static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
22049 #endif
22050
22051 /*
22052 ** This structure holds information passed into individual test
22053 ** threads by the testThreadLockingBehavior() routine.
22054 */
22055 struct threadTestData {
22056   int fd;                /* File to be locked */
22057   struct flock lock;     /* The locking operation */
22058   int result;            /* Result of the locking operation */
22059 };
22060
22061 #ifdef SQLITE_LOCK_TRACE
22062 /*
22063 ** Print out information about all locking operations.
22064 **
22065 ** This routine is used for troubleshooting locks on multithreaded
22066 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
22067 ** command-line option on the compiler.  This code is normally
22068 ** turned off.
22069 */
22070 static int lockTrace(int fd, int op, struct flock *p){
22071   char *zOpName, *zType;
22072   int s;
22073   int savedErrno;
22074   if( op==F_GETLK ){
22075     zOpName = "GETLK";
22076   }else if( op==F_SETLK ){
22077     zOpName = "SETLK";
22078   }else{
22079     s = fcntl(fd, op, p);
22080     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
22081     return s;
22082   }
22083   if( p->l_type==F_RDLCK ){
22084     zType = "RDLCK";
22085   }else if( p->l_type==F_WRLCK ){
22086     zType = "WRLCK";
22087   }else if( p->l_type==F_UNLCK ){
22088     zType = "UNLCK";
22089   }else{
22090     assert( 0 );
22091   }
22092   assert( p->l_whence==SEEK_SET );
22093   s = fcntl(fd, op, p);
22094   savedErrno = errno;
22095   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
22096      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
22097      (int)p->l_pid, s);
22098   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
22099     struct flock l2;
22100     l2 = *p;
22101     fcntl(fd, F_GETLK, &l2);
22102     if( l2.l_type==F_RDLCK ){
22103       zType = "RDLCK";
22104     }else if( l2.l_type==F_WRLCK ){
22105       zType = "WRLCK";
22106     }else if( l2.l_type==F_UNLCK ){
22107       zType = "UNLCK";
22108     }else{
22109       assert( 0 );
22110     }
22111     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
22112        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
22113   }
22114   errno = savedErrno;
22115   return s;
22116 }
22117 #define fcntl lockTrace
22118 #endif /* SQLITE_LOCK_TRACE */
22119
22120 #ifdef __linux__
22121 /*
22122 ** This function is used as the main routine for a thread launched by
22123 ** testThreadLockingBehavior(). It tests whether the shared-lock obtained
22124 ** by the main thread in testThreadLockingBehavior() conflicts with a
22125 ** hypothetical write-lock obtained by this thread on the same file.
22126 **
22127 ** The write-lock is not actually acquired, as this is not possible if 
22128 ** the file is open in read-only mode (see ticket #3472).
22129 */ 
22130 static void *threadLockingTest(void *pArg){
22131   struct threadTestData *pData = (struct threadTestData*)pArg;
22132   pData->result = fcntl(pData->fd, F_GETLK, &pData->lock);
22133   return pArg;
22134 }
22135
22136 /*
22137 ** This procedure attempts to determine whether or not threads
22138 ** can override each others locks then sets the 
22139 ** threadsOverrideEachOthersLocks variable appropriately.
22140 */
22141 static void testThreadLockingBehavior(int fd_orig){
22142   int fd;
22143   int rc;
22144   struct threadTestData d;
22145   struct flock l;
22146   pthread_t t;
22147
22148   fd = dup(fd_orig);
22149   if( fd<0 ) return;
22150   memset(&l, 0, sizeof(l));
22151   l.l_type = F_RDLCK;
22152   l.l_len = 1;
22153   l.l_start = 0;
22154   l.l_whence = SEEK_SET;
22155   rc = fcntl(fd_orig, F_SETLK, &l);
22156   if( rc!=0 ) return;
22157   memset(&d, 0, sizeof(d));
22158   d.fd = fd;
22159   d.lock = l;
22160   d.lock.l_type = F_WRLCK;
22161   pthread_create(&t, 0, threadLockingTest, &d);
22162   pthread_join(t, 0);
22163   close(fd);
22164   if( d.result!=0 ) return;
22165   threadsOverrideEachOthersLocks = (d.lock.l_type==F_UNLCK);
22166 }
22167 #else
22168 /*
22169 ** On anything other than linux, assume threads override each others locks.
22170 */
22171 static void testThreadLockingBehavior(int fd_orig){
22172   threadsOverrideEachOthersLocks = 1;
22173 }
22174 #endif /* __linux__ */
22175
22176 #endif /* SQLITE_THREADSAFE */
22177
22178 /*
22179 ** Release a lockInfo structure previously allocated by findLockInfo().
22180 */
22181 static void releaseLockInfo(struct lockInfo *pLock){
22182   if( pLock ){
22183     pLock->nRef--;
22184     if( pLock->nRef==0 ){
22185       if( pLock->pPrev ){
22186         assert( pLock->pPrev->pNext==pLock );
22187         pLock->pPrev->pNext = pLock->pNext;
22188       }else{
22189         assert( lockList==pLock );
22190         lockList = pLock->pNext;
22191       }
22192       if( pLock->pNext ){
22193         assert( pLock->pNext->pPrev==pLock );
22194         pLock->pNext->pPrev = pLock->pPrev;
22195       }
22196       sqlite3_free(pLock);
22197     }
22198   }
22199 }
22200
22201 /*
22202 ** Release a openCnt structure previously allocated by findLockInfo().
22203 */
22204 static void releaseOpenCnt(struct openCnt *pOpen){
22205   if( pOpen ){
22206     pOpen->nRef--;
22207     if( pOpen->nRef==0 ){
22208       if( pOpen->pPrev ){
22209         assert( pOpen->pPrev->pNext==pOpen );
22210         pOpen->pPrev->pNext = pOpen->pNext;
22211       }else{
22212         assert( openList==pOpen );
22213         openList = pOpen->pNext;
22214       }
22215       if( pOpen->pNext ){
22216         assert( pOpen->pNext->pPrev==pOpen );
22217         pOpen->pNext->pPrev = pOpen->pPrev;
22218       }
22219       sqlite3_free(pOpen->aPending);
22220       sqlite3_free(pOpen);
22221     }
22222   }
22223 }
22224
22225 #if IS_VXWORKS
22226 /*
22227 ** Implementation of a realpath() like function for vxWorks
22228 ** to determine canonical path name from given name. It does
22229 ** not support symlinks. Neither does it handle volume prefixes.
22230 */
22231 char *
22232 vxrealpath(const char *pathname, int dostat)
22233 {
22234   struct stat sbuf;
22235   int len;
22236   char *where, *ptr, *last;
22237   char *result, *curpath, *workpath, *namebuf;
22238
22239   len = pathconf(pathname, _PC_PATH_MAX);
22240   if( len<0 ){
22241     len = PATH_MAX;
22242   }
22243   result = sqlite3_malloc(len * 4);
22244   if( !result ){
22245     return 0;
22246   }
22247   curpath = result + len;
22248   workpath = curpath + len;
22249   namebuf = workpath + len;
22250   strcpy(curpath, pathname);
22251   if( *pathname!='/' ){
22252     if( !getcwd(workpath, len) ){
22253       sqlite3_free(result);
22254       return 0;
22255     }
22256   }else{
22257     *workpath = '\0';
22258   }
22259   where = curpath;
22260   while( *where ){
22261     if( !strcmp(where, ".") ){
22262       where++;
22263       continue;
22264     }
22265     if( !strncmp(where, "./", 2) ){
22266       where += 2;
22267       continue;
22268     }
22269     if( !strncmp(where, "../", 3) ){
22270       where += 3;
22271       ptr = last = workpath;
22272       while( *ptr ){
22273         if( *ptr=='/' ){
22274           last = ptr;
22275         }
22276         ptr++;
22277       }
22278       *last = '\0';
22279       continue;
22280     }
22281     ptr = strchr(where, '/');
22282     if( !ptr ){
22283       ptr = where + strlen(where) - 1;
22284     }else{
22285       *ptr = '\0';
22286     }
22287     strcpy(namebuf, workpath);
22288     for( last = namebuf; *last; last++ ){
22289       continue;
22290     }
22291     if( *--last!='/' ){
22292       strcat(namebuf, "/");
22293     }
22294     strcat(namebuf, where);
22295     where = ++ptr;
22296     if( dostat ){
22297       if( stat(namebuf, &sbuf)==-1 ){
22298         sqlite3_free(result);
22299         return 0;
22300       }
22301       if( (sbuf.st_mode & S_IFDIR)==S_IFDIR ){
22302         strcpy(workpath, namebuf);
22303         continue;
22304       }
22305       if( *where ){
22306         sqlite3_free(result);
22307         return 0;
22308       }
22309     }
22310     strcpy(workpath, namebuf);
22311   }
22312   strcpy(result, workpath);
22313   return result;
22314 }
22315 #endif
22316
22317 #if SQLITE_ENABLE_LOCKING_STYLE
22318 /*
22319 ** Tests a byte-range locking query to see if byte range locks are 
22320 ** supported, if not we fall back to dotlockLockingStyle.
22321 ** On vxWorks we fall back to namedsemLockingStyle.
22322 */
22323 static int testLockingStyle(int fd){
22324   struct flock lockInfo;
22325
22326   /* Test byte-range lock using fcntl(). If the call succeeds, 
22327   ** assume that the file-system supports POSIX style locks. 
22328   */
22329   lockInfo.l_len = 1;
22330   lockInfo.l_start = 0;
22331   lockInfo.l_whence = SEEK_SET;
22332   lockInfo.l_type = F_RDLCK;
22333   if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
22334     return LOCKING_STYLE_POSIX;
22335   }
22336   
22337   /* Testing for flock() can give false positives.  So if if the above 
22338   ** test fails, then we fall back to using dot-file style locking (or
22339   ** named-semaphore locking on vxworks).
22340   */
22341   return (IS_VXWORKS ? LOCKING_STYLE_NAMEDSEM : LOCKING_STYLE_DOTFILE);
22342 }
22343 #endif
22344
22345 /* 
22346 ** If SQLITE_ENABLE_LOCKING_STYLE is defined, this function Examines the 
22347 ** f_fstypename entry in the statfs structure as returned by stat() for 
22348 ** the file system hosting the database file and selects  the appropriate
22349 ** locking style based on its value.  These values and assignments are 
22350 ** based on Darwin/OSX behavior and have not been thoroughly tested on 
22351 ** other systems.
22352 **
22353 ** If SQLITE_ENABLE_LOCKING_STYLE is not defined, this function always
22354 ** returns LOCKING_STYLE_POSIX.
22355 */
22356 #if SQLITE_ENABLE_LOCKING_STYLE
22357 static int detectLockingStyle(
22358   sqlite3_vfs *pVfs,
22359   const char *filePath, 
22360   int fd
22361 ){
22362 #if IS_VXWORKS
22363   if( !filePath ){
22364     return LOCKING_STYLE_NONE;
22365   }
22366   if( pVfs->pAppData ){
22367     return SQLITE_PTR_TO_INT(pVfs->pAppData);
22368   }
22369   if (access(filePath, 0) != -1){
22370     return testLockingStyle(fd);
22371   }
22372 #else
22373   struct Mapping {
22374     const char *zFilesystem;
22375     int eLockingStyle;
22376   } aMap[] = {
22377     { "hfs",    LOCKING_STYLE_POSIX },
22378     { "ufs",    LOCKING_STYLE_POSIX },
22379     { "afpfs",  LOCKING_STYLE_AFP },
22380 #ifdef SQLITE_ENABLE_AFP_LOCKING_SMB
22381     { "smbfs",  LOCKING_STYLE_AFP },
22382 #else
22383     { "smbfs",  LOCKING_STYLE_FLOCK },
22384 #endif
22385     { "msdos",  LOCKING_STYLE_DOTFILE },
22386     { "webdav", LOCKING_STYLE_NONE },
22387     { 0, 0 }
22388   };
22389   int i;
22390   struct statfs fsInfo;
22391
22392   if( !filePath ){
22393     return LOCKING_STYLE_NONE;
22394   }
22395   if( pVfs->pAppData ){
22396     return SQLITE_PTR_TO_INT(pVfs->pAppData);
22397   }
22398
22399   if( statfs(filePath, &fsInfo) != -1 ){
22400     if( fsInfo.f_flags & MNT_RDONLY ){
22401       return LOCKING_STYLE_NONE;
22402     }
22403     for(i=0; aMap[i].zFilesystem; i++){
22404       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
22405         return aMap[i].eLockingStyle;
22406       }
22407     }
22408   }
22409
22410   /* Default case. Handles, amongst others, "nfs". */
22411   return testLockingStyle(fd);  
22412 #endif /* if IS_VXWORKS */
22413   return LOCKING_STYLE_POSIX;
22414 }
22415 #else
22416   #define detectLockingStyle(x,y,z) LOCKING_STYLE_POSIX
22417 #endif /* ifdef SQLITE_ENABLE_LOCKING_STYLE */
22418
22419 /*
22420 ** Given a file descriptor, locate lockInfo and openCnt structures that
22421 ** describes that file descriptor.  Create new ones if necessary.  The
22422 ** return values might be uninitialized if an error occurs.
22423 **
22424 ** Return an appropriate error code.
22425 */
22426 static int findLockInfo(
22427   int fd,                      /* The file descriptor used in the key */
22428 #if IS_VXWORKS
22429   void *rnam,                  /* vxWorks realname */
22430 #endif
22431   struct lockInfo **ppLock,    /* Return the lockInfo structure here */
22432   struct openCnt **ppOpen      /* Return the openCnt structure here */
22433 ){
22434   int rc;
22435   struct lockKey key1;
22436   struct openKey key2;
22437   struct stat statbuf;
22438   struct lockInfo *pLock;
22439   struct openCnt *pOpen;
22440   rc = fstat(fd, &statbuf);
22441   if( rc!=0 ){
22442 #ifdef EOVERFLOW
22443     if( errno==EOVERFLOW ) return SQLITE_NOLFS;
22444 #endif
22445     return SQLITE_IOERR;
22446   }
22447
22448   /* On OS X on an msdos filesystem, the inode number is reported
22449   ** incorrectly for zero-size files.  See ticket #3260.  To work
22450   ** around this problem (we consider it a bug in OS X, not SQLite)
22451   ** we always increase the file size to 1 by writing a single byte
22452   ** prior to accessing the inode number.  The one byte written is
22453   ** an ASCII 'S' character which also happens to be the first byte
22454   ** in the header of every SQLite database.  In this way, if there
22455   ** is a race condition such that another thread has already populated
22456   ** the first page of the database, no damage is done.
22457   */
22458   if( statbuf.st_size==0 ){
22459     write(fd, "S", 1);
22460     rc = fstat(fd, &statbuf);
22461     if( rc!=0 ){
22462       return SQLITE_IOERR;
22463     }
22464   }
22465
22466   memset(&key1, 0, sizeof(key1));
22467   key1.dev = statbuf.st_dev;
22468 #if IS_VXWORKS
22469   key1.rnam = rnam;
22470 #else
22471   key1.ino = statbuf.st_ino;
22472 #endif
22473 #if SQLITE_THREADSAFE
22474   if( threadsOverrideEachOthersLocks<0 ){
22475     testThreadLockingBehavior(fd);
22476   }
22477   key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
22478 #endif
22479   memset(&key2, 0, sizeof(key2));
22480   key2.dev = statbuf.st_dev;
22481 #if IS_VXWORKS
22482   key2.rnam = rnam;
22483 #else
22484   key2.ino = statbuf.st_ino;
22485 #endif
22486   pLock = lockList;
22487   while( pLock && memcmp(&key1, &pLock->key, sizeof(key1)) ){
22488     pLock = pLock->pNext;
22489   }
22490   if( pLock==0 ){
22491     pLock = sqlite3_malloc( sizeof(*pLock) );
22492     if( pLock==0 ){
22493       rc = SQLITE_NOMEM;
22494       goto exit_findlockinfo;
22495     }
22496     pLock->key = key1;
22497     pLock->nRef = 1;
22498     pLock->cnt = 0;
22499     pLock->locktype = 0;
22500     pLock->pNext = lockList;
22501     pLock->pPrev = 0;
22502     if( lockList ) lockList->pPrev = pLock;
22503     lockList = pLock;
22504   }else{
22505     pLock->nRef++;
22506   }
22507   *ppLock = pLock;
22508   if( ppOpen!=0 ){
22509     pOpen = openList;
22510     while( pOpen && memcmp(&key2, &pOpen->key, sizeof(key2)) ){
22511       pOpen = pOpen->pNext;
22512     }
22513     if( pOpen==0 ){
22514       pOpen = sqlite3_malloc( sizeof(*pOpen) );
22515       if( pOpen==0 ){
22516         releaseLockInfo(pLock);
22517         rc = SQLITE_NOMEM;
22518         goto exit_findlockinfo;
22519       }
22520       pOpen->key = key2;
22521       pOpen->nRef = 1;
22522       pOpen->nLock = 0;
22523       pOpen->nPending = 0;
22524       pOpen->aPending = 0;
22525       pOpen->pNext = openList;
22526       pOpen->pPrev = 0;
22527       if( openList ) openList->pPrev = pOpen;
22528       openList = pOpen;
22529 #if IS_VXWORKS
22530       pOpen->pSem = NULL;
22531       pOpen->aSemName[0] = '\0';
22532 #endif
22533     }else{
22534       pOpen->nRef++;
22535     }
22536     *ppOpen = pOpen;
22537   }
22538
22539 exit_findlockinfo:
22540   return rc;
22541 }
22542
22543 #ifdef SQLITE_DEBUG
22544 /*
22545 ** Helper function for printing out trace information from debugging
22546 ** binaries. This returns the string represetation of the supplied
22547 ** integer lock-type.
22548 */
22549 static const char *locktypeName(int locktype){
22550   switch( locktype ){
22551   case NO_LOCK: return "NONE";
22552   case SHARED_LOCK: return "SHARED";
22553   case RESERVED_LOCK: return "RESERVED";
22554   case PENDING_LOCK: return "PENDING";
22555   case EXCLUSIVE_LOCK: return "EXCLUSIVE";
22556   }
22557   return "ERROR";
22558 }
22559 #endif
22560
22561 /*
22562 ** If we are currently in a different thread than the thread that the
22563 ** unixFile argument belongs to, then transfer ownership of the unixFile
22564 ** over to the current thread.
22565 **
22566 ** A unixFile is only owned by a thread on systems where one thread is
22567 ** unable to override locks created by a different thread.  RedHat9 is
22568 ** an example of such a system.
22569 **
22570 ** Ownership transfer is only allowed if the unixFile is currently unlocked.
22571 ** If the unixFile is locked and an ownership is wrong, then return
22572 ** SQLITE_MISUSE.  SQLITE_OK is returned if everything works.
22573 */
22574 #if SQLITE_THREADSAFE
22575 static int transferOwnership(unixFile *pFile){
22576   int rc;
22577   pthread_t hSelf;
22578   if( threadsOverrideEachOthersLocks ){
22579     /* Ownership transfers not needed on this system */
22580     return SQLITE_OK;
22581   }
22582   hSelf = pthread_self();
22583   if( pthread_equal(pFile->tid, hSelf) ){
22584     /* We are still in the same thread */
22585     OSTRACE1("No-transfer, same thread\n");
22586     return SQLITE_OK;
22587   }
22588   if( pFile->locktype!=NO_LOCK ){
22589     /* We cannot change ownership while we are holding a lock! */
22590     return SQLITE_MISUSE;
22591   }
22592   OSTRACE4("Transfer ownership of %d from %d to %d\n",
22593             pFile->h, pFile->tid, hSelf);
22594   pFile->tid = hSelf;
22595   if (pFile->pLock != NULL) {
22596     releaseLockInfo(pFile->pLock);
22597 #if IS_VXWORKS
22598     rc = findLockInfo(pFile->h, pFile->zRealpath, &pFile->pLock, 0);
22599 #else
22600     rc = findLockInfo(pFile->h, &pFile->pLock, 0);
22601 #endif
22602     OSTRACE5("LOCK    %d is now %s(%s,%d)\n", pFile->h,
22603            locktypeName(pFile->locktype),
22604            locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
22605     return rc;
22606   } else {
22607     return SQLITE_OK;
22608   }
22609 }
22610 #else
22611   /* On single-threaded builds, ownership transfer is a no-op */
22612 # define transferOwnership(X) SQLITE_OK
22613 #endif
22614
22615 /*
22616 ** Seek to the offset passed as the second argument, then read cnt 
22617 ** bytes into pBuf. Return the number of bytes actually read.
22618 **
22619 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
22620 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
22621 ** one system to another.  Since SQLite does not define USE_PREAD
22622 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
22623 ** See tickets #2741 and #2681.
22624 */
22625 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
22626   int got;
22627   i64 newOffset;
22628   TIMER_START;
22629 #if defined(USE_PREAD)
22630   got = pread(id->h, pBuf, cnt, offset);
22631   SimulateIOError( got = -1 );
22632 #elif defined(USE_PREAD64)
22633   got = pread64(id->h, pBuf, cnt, offset);
22634   SimulateIOError( got = -1 );
22635 #else
22636   newOffset = lseek(id->h, offset, SEEK_SET);
22637   SimulateIOError( newOffset-- );
22638   if( newOffset!=offset ){
22639     return -1;
22640   }
22641   got = read(id->h, pBuf, cnt);
22642 #endif
22643   TIMER_END;
22644   OSTRACE5("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
22645   return got;
22646 }
22647
22648 /*
22649 ** Read data from a file into a buffer.  Return SQLITE_OK if all
22650 ** bytes were read successfully and SQLITE_IOERR if anything goes
22651 ** wrong.
22652 */
22653 static int unixRead(
22654   sqlite3_file *id, 
22655   void *pBuf, 
22656   int amt,
22657   sqlite3_int64 offset
22658 ){
22659   int got;
22660   assert( id );
22661   got = seekAndRead((unixFile*)id, offset, pBuf, amt);
22662   if( got==amt ){
22663     return SQLITE_OK;
22664   }else if( got<0 ){
22665     return SQLITE_IOERR_READ;
22666   }else{
22667     /* Unread parts of the buffer must be zero-filled */
22668     memset(&((char*)pBuf)[got], 0, amt-got);
22669     return SQLITE_IOERR_SHORT_READ;
22670   }
22671 }
22672
22673 /*
22674 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
22675 ** Return the number of bytes actually read.  Update the offset.
22676 */
22677 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
22678   int got;
22679   i64 newOffset;
22680   TIMER_START;
22681 #if defined(USE_PREAD)
22682   got = pwrite(id->h, pBuf, cnt, offset);
22683 #elif defined(USE_PREAD64)
22684   got = pwrite64(id->h, pBuf, cnt, offset);
22685 #else
22686   newOffset = lseek(id->h, offset, SEEK_SET);
22687   if( newOffset!=offset ){
22688     return -1;
22689   }
22690   got = write(id->h, pBuf, cnt);
22691 #endif
22692   TIMER_END;
22693   OSTRACE5("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
22694   return got;
22695 }
22696
22697
22698 /*
22699 ** Write data from a buffer into a file.  Return SQLITE_OK on success
22700 ** or some other error code on failure.
22701 */
22702 static int unixWrite(
22703   sqlite3_file *id, 
22704   const void *pBuf, 
22705   int amt,
22706   sqlite3_int64 offset 
22707 ){
22708   int wrote = 0;
22709   assert( id );
22710   assert( amt>0 );
22711   while( amt>0 && (wrote = seekAndWrite((unixFile*)id, offset, pBuf, amt))>0 ){
22712     amt -= wrote;
22713     offset += wrote;
22714     pBuf = &((char*)pBuf)[wrote];
22715   }
22716   SimulateIOError(( wrote=(-1), amt=1 ));
22717   SimulateDiskfullError(( wrote=0, amt=1 ));
22718   if( amt>0 ){
22719     if( wrote<0 ){
22720       return SQLITE_IOERR_WRITE;
22721     }else{
22722       return SQLITE_FULL;
22723     }
22724   }
22725   return SQLITE_OK;
22726 }
22727
22728 #ifdef SQLITE_TEST
22729 /*
22730 ** Count the number of fullsyncs and normal syncs.  This is used to test
22731 ** that syncs and fullsyncs are occuring at the right times.
22732 */
22733 SQLITE_API int sqlite3_sync_count = 0;
22734 SQLITE_API int sqlite3_fullsync_count = 0;
22735 #endif
22736
22737 /*
22738 ** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
22739 ** Otherwise use fsync() in its place.
22740 */
22741 #ifndef HAVE_FDATASYNC
22742 # define fdatasync fsync
22743 #endif
22744
22745 /*
22746 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
22747 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
22748 ** only available on Mac OS X.  But that could change.
22749 */
22750 #ifdef F_FULLFSYNC
22751 # define HAVE_FULLFSYNC 1
22752 #else
22753 # define HAVE_FULLFSYNC 0
22754 #endif
22755
22756
22757 /*
22758 ** The fsync() system call does not work as advertised on many
22759 ** unix systems.  The following procedure is an attempt to make
22760 ** it work better.
22761 **
22762 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
22763 ** for testing when we want to run through the test suite quickly.
22764 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
22765 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
22766 ** or power failure will likely corrupt the database file.
22767 */
22768 static int full_fsync(int fd, int fullSync, int dataOnly){
22769   int rc;
22770
22771   /* The following "ifdef/elif/else/" block has the same structure as
22772   ** the one below. It is replicated here solely to avoid cluttering 
22773   ** up the real code with the UNUSED_PARAMETER() macros.
22774   */
22775 #ifdef SQLITE_NO_SYNC
22776   UNUSED_PARAMETER(fd);
22777   UNUSED_PARAMETER(fullSync);
22778   UNUSED_PARAMETER(dataOnly);
22779 #elif HAVE_FULLFSYNC
22780   UNUSED_PARAMETER(dataOnly);
22781 #else
22782   UNUSED_PARAMETER(fullSync);
22783 #endif
22784
22785   /* Record the number of times that we do a normal fsync() and 
22786   ** FULLSYNC.  This is used during testing to verify that this procedure
22787   ** gets called with the correct arguments.
22788   */
22789 #ifdef SQLITE_TEST
22790   if( fullSync ) sqlite3_fullsync_count++;
22791   sqlite3_sync_count++;
22792 #endif
22793
22794   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
22795   ** no-op
22796   */
22797 #ifdef SQLITE_NO_SYNC
22798   rc = SQLITE_OK;
22799 #elif HAVE_FULLFSYNC
22800   if( fullSync ){
22801     rc = fcntl(fd, F_FULLFSYNC, 0);
22802   }else{
22803     rc = 1;
22804   }
22805   /* If the FULLFSYNC failed, fall back to attempting an fsync().
22806    * It shouldn't be possible for fullfsync to fail on the local 
22807    * file system (on OSX), so failure indicates that FULLFSYNC
22808    * isn't supported for this file system. So, attempt an fsync 
22809    * and (for now) ignore the overhead of a superfluous fcntl call.  
22810    * It'd be better to detect fullfsync support once and avoid 
22811    * the fcntl call every time sync is called.
22812    */
22813   if( rc ) rc = fsync(fd);
22814
22815 #else 
22816   if( dataOnly ){
22817     rc = fdatasync(fd);
22818     if( IS_VXWORKS && rc==-1 && errno==ENOTSUP ){
22819       rc = fsync(fd);
22820     }
22821   }else{
22822     rc = fsync(fd);
22823   }
22824 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
22825
22826   if( IS_VXWORKS && rc!= -1 ){
22827     rc = 0;
22828   }
22829   return rc;
22830 }
22831
22832 /*
22833 ** Make sure all writes to a particular file are committed to disk.
22834 **
22835 ** If dataOnly==0 then both the file itself and its metadata (file
22836 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
22837 ** file data is synced.
22838 **
22839 ** Under Unix, also make sure that the directory entry for the file
22840 ** has been created by fsync-ing the directory that contains the file.
22841 ** If we do not do this and we encounter a power failure, the directory
22842 ** entry for the journal might not exist after we reboot.  The next
22843 ** SQLite to access the file will not know that the journal exists (because
22844 ** the directory entry for the journal was never created) and the transaction
22845 ** will not roll back - possibly leading to database corruption.
22846 */
22847 static int unixSync(sqlite3_file *id, int flags){
22848   int rc;
22849   unixFile *pFile = (unixFile*)id;
22850
22851   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
22852   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
22853
22854   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
22855   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
22856       || (flags&0x0F)==SQLITE_SYNC_FULL
22857   );
22858
22859   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
22860   ** line is to test that doing so does not cause any problems.
22861   */
22862   SimulateDiskfullError( return SQLITE_FULL );
22863
22864   assert( pFile );
22865   OSTRACE2("SYNC    %-3d\n", pFile->h);
22866   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
22867   SimulateIOError( rc=1 );
22868   if( rc ){
22869     return SQLITE_IOERR_FSYNC;
22870   }
22871   if( pFile->dirfd>=0 ){
22872     OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
22873             HAVE_FULLFSYNC, isFullsync);
22874 #ifndef SQLITE_DISABLE_DIRSYNC
22875     /* The directory sync is only attempted if full_fsync is
22876     ** turned off or unavailable.  If a full_fsync occurred above,
22877     ** then the directory sync is superfluous.
22878     */
22879     if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
22880        /*
22881        ** We have received multiple reports of fsync() returning
22882        ** errors when applied to directories on certain file systems.
22883        ** A failed directory sync is not a big deal.  So it seems
22884        ** better to ignore the error.  Ticket #1657
22885        */
22886        /* return SQLITE_IOERR; */
22887     }
22888 #endif
22889     close(pFile->dirfd);  /* Only need to sync once, so close the directory */
22890     pFile->dirfd = -1;    /* when we are done. */
22891   }
22892   return SQLITE_OK;
22893 }
22894
22895 /*
22896 ** Truncate an open file to a specified size
22897 */
22898 static int unixTruncate(sqlite3_file *id, i64 nByte){
22899   int rc;
22900   assert( id );
22901   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
22902   rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
22903   if( rc ){
22904     return SQLITE_IOERR_TRUNCATE;
22905   }else{
22906     return SQLITE_OK;
22907   }
22908 }
22909
22910 /*
22911 ** Determine the current size of a file in bytes
22912 */
22913 static int unixFileSize(sqlite3_file *id, i64 *pSize){
22914   int rc;
22915   struct stat buf;
22916   assert( id );
22917   rc = fstat(((unixFile*)id)->h, &buf);
22918   SimulateIOError( rc=1 );
22919   if( rc!=0 ){
22920     return SQLITE_IOERR_FSTAT;
22921   }
22922   *pSize = buf.st_size;
22923
22924   /* When opening a zero-size database, the findLockInfo() procedure
22925   ** writes a single byte into that file in order to work around a bug
22926   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
22927   ** layers, we need to report this file size as zero even though it is
22928   ** really 1.   Ticket #3260.
22929   */
22930   if( *pSize==1 ) *pSize = 0;
22931
22932
22933   return SQLITE_OK;
22934 }
22935
22936 /*
22937 ** This routine translates a standard POSIX errno code into something
22938 ** useful to the clients of the sqlite3 functions.  Specifically, it is
22939 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
22940 ** and a variety of "please close the file descriptor NOW" errors into 
22941 ** SQLITE_IOERR
22942 ** 
22943 ** Errors during initialization of locks, or file system support for locks,
22944 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
22945 */
22946 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
22947   switch (posixError) {
22948   case 0: 
22949     return SQLITE_OK;
22950     
22951   case EAGAIN:
22952   case ETIMEDOUT:
22953   case EBUSY:
22954   case EINTR:
22955   case ENOLCK:  
22956     /* random NFS retry error, unless during file system support 
22957      * introspection, in which it actually means what it says */
22958     return SQLITE_BUSY;
22959     
22960   case EACCES: 
22961     /* EACCES is like EAGAIN during locking operations, but not any other time*/
22962     if( (sqliteIOErr == SQLITE_IOERR_LOCK) || 
22963         (sqliteIOErr == SQLITE_IOERR_UNLOCK) || 
22964         (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
22965         (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
22966       return SQLITE_BUSY;
22967     }
22968     /* else fall through */
22969   case EPERM: 
22970     return SQLITE_PERM;
22971     
22972   case EDEADLK:
22973     return SQLITE_IOERR_BLOCKED;
22974     
22975 #if EOPNOTSUPP!=ENOTSUP
22976   case EOPNOTSUPP: 
22977     /* something went terribly awry, unless during file system support 
22978      * introspection, in which it actually means what it says */
22979 #endif
22980 #ifdef ENOTSUP
22981   case ENOTSUP: 
22982     /* invalid fd, unless during file system support introspection, in which 
22983      * it actually means what it says */
22984 #endif
22985   case EIO:
22986   case EBADF:
22987   case EINVAL:
22988   case ENOTCONN:
22989   case ENODEV:
22990   case ENXIO:
22991   case ENOENT:
22992   case ESTALE:
22993   case ENOSYS:
22994     /* these should force the client to close the file and reconnect */
22995     
22996   default: 
22997     return sqliteIOErr;
22998   }
22999 }
23000
23001 /*
23002 ** This routine checks if there is a RESERVED lock held on the specified
23003 ** file by this or any other process. If such a lock is held, set *pResOut
23004 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
23005 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23006 */
23007 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
23008   int rc = SQLITE_OK;
23009   int reserved = 0;
23010   unixFile *pFile = (unixFile*)id;
23011
23012   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23013
23014   assert( pFile );
23015   enterMutex(); /* Because pFile->pLock is shared across threads */
23016
23017   /* Check if a thread in this process holds such a lock */
23018   if( pFile->pLock->locktype>SHARED_LOCK ){
23019     reserved = 1;
23020   }
23021
23022   /* Otherwise see if some other process holds it.
23023   */
23024   if( !reserved ){
23025     struct flock lock;
23026     lock.l_whence = SEEK_SET;
23027     lock.l_start = RESERVED_BYTE;
23028     lock.l_len = 1;
23029     lock.l_type = F_WRLCK;
23030     if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
23031       int tErrno = errno;
23032       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
23033       pFile->lastErrno = tErrno;
23034     } else if( lock.l_type!=F_UNLCK ){
23035       reserved = 1;
23036     }
23037   }
23038   
23039   leaveMutex();
23040   OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
23041
23042   *pResOut = reserved;
23043   return rc;
23044 }
23045
23046 /*
23047 ** Lock the file with the lock specified by parameter locktype - one
23048 ** of the following:
23049 **
23050 **     (1) SHARED_LOCK
23051 **     (2) RESERVED_LOCK
23052 **     (3) PENDING_LOCK
23053 **     (4) EXCLUSIVE_LOCK
23054 **
23055 ** Sometimes when requesting one lock state, additional lock states
23056 ** are inserted in between.  The locking might fail on one of the later
23057 ** transitions leaving the lock state different from what it started but
23058 ** still short of its goal.  The following chart shows the allowed
23059 ** transitions and the inserted intermediate states:
23060 **
23061 **    UNLOCKED -> SHARED
23062 **    SHARED -> RESERVED
23063 **    SHARED -> (PENDING) -> EXCLUSIVE
23064 **    RESERVED -> (PENDING) -> EXCLUSIVE
23065 **    PENDING -> EXCLUSIVE
23066 **
23067 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23068 ** routine to lower a locking level.
23069 */
23070 static int unixLock(sqlite3_file *id, int locktype){
23071   /* The following describes the implementation of the various locks and
23072   ** lock transitions in terms of the POSIX advisory shared and exclusive
23073   ** lock primitives (called read-locks and write-locks below, to avoid
23074   ** confusion with SQLite lock names). The algorithms are complicated
23075   ** slightly in order to be compatible with windows systems simultaneously
23076   ** accessing the same database file, in case that is ever required.
23077   **
23078   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
23079   ** byte', each single bytes at well known offsets, and the 'shared byte
23080   ** range', a range of 510 bytes at a well known offset.
23081   **
23082   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
23083   ** byte'.  If this is successful, a random byte from the 'shared byte
23084   ** range' is read-locked and the lock on the 'pending byte' released.
23085   **
23086   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
23087   ** A RESERVED lock is implemented by grabbing a write-lock on the
23088   ** 'reserved byte'. 
23089   **
23090   ** A process may only obtain a PENDING lock after it has obtained a
23091   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
23092   ** on the 'pending byte'. This ensures that no new SHARED locks can be
23093   ** obtained, but existing SHARED locks are allowed to persist. A process
23094   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
23095   ** This property is used by the algorithm for rolling back a journal file
23096   ** after a crash.
23097   **
23098   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
23099   ** implemented by obtaining a write-lock on the entire 'shared byte
23100   ** range'. Since all other locks require a read-lock on one of the bytes
23101   ** within this range, this ensures that no other locks are held on the
23102   ** database. 
23103   **
23104   ** The reason a single byte cannot be used instead of the 'shared byte
23105   ** range' is that some versions of windows do not support read-locks. By
23106   ** locking a random byte from a range, concurrent SHARED locks may exist
23107   ** even if the locking primitive used is always a write-lock.
23108   */
23109   int rc = SQLITE_OK;
23110   unixFile *pFile = (unixFile*)id;
23111   struct lockInfo *pLock = pFile->pLock;
23112   struct flock lock;
23113   int s;
23114
23115   assert( pFile );
23116   OSTRACE7("LOCK    %d %s was %s(%s,%d) pid=%d\n", pFile->h,
23117       locktypeName(locktype), locktypeName(pFile->locktype),
23118       locktypeName(pLock->locktype), pLock->cnt , getpid());
23119
23120   /* If there is already a lock of this type or more restrictive on the
23121   ** unixFile, do nothing. Don't use the end_lock: exit path, as
23122   ** enterMutex() hasn't been called yet.
23123   */
23124   if( pFile->locktype>=locktype ){
23125     OSTRACE3("LOCK    %d %s ok (already held)\n", pFile->h,
23126             locktypeName(locktype));
23127     return SQLITE_OK;
23128   }
23129
23130   /* Make sure the locking sequence is correct
23131   */
23132   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
23133   assert( locktype!=PENDING_LOCK );
23134   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
23135
23136   /* This mutex is needed because pFile->pLock is shared across threads
23137   */
23138   enterMutex();
23139
23140   /* Make sure the current thread owns the pFile.
23141   */
23142   rc = transferOwnership(pFile);
23143   if( rc!=SQLITE_OK ){
23144     leaveMutex();
23145     return rc;
23146   }
23147   pLock = pFile->pLock;
23148
23149   /* If some thread using this PID has a lock via a different unixFile*
23150   ** handle that precludes the requested lock, return BUSY.
23151   */
23152   if( (pFile->locktype!=pLock->locktype && 
23153           (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
23154   ){
23155     rc = SQLITE_BUSY;
23156     goto end_lock;
23157   }
23158
23159   /* If a SHARED lock is requested, and some thread using this PID already
23160   ** has a SHARED or RESERVED lock, then increment reference counts and
23161   ** return SQLITE_OK.
23162   */
23163   if( locktype==SHARED_LOCK && 
23164       (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
23165     assert( locktype==SHARED_LOCK );
23166     assert( pFile->locktype==0 );
23167     assert( pLock->cnt>0 );
23168     pFile->locktype = SHARED_LOCK;
23169     pLock->cnt++;
23170     pFile->pOpen->nLock++;
23171     goto end_lock;
23172   }
23173
23174   lock.l_len = 1L;
23175
23176   lock.l_whence = SEEK_SET;
23177
23178   /* A PENDING lock is needed before acquiring a SHARED lock and before
23179   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
23180   ** be released.
23181   */
23182   if( locktype==SHARED_LOCK 
23183       || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
23184   ){
23185     lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
23186     lock.l_start = PENDING_BYTE;
23187     s = fcntl(pFile->h, F_SETLK, &lock);
23188     if( s==(-1) ){
23189       int tErrno = errno;
23190       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23191       if( IS_LOCK_ERROR(rc) ){
23192         pFile->lastErrno = tErrno;
23193       }
23194       goto end_lock;
23195     }
23196   }
23197
23198
23199   /* If control gets to this point, then actually go ahead and make
23200   ** operating system calls for the specified lock.
23201   */
23202   if( locktype==SHARED_LOCK ){
23203     int tErrno = 0;
23204     assert( pLock->cnt==0 );
23205     assert( pLock->locktype==0 );
23206
23207     /* Now get the read-lock */
23208     lock.l_start = SHARED_FIRST;
23209     lock.l_len = SHARED_SIZE;
23210     if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
23211       tErrno = errno;
23212     }
23213     /* Drop the temporary PENDING lock */
23214     lock.l_start = PENDING_BYTE;
23215     lock.l_len = 1L;
23216     lock.l_type = F_UNLCK;
23217     if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
23218       if( s != -1 ){
23219         /* This could happen with a network mount */
23220         tErrno = errno; 
23221         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); 
23222         if( IS_LOCK_ERROR(rc) ){
23223           pFile->lastErrno = tErrno;
23224         }
23225         goto end_lock;
23226       }
23227     }
23228     if( s==(-1) ){
23229       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23230       if( IS_LOCK_ERROR(rc) ){
23231         pFile->lastErrno = tErrno;
23232       }
23233     }else{
23234       pFile->locktype = SHARED_LOCK;
23235       pFile->pOpen->nLock++;
23236       pLock->cnt = 1;
23237     }
23238   }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
23239     /* We are trying for an exclusive lock but another thread in this
23240     ** same process is still holding a shared lock. */
23241     rc = SQLITE_BUSY;
23242   }else{
23243     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
23244     ** assumed that there is a SHARED or greater lock on the file
23245     ** already.
23246     */
23247     assert( 0!=pFile->locktype );
23248     lock.l_type = F_WRLCK;
23249     switch( locktype ){
23250       case RESERVED_LOCK:
23251         lock.l_start = RESERVED_BYTE;
23252         break;
23253       case EXCLUSIVE_LOCK:
23254         lock.l_start = SHARED_FIRST;
23255         lock.l_len = SHARED_SIZE;
23256         break;
23257       default:
23258         assert(0);
23259     }
23260     s = fcntl(pFile->h, F_SETLK, &lock);
23261     if( s==(-1) ){
23262       int tErrno = errno;
23263       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23264       if( IS_LOCK_ERROR(rc) ){
23265         pFile->lastErrno = tErrno;
23266       }
23267     }
23268   }
23269   
23270   if( rc==SQLITE_OK ){
23271     pFile->locktype = locktype;
23272     pLock->locktype = locktype;
23273   }else if( locktype==EXCLUSIVE_LOCK ){
23274     pFile->locktype = PENDING_LOCK;
23275     pLock->locktype = PENDING_LOCK;
23276   }
23277
23278 end_lock:
23279   leaveMutex();
23280   OSTRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
23281       rc==SQLITE_OK ? "ok" : "failed");
23282   return rc;
23283 }
23284
23285 /*
23286 ** Lower the locking level on file descriptor pFile to locktype.  locktype
23287 ** must be either NO_LOCK or SHARED_LOCK.
23288 **
23289 ** If the locking level of the file descriptor is already at or below
23290 ** the requested locking level, this routine is a no-op.
23291 */
23292 static int unixUnlock(sqlite3_file *id, int locktype){
23293   struct lockInfo *pLock;
23294   struct flock lock;
23295   int rc = SQLITE_OK;
23296   unixFile *pFile = (unixFile*)id;
23297   int h;
23298
23299   assert( pFile );
23300   OSTRACE7("UNLOCK  %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
23301       pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
23302
23303   assert( locktype<=SHARED_LOCK );
23304   if( pFile->locktype<=locktype ){
23305     return SQLITE_OK;
23306   }
23307   if( CHECK_THREADID(pFile) ){
23308     return SQLITE_MISUSE;
23309   }
23310   enterMutex();
23311   h = pFile->h;
23312   pLock = pFile->pLock;
23313   assert( pLock->cnt!=0 );
23314   if( pFile->locktype>SHARED_LOCK ){
23315     assert( pLock->locktype==pFile->locktype );
23316     SimulateIOErrorBenign(1);
23317     SimulateIOError( h=(-1) )
23318     SimulateIOErrorBenign(0);
23319     if( locktype==SHARED_LOCK ){
23320       lock.l_type = F_RDLCK;
23321       lock.l_whence = SEEK_SET;
23322       lock.l_start = SHARED_FIRST;
23323       lock.l_len = SHARED_SIZE;
23324       if( fcntl(h, F_SETLK, &lock)==(-1) ){
23325         int tErrno = errno;
23326         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
23327         if( IS_LOCK_ERROR(rc) ){
23328           pFile->lastErrno = tErrno;
23329         }
23330                                 goto end_unlock;
23331       }
23332     }
23333     lock.l_type = F_UNLCK;
23334     lock.l_whence = SEEK_SET;
23335     lock.l_start = PENDING_BYTE;
23336     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
23337     if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23338       pLock->locktype = SHARED_LOCK;
23339     }else{
23340       int tErrno = errno;
23341       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23342       if( IS_LOCK_ERROR(rc) ){
23343         pFile->lastErrno = tErrno;
23344       }
23345                         goto end_unlock;
23346     }
23347   }
23348   if( locktype==NO_LOCK ){
23349     struct openCnt *pOpen;
23350
23351     /* Decrement the shared lock counter.  Release the lock using an
23352     ** OS call only when all threads in this same process have released
23353     ** the lock.
23354     */
23355     pLock->cnt--;
23356     if( pLock->cnt==0 ){
23357       lock.l_type = F_UNLCK;
23358       lock.l_whence = SEEK_SET;
23359       lock.l_start = lock.l_len = 0L;
23360       SimulateIOErrorBenign(1);
23361       SimulateIOError( h=(-1) )
23362       SimulateIOErrorBenign(0);
23363       if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23364         pLock->locktype = NO_LOCK;
23365       }else{
23366         int tErrno = errno;
23367         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23368         if( IS_LOCK_ERROR(rc) ){
23369           pFile->lastErrno = tErrno;
23370         }
23371         pLock->cnt = 1;
23372                                 goto end_unlock;
23373       }
23374     }
23375
23376     /* Decrement the count of locks against this same file.  When the
23377     ** count reaches zero, close any other file descriptors whose close
23378     ** was deferred because of outstanding locks.
23379     */
23380     if( rc==SQLITE_OK ){
23381       pOpen = pFile->pOpen;
23382       pOpen->nLock--;
23383       assert( pOpen->nLock>=0 );
23384       if( pOpen->nLock==0 && pOpen->nPending>0 ){
23385         int i;
23386         for(i=0; i<pOpen->nPending; i++){
23387           close(pOpen->aPending[i]);
23388         }
23389         sqlite3_free(pOpen->aPending);
23390         pOpen->nPending = 0;
23391         pOpen->aPending = 0;
23392       }
23393     }
23394   }
23395         
23396 end_unlock:
23397   leaveMutex();
23398   if( rc==SQLITE_OK ) pFile->locktype = locktype;
23399   return rc;
23400 }
23401
23402 /*
23403 ** This function performs the parts of the "close file" operation 
23404 ** common to all locking schemes. It closes the directory and file
23405 ** handles, if they are valid, and sets all fields of the unixFile
23406 ** structure to 0.
23407 */
23408 static int closeUnixFile(sqlite3_file *id){
23409   unixFile *pFile = (unixFile*)id;
23410   if( pFile ){
23411     if( pFile->dirfd>=0 ){
23412       close(pFile->dirfd);
23413     }
23414     if( pFile->h>=0 ){
23415       close(pFile->h);
23416     }
23417 #if IS_VXWORKS
23418     if( pFile->isDelete && pFile->zRealpath ){
23419       unlink(pFile->zRealpath);
23420     }
23421     if( pFile->zRealpath ){
23422       HashElem *pElem;
23423       int n = strlen(pFile->zRealpath) + 1;
23424       pElem = sqlite3HashFindElem(&nameHash, pFile->zRealpath, n);
23425       if( pElem ){
23426         long cnt = (long)pElem->data;
23427         cnt--;
23428         if( cnt==0 ){
23429           sqlite3HashInsert(&nameHash, pFile->zRealpath, n, 0);
23430         }else{
23431           pElem->data = (void*)cnt;
23432         }
23433       }
23434     }
23435 #endif
23436     OSTRACE2("CLOSE   %-3d\n", pFile->h);
23437     OpenCounter(-1);
23438     memset(pFile, 0, sizeof(unixFile));
23439   }
23440   return SQLITE_OK;
23441 }
23442
23443 /*
23444 ** Close a file.
23445 */
23446 static int unixClose(sqlite3_file *id){
23447   if( id ){
23448     unixFile *pFile = (unixFile *)id;
23449     unixUnlock(id, NO_LOCK);
23450     enterMutex();
23451     if( pFile->pOpen && pFile->pOpen->nLock ){
23452       /* If there are outstanding locks, do not actually close the file just
23453       ** yet because that would clear those locks.  Instead, add the file
23454       ** descriptor to pOpen->aPending.  It will be automatically closed when
23455       ** the last lock is cleared.
23456       */
23457       int *aNew;
23458       struct openCnt *pOpen = pFile->pOpen;
23459       aNew = sqlite3_realloc(pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
23460       if( aNew==0 ){
23461         /* If a malloc fails, just leak the file descriptor */
23462       }else{
23463         pOpen->aPending = aNew;
23464         pOpen->aPending[pOpen->nPending] = pFile->h;
23465         pOpen->nPending++;
23466         pFile->h = -1;
23467       }
23468     }
23469     releaseLockInfo(pFile->pLock);
23470     releaseOpenCnt(pFile->pOpen);
23471     closeUnixFile(id);
23472     leaveMutex();
23473   }
23474   return SQLITE_OK;
23475 }
23476
23477
23478 #if SQLITE_ENABLE_LOCKING_STYLE
23479
23480 #if !IS_VXWORKS
23481 #pragma mark AFP Support
23482
23483 /*
23484  ** The afpLockingContext structure contains all afp lock specific state
23485  */
23486 typedef struct afpLockingContext afpLockingContext;
23487 struct afpLockingContext {
23488   unsigned long long sharedLockByte;
23489   const char *filePath;
23490 };
23491
23492 struct ByteRangeLockPB2
23493 {
23494   unsigned long long offset;        /* offset to first byte to lock */
23495   unsigned long long length;        /* nbr of bytes to lock */
23496   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
23497   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
23498   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
23499   int fd;                           /* file desc to assoc this lock with */
23500 };
23501
23502 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
23503
23504 /* 
23505  ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
23506  */
23507 static int _AFPFSSetLock(
23508   const char *path, 
23509   unixFile *pFile, 
23510   unsigned long long offset, 
23511   unsigned long long length, 
23512   int setLockFlag
23513 ){
23514   struct ByteRangeLockPB2       pb;
23515   int                     err;
23516   
23517   pb.unLockFlag = setLockFlag ? 0 : 1;
23518   pb.startEndFlag = 0;
23519   pb.offset = offset;
23520   pb.length = length; 
23521   pb.fd = pFile->h;
23522   OSTRACE5("AFPLOCK setting lock %s for %d in range %llx:%llx\n", 
23523     (setLockFlag?"ON":"OFF"), pFile->h, offset, length);
23524   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
23525   if ( err==-1 ) {
23526     int rc;
23527     int tErrno = errno;
23528     OSTRACE4("AFPLOCK failed to fsctl() '%s' %d %s\n", path, tErrno, strerror(tErrno));
23529     rc = sqliteErrorFromPosixError(tErrno, setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK); /* error */
23530     if( IS_LOCK_ERROR(rc) ){
23531       pFile->lastErrno = tErrno;
23532     }
23533     return rc;
23534   } else {
23535     return SQLITE_OK;
23536   }
23537 }
23538
23539 /* AFP-style reserved lock checking following the behavior of 
23540 ** unixCheckReservedLock, see the unixCheckReservedLock function comments */
23541 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
23542   int rc = SQLITE_OK;
23543   int reserved = 0;
23544   unixFile *pFile = (unixFile*)id;
23545   
23546   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23547   
23548   assert( pFile );
23549   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
23550   
23551   /* Check if a thread in this process holds such a lock */
23552   if( pFile->locktype>SHARED_LOCK ){
23553     reserved = 1;
23554   }
23555   
23556   /* Otherwise see if some other process holds it.
23557    */
23558   if( !reserved ){
23559     /* lock the RESERVED byte */
23560     int lrc = _AFPFSSetLock(context->filePath, pFile, RESERVED_BYTE, 1,1);  
23561     if( SQLITE_OK==lrc ){
23562       /* if we succeeded in taking the reserved lock, unlock it to restore
23563       ** the original state */
23564       lrc = _AFPFSSetLock(context->filePath, pFile, RESERVED_BYTE, 1, 0);
23565     } else {
23566       /* if we failed to get the lock then someone else must have it */
23567       reserved = 1;
23568     }
23569     if( IS_LOCK_ERROR(lrc) ){
23570       rc=lrc;
23571     }
23572   }
23573   
23574   OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
23575   
23576   *pResOut = reserved;
23577   return rc;
23578 }
23579
23580 /* AFP-style locking following the behavior of unixLock, see the unixLock 
23581 ** function comments for details of lock management. */
23582 static int afpLock(sqlite3_file *id, int locktype){
23583   int rc = SQLITE_OK;
23584   unixFile *pFile = (unixFile*)id;
23585   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
23586   
23587   assert( pFile );
23588   OSTRACE5("LOCK    %d %s was %s pid=%d\n", pFile->h,
23589          locktypeName(locktype), locktypeName(pFile->locktype), getpid());
23590
23591   /* If there is already a lock of this type or more restrictive on the
23592   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
23593   ** enterMutex() hasn't been called yet.
23594   */
23595   if( pFile->locktype>=locktype ){
23596     OSTRACE3("LOCK    %d %s ok (already held)\n", pFile->h,
23597            locktypeName(locktype));
23598     return SQLITE_OK;
23599   }
23600
23601   /* Make sure the locking sequence is correct
23602   */
23603   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
23604   assert( locktype!=PENDING_LOCK );
23605   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
23606   
23607   /* This mutex is needed because pFile->pLock is shared across threads
23608   */
23609   enterMutex();
23610
23611   /* Make sure the current thread owns the pFile.
23612   */
23613   rc = transferOwnership(pFile);
23614   if( rc!=SQLITE_OK ){
23615     leaveMutex();
23616     return rc;
23617   }
23618     
23619   /* A PENDING lock is needed before acquiring a SHARED lock and before
23620   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
23621   ** be released.
23622   */
23623   if( locktype==SHARED_LOCK 
23624       || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
23625   ){
23626     int failed;
23627     failed = _AFPFSSetLock(context->filePath, pFile, PENDING_BYTE, 1, 1);
23628     if (failed) {
23629       rc = failed;
23630       goto afp_end_lock;
23631     }
23632   }
23633   
23634   /* If control gets to this point, then actually go ahead and make
23635   ** operating system calls for the specified lock.
23636   */
23637   if( locktype==SHARED_LOCK ){
23638     int lk, lrc1, lrc2, lrc1Errno;
23639     
23640     /* Now get the read-lock SHARED_LOCK */
23641     /* note that the quality of the randomness doesn't matter that much */
23642     lk = random(); 
23643     context->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
23644     lrc1 = _AFPFSSetLock(context->filePath, pFile, 
23645           SHARED_FIRST+context->sharedLockByte, 1, 1);
23646     if( IS_LOCK_ERROR(lrc1) ){
23647       lrc1Errno = pFile->lastErrno;
23648     }
23649     /* Drop the temporary PENDING lock */
23650     lrc2 = _AFPFSSetLock(context->filePath, pFile, PENDING_BYTE, 1, 0);
23651     
23652     if( IS_LOCK_ERROR(lrc1) ) {
23653       pFile->lastErrno = lrc1Errno;
23654       rc = lrc1;
23655       goto afp_end_lock;
23656     } else if( IS_LOCK_ERROR(lrc2) ){
23657       rc = lrc2;
23658       goto afp_end_lock;
23659     } else if( lrc1 != SQLITE_OK ) {
23660       rc = lrc1;
23661     } else {
23662       pFile->locktype = SHARED_LOCK;
23663     }
23664   }else{
23665     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
23666     ** assumed that there is a SHARED or greater lock on the file
23667     ** already.
23668     */
23669     int failed = 0;
23670     assert( 0!=pFile->locktype );
23671     if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
23672         /* Acquire a RESERVED lock */
23673         failed = _AFPFSSetLock(context->filePath, pFile, RESERVED_BYTE, 1,1);
23674     }
23675     if (!failed && locktype == EXCLUSIVE_LOCK) {
23676       /* Acquire an EXCLUSIVE lock */
23677         
23678       /* Remove the shared lock before trying the range.  we'll need to 
23679       ** reestablish the shared lock if we can't get the  afpUnlock
23680       */
23681       if (!(failed = _AFPFSSetLock(context->filePath, pFile, SHARED_FIRST +
23682                          context->sharedLockByte, 1, 0))) {
23683         /* now attemmpt to get the exclusive lock range */
23684         failed = _AFPFSSetLock(context->filePath, pFile, SHARED_FIRST, 
23685                                SHARED_SIZE, 1);
23686         if (failed && (failed = _AFPFSSetLock(context->filePath, pFile, 
23687                        SHARED_FIRST + context->sharedLockByte, 1, 1))) {
23688           rc = failed;
23689         }
23690       } else {
23691         rc = failed; 
23692       }
23693     }
23694     if( failed ){
23695       rc = failed;
23696     }
23697   }
23698   
23699   if( rc==SQLITE_OK ){
23700     pFile->locktype = locktype;
23701   }else if( locktype==EXCLUSIVE_LOCK ){
23702     pFile->locktype = PENDING_LOCK;
23703   }
23704   
23705 afp_end_lock:
23706   leaveMutex();
23707   OSTRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
23708          rc==SQLITE_OK ? "ok" : "failed");
23709   return rc;
23710 }
23711
23712 /*
23713 ** Lower the locking level on file descriptor pFile to locktype.  locktype
23714 ** must be either NO_LOCK or SHARED_LOCK.
23715 **
23716 ** If the locking level of the file descriptor is already at or below
23717 ** the requested locking level, this routine is a no-op.
23718 */
23719 static int afpUnlock(sqlite3_file *id, int locktype) {
23720   int rc = SQLITE_OK;
23721   unixFile *pFile = (unixFile*)id;
23722   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
23723
23724   assert( pFile );
23725   OSTRACE5("UNLOCK  %d %d was %d pid=%d\n", pFile->h, locktype,
23726          pFile->locktype, getpid());
23727
23728   assert( locktype<=SHARED_LOCK );
23729   if( pFile->locktype<=locktype ){
23730     return SQLITE_OK;
23731   }
23732   if( CHECK_THREADID(pFile) ){
23733     return SQLITE_MISUSE;
23734   }
23735   enterMutex();
23736   int failed = SQLITE_OK;
23737   if( pFile->locktype>SHARED_LOCK ){
23738     if( locktype==SHARED_LOCK ){
23739
23740       /* unlock the exclusive range - then re-establish the shared lock */
23741       if (pFile->locktype==EXCLUSIVE_LOCK) {
23742         failed = _AFPFSSetLock(context->filePath, pFile, SHARED_FIRST, 
23743                                  SHARED_SIZE, 0);
23744         if (!failed) {
23745           /* successfully removed the exclusive lock */
23746           if ((failed = _AFPFSSetLock(context->filePath, pFile, SHARED_FIRST+
23747                             context->sharedLockByte, 1, 1))) {
23748             /* failed to re-establish our shared lock */
23749             rc = failed;
23750           }
23751         } else {
23752           rc = failed;
23753         } 
23754       }
23755     }
23756     if (rc == SQLITE_OK && pFile->locktype>=PENDING_LOCK) {
23757       if ((failed = _AFPFSSetLock(context->filePath, pFile, 
23758                                   PENDING_BYTE, 1, 0))){
23759         /* failed to release the pending lock */
23760         rc = failed; 
23761       }
23762     } 
23763     if (rc == SQLITE_OK && pFile->locktype>=RESERVED_LOCK) {
23764       if ((failed = _AFPFSSetLock(context->filePath, pFile, 
23765                                   RESERVED_BYTE, 1, 0))) {
23766         /* failed to release the reserved lock */
23767         rc = failed;  
23768       }
23769     } 
23770   }
23771   if( locktype==NO_LOCK ){
23772     int failed = _AFPFSSetLock(context->filePath, pFile, 
23773                                SHARED_FIRST + context->sharedLockByte, 1, 0);
23774     if (failed) {
23775       rc = failed;  
23776     }
23777   }
23778   if (rc == SQLITE_OK)
23779     pFile->locktype = locktype;
23780   leaveMutex();
23781   return rc;
23782 }
23783
23784 /*
23785 ** Close a file & cleanup AFP specific locking context 
23786 */
23787 static int afpClose(sqlite3_file *id) {
23788   if( id ){
23789     unixFile *pFile = (unixFile*)id;
23790     afpUnlock(id, NO_LOCK);
23791     sqlite3_free(pFile->lockingContext);
23792   }
23793   return closeUnixFile(id);
23794 }
23795
23796
23797 #pragma mark flock() style locking
23798
23799 /*
23800 ** The flockLockingContext is not used
23801 */
23802 typedef void flockLockingContext;
23803
23804 /* flock-style reserved lock checking following the behavior of 
23805  ** unixCheckReservedLock, see the unixCheckReservedLock function comments */
23806 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
23807   int rc = SQLITE_OK;
23808   int reserved = 0;
23809   unixFile *pFile = (unixFile*)id;
23810   
23811   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23812   
23813   assert( pFile );
23814   
23815   /* Check if a thread in this process holds such a lock */
23816   if( pFile->locktype>SHARED_LOCK ){
23817     reserved = 1;
23818   }
23819   
23820   /* Otherwise see if some other process holds it. */
23821   if( !reserved ){
23822     /* attempt to get the lock */
23823     int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
23824     if( !lrc ){
23825       /* got the lock, unlock it */
23826       lrc = flock(pFile->h, LOCK_UN);
23827       if ( lrc ) {
23828         int tErrno = errno;
23829         /* unlock failed with an error */
23830         lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); 
23831         if( IS_LOCK_ERROR(lrc) ){
23832           pFile->lastErrno = tErrno;
23833           rc = lrc;
23834         }
23835       }
23836     } else {
23837       int tErrno = errno;
23838       reserved = 1;
23839       /* someone else might have it reserved */
23840       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 
23841       if( IS_LOCK_ERROR(lrc) ){
23842         pFile->lastErrno = tErrno;
23843         rc = lrc;
23844       }
23845     }
23846   }
23847   OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
23848
23849   *pResOut = reserved;
23850   return rc;
23851 }
23852
23853 static int flockLock(sqlite3_file *id, int locktype) {
23854   int rc = SQLITE_OK;
23855   unixFile *pFile = (unixFile*)id;
23856
23857   assert( pFile );
23858
23859   /* if we already have a lock, it is exclusive.  
23860   ** Just adjust level and punt on outta here. */
23861   if (pFile->locktype > NO_LOCK) {
23862     pFile->locktype = locktype;
23863     return SQLITE_OK;
23864   }
23865   
23866   /* grab an exclusive lock */
23867   
23868   if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
23869     int tErrno = errno;
23870     /* didn't get, must be busy */
23871     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23872     if( IS_LOCK_ERROR(rc) ){
23873       pFile->lastErrno = tErrno;
23874     }
23875   } else {
23876     /* got it, set the type and return ok */
23877     pFile->locktype = locktype;
23878   }
23879   OSTRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
23880            rc==SQLITE_OK ? "ok" : "failed");
23881   return rc;
23882 }
23883
23884 static int flockUnlock(sqlite3_file *id, int locktype) {
23885   unixFile *pFile = (unixFile*)id;
23886   
23887   assert( pFile );
23888   OSTRACE5("UNLOCK  %d %d was %d pid=%d\n", pFile->h, locktype,
23889            pFile->locktype, getpid());
23890   assert( locktype<=SHARED_LOCK );
23891   
23892   /* no-op if possible */
23893   if( pFile->locktype==locktype ){
23894     return SQLITE_OK;
23895   }
23896   
23897   /* shared can just be set because we always have an exclusive */
23898   if (locktype==SHARED_LOCK) {
23899     pFile->locktype = locktype;
23900     return SQLITE_OK;
23901   }
23902   
23903   /* no, really, unlock. */
23904   int rc = flock(pFile->h, LOCK_UN);
23905   if (rc) {
23906     int r, tErrno = errno;
23907     r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23908     if( IS_LOCK_ERROR(r) ){
23909       pFile->lastErrno = tErrno;
23910     }
23911     return r;
23912   } else {
23913     pFile->locktype = NO_LOCK;
23914     return SQLITE_OK;
23915   }
23916 }
23917
23918 /*
23919 ** Close a file.
23920 */
23921 static int flockClose(sqlite3_file *id) {
23922   if( id ){
23923     flockUnlock(id, NO_LOCK);
23924   }
23925   return closeUnixFile(id);
23926 }
23927
23928 #endif /* !IS_VXWORKS */
23929
23930 #pragma mark Old-School .lock file based locking
23931
23932 /* Dotlock-style reserved lock checking following the behavior of 
23933 ** unixCheckReservedLock, see the unixCheckReservedLock function comments */
23934 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
23935   int rc = SQLITE_OK;
23936   int reserved = 0;
23937   unixFile *pFile = (unixFile*)id;
23938
23939   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23940   
23941   assert( pFile );
23942
23943   /* Check if a thread in this process holds such a lock */
23944   if( pFile->locktype>SHARED_LOCK ){
23945     reserved = 1;
23946   }
23947   
23948   /* Otherwise see if some other process holds it. */
23949   if( !reserved ){
23950     char *zLockFile = (char *)pFile->lockingContext;
23951     struct stat statBuf;
23952     
23953     if( lstat(zLockFile, &statBuf)==0 ){
23954       /* file exists, someone else has the lock */
23955       reserved = 1;
23956     }else{
23957       /* file does not exist, we could have it if we want it */
23958       int tErrno = errno;
23959       if( ENOENT != tErrno ){
23960         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
23961         pFile->lastErrno = tErrno;
23962       }
23963     }
23964   }
23965   OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
23966
23967   *pResOut = reserved;
23968   return rc;
23969 }
23970
23971 static int dotlockLock(sqlite3_file *id, int locktype) {
23972   unixFile *pFile = (unixFile*)id;
23973   int fd;
23974   char *zLockFile = (char *)pFile->lockingContext;
23975   int rc=SQLITE_OK;
23976
23977   /* if we already have a lock, it is exclusive.  
23978   ** Just adjust level and punt on outta here. */
23979   if (pFile->locktype > NO_LOCK) {
23980     pFile->locktype = locktype;
23981 #if !IS_VXWORKS
23982     /* Always update the timestamp on the old file */
23983     utimes(zLockFile, NULL);
23984 #endif
23985     rc = SQLITE_OK;
23986     goto dotlock_end_lock;
23987   }
23988   
23989   /* check to see if lock file already exists */
23990   struct stat statBuf;
23991   if (lstat(zLockFile,&statBuf) == 0){
23992     rc = SQLITE_BUSY; /* it does, busy */
23993     goto dotlock_end_lock;
23994   }
23995   
23996   /* grab an exclusive lock */
23997   fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
23998   if( fd<0 ){
23999     /* failed to open/create the file, someone else may have stolen the lock */
24000     int tErrno = errno;
24001     if( EEXIST == tErrno ){
24002       rc = SQLITE_BUSY;
24003     } else {
24004       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24005       if( IS_LOCK_ERROR(rc) ){
24006         pFile->lastErrno = tErrno;
24007       }
24008     }
24009     goto dotlock_end_lock;
24010   } 
24011   close(fd);
24012   
24013   /* got it, set the type and return ok */
24014   pFile->locktype = locktype;
24015
24016  dotlock_end_lock:
24017   return rc;
24018 }
24019
24020 static int dotlockUnlock(sqlite3_file *id, int locktype) {
24021   unixFile *pFile = (unixFile*)id;
24022   char *zLockFile = (char *)pFile->lockingContext;
24023
24024   assert( pFile );
24025   OSTRACE5("UNLOCK  %d %d was %d pid=%d\n", pFile->h, locktype,
24026            pFile->locktype, getpid());
24027   assert( locktype<=SHARED_LOCK );
24028   
24029   /* no-op if possible */
24030   if( pFile->locktype==locktype ){
24031     return SQLITE_OK;
24032   }
24033   
24034   /* shared can just be set because we always have an exclusive */
24035   if (locktype==SHARED_LOCK) {
24036     pFile->locktype = locktype;
24037     return SQLITE_OK;
24038   }
24039   
24040   /* no, really, unlock. */
24041   if (unlink(zLockFile) ) {
24042     int rc, tErrno = errno;
24043     if( ENOENT != tErrno ){
24044       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24045     }
24046     if( IS_LOCK_ERROR(rc) ){
24047       pFile->lastErrno = tErrno;
24048     }
24049     return rc; 
24050   }
24051   pFile->locktype = NO_LOCK;
24052   return SQLITE_OK;
24053 }
24054
24055 /*
24056  ** Close a file.
24057  */
24058 static int dotlockClose(sqlite3_file *id) {
24059   int rc;
24060   if( id ){
24061     unixFile *pFile = (unixFile*)id;
24062     dotlockUnlock(id, NO_LOCK);
24063     sqlite3_free(pFile->lockingContext);
24064   }
24065   if( IS_VXWORKS ) enterMutex();
24066   rc = closeUnixFile(id);
24067   if( IS_VXWORKS ) leaveMutex();
24068   return rc;
24069 }
24070
24071 #if IS_VXWORKS
24072
24073 #pragma mark POSIX/vxWorks named semaphore based locking
24074
24075 /* Namedsem-style reserved lock checking following the behavior of 
24076 ** unixCheckReservedLock, see the unixCheckReservedLock function comments */
24077 static int namedsemCheckReservedLock(sqlite3_file *id, int *pResOut) {
24078   int rc = SQLITE_OK;
24079   int reserved = 0;
24080   unixFile *pFile = (unixFile*)id;
24081
24082   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24083   
24084   assert( pFile );
24085
24086   /* Check if a thread in this process holds such a lock */
24087   if( pFile->locktype>SHARED_LOCK ){
24088     reserved = 1;
24089   }
24090   
24091   /* Otherwise see if some other process holds it. */
24092   if( !reserved ){
24093     sem_t *pSem = pFile->pOpen->pSem;
24094     struct stat statBuf;
24095
24096     if( sem_trywait(pSem)==-1 ){
24097       int tErrno = errno;
24098       if( EAGAIN != tErrno ){
24099         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
24100         pFile->lastErrno = tErrno;
24101       } else {
24102         /* someone else has the lock when we are in NO_LOCK */
24103         reserved = (pFile->locktype < SHARED_LOCK);
24104       }
24105     }else{
24106       /* we could have it if we want it */
24107       sem_post(pSem);
24108     }
24109   }
24110   OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
24111
24112   *pResOut = reserved;
24113   return rc;
24114 }
24115
24116 static int namedsemLock(sqlite3_file *id, int locktype) {
24117   unixFile *pFile = (unixFile*)id;
24118   int fd;
24119   sem_t *pSem = pFile->pOpen->pSem;
24120   int rc = SQLITE_OK;
24121
24122   /* if we already have a lock, it is exclusive.  
24123   ** Just adjust level and punt on outta here. */
24124   if (pFile->locktype > NO_LOCK) {
24125     pFile->locktype = locktype;
24126     rc = SQLITE_OK;
24127     goto namedsem_end_lock;
24128   }
24129   
24130   /* lock semaphore now but bail out when already locked. */
24131   if( sem_trywait(pSem)==-1 ){
24132     rc = SQLITE_BUSY;
24133     goto namedsem_end_lock;
24134   }
24135
24136   /* got it, set the type and return ok */
24137   pFile->locktype = locktype;
24138
24139  namedsem_end_lock:
24140   return rc;
24141 }
24142
24143 static int namedsemUnlock(sqlite3_file *id, int locktype) {
24144   unixFile *pFile = (unixFile*)id;
24145   sem_t *pSem = pFile->pOpen->pSem;
24146
24147   assert( pFile );
24148   assert( pSem );
24149   OSTRACE5("UNLOCK  %d %d was %d pid=%d\n", pFile->h, locktype,
24150            pFile->locktype, getpid());
24151   assert( locktype<=SHARED_LOCK );
24152   
24153   /* no-op if possible */
24154   if( pFile->locktype==locktype ){
24155     return SQLITE_OK;
24156   }
24157   
24158   /* shared can just be set because we always have an exclusive */
24159   if (locktype==SHARED_LOCK) {
24160     pFile->locktype = locktype;
24161     return SQLITE_OK;
24162   }
24163   
24164   /* no, really unlock. */
24165   if ( sem_post(pSem)==-1 ) {
24166     int rc, tErrno = errno;
24167     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24168     if( IS_LOCK_ERROR(rc) ){
24169       pFile->lastErrno = tErrno;
24170     }
24171     return rc; 
24172   }
24173   pFile->locktype = NO_LOCK;
24174   return SQLITE_OK;
24175 }
24176
24177 /*
24178  ** Close a file.
24179  */
24180 static int namedsemClose(sqlite3_file *id) {
24181   if( id ){
24182     unixFile *pFile = (unixFile*)id;
24183     namedsemUnlock(id, NO_LOCK);
24184     assert( pFile );
24185     enterMutex();
24186     releaseLockInfo(pFile->pLock);
24187     releaseOpenCnt(pFile->pOpen);
24188     closeUnixFile(id);
24189     leaveMutex();
24190   }
24191   return SQLITE_OK;
24192 }
24193
24194 #endif /* IS_VXWORKS */
24195
24196 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
24197
24198 /*
24199 ** The nolockLockingContext is void
24200 */
24201 typedef void nolockLockingContext;
24202
24203 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
24204   UNUSED_PARAMETER(NotUsed);
24205   *pResOut = 0;
24206   return SQLITE_OK;
24207 }
24208
24209 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
24210   UNUSED_PARAMETER2(NotUsed, NotUsed2);
24211   return SQLITE_OK;
24212 }
24213
24214 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
24215   UNUSED_PARAMETER2(NotUsed, NotUsed2);
24216   return SQLITE_OK;
24217 }
24218
24219 /*
24220 ** Close a file.
24221 */
24222 static int nolockClose(sqlite3_file *id) {
24223   int rc;
24224   if( IS_VXWORKS ) enterMutex();
24225   rc = closeUnixFile(id);
24226   if( IS_VXWORKS ) leaveMutex();
24227   return rc;
24228 }
24229
24230
24231 /*
24232 ** Information and control of an open file handle.
24233 */
24234 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
24235   switch( op ){
24236     case SQLITE_FCNTL_LOCKSTATE: {
24237       *(int*)pArg = ((unixFile*)id)->locktype;
24238       return SQLITE_OK;
24239     }
24240   }
24241   return SQLITE_ERROR;
24242 }
24243
24244 /*
24245 ** Return the sector size in bytes of the underlying block device for
24246 ** the specified file. This is almost always 512 bytes, but may be
24247 ** larger for some devices.
24248 **
24249 ** SQLite code assumes this function cannot fail. It also assumes that
24250 ** if two files are created in the same file-system directory (i.e.
24251 ** a database and its journal file) that the sector size will be the
24252 ** same for both.
24253 */
24254 static int unixSectorSize(sqlite3_file *NotUsed){
24255   UNUSED_PARAMETER(NotUsed);
24256   return SQLITE_DEFAULT_SECTOR_SIZE;
24257 }
24258
24259 /*
24260 ** Return the device characteristics for the file. This is always 0 for unix.
24261 */
24262 static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
24263   UNUSED_PARAMETER(NotUsed);
24264   return 0;
24265 }
24266
24267 /*
24268 ** Initialize the contents of the unixFile structure pointed to by pId.
24269 **
24270 ** When locking extensions are enabled, the filepath and locking style 
24271 ** are needed to determine the unixFile pMethod to use for locking operations.
24272 ** The locking-style specific lockingContext data structure is created 
24273 ** and assigned here also.
24274 */
24275 static int fillInUnixFile(
24276   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
24277   int h,                  /* Open file descriptor of file being opened */
24278   int dirfd,              /* Directory file descriptor */
24279   sqlite3_file *pId,      /* Write to the unixFile structure here */
24280   const char *zFilename,  /* Name of the file being opened */
24281   int noLock,             /* Omit locking if true */
24282   int isDelete            /* Delete on close if true */
24283 ){
24284   int eLockingStyle;
24285   unixFile *pNew = (unixFile *)pId;
24286   int rc = SQLITE_OK;
24287
24288   /* Macro to define the static contents of an sqlite3_io_methods 
24289   ** structure for a unix backend file. Different locking methods
24290   ** require different functions for the xClose, xLock, xUnlock and
24291   ** xCheckReservedLock methods.
24292   */
24293   #define IOMETHODS(xClose, xLock, xUnlock, xCheckReservedLock) {    \
24294     1,                          /* iVersion */                           \
24295     xClose,                     /* xClose */                             \
24296     unixRead,                   /* xRead */                              \
24297     unixWrite,                  /* xWrite */                             \
24298     unixTruncate,               /* xTruncate */                          \
24299     unixSync,                   /* xSync */                              \
24300     unixFileSize,               /* xFileSize */                          \
24301     xLock,                      /* xLock */                              \
24302     xUnlock,                    /* xUnlock */                            \
24303     xCheckReservedLock,         /* xCheckReservedLock */                 \
24304     unixFileControl,            /* xFileControl */                       \
24305     unixSectorSize,             /* xSectorSize */                        \
24306     unixDeviceCharacteristics   /* xDeviceCapabilities */                \
24307   }
24308   static sqlite3_io_methods aIoMethod[] = {
24309     IOMETHODS(unixClose, unixLock, unixUnlock, unixCheckReservedLock) 
24310    ,IOMETHODS(nolockClose, nolockLock, nolockUnlock, nolockCheckReservedLock)
24311 #if SQLITE_ENABLE_LOCKING_STYLE
24312    ,IOMETHODS(dotlockClose, dotlockLock, dotlockUnlock,dotlockCheckReservedLock)
24313 #if IS_VXWORKS
24314    ,IOMETHODS(nolockClose, nolockLock, nolockUnlock, nolockCheckReservedLock)
24315    ,IOMETHODS(nolockClose, nolockLock, nolockUnlock, nolockCheckReservedLock)
24316    ,IOMETHODS(namedsemClose, namedsemLock, namedsemUnlock, namedsemCheckReservedLock)
24317 #else
24318    ,IOMETHODS(flockClose, flockLock, flockUnlock, flockCheckReservedLock)
24319    ,IOMETHODS(afpClose, afpLock, afpUnlock, afpCheckReservedLock)
24320    ,IOMETHODS(nolockClose, nolockLock, nolockUnlock, nolockCheckReservedLock)
24321 #endif
24322 #endif
24323   };
24324   /* The order of the IOMETHODS macros above is important.  It must be the
24325   ** same order as the LOCKING_STYLE numbers
24326   */
24327   assert(LOCKING_STYLE_POSIX==1);
24328   assert(LOCKING_STYLE_NONE==2);
24329   assert(LOCKING_STYLE_DOTFILE==3);
24330   assert(LOCKING_STYLE_FLOCK==4);
24331   assert(LOCKING_STYLE_AFP==5);
24332   assert(LOCKING_STYLE_NAMEDSEM==6);
24333
24334   assert( pNew->pLock==NULL );
24335   assert( pNew->pOpen==NULL );
24336
24337   /* Parameter isDelete is only used on vxworks. Parameter pVfs is only
24338   ** used if ENABLE_LOCKING_STYLE is defined. Express this explicitly 
24339   ** here to prevent compiler warnings about unused parameters.
24340   */
24341   if( !IS_VXWORKS ) UNUSED_PARAMETER(isDelete);
24342   if( !SQLITE_ENABLE_LOCKING_STYLE ) UNUSED_PARAMETER(pVfs);
24343   if( !IS_VXWORKS && !SQLITE_ENABLE_LOCKING_STYLE ) UNUSED_PARAMETER(zFilename);
24344
24345   OSTRACE3("OPEN    %-3d %s\n", h, zFilename);    
24346   pNew->h = h;
24347   pNew->dirfd = dirfd;
24348   SET_THREADID(pNew);
24349
24350 #if IS_VXWORKS
24351   {
24352     HashElem *pElem;
24353     char *zRealname = vxrealpath(zFilename, 1);
24354     int n;
24355     pNew->zRealpath = 0;
24356     if( !zRealname ){
24357       rc = SQLITE_NOMEM;
24358       eLockingStyle = LOCKING_STYLE_NONE;
24359     }else{
24360       n = strlen(zRealname) + 1;
24361       enterMutex();
24362       pElem = sqlite3HashFindElem(&nameHash, zRealname, n);
24363       if( pElem ){
24364         long cnt = (long)pElem->data;
24365         cnt++;
24366         pNew->zRealpath = pElem->pKey;
24367         pElem->data = (void*)cnt;
24368       }else{
24369         if( sqlite3HashInsert(&nameHash, zRealname, n, (void*)1)==0 ){
24370           pElem = sqlite3HashFindElem(&nameHash, zRealname, n);
24371           if( pElem ){
24372             pNew->zRealpath = pElem->pKey;
24373           }else{
24374             sqlite3HashInsert(&nameHash, zRealname, n, 0);
24375             rc = SQLITE_NOMEM;
24376             eLockingStyle = LOCKING_STYLE_NONE;
24377           }
24378         }
24379       }
24380       leaveMutex();
24381       sqlite3_free(zRealname);
24382     }
24383   }
24384 #endif
24385
24386   if( noLock ){
24387     eLockingStyle = LOCKING_STYLE_NONE;
24388   }else{
24389     eLockingStyle = detectLockingStyle(pVfs, zFilename, h);
24390   }
24391
24392   switch( eLockingStyle ){
24393
24394     case LOCKING_STYLE_POSIX: {
24395       enterMutex();
24396 #if IS_VXWORKS
24397       rc = findLockInfo(h, pNew->zRealpath, &pNew->pLock, &pNew->pOpen);
24398 #else
24399       rc = findLockInfo(h, &pNew->pLock, &pNew->pOpen);
24400 #endif
24401       leaveMutex();
24402       break;
24403     }
24404
24405 #if SQLITE_ENABLE_LOCKING_STYLE
24406
24407 #if !IS_VXWORKS
24408     case LOCKING_STYLE_AFP: {
24409       /* AFP locking uses the file path so it needs to be included in
24410       ** the afpLockingContext.
24411       */
24412       afpLockingContext *pCtx;
24413       pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
24414       if( pCtx==0 ){
24415         rc = SQLITE_NOMEM;
24416       }else{
24417         /* NB: zFilename exists and remains valid until the file is closed
24418         ** according to requirement F11141.  So we do not need to make a
24419         ** copy of the filename. */
24420         pCtx->filePath = zFilename;
24421         srandomdev();
24422       }
24423       break;
24424     }
24425 #endif
24426
24427     case LOCKING_STYLE_DOTFILE: {
24428       /* Dotfile locking uses the file path so it needs to be included in
24429       ** the dotlockLockingContext 
24430       */
24431       char *zLockFile;
24432       int nFilename;
24433       nFilename = strlen(zFilename) + 6;
24434       zLockFile = (char *)sqlite3_malloc(nFilename);
24435       if( zLockFile==0 ){
24436         rc = SQLITE_NOMEM;
24437       }else{
24438         sqlite3_snprintf(nFilename, zLockFile, "%s.lock", zFilename);
24439       }
24440       pNew->lockingContext = zLockFile;
24441       break;
24442     }
24443
24444 #if IS_VXWORKS
24445     case LOCKING_STYLE_NAMEDSEM: {
24446       /* Named semaphore locking uses the file path so it needs to be
24447       ** included in the namedsemLockingContext
24448       */
24449       enterMutex();
24450       rc = findLockInfo(h, pNew->zRealpath, &pNew->pLock, &pNew->pOpen);
24451       if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){
24452         char *zSemName = pNew->pOpen->aSemName;
24453         int n;
24454         sqlite3_snprintf(MAX_PATHNAME, zSemName, "%s.sem", pNew->zRealpath);
24455         for( n=0; zSemName[n]; n++ )
24456           if( zSemName[n]=='/' ) zSemName[n] = '_';
24457         pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
24458         if( pNew->pOpen->pSem == SEM_FAILED ){
24459           rc = SQLITE_NOMEM;
24460           pNew->pOpen->aSemName[0] = '\0';
24461         }
24462       }
24463       leaveMutex();
24464       break;
24465     }
24466 #endif
24467
24468     case LOCKING_STYLE_FLOCK: 
24469     case LOCKING_STYLE_NONE: 
24470       break;
24471 #endif
24472   }
24473   
24474   pNew->lastErrno = 0;
24475 #if IS_VXWORKS
24476   if( rc!=SQLITE_OK ){
24477     unlink(zFilename);
24478     isDelete = 0;
24479   }
24480   pNew->isDelete = isDelete;
24481 #endif
24482   if( rc!=SQLITE_OK ){
24483     if( dirfd>=0 ) close(dirfd);
24484     close(h);
24485   }else{
24486     pNew->pMethod = &aIoMethod[eLockingStyle-1];
24487     OpenCounter(+1);
24488   }
24489   return rc;
24490 }
24491
24492 /*
24493 ** Open a file descriptor to the directory containing file zFilename.
24494 ** If successful, *pFd is set to the opened file descriptor and
24495 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
24496 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
24497 ** value.
24498 **
24499 ** If SQLITE_OK is returned, the caller is responsible for closing
24500 ** the file descriptor *pFd using close().
24501 */
24502 static int openDirectory(const char *zFilename, int *pFd){
24503   int ii;
24504   int fd = -1;
24505   char zDirname[MAX_PATHNAME+1];
24506
24507   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
24508   for(ii=strlen(zDirname); ii>=0 && zDirname[ii]!='/'; ii--);
24509   if( ii>0 ){
24510     zDirname[ii] = '\0';
24511     fd = open(zDirname, O_RDONLY|O_BINARY, 0);
24512     if( fd>=0 ){
24513 #ifdef FD_CLOEXEC
24514       fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
24515 #endif
24516       OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
24517     }
24518   }
24519   *pFd = fd;
24520   return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
24521 }
24522
24523 /*
24524 ** Create a temporary file name in zBuf.  zBuf must be allocated
24525 ** by the calling process and must be big enough to hold at least
24526 ** pVfs->mxPathname bytes.
24527 */
24528 static int getTempname(int nBuf, char *zBuf){
24529   static const char *azDirs[] = {
24530      0,
24531      "/var/tmp",
24532      "/usr/tmp",
24533      "/tmp",
24534      ".",
24535   };
24536   static const unsigned char zChars[] =
24537     "abcdefghijklmnopqrstuvwxyz"
24538     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
24539     "0123456789";
24540   int i, j;
24541   struct stat buf;
24542   const char *zDir = ".";
24543
24544   /* It's odd to simulate an io-error here, but really this is just
24545   ** using the io-error infrastructure to test that SQLite handles this
24546   ** function failing. 
24547   */
24548   SimulateIOError( return SQLITE_IOERR );
24549
24550   azDirs[0] = sqlite3_temp_directory;
24551   for(i=0; i<ArraySize(azDirs); i++){
24552     if( azDirs[i]==0 ) continue;
24553     if( stat(azDirs[i], &buf) ) continue;
24554     if( !S_ISDIR(buf.st_mode) ) continue;
24555     if( access(azDirs[i], 07) ) continue;
24556     zDir = azDirs[i];
24557     break;
24558   }
24559
24560   /* Check that the output buffer is large enough for the temporary file 
24561   ** name. If it is not, return SQLITE_ERROR.
24562   */
24563   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
24564     return SQLITE_ERROR;
24565   }
24566
24567   do{
24568     sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
24569     j = strlen(zBuf);
24570     sqlite3_randomness(15, &zBuf[j]);
24571     for(i=0; i<15; i++, j++){
24572       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
24573     }
24574     zBuf[j] = 0;
24575   }while( access(zBuf,0)==0 );
24576   return SQLITE_OK;
24577 }
24578
24579
24580 /*
24581 ** Open the file zPath.
24582 ** 
24583 ** Previously, the SQLite OS layer used three functions in place of this
24584 ** one:
24585 **
24586 **     sqlite3OsOpenReadWrite();
24587 **     sqlite3OsOpenReadOnly();
24588 **     sqlite3OsOpenExclusive();
24589 **
24590 ** These calls correspond to the following combinations of flags:
24591 **
24592 **     ReadWrite() ->     (READWRITE | CREATE)
24593 **     ReadOnly()  ->     (READONLY) 
24594 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
24595 **
24596 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
24597 ** true, the file was configured to be automatically deleted when the
24598 ** file handle closed. To achieve the same effect using this new 
24599 ** interface, add the DELETEONCLOSE flag to those specified above for 
24600 ** OpenExclusive().
24601 */
24602 static int unixOpen(
24603   sqlite3_vfs *pVfs, 
24604   const char *zPath, 
24605   sqlite3_file *pFile,
24606   int flags,
24607   int *pOutFlags
24608 ){
24609   int fd = 0;                    /* File descriptor returned by open() */
24610   int dirfd = -1;                /* Directory file descriptor */
24611   int oflags = 0;                /* Flags to pass to open() */
24612   int eType = flags&0xFFFFFF00;  /* Type of file to open */
24613   int noLock;                    /* True to omit locking primitives */
24614
24615   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
24616   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
24617   int isCreate     = (flags & SQLITE_OPEN_CREATE);
24618   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
24619   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
24620
24621   /* If creating a master or main-file journal, this function will open
24622   ** a file-descriptor on the directory too. The first time unixSync()
24623   ** is called the directory file descriptor will be fsync()ed and close()d.
24624   */
24625   int isOpenDirectory = (isCreate && 
24626       (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
24627   );
24628
24629   /* If argument zPath is a NULL pointer, this function is required to open
24630   ** a temporary file. Use this buffer to store the file name in.
24631   */
24632   char zTmpname[MAX_PATHNAME+1];
24633   const char *zName = zPath;
24634
24635   /* Check the following statements are true: 
24636   **
24637   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
24638   **   (b) if CREATE is set, then READWRITE must also be set, and
24639   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
24640   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
24641   */
24642   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
24643   assert(isCreate==0 || isReadWrite);
24644   assert(isExclusive==0 || isCreate);
24645   assert(isDelete==0 || isCreate);
24646
24647   /* The main DB, main journal, and master journal are never automatically
24648   ** deleted
24649   */
24650   assert( eType!=SQLITE_OPEN_MAIN_DB || !isDelete );
24651   assert( eType!=SQLITE_OPEN_MAIN_JOURNAL || !isDelete );
24652   assert( eType!=SQLITE_OPEN_MASTER_JOURNAL || !isDelete );
24653
24654   /* Assert that the upper layer has set one of the "file-type" flags. */
24655   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
24656        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
24657        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
24658        || eType==SQLITE_OPEN_TRANSIENT_DB
24659   );
24660
24661   memset(pFile, 0, sizeof(unixFile));
24662
24663   if( !zName ){
24664     int rc;
24665     assert(isDelete && !isOpenDirectory);
24666     rc = getTempname(MAX_PATHNAME+1, zTmpname);
24667     if( rc!=SQLITE_OK ){
24668       return rc;
24669     }
24670     zName = zTmpname;
24671   }
24672
24673   if( isReadonly )  oflags |= O_RDONLY;
24674   if( isReadWrite ) oflags |= O_RDWR;
24675   if( isCreate )    oflags |= O_CREAT;
24676   if( isExclusive ) oflags |= (O_EXCL|O_NOFOLLOW);
24677   oflags |= (O_LARGEFILE|O_BINARY);
24678
24679   fd = open(zName, oflags, isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
24680   OSTRACE4("OPENX   %-3d %s 0%o\n", fd, zName, oflags);
24681   if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
24682     /* Failed to open the file for read/write access. Try read-only. */
24683     flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
24684     flags |= SQLITE_OPEN_READONLY;
24685     return unixOpen(pVfs, zPath, pFile, flags, pOutFlags);
24686   }
24687   if( fd<0 ){
24688     return SQLITE_CANTOPEN;
24689   }
24690   if( isDelete ){
24691 #if IS_VXWORKS
24692     zPath = zName;
24693 #else
24694     unlink(zName);
24695 #endif
24696   }
24697   if( pOutFlags ){
24698     *pOutFlags = flags;
24699   }
24700
24701   assert(fd!=0);
24702   if( isOpenDirectory ){
24703     int rc = openDirectory(zPath, &dirfd);
24704     if( rc!=SQLITE_OK ){
24705       close(fd);
24706       return rc;
24707     }
24708   }
24709
24710 #ifdef FD_CLOEXEC
24711   fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
24712 #endif
24713
24714   noLock = eType!=SQLITE_OPEN_MAIN_DB;
24715   return fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
24716 }
24717
24718 /*
24719 ** Delete the file at zPath. If the dirSync argument is true, fsync()
24720 ** the directory after deleting the file.
24721 */
24722 static int unixDelete(sqlite3_vfs *NotUsed, const char *zPath, int dirSync){
24723   int rc = SQLITE_OK;
24724   UNUSED_PARAMETER(NotUsed);
24725   SimulateIOError(return SQLITE_IOERR_DELETE);
24726   unlink(zPath);
24727 #ifndef SQLITE_DISABLE_DIRSYNC
24728   if( dirSync ){
24729     int fd;
24730     rc = openDirectory(zPath, &fd);
24731     if( rc==SQLITE_OK ){
24732 #if IS_VXWORKS
24733       if( fsync(fd)==-1 )
24734 #else
24735       if( fsync(fd) )
24736 #endif
24737       {
24738         rc = SQLITE_IOERR_DIR_FSYNC;
24739       }
24740       close(fd);
24741     }
24742   }
24743 #endif
24744   return rc;
24745 }
24746
24747 /*
24748 ** Test the existance of or access permissions of file zPath. The
24749 ** test performed depends on the value of flags:
24750 **
24751 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
24752 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
24753 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
24754 **
24755 ** Otherwise return 0.
24756 */
24757 static int unixAccess(
24758   sqlite3_vfs *NotUsed, 
24759   const char *zPath, 
24760   int flags, 
24761   int *pResOut
24762 ){
24763   int amode = 0;
24764   UNUSED_PARAMETER(NotUsed);
24765   SimulateIOError( return SQLITE_IOERR_ACCESS; );
24766   switch( flags ){
24767     case SQLITE_ACCESS_EXISTS:
24768       amode = F_OK;
24769       break;
24770     case SQLITE_ACCESS_READWRITE:
24771       amode = W_OK|R_OK;
24772       break;
24773     case SQLITE_ACCESS_READ:
24774       amode = R_OK;
24775       break;
24776
24777     default:
24778       assert(!"Invalid flags argument");
24779   }
24780   *pResOut = (access(zPath, amode)==0);
24781   return SQLITE_OK;
24782 }
24783
24784
24785 /*
24786 ** Turn a relative pathname into a full pathname. The relative path
24787 ** is stored as a nul-terminated string in the buffer pointed to by
24788 ** zPath. 
24789 **
24790 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
24791 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
24792 ** this buffer before returning.
24793 */
24794 static int unixFullPathname(
24795   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
24796   const char *zPath,            /* Possibly relative input path */
24797   int nOut,                     /* Size of output buffer in bytes */
24798   char *zOut                    /* Output buffer */
24799 ){
24800
24801   /* It's odd to simulate an io-error here, but really this is just
24802   ** using the io-error infrastructure to test that SQLite handles this
24803   ** function failing. This function could fail if, for example, the
24804   ** current working directly has been unlinked.
24805   */
24806   SimulateIOError( return SQLITE_ERROR );
24807
24808   assert( pVfs->mxPathname==MAX_PATHNAME );
24809   UNUSED_PARAMETER(pVfs);
24810
24811 #if IS_VXWORKS
24812   {
24813     char *zRealname = vxrealpath(zPath, 0);
24814     zOut[0] = '\0';
24815     if( !zRealname ){
24816       return SQLITE_CANTOPEN;
24817     }
24818     sqlite3_snprintf(nOut, zOut, "%s", zRealname);
24819     sqlite3_free(zRealname);
24820     return SQLITE_OK;
24821   }
24822 #else
24823   zOut[nOut-1] = '\0';
24824   if( zPath[0]=='/' ){
24825     sqlite3_snprintf(nOut, zOut, "%s", zPath);
24826   }else{
24827     int nCwd;
24828     if( getcwd(zOut, nOut-1)==0 ){
24829       return SQLITE_CANTOPEN;
24830     }
24831     nCwd = strlen(zOut);
24832     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
24833   }
24834   return SQLITE_OK;
24835
24836 #if 0
24837   /*
24838   ** Remove "/./" path elements and convert "/A/./" path elements
24839   ** to just "/".
24840   */
24841   if( zFull ){
24842     int i, j;
24843     for(i=j=0; zFull[i]; i++){
24844       if( zFull[i]=='/' ){
24845         if( zFull[i+1]=='/' ) continue;
24846         if( zFull[i+1]=='.' && zFull[i+2]=='/' ){
24847           i += 1;
24848           continue;
24849         }
24850         if( zFull[i+1]=='.' && zFull[i+2]=='.' && zFull[i+3]=='/' ){
24851           while( j>0 && zFull[j-1]!='/' ){ j--; }
24852           i += 3;
24853           continue;
24854         }
24855       }
24856       zFull[j++] = zFull[i];
24857     }
24858     zFull[j] = 0;
24859   }
24860 #endif
24861 #endif
24862 }
24863
24864
24865 #ifndef SQLITE_OMIT_LOAD_EXTENSION
24866 /*
24867 ** Interfaces for opening a shared library, finding entry points
24868 ** within the shared library, and closing the shared library.
24869 */
24870 #include <dlfcn.h>
24871 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
24872   UNUSED_PARAMETER(NotUsed);
24873   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
24874 }
24875
24876 /*
24877 ** SQLite calls this function immediately after a call to unixDlSym() or
24878 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
24879 ** message is available, it is written to zBufOut. If no error message
24880 ** is available, zBufOut is left unmodified and SQLite uses a default
24881 ** error message.
24882 */
24883 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
24884   char *zErr;
24885   UNUSED_PARAMETER(NotUsed);
24886   enterMutex();
24887   zErr = dlerror();
24888   if( zErr ){
24889     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
24890   }
24891   leaveMutex();
24892 }
24893 static void *unixDlSym(sqlite3_vfs *NotUsed, void *pHandle, const char*zSymbol){
24894   UNUSED_PARAMETER(NotUsed);
24895   return dlsym(pHandle, zSymbol);
24896 }
24897 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
24898   UNUSED_PARAMETER(NotUsed);
24899   dlclose(pHandle);
24900 }
24901 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
24902   #define unixDlOpen  0
24903   #define unixDlError 0
24904   #define unixDlSym   0
24905   #define unixDlClose 0
24906 #endif
24907
24908 /*
24909 ** Write nBuf bytes of random data to the supplied buffer zBuf.
24910 */
24911 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
24912   UNUSED_PARAMETER(NotUsed);
24913   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
24914
24915   /* We have to initialize zBuf to prevent valgrind from reporting
24916   ** errors.  The reports issued by valgrind are incorrect - we would
24917   ** prefer that the randomness be increased by making use of the
24918   ** uninitialized space in zBuf - but valgrind errors tend to worry
24919   ** some users.  Rather than argue, it seems easier just to initialize
24920   ** the whole array and silence valgrind, even if that means less randomness
24921   ** in the random seed.
24922   **
24923   ** When testing, initializing zBuf[] to zero is all we do.  That means
24924   ** that we always use the same random number sequence.  This makes the
24925   ** tests repeatable.
24926   */
24927   memset(zBuf, 0, nBuf);
24928 #if !defined(SQLITE_TEST)
24929   {
24930     int pid, fd;
24931     fd = open("/dev/urandom", O_RDONLY);
24932     if( fd<0 ){
24933       time_t t;
24934       time(&t);
24935       memcpy(zBuf, &t, sizeof(t));
24936       pid = getpid();
24937       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
24938       assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
24939       nBuf = sizeof(t) + sizeof(pid);
24940     }else{
24941       nBuf = read(fd, zBuf, nBuf);
24942       close(fd);
24943     }
24944   }
24945 #endif
24946   return nBuf;
24947 }
24948
24949
24950 /*
24951 ** Sleep for a little while.  Return the amount of time slept.
24952 ** The argument is the number of microseconds we want to sleep.
24953 ** The return value is the number of microseconds of sleep actually
24954 ** requested from the underlying operating system, a number which
24955 ** might be greater than or equal to the argument, but not less
24956 ** than the argument.
24957 */
24958 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
24959 #if IS_VXWORKS
24960   struct timespec sp;
24961
24962   sp.tv_sec = microseconds / 1000000;
24963   sp.tv_nsec = (microseconds % 1000000) * 1000;
24964   nanosleep(&sp, NULL);
24965   return microseconds;
24966 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
24967   usleep(microseconds);
24968   return microseconds;
24969 #else
24970   int seconds = (microseconds+999999)/1000000;
24971   sleep(seconds);
24972   return seconds*1000000;
24973 #endif
24974   UNUSED_PARAMETER(NotUsed);
24975 }
24976
24977 /*
24978 ** The following variable, if set to a non-zero value, becomes the result
24979 ** returned from sqlite3OsCurrentTime().  This is used for testing.
24980 */
24981 #ifdef SQLITE_TEST
24982 SQLITE_API int sqlite3_current_time = 0;
24983 #endif
24984
24985 /*
24986 ** Find the current time (in Universal Coordinated Time).  Write the
24987 ** current time and date as a Julian Day number into *prNow and
24988 ** return 0.  Return 1 if the time and date cannot be found.
24989 */
24990 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
24991 #if IS_VXWORKS
24992   struct timespec sNow;
24993   clock_gettime(CLOCK_REALTIME, &sNow);
24994   *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_nsec/86400000000000.0;
24995 #elif defined(NO_GETTOD)
24996   time_t t;
24997   time(&t);
24998   *prNow = t/86400.0 + 2440587.5;
24999 #else
25000   struct timeval sNow;
25001   gettimeofday(&sNow, 0);
25002   *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
25003 #endif
25004
25005 #ifdef SQLITE_TEST
25006   if( sqlite3_current_time ){
25007     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
25008   }
25009 #endif
25010   UNUSED_PARAMETER(NotUsed);
25011   return 0;
25012 }
25013
25014 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
25015   UNUSED_PARAMETER(NotUsed);
25016   UNUSED_PARAMETER(NotUsed2);
25017   UNUSED_PARAMETER(NotUsed3);
25018   return 0;
25019 }
25020
25021 /*
25022 ** Initialize the operating system interface.
25023 */
25024 SQLITE_API int sqlite3_os_init(void){ 
25025   /* Macro to define the static contents of an sqlite3_vfs structure for
25026   ** the unix backend. The two parameters are the values to use for
25027   ** the sqlite3_vfs.zName and sqlite3_vfs.pAppData fields, respectively.
25028   ** 
25029   */
25030   #define UNIXVFS(zVfsName, pVfsAppData) {                  \
25031     1,                    /* iVersion */                    \
25032     sizeof(unixFile),     /* szOsFile */                    \
25033     MAX_PATHNAME,         /* mxPathname */                  \
25034     0,                    /* pNext */                       \
25035     zVfsName,             /* zName */                       \
25036     (void *)pVfsAppData,  /* pAppData */                    \
25037     unixOpen,             /* xOpen */                       \
25038     unixDelete,           /* xDelete */                     \
25039     unixAccess,           /* xAccess */                     \
25040     unixFullPathname,     /* xFullPathname */               \
25041     unixDlOpen,           /* xDlOpen */                     \
25042     unixDlError,          /* xDlError */                    \
25043     unixDlSym,            /* xDlSym */                      \
25044     unixDlClose,          /* xDlClose */                    \
25045     unixRandomness,       /* xRandomness */                 \
25046     unixSleep,            /* xSleep */                      \
25047     unixCurrentTime,      /* xCurrentTime */                \
25048     unixGetLastError      /* xGetLastError */               \
25049   }
25050
25051   static sqlite3_vfs unixVfs = UNIXVFS("unix", 0);
25052 #if SQLITE_ENABLE_LOCKING_STYLE
25053   int i;
25054   static sqlite3_vfs aVfs[] = {
25055     UNIXVFS("unix-posix",   LOCKING_STYLE_POSIX), 
25056     UNIXVFS("unix-afp",     LOCKING_STYLE_AFP), 
25057     UNIXVFS("unix-flock",   LOCKING_STYLE_FLOCK), 
25058     UNIXVFS("unix-dotfile", LOCKING_STYLE_DOTFILE), 
25059     UNIXVFS("unix-none",    LOCKING_STYLE_NONE),
25060     UNIXVFS("unix-namedsem",LOCKING_STYLE_NAMEDSEM),
25061   };
25062   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
25063     sqlite3_vfs_register(&aVfs[i], 0);
25064   }
25065 #endif
25066 #if IS_VXWORKS
25067   sqlite3HashInit(&nameHash, 1);
25068 #endif
25069   sqlite3_vfs_register(&unixVfs, 1);
25070   return SQLITE_OK; 
25071 }
25072
25073 /*
25074 ** Shutdown the operating system interface. This is a no-op for unix.
25075 */
25076 SQLITE_API int sqlite3_os_end(void){ 
25077   return SQLITE_OK; 
25078 }
25079  
25080 #endif /* SQLITE_OS_UNIX */
25081
25082 /************** End of os_unix.c *********************************************/
25083 /************** Begin file os_win.c ******************************************/
25084 /*
25085 ** 2004 May 22
25086 **
25087 ** The author disclaims copyright to this source code.  In place of
25088 ** a legal notice, here is a blessing:
25089 **
25090 **    May you do good and not evil.
25091 **    May you find forgiveness for yourself and forgive others.
25092 **    May you share freely, never taking more than you give.
25093 **
25094 ******************************************************************************
25095 **
25096 ** This file contains code that is specific to windows.
25097 **
25098 ** $Id: os_win.c,v 1.140 2008/11/19 21:35:47 shane Exp $
25099 */
25100 #if SQLITE_OS_WIN               /* This file is used for windows only */
25101
25102
25103 /*
25104 ** A Note About Memory Allocation:
25105 **
25106 ** This driver uses malloc()/free() directly rather than going through
25107 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
25108 ** are designed for use on embedded systems where memory is scarce and
25109 ** malloc failures happen frequently.  Win32 does not typically run on
25110 ** embedded systems, and when it does the developers normally have bigger
25111 ** problems to worry about than running out of memory.  So there is not
25112 ** a compelling need to use the wrappers.
25113 **
25114 ** But there is a good reason to not use the wrappers.  If we use the
25115 ** wrappers then we will get simulated malloc() failures within this
25116 ** driver.  And that causes all kinds of problems for our tests.  We
25117 ** could enhance SQLite to deal with simulated malloc failures within
25118 ** the OS driver, but the code to deal with those failure would not
25119 ** be exercised on Linux (which does not need to malloc() in the driver)
25120 ** and so we would have difficulty writing coverage tests for that
25121 ** code.  Better to leave the code out, we think.
25122 **
25123 ** The point of this discussion is as follows:  When creating a new
25124 ** OS layer for an embedded system, if you use this file as an example,
25125 ** avoid the use of malloc()/free().  Those routines work ok on windows
25126 ** desktops but not so well in embedded systems.
25127 */
25128
25129 #include <winbase.h>
25130
25131 #ifdef __CYGWIN__
25132 # include <sys/cygwin.h>
25133 #endif
25134
25135 /*
25136 ** Macros used to determine whether or not to use threads.
25137 */
25138 #if defined(THREADSAFE) && THREADSAFE
25139 # define SQLITE_W32_THREADS 1
25140 #endif
25141
25142 /*
25143 ** Include code that is common to all os_*.c files
25144 */
25145 /************** Include os_common.h in the middle of os_win.c ****************/
25146 /************** Begin file os_common.h ***************************************/
25147 /*
25148 ** 2004 May 22
25149 **
25150 ** The author disclaims copyright to this source code.  In place of
25151 ** a legal notice, here is a blessing:
25152 **
25153 **    May you do good and not evil.
25154 **    May you find forgiveness for yourself and forgive others.
25155 **    May you share freely, never taking more than you give.
25156 **
25157 ******************************************************************************
25158 **
25159 ** This file contains macros and a little bit of code that is common to
25160 ** all of the platform-specific files (os_*.c) and is #included into those
25161 ** files.
25162 **
25163 ** This file should be #included by the os_*.c files only.  It is not a
25164 ** general purpose header file.
25165 **
25166 ** $Id: os_common.h,v 1.37 2008/05/29 20:22:37 shane Exp $
25167 */
25168 #ifndef _OS_COMMON_H_
25169 #define _OS_COMMON_H_
25170
25171 /*
25172 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
25173 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
25174 ** switch.  The following code should catch this problem at compile-time.
25175 */
25176 #ifdef MEMORY_DEBUG
25177 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
25178 #endif
25179
25180
25181 /*
25182  * When testing, this global variable stores the location of the
25183  * pending-byte in the database file.
25184  */
25185 #ifdef SQLITE_TEST
25186 SQLITE_API unsigned int sqlite3_pending_byte = 0x40000000;
25187 #endif
25188
25189 #ifdef SQLITE_DEBUG
25190 SQLITE_PRIVATE int sqlite3OSTrace = 0;
25191 #define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
25192 #define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
25193 #define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
25194 #define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
25195 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
25196 #define OSTRACE6(X,Y,Z,A,B,C) \
25197     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
25198 #define OSTRACE7(X,Y,Z,A,B,C,D) \
25199     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
25200 #else
25201 #define OSTRACE1(X)
25202 #define OSTRACE2(X,Y)
25203 #define OSTRACE3(X,Y,Z)
25204 #define OSTRACE4(X,Y,Z,A)
25205 #define OSTRACE5(X,Y,Z,A,B)
25206 #define OSTRACE6(X,Y,Z,A,B,C)
25207 #define OSTRACE7(X,Y,Z,A,B,C,D)
25208 #endif
25209
25210 /*
25211 ** Macros for performance tracing.  Normally turned off.  Only works
25212 ** on i486 hardware.
25213 */
25214 #ifdef SQLITE_PERFORMANCE_TRACE
25215
25216 /* 
25217 ** hwtime.h contains inline assembler code for implementing 
25218 ** high-performance timing routines.
25219 */
25220 /************** Include hwtime.h in the middle of os_common.h ****************/
25221 /************** Begin file hwtime.h ******************************************/
25222 /*
25223 ** 2008 May 27
25224 **
25225 ** The author disclaims copyright to this source code.  In place of
25226 ** a legal notice, here is a blessing:
25227 **
25228 **    May you do good and not evil.
25229 **    May you find forgiveness for yourself and forgive others.
25230 **    May you share freely, never taking more than you give.
25231 **
25232 ******************************************************************************
25233 **
25234 ** This file contains inline asm code for retrieving "high-performance"
25235 ** counters for x86 class CPUs.
25236 **
25237 ** $Id: hwtime.h,v 1.3 2008/08/01 14:33:15 shane Exp $
25238 */
25239 #ifndef _HWTIME_H_
25240 #define _HWTIME_H_
25241
25242 /*
25243 ** The following routine only works on pentium-class (or newer) processors.
25244 ** It uses the RDTSC opcode to read the cycle count value out of the
25245 ** processor and returns that value.  This can be used for high-res
25246 ** profiling.
25247 */
25248 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
25249       (defined(i386) || defined(__i386__) || defined(_M_IX86))
25250
25251   #if defined(__GNUC__)
25252
25253   __inline__ sqlite_uint64 sqlite3Hwtime(void){
25254      unsigned int lo, hi;
25255      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
25256      return (sqlite_uint64)hi << 32 | lo;
25257   }
25258
25259   #elif defined(_MSC_VER)
25260
25261   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
25262      __asm {
25263         rdtsc
25264         ret       ; return value at EDX:EAX
25265      }
25266   }
25267
25268   #endif
25269
25270 #elif (defined(__GNUC__) && defined(__x86_64__))
25271
25272   __inline__ sqlite_uint64 sqlite3Hwtime(void){
25273       unsigned long val;
25274       __asm__ __volatile__ ("rdtsc" : "=A" (val));
25275       return val;
25276   }
25277  
25278 #elif (defined(__GNUC__) && defined(__ppc__))
25279
25280   __inline__ sqlite_uint64 sqlite3Hwtime(void){
25281       unsigned long long retval;
25282       unsigned long junk;
25283       __asm__ __volatile__ ("\n\
25284           1:      mftbu   %1\n\
25285                   mftb    %L0\n\
25286                   mftbu   %0\n\
25287                   cmpw    %0,%1\n\
25288                   bne     1b"
25289                   : "=r" (retval), "=r" (junk));
25290       return retval;
25291   }
25292
25293 #else
25294
25295   #error Need implementation of sqlite3Hwtime() for your platform.
25296
25297   /*
25298   ** To compile without implementing sqlite3Hwtime() for your platform,
25299   ** you can remove the above #error and use the following
25300   ** stub function.  You will lose timing support for many
25301   ** of the debugging and testing utilities, but it should at
25302   ** least compile and run.
25303   */
25304 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
25305
25306 #endif
25307
25308 #endif /* !defined(_HWTIME_H_) */
25309
25310 /************** End of hwtime.h **********************************************/
25311 /************** Continuing where we left off in os_common.h ******************/
25312
25313 static sqlite_uint64 g_start;
25314 static sqlite_uint64 g_elapsed;
25315 #define TIMER_START       g_start=sqlite3Hwtime()
25316 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
25317 #define TIMER_ELAPSED     g_elapsed
25318 #else
25319 #define TIMER_START
25320 #define TIMER_END
25321 #define TIMER_ELAPSED     ((sqlite_uint64)0)
25322 #endif
25323
25324 /*
25325 ** If we compile with the SQLITE_TEST macro set, then the following block
25326 ** of code will give us the ability to simulate a disk I/O error.  This
25327 ** is used for testing the I/O recovery logic.
25328 */
25329 #ifdef SQLITE_TEST
25330 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
25331 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
25332 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
25333 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
25334 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
25335 SQLITE_API int sqlite3_diskfull_pending = 0;
25336 SQLITE_API int sqlite3_diskfull = 0;
25337 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
25338 #define SimulateIOError(CODE)  \
25339   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
25340        || sqlite3_io_error_pending-- == 1 )  \
25341               { local_ioerr(); CODE; }
25342 static void local_ioerr(){
25343   IOTRACE(("IOERR\n"));
25344   sqlite3_io_error_hit++;
25345   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
25346 }
25347 #define SimulateDiskfullError(CODE) \
25348    if( sqlite3_diskfull_pending ){ \
25349      if( sqlite3_diskfull_pending == 1 ){ \
25350        local_ioerr(); \
25351        sqlite3_diskfull = 1; \
25352        sqlite3_io_error_hit = 1; \
25353        CODE; \
25354      }else{ \
25355        sqlite3_diskfull_pending--; \
25356      } \
25357    }
25358 #else
25359 #define SimulateIOErrorBenign(X)
25360 #define SimulateIOError(A)
25361 #define SimulateDiskfullError(A)
25362 #endif
25363
25364 /*
25365 ** When testing, keep a count of the number of open files.
25366 */
25367 #ifdef SQLITE_TEST
25368 SQLITE_API int sqlite3_open_file_count = 0;
25369 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
25370 #else
25371 #define OpenCounter(X)
25372 #endif
25373
25374 #endif /* !defined(_OS_COMMON_H_) */
25375
25376 /************** End of os_common.h *******************************************/
25377 /************** Continuing where we left off in os_win.c *********************/
25378
25379 /*
25380 ** Some microsoft compilers lack this definition.
25381 */
25382 #ifndef INVALID_FILE_ATTRIBUTES
25383 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) 
25384 #endif
25385
25386 /*
25387 ** Determine if we are dealing with WindowsCE - which has a much
25388 ** reduced API.
25389 */
25390 #if SQLITE_OS_WINCE
25391 # define AreFileApisANSI() 1
25392 #endif
25393
25394 /*
25395 ** WinCE lacks native support for file locking so we have to fake it
25396 ** with some code of our own.
25397 */
25398 #if SQLITE_OS_WINCE
25399 typedef struct winceLock {
25400   int nReaders;       /* Number of reader locks obtained */
25401   BOOL bPending;      /* Indicates a pending lock has been obtained */
25402   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
25403   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
25404 } winceLock;
25405 #endif
25406
25407 /*
25408 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
25409 ** portability layer.
25410 */
25411 typedef struct winFile winFile;
25412 struct winFile {
25413   const sqlite3_io_methods *pMethod;/* Must be first */
25414   HANDLE h;               /* Handle for accessing the file */
25415   unsigned char locktype; /* Type of lock currently held on this file */
25416   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
25417 #if SQLITE_OS_WINCE
25418   WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
25419   HANDLE hMutex;          /* Mutex used to control access to shared lock */  
25420   HANDLE hShared;         /* Shared memory segment used for locking */
25421   winceLock local;        /* Locks obtained by this instance of winFile */
25422   winceLock *shared;      /* Global shared lock memory for the file  */
25423 #endif
25424 };
25425
25426
25427 /*
25428 ** The following variable is (normally) set once and never changes
25429 ** thereafter.  It records whether the operating system is Win95
25430 ** or WinNT.
25431 **
25432 ** 0:   Operating system unknown.
25433 ** 1:   Operating system is Win95.
25434 ** 2:   Operating system is WinNT.
25435 **
25436 ** In order to facilitate testing on a WinNT system, the test fixture
25437 ** can manually set this value to 1 to emulate Win98 behavior.
25438 */
25439 #ifdef SQLITE_TEST
25440 SQLITE_API int sqlite3_os_type = 0;
25441 #else
25442 static int sqlite3_os_type = 0;
25443 #endif
25444
25445 /*
25446 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
25447 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
25448 **
25449 ** Here is an interesting observation:  Win95, Win98, and WinME lack
25450 ** the LockFileEx() API.  But we can still statically link against that
25451 ** API as long as we don't call it win running Win95/98/ME.  A call to
25452 ** this routine is used to determine if the host is Win95/98/ME or
25453 ** WinNT/2K/XP so that we will know whether or not we can safely call
25454 ** the LockFileEx() API.
25455 */
25456 #if SQLITE_OS_WINCE
25457 # define isNT()  (1)
25458 #else
25459   static int isNT(void){
25460     if( sqlite3_os_type==0 ){
25461       OSVERSIONINFO sInfo;
25462       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
25463       GetVersionEx(&sInfo);
25464       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
25465     }
25466     return sqlite3_os_type==2;
25467   }
25468 #endif /* SQLITE_OS_WINCE */
25469
25470 /*
25471 ** Convert a UTF-8 string to microsoft unicode (UTF-16?). 
25472 **
25473 ** Space to hold the returned string is obtained from malloc.
25474 */
25475 static WCHAR *utf8ToUnicode(const char *zFilename){
25476   int nChar;
25477   WCHAR *zWideFilename;
25478
25479   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
25480   zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
25481   if( zWideFilename==0 ){
25482     return 0;
25483   }
25484   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
25485   if( nChar==0 ){
25486     free(zWideFilename);
25487     zWideFilename = 0;
25488   }
25489   return zWideFilename;
25490 }
25491
25492 /*
25493 ** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
25494 ** obtained from malloc().
25495 */
25496 static char *unicodeToUtf8(const WCHAR *zWideFilename){
25497   int nByte;
25498   char *zFilename;
25499
25500   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
25501   zFilename = malloc( nByte );
25502   if( zFilename==0 ){
25503     return 0;
25504   }
25505   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
25506                               0, 0);
25507   if( nByte == 0 ){
25508     free(zFilename);
25509     zFilename = 0;
25510   }
25511   return zFilename;
25512 }
25513
25514 /*
25515 ** Convert an ansi string to microsoft unicode, based on the
25516 ** current codepage settings for file apis.
25517 ** 
25518 ** Space to hold the returned string is obtained
25519 ** from malloc.
25520 */
25521 static WCHAR *mbcsToUnicode(const char *zFilename){
25522   int nByte;
25523   WCHAR *zMbcsFilename;
25524   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
25525
25526   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
25527   zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
25528   if( zMbcsFilename==0 ){
25529     return 0;
25530   }
25531   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
25532   if( nByte==0 ){
25533     free(zMbcsFilename);
25534     zMbcsFilename = 0;
25535   }
25536   return zMbcsFilename;
25537 }
25538
25539 /*
25540 ** Convert microsoft unicode to multibyte character string, based on the
25541 ** user's Ansi codepage.
25542 **
25543 ** Space to hold the returned string is obtained from
25544 ** malloc().
25545 */
25546 static char *unicodeToMbcs(const WCHAR *zWideFilename){
25547   int nByte;
25548   char *zFilename;
25549   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
25550
25551   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
25552   zFilename = malloc( nByte );
25553   if( zFilename==0 ){
25554     return 0;
25555   }
25556   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
25557                               0, 0);
25558   if( nByte == 0 ){
25559     free(zFilename);
25560     zFilename = 0;
25561   }
25562   return zFilename;
25563 }
25564
25565 /*
25566 ** Convert multibyte character string to UTF-8.  Space to hold the
25567 ** returned string is obtained from malloc().
25568 */
25569 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
25570   char *zFilenameUtf8;
25571   WCHAR *zTmpWide;
25572
25573   zTmpWide = mbcsToUnicode(zFilename);
25574   if( zTmpWide==0 ){
25575     return 0;
25576   }
25577   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
25578   free(zTmpWide);
25579   return zFilenameUtf8;
25580 }
25581
25582 /*
25583 ** Convert UTF-8 to multibyte character string.  Space to hold the 
25584 ** returned string is obtained from malloc().
25585 */
25586 static char *utf8ToMbcs(const char *zFilename){
25587   char *zFilenameMbcs;
25588   WCHAR *zTmpWide;
25589
25590   zTmpWide = utf8ToUnicode(zFilename);
25591   if( zTmpWide==0 ){
25592     return 0;
25593   }
25594   zFilenameMbcs = unicodeToMbcs(zTmpWide);
25595   free(zTmpWide);
25596   return zFilenameMbcs;
25597 }
25598
25599 #if SQLITE_OS_WINCE
25600 /*************************************************************************
25601 ** This section contains code for WinCE only.
25602 */
25603 /*
25604 ** WindowsCE does not have a localtime() function.  So create a
25605 ** substitute.
25606 */
25607 struct tm *__cdecl localtime(const time_t *t)
25608 {
25609   static struct tm y;
25610   FILETIME uTm, lTm;
25611   SYSTEMTIME pTm;
25612   sqlite3_int64 t64;
25613   t64 = *t;
25614   t64 = (t64 + 11644473600)*10000000;
25615   uTm.dwLowDateTime = t64 & 0xFFFFFFFF;
25616   uTm.dwHighDateTime= t64 >> 32;
25617   FileTimeToLocalFileTime(&uTm,&lTm);
25618   FileTimeToSystemTime(&lTm,&pTm);
25619   y.tm_year = pTm.wYear - 1900;
25620   y.tm_mon = pTm.wMonth - 1;
25621   y.tm_wday = pTm.wDayOfWeek;
25622   y.tm_mday = pTm.wDay;
25623   y.tm_hour = pTm.wHour;
25624   y.tm_min = pTm.wMinute;
25625   y.tm_sec = pTm.wSecond;
25626   return &y;
25627 }
25628
25629 /* This will never be called, but defined to make the code compile */
25630 #define GetTempPathA(a,b)
25631
25632 #define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
25633 #define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
25634 #define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
25635
25636 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-offsetof(winFile,h)]
25637
25638 /*
25639 ** Acquire a lock on the handle h
25640 */
25641 static void winceMutexAcquire(HANDLE h){
25642    DWORD dwErr;
25643    do {
25644      dwErr = WaitForSingleObject(h, INFINITE);
25645    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
25646 }
25647 /*
25648 ** Release a lock acquired by winceMutexAcquire()
25649 */
25650 #define winceMutexRelease(h) ReleaseMutex(h)
25651
25652 /*
25653 ** Create the mutex and shared memory used for locking in the file
25654 ** descriptor pFile
25655 */
25656 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
25657   WCHAR *zTok;
25658   WCHAR *zName = utf8ToUnicode(zFilename);
25659   BOOL bInit = TRUE;
25660
25661   /* Initialize the local lockdata */
25662   ZeroMemory(&pFile->local, sizeof(pFile->local));
25663
25664   /* Replace the backslashes from the filename and lowercase it
25665   ** to derive a mutex name. */
25666   zTok = CharLowerW(zName);
25667   for (;*zTok;zTok++){
25668     if (*zTok == '\\') *zTok = '_';
25669   }
25670
25671   /* Create/open the named mutex */
25672   pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
25673   if (!pFile->hMutex){
25674     free(zName);
25675     return FALSE;
25676   }
25677
25678   /* Acquire the mutex before continuing */
25679   winceMutexAcquire(pFile->hMutex);
25680   
25681   /* Since the names of named mutexes, semaphores, file mappings etc are 
25682   ** case-sensitive, take advantage of that by uppercasing the mutex name
25683   ** and using that as the shared filemapping name.
25684   */
25685   CharUpperW(zName);
25686   pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
25687                                        PAGE_READWRITE, 0, sizeof(winceLock),
25688                                        zName);  
25689
25690   /* Set a flag that indicates we're the first to create the memory so it 
25691   ** must be zero-initialized */
25692   if (GetLastError() == ERROR_ALREADY_EXISTS){
25693     bInit = FALSE;
25694   }
25695
25696   free(zName);
25697
25698   /* If we succeeded in making the shared memory handle, map it. */
25699   if (pFile->hShared){
25700     pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared, 
25701              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
25702     /* If mapping failed, close the shared memory handle and erase it */
25703     if (!pFile->shared){
25704       CloseHandle(pFile->hShared);
25705       pFile->hShared = NULL;
25706     }
25707   }
25708
25709   /* If shared memory could not be created, then close the mutex and fail */
25710   if (pFile->hShared == NULL){
25711     winceMutexRelease(pFile->hMutex);
25712     CloseHandle(pFile->hMutex);
25713     pFile->hMutex = NULL;
25714     return FALSE;
25715   }
25716   
25717   /* Initialize the shared memory if we're supposed to */
25718   if (bInit) {
25719     ZeroMemory(pFile->shared, sizeof(winceLock));
25720   }
25721
25722   winceMutexRelease(pFile->hMutex);
25723   return TRUE;
25724 }
25725
25726 /*
25727 ** Destroy the part of winFile that deals with wince locks
25728 */
25729 static void winceDestroyLock(winFile *pFile){
25730   if (pFile->hMutex){
25731     /* Acquire the mutex */
25732     winceMutexAcquire(pFile->hMutex);
25733
25734     /* The following blocks should probably assert in debug mode, but they
25735        are to cleanup in case any locks remained open */
25736     if (pFile->local.nReaders){
25737       pFile->shared->nReaders --;
25738     }
25739     if (pFile->local.bReserved){
25740       pFile->shared->bReserved = FALSE;
25741     }
25742     if (pFile->local.bPending){
25743       pFile->shared->bPending = FALSE;
25744     }
25745     if (pFile->local.bExclusive){
25746       pFile->shared->bExclusive = FALSE;
25747     }
25748
25749     /* De-reference and close our copy of the shared memory handle */
25750     UnmapViewOfFile(pFile->shared);
25751     CloseHandle(pFile->hShared);
25752
25753     /* Done with the mutex */
25754     winceMutexRelease(pFile->hMutex);    
25755     CloseHandle(pFile->hMutex);
25756     pFile->hMutex = NULL;
25757   }
25758 }
25759
25760 /* 
25761 ** An implementation of the LockFile() API of windows for wince
25762 */
25763 static BOOL winceLockFile(
25764   HANDLE *phFile,
25765   DWORD dwFileOffsetLow,
25766   DWORD dwFileOffsetHigh,
25767   DWORD nNumberOfBytesToLockLow,
25768   DWORD nNumberOfBytesToLockHigh
25769 ){
25770   winFile *pFile = HANDLE_TO_WINFILE(phFile);
25771   BOOL bReturn = FALSE;
25772
25773   if (!pFile->hMutex) return TRUE;
25774   winceMutexAcquire(pFile->hMutex);
25775
25776   /* Wanting an exclusive lock? */
25777   if (dwFileOffsetLow == SHARED_FIRST
25778        && nNumberOfBytesToLockLow == SHARED_SIZE){
25779     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
25780        pFile->shared->bExclusive = TRUE;
25781        pFile->local.bExclusive = TRUE;
25782        bReturn = TRUE;
25783     }
25784   }
25785
25786   /* Want a read-only lock? */
25787   else if ((dwFileOffsetLow >= SHARED_FIRST &&
25788             dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE) &&
25789             nNumberOfBytesToLockLow == 1){
25790     if (pFile->shared->bExclusive == 0){
25791       pFile->local.nReaders ++;
25792       if (pFile->local.nReaders == 1){
25793         pFile->shared->nReaders ++;
25794       }
25795       bReturn = TRUE;
25796     }
25797   }
25798
25799   /* Want a pending lock? */
25800   else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToLockLow == 1){
25801     /* If no pending lock has been acquired, then acquire it */
25802     if (pFile->shared->bPending == 0) {
25803       pFile->shared->bPending = TRUE;
25804       pFile->local.bPending = TRUE;
25805       bReturn = TRUE;
25806     }
25807   }
25808   /* Want a reserved lock? */
25809   else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
25810     if (pFile->shared->bReserved == 0) {
25811       pFile->shared->bReserved = TRUE;
25812       pFile->local.bReserved = TRUE;
25813       bReturn = TRUE;
25814     }
25815   }
25816
25817   winceMutexRelease(pFile->hMutex);
25818   return bReturn;
25819 }
25820
25821 /*
25822 ** An implementation of the UnlockFile API of windows for wince
25823 */
25824 static BOOL winceUnlockFile(
25825   HANDLE *phFile,
25826   DWORD dwFileOffsetLow,
25827   DWORD dwFileOffsetHigh,
25828   DWORD nNumberOfBytesToUnlockLow,
25829   DWORD nNumberOfBytesToUnlockHigh
25830 ){
25831   winFile *pFile = HANDLE_TO_WINFILE(phFile);
25832   BOOL bReturn = FALSE;
25833
25834   if (!pFile->hMutex) return TRUE;
25835   winceMutexAcquire(pFile->hMutex);
25836
25837   /* Releasing a reader lock or an exclusive lock */
25838   if (dwFileOffsetLow >= SHARED_FIRST &&
25839        dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE){
25840     /* Did we have an exclusive lock? */
25841     if (pFile->local.bExclusive){
25842       pFile->local.bExclusive = FALSE;
25843       pFile->shared->bExclusive = FALSE;
25844       bReturn = TRUE;
25845     }
25846
25847     /* Did we just have a reader lock? */
25848     else if (pFile->local.nReaders){
25849       pFile->local.nReaders --;
25850       if (pFile->local.nReaders == 0)
25851       {
25852         pFile->shared->nReaders --;
25853       }
25854       bReturn = TRUE;
25855     }
25856   }
25857
25858   /* Releasing a pending lock */
25859   else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
25860     if (pFile->local.bPending){
25861       pFile->local.bPending = FALSE;
25862       pFile->shared->bPending = FALSE;
25863       bReturn = TRUE;
25864     }
25865   }
25866   /* Releasing a reserved lock */
25867   else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
25868     if (pFile->local.bReserved) {
25869       pFile->local.bReserved = FALSE;
25870       pFile->shared->bReserved = FALSE;
25871       bReturn = TRUE;
25872     }
25873   }
25874
25875   winceMutexRelease(pFile->hMutex);
25876   return bReturn;
25877 }
25878
25879 /*
25880 ** An implementation of the LockFileEx() API of windows for wince
25881 */
25882 static BOOL winceLockFileEx(
25883   HANDLE *phFile,
25884   DWORD dwFlags,
25885   DWORD dwReserved,
25886   DWORD nNumberOfBytesToLockLow,
25887   DWORD nNumberOfBytesToLockHigh,
25888   LPOVERLAPPED lpOverlapped
25889 ){
25890   /* If the caller wants a shared read lock, forward this call
25891   ** to winceLockFile */
25892   if (lpOverlapped->Offset == SHARED_FIRST &&
25893       dwFlags == 1 &&
25894       nNumberOfBytesToLockLow == SHARED_SIZE){
25895     return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
25896   }
25897   return FALSE;
25898 }
25899 /*
25900 ** End of the special code for wince
25901 *****************************************************************************/
25902 #endif /* SQLITE_OS_WINCE */
25903
25904 /*****************************************************************************
25905 ** The next group of routines implement the I/O methods specified
25906 ** by the sqlite3_io_methods object.
25907 ******************************************************************************/
25908
25909 /*
25910 ** Close a file.
25911 **
25912 ** It is reported that an attempt to close a handle might sometimes
25913 ** fail.  This is a very unreasonable result, but windows is notorious
25914 ** for being unreasonable so I do not doubt that it might happen.  If
25915 ** the close fails, we pause for 100 milliseconds and try again.  As
25916 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
25917 ** giving up and returning an error.
25918 */
25919 #define MX_CLOSE_ATTEMPT 3
25920 static int winClose(sqlite3_file *id){
25921   int rc, cnt = 0;
25922   winFile *pFile = (winFile*)id;
25923   OSTRACE2("CLOSE %d\n", pFile->h);
25924   do{
25925     rc = CloseHandle(pFile->h);
25926   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
25927 #if SQLITE_OS_WINCE
25928 #define WINCE_DELETION_ATTEMPTS 3
25929   winceDestroyLock(pFile);
25930   if( pFile->zDeleteOnClose ){
25931     int cnt = 0;
25932     while(
25933            DeleteFileW(pFile->zDeleteOnClose)==0
25934         && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
25935         && cnt++ < WINCE_DELETION_ATTEMPTS
25936     ){
25937        Sleep(100);  /* Wait a little before trying again */
25938     }
25939     free(pFile->zDeleteOnClose);
25940   }
25941 #endif
25942   OpenCounter(-1);
25943   return rc ? SQLITE_OK : SQLITE_IOERR;
25944 }
25945
25946 /*
25947 ** Some microsoft compilers lack this definition.
25948 */
25949 #ifndef INVALID_SET_FILE_POINTER
25950 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
25951 #endif
25952
25953 /*
25954 ** Read data from a file into a buffer.  Return SQLITE_OK if all
25955 ** bytes were read successfully and SQLITE_IOERR if anything goes
25956 ** wrong.
25957 */
25958 static int winRead(
25959   sqlite3_file *id,          /* File to read from */
25960   void *pBuf,                /* Write content into this buffer */
25961   int amt,                   /* Number of bytes to read */
25962   sqlite3_int64 offset       /* Begin reading at this offset */
25963 ){
25964   LONG upperBits = (offset>>32) & 0x7fffffff;
25965   LONG lowerBits = offset & 0xffffffff;
25966   DWORD rc;
25967   DWORD got;
25968   winFile *pFile = (winFile*)id;
25969   assert( id!=0 );
25970   SimulateIOError(return SQLITE_IOERR_READ);
25971   OSTRACE3("READ %d lock=%d\n", pFile->h, pFile->locktype);
25972   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
25973   if( rc==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR ){
25974     return SQLITE_FULL;
25975   }
25976   if( !ReadFile(pFile->h, pBuf, amt, &got, 0) ){
25977     return SQLITE_IOERR_READ;
25978   }
25979   if( got==(DWORD)amt ){
25980     return SQLITE_OK;
25981   }else{
25982     /* Unread parts of the buffer must be zero-filled */
25983     memset(&((char*)pBuf)[got], 0, amt-got);
25984     return SQLITE_IOERR_SHORT_READ;
25985   }
25986 }
25987
25988 /*
25989 ** Write data from a buffer into a file.  Return SQLITE_OK on success
25990 ** or some other error code on failure.
25991 */
25992 static int winWrite(
25993   sqlite3_file *id,         /* File to write into */
25994   const void *pBuf,         /* The bytes to be written */
25995   int amt,                  /* Number of bytes to write */
25996   sqlite3_int64 offset      /* Offset into the file to begin writing at */
25997 ){
25998   LONG upperBits = (offset>>32) & 0x7fffffff;
25999   LONG lowerBits = offset & 0xffffffff;
26000   DWORD rc;
26001   DWORD wrote;
26002   winFile *pFile = (winFile*)id;
26003   assert( id!=0 );
26004   SimulateIOError(return SQLITE_IOERR_WRITE);
26005   SimulateDiskfullError(return SQLITE_FULL);
26006   OSTRACE3("WRITE %d lock=%d\n", pFile->h, pFile->locktype);
26007   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
26008   if( rc==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR ){
26009     return SQLITE_FULL;
26010   }
26011   assert( amt>0 );
26012   while(
26013      amt>0
26014      && (rc = WriteFile(pFile->h, pBuf, amt, &wrote, 0))!=0
26015      && wrote>0
26016   ){
26017     amt -= wrote;
26018     pBuf = &((char*)pBuf)[wrote];
26019   }
26020   if( !rc || amt>(int)wrote ){
26021     return SQLITE_FULL;
26022   }
26023   return SQLITE_OK;
26024 }
26025
26026 /*
26027 ** Truncate an open file to a specified size
26028 */
26029 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
26030   DWORD rc;
26031   LONG upperBits = (nByte>>32) & 0x7fffffff;
26032   LONG lowerBits = nByte & 0xffffffff;
26033   winFile *pFile = (winFile*)id;
26034   OSTRACE3("TRUNCATE %d %lld\n", pFile->h, nByte);
26035   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
26036   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
26037   if( INVALID_SET_FILE_POINTER != rc ){
26038     /* SetEndOfFile will fail if nByte is negative */
26039     if( SetEndOfFile(pFile->h) ){
26040       return SQLITE_OK;
26041     }
26042   }
26043   return SQLITE_IOERR_TRUNCATE;
26044 }
26045
26046 #ifdef SQLITE_TEST
26047 /*
26048 ** Count the number of fullsyncs and normal syncs.  This is used to test
26049 ** that syncs and fullsyncs are occuring at the right times.
26050 */
26051 SQLITE_API int sqlite3_sync_count = 0;
26052 SQLITE_API int sqlite3_fullsync_count = 0;
26053 #endif
26054
26055 /*
26056 ** Make sure all writes to a particular file are committed to disk.
26057 */
26058 static int winSync(sqlite3_file *id, int flags){
26059   winFile *pFile = (winFile*)id;
26060   OSTRACE3("SYNC %d lock=%d\n", pFile->h, pFile->locktype);
26061 #ifdef SQLITE_TEST
26062   if( flags & SQLITE_SYNC_FULL ){
26063     sqlite3_fullsync_count++;
26064   }
26065   sqlite3_sync_count++;
26066 #endif
26067   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
26068   ** no-op
26069   */
26070 #ifdef SQLITE_NO_SYNC
26071     return SQLITE_OK;
26072 #else
26073   if( FlushFileBuffers(pFile->h) ){
26074     return SQLITE_OK;
26075   }else{
26076     return SQLITE_IOERR;
26077   }
26078 #endif
26079 }
26080
26081 /*
26082 ** Determine the current size of a file in bytes
26083 */
26084 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
26085   winFile *pFile = (winFile*)id;
26086   DWORD upperBits, lowerBits;
26087   SimulateIOError(return SQLITE_IOERR_FSTAT);
26088   lowerBits = GetFileSize(pFile->h, &upperBits);
26089   *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
26090   return SQLITE_OK;
26091 }
26092
26093 /*
26094 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
26095 */
26096 #ifndef LOCKFILE_FAIL_IMMEDIATELY
26097 # define LOCKFILE_FAIL_IMMEDIATELY 1
26098 #endif
26099
26100 /*
26101 ** Acquire a reader lock.
26102 ** Different API routines are called depending on whether or not this
26103 ** is Win95 or WinNT.
26104 */
26105 static int getReadLock(winFile *pFile){
26106   int res;
26107   if( isNT() ){
26108     OVERLAPPED ovlp;
26109     ovlp.Offset = SHARED_FIRST;
26110     ovlp.OffsetHigh = 0;
26111     ovlp.hEvent = 0;
26112     res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
26113                      0, SHARED_SIZE, 0, &ovlp);
26114 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
26115 */
26116 #if SQLITE_OS_WINCE==0
26117   }else{
26118     int lk;
26119     sqlite3_randomness(sizeof(lk), &lk);
26120     pFile->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
26121     res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
26122 #endif
26123   }
26124   return res;
26125 }
26126
26127 /*
26128 ** Undo a readlock
26129 */
26130 static int unlockReadLock(winFile *pFile){
26131   int res;
26132   if( isNT() ){
26133     res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
26134 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
26135 */
26136 #if SQLITE_OS_WINCE==0
26137   }else{
26138     res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
26139 #endif
26140   }
26141   return res;
26142 }
26143
26144 /*
26145 ** Lock the file with the lock specified by parameter locktype - one
26146 ** of the following:
26147 **
26148 **     (1) SHARED_LOCK
26149 **     (2) RESERVED_LOCK
26150 **     (3) PENDING_LOCK
26151 **     (4) EXCLUSIVE_LOCK
26152 **
26153 ** Sometimes when requesting one lock state, additional lock states
26154 ** are inserted in between.  The locking might fail on one of the later
26155 ** transitions leaving the lock state different from what it started but
26156 ** still short of its goal.  The following chart shows the allowed
26157 ** transitions and the inserted intermediate states:
26158 **
26159 **    UNLOCKED -> SHARED
26160 **    SHARED -> RESERVED
26161 **    SHARED -> (PENDING) -> EXCLUSIVE
26162 **    RESERVED -> (PENDING) -> EXCLUSIVE
26163 **    PENDING -> EXCLUSIVE
26164 **
26165 ** This routine will only increase a lock.  The winUnlock() routine
26166 ** erases all locks at once and returns us immediately to locking level 0.
26167 ** It is not possible to lower the locking level one step at a time.  You
26168 ** must go straight to locking level 0.
26169 */
26170 static int winLock(sqlite3_file *id, int locktype){
26171   int rc = SQLITE_OK;    /* Return code from subroutines */
26172   int res = 1;           /* Result of a windows lock call */
26173   int newLocktype;       /* Set pFile->locktype to this value before exiting */
26174   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
26175   winFile *pFile = (winFile*)id;
26176
26177   assert( pFile!=0 );
26178   OSTRACE5("LOCK %d %d was %d(%d)\n",
26179           pFile->h, locktype, pFile->locktype, pFile->sharedLockByte);
26180
26181   /* If there is already a lock of this type or more restrictive on the
26182   ** OsFile, do nothing. Don't use the end_lock: exit path, as
26183   ** sqlite3OsEnterMutex() hasn't been called yet.
26184   */
26185   if( pFile->locktype>=locktype ){
26186     return SQLITE_OK;
26187   }
26188
26189   /* Make sure the locking sequence is correct
26190   */
26191   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
26192   assert( locktype!=PENDING_LOCK );
26193   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
26194
26195   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
26196   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
26197   ** the PENDING_LOCK byte is temporary.
26198   */
26199   newLocktype = pFile->locktype;
26200   if( pFile->locktype==NO_LOCK
26201    || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
26202   ){
26203     int cnt = 3;
26204     while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
26205       /* Try 3 times to get the pending lock.  The pending lock might be
26206       ** held by another reader process who will release it momentarily.
26207       */
26208       OSTRACE2("could not get a PENDING lock. cnt=%d\n", cnt);
26209       Sleep(1);
26210     }
26211     gotPendingLock = res;
26212   }
26213
26214   /* Acquire a shared lock
26215   */
26216   if( locktype==SHARED_LOCK && res ){
26217     assert( pFile->locktype==NO_LOCK );
26218     res = getReadLock(pFile);
26219     if( res ){
26220       newLocktype = SHARED_LOCK;
26221     }
26222   }
26223
26224   /* Acquire a RESERVED lock
26225   */
26226   if( locktype==RESERVED_LOCK && res ){
26227     assert( pFile->locktype==SHARED_LOCK );
26228     res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
26229     if( res ){
26230       newLocktype = RESERVED_LOCK;
26231     }
26232   }
26233
26234   /* Acquire a PENDING lock
26235   */
26236   if( locktype==EXCLUSIVE_LOCK && res ){
26237     newLocktype = PENDING_LOCK;
26238     gotPendingLock = 0;
26239   }
26240
26241   /* Acquire an EXCLUSIVE lock
26242   */
26243   if( locktype==EXCLUSIVE_LOCK && res ){
26244     assert( pFile->locktype>=SHARED_LOCK );
26245     res = unlockReadLock(pFile);
26246     OSTRACE2("unreadlock = %d\n", res);
26247     res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
26248     if( res ){
26249       newLocktype = EXCLUSIVE_LOCK;
26250     }else{
26251       OSTRACE2("error-code = %d\n", GetLastError());
26252       getReadLock(pFile);
26253     }
26254   }
26255
26256   /* If we are holding a PENDING lock that ought to be released, then
26257   ** release it now.
26258   */
26259   if( gotPendingLock && locktype==SHARED_LOCK ){
26260     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
26261   }
26262
26263   /* Update the state of the lock has held in the file descriptor then
26264   ** return the appropriate result code.
26265   */
26266   if( res ){
26267     rc = SQLITE_OK;
26268   }else{
26269     OSTRACE4("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
26270            locktype, newLocktype);
26271     rc = SQLITE_BUSY;
26272   }
26273   pFile->locktype = newLocktype;
26274   return rc;
26275 }
26276
26277 /*
26278 ** This routine checks if there is a RESERVED lock held on the specified
26279 ** file by this or any other process. If such a lock is held, return
26280 ** non-zero, otherwise zero.
26281 */
26282 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
26283   int rc;
26284   winFile *pFile = (winFile*)id;
26285   assert( pFile!=0 );
26286   if( pFile->locktype>=RESERVED_LOCK ){
26287     rc = 1;
26288     OSTRACE3("TEST WR-LOCK %d %d (local)\n", pFile->h, rc);
26289   }else{
26290     rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
26291     if( rc ){
26292       UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
26293     }
26294     rc = !rc;
26295     OSTRACE3("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc);
26296   }
26297   *pResOut = rc;
26298   return SQLITE_OK;
26299 }
26300
26301 /*
26302 ** Lower the locking level on file descriptor id to locktype.  locktype
26303 ** must be either NO_LOCK or SHARED_LOCK.
26304 **
26305 ** If the locking level of the file descriptor is already at or below
26306 ** the requested locking level, this routine is a no-op.
26307 **
26308 ** It is not possible for this routine to fail if the second argument
26309 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
26310 ** might return SQLITE_IOERR;
26311 */
26312 static int winUnlock(sqlite3_file *id, int locktype){
26313   int type;
26314   winFile *pFile = (winFile*)id;
26315   int rc = SQLITE_OK;
26316   assert( pFile!=0 );
26317   assert( locktype<=SHARED_LOCK );
26318   OSTRACE5("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
26319           pFile->locktype, pFile->sharedLockByte);
26320   type = pFile->locktype;
26321   if( type>=EXCLUSIVE_LOCK ){
26322     UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
26323     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
26324       /* This should never happen.  We should always be able to
26325       ** reacquire the read lock */
26326       rc = SQLITE_IOERR_UNLOCK;
26327     }
26328   }
26329   if( type>=RESERVED_LOCK ){
26330     UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
26331   }
26332   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
26333     unlockReadLock(pFile);
26334   }
26335   if( type>=PENDING_LOCK ){
26336     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
26337   }
26338   pFile->locktype = locktype;
26339   return rc;
26340 }
26341
26342 /*
26343 ** Control and query of the open file handle.
26344 */
26345 static int winFileControl(sqlite3_file *id, int op, void *pArg){
26346   switch( op ){
26347     case SQLITE_FCNTL_LOCKSTATE: {
26348       *(int*)pArg = ((winFile*)id)->locktype;
26349       return SQLITE_OK;
26350     }
26351   }
26352   return SQLITE_ERROR;
26353 }
26354
26355 /*
26356 ** Return the sector size in bytes of the underlying block device for
26357 ** the specified file. This is almost always 512 bytes, but may be
26358 ** larger for some devices.
26359 **
26360 ** SQLite code assumes this function cannot fail. It also assumes that
26361 ** if two files are created in the same file-system directory (i.e.
26362 ** a database and its journal file) that the sector size will be the
26363 ** same for both.
26364 */
26365 static int winSectorSize(sqlite3_file *id){
26366   return SQLITE_DEFAULT_SECTOR_SIZE;
26367 }
26368
26369 /*
26370 ** Return a vector of device characteristics.
26371 */
26372 static int winDeviceCharacteristics(sqlite3_file *id){
26373   return 0;
26374 }
26375
26376 /*
26377 ** This vector defines all the methods that can operate on an
26378 ** sqlite3_file for win32.
26379 */
26380 static const sqlite3_io_methods winIoMethod = {
26381   1,                        /* iVersion */
26382   winClose,
26383   winRead,
26384   winWrite,
26385   winTruncate,
26386   winSync,
26387   winFileSize,
26388   winLock,
26389   winUnlock,
26390   winCheckReservedLock,
26391   winFileControl,
26392   winSectorSize,
26393   winDeviceCharacteristics
26394 };
26395
26396 /***************************************************************************
26397 ** Here ends the I/O methods that form the sqlite3_io_methods object.
26398 **
26399 ** The next block of code implements the VFS methods.
26400 ****************************************************************************/
26401
26402 /*
26403 ** Convert a UTF-8 filename into whatever form the underlying
26404 ** operating system wants filenames in.  Space to hold the result
26405 ** is obtained from malloc and must be freed by the calling
26406 ** function.
26407 */
26408 static void *convertUtf8Filename(const char *zFilename){
26409   void *zConverted = 0;
26410   if( isNT() ){
26411     zConverted = utf8ToUnicode(zFilename);
26412 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
26413 */
26414 #if SQLITE_OS_WINCE==0
26415   }else{
26416     zConverted = utf8ToMbcs(zFilename);
26417 #endif
26418   }
26419   /* caller will handle out of memory */
26420   return zConverted;
26421 }
26422
26423 /*
26424 ** Create a temporary file name in zBuf.  zBuf must be big enough to
26425 ** hold at pVfs->mxPathname characters.
26426 */
26427 static int getTempname(int nBuf, char *zBuf){
26428   static char zChars[] =
26429     "abcdefghijklmnopqrstuvwxyz"
26430     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
26431     "0123456789";
26432   size_t i, j;
26433   char zTempPath[MAX_PATH+1];
26434   if( sqlite3_temp_directory ){
26435     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
26436   }else if( isNT() ){
26437     char *zMulti;
26438     WCHAR zWidePath[MAX_PATH];
26439     GetTempPathW(MAX_PATH-30, zWidePath);
26440     zMulti = unicodeToUtf8(zWidePath);
26441     if( zMulti ){
26442       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
26443       free(zMulti);
26444     }else{
26445       return SQLITE_NOMEM;
26446     }
26447 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
26448 ** Since the ASCII version of these Windows API do not exist for WINCE,
26449 ** it's important to not reference them for WINCE builds.
26450 */
26451 #if SQLITE_OS_WINCE==0
26452   }else{
26453     char *zUtf8;
26454     char zMbcsPath[MAX_PATH];
26455     GetTempPathA(MAX_PATH-30, zMbcsPath);
26456     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
26457     if( zUtf8 ){
26458       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
26459       free(zUtf8);
26460     }else{
26461       return SQLITE_NOMEM;
26462     }
26463 #endif
26464   }
26465   for(i=strlen(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
26466   zTempPath[i] = 0;
26467   sqlite3_snprintf(nBuf-30, zBuf,
26468                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
26469   j = strlen(zBuf);
26470   sqlite3_randomness(20, &zBuf[j]);
26471   for(i=0; i<20; i++, j++){
26472     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
26473   }
26474   zBuf[j] = 0;
26475   OSTRACE2("TEMP FILENAME: %s\n", zBuf);
26476   return SQLITE_OK; 
26477 }
26478
26479 /*
26480 ** The return value of getLastErrorMsg
26481 ** is zero if the error message fits in the buffer, or non-zero
26482 ** otherwise (if the message was truncated).
26483 */
26484 static int getLastErrorMsg(int nBuf, char *zBuf){
26485   DWORD error = GetLastError();
26486
26487 #if SQLITE_OS_WINCE
26488   sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
26489 #else
26490   /* FormatMessage returns 0 on failure.  Otherwise it
26491   ** returns the number of TCHARs written to the output
26492   ** buffer, excluding the terminating null char.
26493   */
26494   if (!FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
26495                       NULL,
26496                       error,
26497                       0,
26498                       zBuf,
26499                       nBuf-1,
26500                       0))
26501   {
26502     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
26503   }
26504 #endif
26505
26506   return 0;
26507 }
26508
26509
26510 /*
26511 ** Open a file.
26512 */
26513 static int winOpen(
26514   sqlite3_vfs *pVfs,        /* Not used */
26515   const char *zName,        /* Name of the file (UTF-8) */
26516   sqlite3_file *id,         /* Write the SQLite file handle here */
26517   int flags,                /* Open mode flags */
26518   int *pOutFlags            /* Status return flags */
26519 ){
26520   HANDLE h;
26521   DWORD dwDesiredAccess;
26522   DWORD dwShareMode;
26523   DWORD dwCreationDisposition;
26524   DWORD dwFlagsAndAttributes = 0;
26525 #if SQLITE_OS_WINCE
26526   int isTemp = 0;
26527 #endif
26528   winFile *pFile = (winFile*)id;
26529   void *zConverted;                 /* Filename in OS encoding */
26530   const char *zUtf8Name = zName;    /* Filename in UTF-8 encoding */
26531   char zTmpname[MAX_PATH+1];        /* Buffer used to create temp filename */
26532
26533   /* If the second argument to this function is NULL, generate a 
26534   ** temporary file name to use 
26535   */
26536   if( !zUtf8Name ){
26537     int rc = getTempname(MAX_PATH+1, zTmpname);
26538     if( rc!=SQLITE_OK ){
26539       return rc;
26540     }
26541     zUtf8Name = zTmpname;
26542   }
26543
26544   /* Convert the filename to the system encoding. */
26545   zConverted = convertUtf8Filename(zUtf8Name);
26546   if( zConverted==0 ){
26547     return SQLITE_NOMEM;
26548   }
26549
26550   if( flags & SQLITE_OPEN_READWRITE ){
26551     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
26552   }else{
26553     dwDesiredAccess = GENERIC_READ;
26554   }
26555   if( flags & SQLITE_OPEN_CREATE ){
26556     dwCreationDisposition = OPEN_ALWAYS;
26557   }else{
26558     dwCreationDisposition = OPEN_EXISTING;
26559   }
26560   if( flags & SQLITE_OPEN_MAIN_DB ){
26561     dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
26562   }else{
26563     dwShareMode = 0;
26564   }
26565   if( flags & SQLITE_OPEN_DELETEONCLOSE ){
26566 #if SQLITE_OS_WINCE
26567     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
26568     isTemp = 1;
26569 #else
26570     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
26571                                | FILE_ATTRIBUTE_HIDDEN
26572                                | FILE_FLAG_DELETE_ON_CLOSE;
26573 #endif
26574   }else{
26575     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
26576   }
26577   /* Reports from the internet are that performance is always
26578   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
26579 #if SQLITE_OS_WINCE
26580   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
26581 #endif
26582   if( isNT() ){
26583     h = CreateFileW((WCHAR*)zConverted,
26584        dwDesiredAccess,
26585        dwShareMode,
26586        NULL,
26587        dwCreationDisposition,
26588        dwFlagsAndAttributes,
26589        NULL
26590     );
26591 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
26592 ** Since the ASCII version of these Windows API do not exist for WINCE,
26593 ** it's important to not reference them for WINCE builds.
26594 */
26595 #if SQLITE_OS_WINCE==0
26596   }else{
26597     h = CreateFileA((char*)zConverted,
26598        dwDesiredAccess,
26599        dwShareMode,
26600        NULL,
26601        dwCreationDisposition,
26602        dwFlagsAndAttributes,
26603        NULL
26604     );
26605 #endif
26606   }
26607   if( h==INVALID_HANDLE_VALUE ){
26608     free(zConverted);
26609     if( flags & SQLITE_OPEN_READWRITE ){
26610       return winOpen(0, zName, id, 
26611              ((flags|SQLITE_OPEN_READONLY)&~SQLITE_OPEN_READWRITE), pOutFlags);
26612     }else{
26613       return SQLITE_CANTOPEN;
26614     }
26615   }
26616   if( pOutFlags ){
26617     if( flags & SQLITE_OPEN_READWRITE ){
26618       *pOutFlags = SQLITE_OPEN_READWRITE;
26619     }else{
26620       *pOutFlags = SQLITE_OPEN_READONLY;
26621     }
26622   }
26623   memset(pFile, 0, sizeof(*pFile));
26624   pFile->pMethod = &winIoMethod;
26625   pFile->h = h;
26626 #if SQLITE_OS_WINCE
26627   if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
26628                (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)
26629        && !winceCreateLock(zName, pFile)
26630   ){
26631     CloseHandle(h);
26632     free(zConverted);
26633     return SQLITE_CANTOPEN;
26634   }
26635   if( isTemp ){
26636     pFile->zDeleteOnClose = zConverted;
26637   }else
26638 #endif
26639   {
26640     free(zConverted);
26641   }
26642   OpenCounter(+1);
26643   return SQLITE_OK;
26644 }
26645
26646 /*
26647 ** Delete the named file.
26648 **
26649 ** Note that windows does not allow a file to be deleted if some other
26650 ** process has it open.  Sometimes a virus scanner or indexing program
26651 ** will open a journal file shortly after it is created in order to do
26652 ** whatever it does.  While this other process is holding the
26653 ** file open, we will be unable to delete it.  To work around this
26654 ** problem, we delay 100 milliseconds and try to delete again.  Up
26655 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
26656 ** up and returning an error.
26657 */
26658 #define MX_DELETION_ATTEMPTS 5
26659 static int winDelete(
26660   sqlite3_vfs *pVfs,          /* Not used on win32 */
26661   const char *zFilename,      /* Name of file to delete */
26662   int syncDir                 /* Not used on win32 */
26663 ){
26664   int cnt = 0;
26665   DWORD rc;
26666   DWORD error;
26667   void *zConverted = convertUtf8Filename(zFilename);
26668   if( zConverted==0 ){
26669     return SQLITE_NOMEM;
26670   }
26671   SimulateIOError(return SQLITE_IOERR_DELETE);
26672   if( isNT() ){
26673     do{
26674       DeleteFileW(zConverted);
26675     }while(   (   ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
26676                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
26677            && (++cnt < MX_DELETION_ATTEMPTS)
26678            && (Sleep(100), 1) );
26679 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
26680 ** Since the ASCII version of these Windows API do not exist for WINCE,
26681 ** it's important to not reference them for WINCE builds.
26682 */
26683 #if SQLITE_OS_WINCE==0
26684   }else{
26685     do{
26686       DeleteFileA(zConverted);
26687     }while(   (   ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
26688                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
26689            && (++cnt < MX_DELETION_ATTEMPTS)
26690            && (Sleep(100), 1) );
26691 #endif
26692   }
26693   free(zConverted);
26694   OSTRACE2("DELETE \"%s\"\n", zFilename);
26695   return (   (rc == INVALID_FILE_ATTRIBUTES) 
26696           && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
26697 }
26698
26699 /*
26700 ** Check the existance and status of a file.
26701 */
26702 static int winAccess(
26703   sqlite3_vfs *pVfs,         /* Not used on win32 */
26704   const char *zFilename,     /* Name of file to check */
26705   int flags,                 /* Type of test to make on this file */
26706   int *pResOut               /* OUT: Result */
26707 ){
26708   DWORD attr;
26709   int rc;
26710   void *zConverted = convertUtf8Filename(zFilename);
26711   if( zConverted==0 ){
26712     return SQLITE_NOMEM;
26713   }
26714   if( isNT() ){
26715     attr = GetFileAttributesW((WCHAR*)zConverted);
26716 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
26717 ** Since the ASCII version of these Windows API do not exist for WINCE,
26718 ** it's important to not reference them for WINCE builds.
26719 */
26720 #if SQLITE_OS_WINCE==0
26721   }else{
26722     attr = GetFileAttributesA((char*)zConverted);
26723 #endif
26724   }
26725   free(zConverted);
26726   switch( flags ){
26727     case SQLITE_ACCESS_READ:
26728     case SQLITE_ACCESS_EXISTS:
26729       rc = attr!=INVALID_FILE_ATTRIBUTES;
26730       break;
26731     case SQLITE_ACCESS_READWRITE:
26732       rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
26733       break;
26734     default:
26735       assert(!"Invalid flags argument");
26736   }
26737   *pResOut = rc;
26738   return SQLITE_OK;
26739 }
26740
26741
26742 /*
26743 ** Turn a relative pathname into a full pathname.  Write the full
26744 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
26745 ** bytes in size.
26746 */
26747 static int winFullPathname(
26748   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
26749   const char *zRelative,        /* Possibly relative input path */
26750   int nFull,                    /* Size of output buffer in bytes */
26751   char *zFull                   /* Output buffer */
26752 ){
26753
26754 #if defined(__CYGWIN__)
26755   cygwin_conv_to_full_win32_path(zRelative, zFull);
26756   return SQLITE_OK;
26757 #endif
26758
26759 #if SQLITE_OS_WINCE
26760   /* WinCE has no concept of a relative pathname, or so I am told. */
26761   sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
26762   return SQLITE_OK;
26763 #endif
26764
26765 #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
26766   int nByte;
26767   void *zConverted;
26768   char *zOut;
26769   zConverted = convertUtf8Filename(zRelative);
26770   if( isNT() ){
26771     WCHAR *zTemp;
26772     nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
26773     zTemp = malloc( nByte*sizeof(zTemp[0]) );
26774     if( zTemp==0 ){
26775       free(zConverted);
26776       return SQLITE_NOMEM;
26777     }
26778     GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
26779     free(zConverted);
26780     zOut = unicodeToUtf8(zTemp);
26781     free(zTemp);
26782 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
26783 ** Since the ASCII version of these Windows API do not exist for WINCE,
26784 ** it's important to not reference them for WINCE builds.
26785 */
26786 #if SQLITE_OS_WINCE==0
26787   }else{
26788     char *zTemp;
26789     nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
26790     zTemp = malloc( nByte*sizeof(zTemp[0]) );
26791     if( zTemp==0 ){
26792       free(zConverted);
26793       return SQLITE_NOMEM;
26794     }
26795     GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
26796     free(zConverted);
26797     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
26798     free(zTemp);
26799 #endif
26800   }
26801   if( zOut ){
26802     sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
26803     free(zOut);
26804     return SQLITE_OK;
26805   }else{
26806     return SQLITE_NOMEM;
26807   }
26808 #endif
26809 }
26810
26811 #ifndef SQLITE_OMIT_LOAD_EXTENSION
26812 /*
26813 ** Interfaces for opening a shared library, finding entry points
26814 ** within the shared library, and closing the shared library.
26815 */
26816 /*
26817 ** Interfaces for opening a shared library, finding entry points
26818 ** within the shared library, and closing the shared library.
26819 */
26820 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
26821   HANDLE h;
26822   void *zConverted = convertUtf8Filename(zFilename);
26823   if( zConverted==0 ){
26824     return 0;
26825   }
26826   if( isNT() ){
26827     h = LoadLibraryW((WCHAR*)zConverted);
26828 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
26829 ** Since the ASCII version of these Windows API do not exist for WINCE,
26830 ** it's important to not reference them for WINCE builds.
26831 */
26832 #if SQLITE_OS_WINCE==0
26833   }else{
26834     h = LoadLibraryA((char*)zConverted);
26835 #endif
26836   }
26837   free(zConverted);
26838   return (void*)h;
26839 }
26840 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
26841   getLastErrorMsg(nBuf, zBufOut);
26842 }
26843 void *winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
26844 #if SQLITE_OS_WINCE
26845   /* The GetProcAddressA() routine is only available on wince. */
26846   return GetProcAddressA((HANDLE)pHandle, zSymbol);
26847 #else
26848   /* All other windows platforms expect GetProcAddress() to take
26849   ** an Ansi string regardless of the _UNICODE setting */
26850   return GetProcAddress((HANDLE)pHandle, zSymbol);
26851 #endif
26852 }
26853 void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
26854   FreeLibrary((HANDLE)pHandle);
26855 }
26856 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
26857   #define winDlOpen  0
26858   #define winDlError 0
26859   #define winDlSym   0
26860   #define winDlClose 0
26861 #endif
26862
26863
26864 /*
26865 ** Write up to nBuf bytes of randomness into zBuf.
26866 */
26867 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
26868   int n = 0;
26869   UNUSED_PARAMETER(pVfs);
26870 #if defined(SQLITE_TEST)
26871   n = nBuf;
26872   memset(zBuf, 0, nBuf);
26873 #else
26874   if( sizeof(SYSTEMTIME)<=nBuf-n ){
26875     SYSTEMTIME x;
26876     GetSystemTime(&x);
26877     memcpy(&zBuf[n], &x, sizeof(x));
26878     n += sizeof(x);
26879   }
26880   if( sizeof(DWORD)<=nBuf-n ){
26881     DWORD pid = GetCurrentProcessId();
26882     memcpy(&zBuf[n], &pid, sizeof(pid));
26883     n += sizeof(pid);
26884   }
26885   if( sizeof(DWORD)<=nBuf-n ){
26886     DWORD cnt = GetTickCount();
26887     memcpy(&zBuf[n], &cnt, sizeof(cnt));
26888     n += sizeof(cnt);
26889   }
26890   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
26891     LARGE_INTEGER i;
26892     QueryPerformanceCounter(&i);
26893     memcpy(&zBuf[n], &i, sizeof(i));
26894     n += sizeof(i);
26895   }
26896 #endif
26897   return n;
26898 }
26899
26900
26901 /*
26902 ** Sleep for a little while.  Return the amount of time slept.
26903 */
26904 static int winSleep(sqlite3_vfs *pVfs, int microsec){
26905   Sleep((microsec+999)/1000);
26906   return ((microsec+999)/1000)*1000;
26907 }
26908
26909 /*
26910 ** The following variable, if set to a non-zero value, becomes the result
26911 ** returned from sqlite3OsCurrentTime().  This is used for testing.
26912 */
26913 #ifdef SQLITE_TEST
26914 SQLITE_API int sqlite3_current_time = 0;
26915 #endif
26916
26917 /*
26918 ** Find the current time (in Universal Coordinated Time).  Write the
26919 ** current time and date as a Julian Day number into *prNow and
26920 ** return 0.  Return 1 if the time and date cannot be found.
26921 */
26922 int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
26923   FILETIME ft;
26924   /* FILETIME structure is a 64-bit value representing the number of 
26925      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
26926   */
26927   double now;
26928 #if SQLITE_OS_WINCE
26929   SYSTEMTIME time;
26930   GetSystemTime(&time);
26931   /* if SystemTimeToFileTime() fails, it returns zero. */
26932   if (!SystemTimeToFileTime(&time,&ft)){
26933     return 1;
26934   }
26935 #else
26936   GetSystemTimeAsFileTime( &ft );
26937 #endif
26938   now = ((double)ft.dwHighDateTime) * 4294967296.0; 
26939   *prNow = (now + ft.dwLowDateTime)/864000000000.0 + 2305813.5;
26940 #ifdef SQLITE_TEST
26941   if( sqlite3_current_time ){
26942     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
26943   }
26944 #endif
26945   return 0;
26946 }
26947
26948 /*
26949 ** The idea is that this function works like a combination of
26950 ** GetLastError() and FormatMessage() on windows (or errno and
26951 ** strerror_r() on unix). After an error is returned by an OS
26952 ** function, SQLite calls this function with zBuf pointing to
26953 ** a buffer of nBuf bytes. The OS layer should populate the
26954 ** buffer with a nul-terminated UTF-8 encoded error message
26955 ** describing the last IO error to have occured within the calling
26956 ** thread.
26957 **
26958 ** If the error message is too large for the supplied buffer,
26959 ** it should be truncated. The return value of xGetLastError
26960 ** is zero if the error message fits in the buffer, or non-zero
26961 ** otherwise (if the message was truncated). If non-zero is returned,
26962 ** then it is not necessary to include the nul-terminator character
26963 ** in the output buffer.
26964 **
26965 ** Not supplying an error message will have no adverse effect
26966 ** on SQLite. It is fine to have an implementation that never
26967 ** returns an error message:
26968 **
26969 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
26970 **     assert(zBuf[0]=='\0');
26971 **     return 0;
26972 **   }
26973 **
26974 ** However if an error message is supplied, it will be incorporated
26975 ** by sqlite into the error message available to the user using
26976 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
26977 */
26978 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
26979   return getLastErrorMsg(nBuf, zBuf);
26980 }
26981
26982 /*
26983 ** Initialize and deinitialize the operating system interface.
26984 */
26985 SQLITE_API int sqlite3_os_init(void){
26986   static sqlite3_vfs winVfs = {
26987     1,                 /* iVersion */
26988     sizeof(winFile),   /* szOsFile */
26989     MAX_PATH,          /* mxPathname */
26990     0,                 /* pNext */
26991     "win32",           /* zName */
26992     0,                 /* pAppData */
26993  
26994     winOpen,           /* xOpen */
26995     winDelete,         /* xDelete */
26996     winAccess,         /* xAccess */
26997     winFullPathname,   /* xFullPathname */
26998     winDlOpen,         /* xDlOpen */
26999     winDlError,        /* xDlError */
27000     winDlSym,          /* xDlSym */
27001     winDlClose,        /* xDlClose */
27002     winRandomness,     /* xRandomness */
27003     winSleep,          /* xSleep */
27004     winCurrentTime,    /* xCurrentTime */
27005     winGetLastError    /* xGetLastError */
27006   };
27007   sqlite3_vfs_register(&winVfs, 1);
27008   return SQLITE_OK; 
27009 }
27010 SQLITE_API int sqlite3_os_end(void){ 
27011   return SQLITE_OK;
27012 }
27013
27014 #endif /* SQLITE_OS_WIN */
27015
27016 /************** End of os_win.c **********************************************/
27017 /************** Begin file bitvec.c ******************************************/
27018 /*
27019 ** 2008 February 16
27020 **
27021 ** The author disclaims copyright to this source code.  In place of
27022 ** a legal notice, here is a blessing:
27023 **
27024 **    May you do good and not evil.
27025 **    May you find forgiveness for yourself and forgive others.
27026 **    May you share freely, never taking more than you give.
27027 **
27028 *************************************************************************
27029 ** This file implements an object that represents a fixed-length
27030 ** bitmap.  Bits are numbered starting with 1.
27031 **
27032 ** A bitmap is used to record which pages of a database file have been
27033 ** journalled during a transaction, or which pages have the "dont-write"
27034 ** property.  Usually only a few pages are meet either condition.
27035 ** So the bitmap is usually sparse and has low cardinality.
27036 ** But sometimes (for example when during a DROP of a large table) most
27037 ** or all of the pages in a database can get journalled.  In those cases, 
27038 ** the bitmap becomes dense with high cardinality.  The algorithm needs 
27039 ** to handle both cases well.
27040 **
27041 ** The size of the bitmap is fixed when the object is created.
27042 **
27043 ** All bits are clear when the bitmap is created.  Individual bits
27044 ** may be set or cleared one at a time.
27045 **
27046 ** Test operations are about 100 times more common that set operations.
27047 ** Clear operations are exceedingly rare.  There are usually between
27048 ** 5 and 500 set operations per Bitvec object, though the number of sets can
27049 ** sometimes grow into tens of thousands or larger.  The size of the
27050 ** Bitvec object is the number of pages in the database file at the
27051 ** start of a transaction, and is thus usually less than a few thousand,
27052 ** but can be as large as 2 billion for a really big database.
27053 **
27054 ** @(#) $Id: bitvec.c,v 1.9 2008/11/19 18:30:35 shane Exp $
27055 */
27056
27057 /* Size of the Bitvec structure in bytes. */
27058 #define BITVEC_SZ        512
27059
27060 /* Round the union size down to the nearest pointer boundary, since that's how 
27061 ** it will be aligned within the Bitvec struct. */
27062 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
27063
27064 /* Type of the array "element" for the bitmap representation. 
27065 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. 
27066 ** Setting this to the "natural word" size of your CPU may improve
27067 ** performance. */
27068 #define BITVEC_TELEM     u8
27069 /* Size, in bits, of the bitmap element. */
27070 #define BITVEC_SZELEM    8
27071 /* Number of elements in a bitmap array. */
27072 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
27073 /* Number of bits in the bitmap array. */
27074 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
27075
27076 /* Number of u32 values in hash table. */
27077 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
27078 /* Maximum number of entries in hash table before 
27079 ** sub-dividing and re-hashing. */
27080 #define BITVEC_MXHASH    (BITVEC_NINT/2)
27081 /* Hashing function for the aHash representation.
27082 ** Empirical testing showed that the *37 multiplier 
27083 ** (an arbitrary prime)in the hash function provided 
27084 ** no fewer collisions than the no-op *1. */
27085 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
27086
27087 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
27088
27089
27090 /*
27091 ** A bitmap is an instance of the following structure.
27092 **
27093 ** This bitmap records the existance of zero or more bits
27094 ** with values between 1 and iSize, inclusive.
27095 **
27096 ** There are three possible representations of the bitmap.
27097 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
27098 ** bitmap.  The least significant bit is bit 1.
27099 **
27100 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
27101 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
27102 **
27103 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
27104 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
27105 ** handles up to iDivisor separate values of i.  apSub[0] holds
27106 ** values between 1 and iDivisor.  apSub[1] holds values between
27107 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
27108 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
27109 ** to hold deal with values between 1 and iDivisor.
27110 */
27111 struct Bitvec {
27112   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
27113   u32 nSet;       /* Number of bits that are set - only valid for aHash element */
27114                   /* Max nSet is BITVEC_NINT.  For BITVEC_SZ of 512, this would be 125. */
27115   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
27116                   /* Should >=0 for apSub element. */
27117                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
27118                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
27119   union {
27120     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
27121     u32 aHash[BITVEC_NINT];      /* Hash table representation */
27122     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
27123   } u;
27124 };
27125
27126 /*
27127 ** Create a new bitmap object able to handle bits between 0 and iSize,
27128 ** inclusive.  Return a pointer to the new object.  Return NULL if 
27129 ** malloc fails.
27130 */
27131 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
27132   Bitvec *p;
27133   assert( sizeof(*p)==BITVEC_SZ );
27134   p = sqlite3MallocZero( sizeof(*p) );
27135   if( p ){
27136     p->iSize = iSize;
27137   }
27138   return p;
27139 }
27140
27141 /*
27142 ** Check to see if the i-th bit is set.  Return true or false.
27143 ** If p is NULL (if the bitmap has not been created) or if
27144 ** i is out of range, then return false.
27145 */
27146 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
27147   if( p==0 ) return 0;
27148   if( i>p->iSize || i==0 ) return 0;
27149   i--;
27150   while( p->iDivisor ){
27151     u32 bin = i/p->iDivisor;
27152     i = i%p->iDivisor;
27153     p = p->u.apSub[bin];
27154     if (!p) {
27155       return 0;
27156     }
27157   }
27158   if( p->iSize<=BITVEC_NBIT ){
27159     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
27160   } else{
27161     u32 h = BITVEC_HASH(i++);
27162     while( p->u.aHash[h] ){
27163       if( p->u.aHash[h]==i ) return 1;
27164       h++;
27165       if( h>=BITVEC_NINT ) h = 0;
27166     }
27167     return 0;
27168   }
27169 }
27170
27171 /*
27172 ** Set the i-th bit.  Return 0 on success and an error code if
27173 ** anything goes wrong.
27174 **
27175 ** This routine might cause sub-bitmaps to be allocated.  Failing
27176 ** to get the memory needed to hold the sub-bitmap is the only
27177 ** that can go wrong with an insert, assuming p and i are valid.
27178 **
27179 ** The calling function must ensure that p is a valid Bitvec object
27180 ** and that the value for "i" is within range of the Bitvec object.
27181 ** Otherwise the behavior is undefined.
27182 */
27183 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
27184   u32 h;
27185   assert( p!=0 );
27186   assert( i>0 );
27187   assert( i<=p->iSize );
27188   i--;
27189   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
27190     u32 bin = i/p->iDivisor;
27191     i = i%p->iDivisor;
27192     if( p->u.apSub[bin]==0 ){
27193       sqlite3BeginBenignMalloc();
27194       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
27195       sqlite3EndBenignMalloc();
27196       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
27197     }
27198     p = p->u.apSub[bin];
27199   }
27200   if( p->iSize<=BITVEC_NBIT ){
27201     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
27202     return SQLITE_OK;
27203   }
27204   h = BITVEC_HASH(i++);
27205   /* if there wasn't a hash collision, and this doesn't */
27206   /* completely fill the hash, then just add it without */
27207   /* worring about sub-dividing and re-hashing. */
27208   if( !p->u.aHash[h] ){
27209     if (p->nSet<(BITVEC_NINT-1)) {
27210       goto bitvec_set_end;
27211     } else {
27212       goto bitvec_set_rehash;
27213     }
27214   }
27215   /* there was a collision, check to see if it's already */
27216   /* in hash, if not, try to find a spot for it */
27217   do {
27218     if( p->u.aHash[h]==i ) return SQLITE_OK;
27219     h++;
27220     if( h>=BITVEC_NINT ) h = 0;
27221   } while( p->u.aHash[h] );
27222   /* we didn't find it in the hash.  h points to the first */
27223   /* available free spot. check to see if this is going to */
27224   /* make our hash too "full".  */
27225 bitvec_set_rehash:
27226   if( p->nSet>=BITVEC_MXHASH ){
27227     unsigned int j;
27228     int rc;
27229     u32 aiValues[BITVEC_NINT];
27230     memcpy(aiValues, p->u.aHash, sizeof(aiValues));
27231     memset(p->u.apSub, 0, sizeof(aiValues));
27232     p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
27233     rc = sqlite3BitvecSet(p, i);
27234     for(j=0; j<BITVEC_NINT; j++){
27235       if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
27236     }
27237     return rc;
27238   }
27239 bitvec_set_end:
27240   p->nSet++;
27241   p->u.aHash[h] = i;
27242   return SQLITE_OK;
27243 }
27244
27245 /*
27246 ** Clear the i-th bit.
27247 */
27248 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i){
27249   assert( p!=0 );
27250   assert( i>0 );
27251   i--;
27252   while( p->iDivisor ){
27253     u32 bin = i/p->iDivisor;
27254     i = i%p->iDivisor;
27255     p = p->u.apSub[bin];
27256     if (!p) {
27257       return;
27258     }
27259   }
27260   if( p->iSize<=BITVEC_NBIT ){
27261     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
27262   }else{
27263     unsigned int j;
27264     u32 aiValues[BITVEC_NINT];
27265     memcpy(aiValues, p->u.aHash, sizeof(aiValues));
27266     memset(p->u.aHash, 0, sizeof(aiValues));
27267     p->nSet = 0;
27268     for(j=0; j<BITVEC_NINT; j++){
27269       if( aiValues[j] && aiValues[j]!=(i+1) ){
27270         u32 h = BITVEC_HASH(aiValues[j]-1);
27271         p->nSet++;
27272         while( p->u.aHash[h] ){
27273           h++;
27274           if( h>=BITVEC_NINT ) h = 0;
27275         }
27276         p->u.aHash[h] = aiValues[j];
27277       }
27278     }
27279   }
27280 }
27281
27282 /*
27283 ** Destroy a bitmap object.  Reclaim all memory used.
27284 */
27285 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
27286   if( p==0 ) return;
27287   if( p->iDivisor ){
27288     unsigned int i;
27289     for(i=0; i<BITVEC_NPTR; i++){
27290       sqlite3BitvecDestroy(p->u.apSub[i]);
27291     }
27292   }
27293   sqlite3_free(p);
27294 }
27295
27296 #ifndef SQLITE_OMIT_BUILTIN_TEST
27297 /*
27298 ** Let V[] be an array of unsigned characters sufficient to hold
27299 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
27300 ** Then the following macros can be used to set, clear, or test
27301 ** individual bits within V.
27302 */
27303 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
27304 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
27305 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
27306
27307 /*
27308 ** This routine runs an extensive test of the Bitvec code.
27309 **
27310 ** The input is an array of integers that acts as a program
27311 ** to test the Bitvec.  The integers are opcodes followed
27312 ** by 0, 1, or 3 operands, depending on the opcode.  Another
27313 ** opcode follows immediately after the last operand.
27314 **
27315 ** There are 6 opcodes numbered from 0 through 5.  0 is the
27316 ** "halt" opcode and causes the test to end.
27317 **
27318 **    0          Halt and return the number of errors
27319 **    1 N S X    Set N bits beginning with S and incrementing by X
27320 **    2 N S X    Clear N bits beginning with S and incrementing by X
27321 **    3 N        Set N randomly chosen bits
27322 **    4 N        Clear N randomly chosen bits
27323 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
27324 **
27325 ** The opcodes 1 through 4 perform set and clear operations are performed
27326 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
27327 ** Opcode 5 works on the linear array only, not on the Bitvec.
27328 ** Opcode 5 is used to deliberately induce a fault in order to
27329 ** confirm that error detection works.
27330 **
27331 ** At the conclusion of the test the linear array is compared
27332 ** against the Bitvec object.  If there are any differences,
27333 ** an error is returned.  If they are the same, zero is returned.
27334 **
27335 ** If a memory allocation error occurs, return -1.
27336 */
27337 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
27338   Bitvec *pBitvec = 0;
27339   unsigned char *pV = 0;
27340   int rc = -1;
27341   int i, nx, pc, op;
27342
27343   /* Allocate the Bitvec to be tested and a linear array of
27344   ** bits to act as the reference */
27345   pBitvec = sqlite3BitvecCreate( sz );
27346   pV = sqlite3_malloc( (sz+7)/8 + 1 );
27347   if( pBitvec==0 || pV==0 ) goto bitvec_end;
27348   memset(pV, 0, (sz+7)/8 + 1);
27349
27350   /* Run the program */
27351   pc = 0;
27352   while( (op = aOp[pc])!=0 ){
27353     switch( op ){
27354       case 1:
27355       case 2:
27356       case 5: {
27357         nx = 4;
27358         i = aOp[pc+2] - 1;
27359         aOp[pc+2] += aOp[pc+3];
27360         break;
27361       }
27362       case 3:
27363       case 4: 
27364       default: {
27365         nx = 2;
27366         sqlite3_randomness(sizeof(i), &i);
27367         break;
27368       }
27369     }
27370     if( (--aOp[pc+1]) > 0 ) nx = 0;
27371     pc += nx;
27372     i = (i & 0x7fffffff)%sz;
27373     if( (op & 1)!=0 ){
27374       SETBIT(pV, (i+1));
27375       if( op!=5 ){
27376         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
27377       }
27378     }else{
27379       CLEARBIT(pV, (i+1));
27380       sqlite3BitvecClear(pBitvec, i+1);
27381     }
27382   }
27383
27384   /* Test to make sure the linear array exactly matches the
27385   ** Bitvec object.  Start with the assumption that they do
27386   ** match (rc==0).  Change rc to non-zero if a discrepancy
27387   ** is found.
27388   */
27389   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
27390           + sqlite3BitvecTest(pBitvec, 0);
27391   for(i=1; i<=sz; i++){
27392     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
27393       rc = i;
27394       break;
27395     }
27396   }
27397
27398   /* Free allocated structure */
27399 bitvec_end:
27400   sqlite3_free(pV);
27401   sqlite3BitvecDestroy(pBitvec);
27402   return rc;
27403 }
27404 #endif /* SQLITE_OMIT_BUILTIN_TEST */
27405
27406 /************** End of bitvec.c **********************************************/
27407 /************** Begin file pcache.c ******************************************/
27408 /*
27409 ** 2008 August 05
27410 **
27411 ** The author disclaims copyright to this source code.  In place of
27412 ** a legal notice, here is a blessing:
27413 **
27414 **    May you do good and not evil.
27415 **    May you find forgiveness for yourself and forgive others.
27416 **    May you share freely, never taking more than you give.
27417 **
27418 *************************************************************************
27419 ** This file implements that page cache.
27420 **
27421 ** @(#) $Id: pcache.c,v 1.38 2008/11/19 16:52:44 danielk1977 Exp $
27422 */
27423
27424 /*
27425 ** A complete page cache is an instance of this structure.
27426 */
27427 struct PCache {
27428   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
27429   PgHdr *pSynced;                     /* Last synced page in dirty page list */
27430   int nRef;                           /* Number of referenced pages */
27431   int nMax;                           /* Configured cache size */
27432   int nMin;                           /* Configured minimum cache size */
27433   int szPage;                         /* Size of every page in this cache */
27434   int szExtra;                        /* Size of extra space for each page */
27435   int bPurgeable;                     /* True if pages are on backing store */
27436   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
27437   void *pStress;                      /* Argument to xStress */
27438   sqlite3_pcache *pCache;             /* Pluggable cache module */
27439   PgHdr *pPage1;
27440 };
27441
27442 /*
27443 ** Some of the assert() macros in this code are too expensive to run
27444 ** even during normal debugging.  Use them only rarely on long-running
27445 ** tests.  Enable the expensive asserts using the
27446 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
27447 */
27448 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
27449 # define expensive_assert(X)  assert(X)
27450 #else
27451 # define expensive_assert(X)
27452 #endif
27453
27454 /********************************** Linked List Management ********************/
27455
27456 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
27457 /*
27458 ** Check that the pCache->pSynced variable is set correctly. If it
27459 ** is not, either fail an assert or return zero. Otherwise, return
27460 ** non-zero. This is only used in debugging builds, as follows:
27461 **
27462 **   expensive_assert( pcacheCheckSynced(pCache) );
27463 */
27464 static int pcacheCheckSynced(PCache *pCache){
27465   PgHdr *p;
27466   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
27467     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
27468   }
27469   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
27470 }
27471 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
27472
27473 /*
27474 ** Remove page pPage from the list of dirty pages.
27475 */
27476 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
27477   PCache *p = pPage->pCache;
27478
27479   assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
27480   assert( pPage->pDirtyPrev || pPage==p->pDirty );
27481
27482   /* Update the PCache1.pSynced variable if necessary. */
27483   if( p->pSynced==pPage ){
27484     PgHdr *pSynced = pPage->pDirtyPrev;
27485     while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
27486       pSynced = pSynced->pDirtyPrev;
27487     }
27488     p->pSynced = pSynced;
27489   }
27490
27491   if( pPage->pDirtyNext ){
27492     pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
27493   }else{
27494     assert( pPage==p->pDirtyTail );
27495     p->pDirtyTail = pPage->pDirtyPrev;
27496   }
27497   if( pPage->pDirtyPrev ){
27498     pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
27499   }else{
27500     assert( pPage==p->pDirty );
27501     p->pDirty = pPage->pDirtyNext;
27502   }
27503   pPage->pDirtyNext = 0;
27504   pPage->pDirtyPrev = 0;
27505
27506   expensive_assert( pcacheCheckSynced(p) );
27507 }
27508
27509 /*
27510 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
27511 ** pPage).
27512 */
27513 static void pcacheAddToDirtyList(PgHdr *pPage){
27514   PCache *p = pPage->pCache;
27515
27516   assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
27517
27518   pPage->pDirtyNext = p->pDirty;
27519   if( pPage->pDirtyNext ){
27520     assert( pPage->pDirtyNext->pDirtyPrev==0 );
27521     pPage->pDirtyNext->pDirtyPrev = pPage;
27522   }
27523   p->pDirty = pPage;
27524   if( !p->pDirtyTail ){
27525     p->pDirtyTail = pPage;
27526   }
27527   if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
27528     p->pSynced = pPage;
27529   }
27530   expensive_assert( pcacheCheckSynced(p) );
27531 }
27532
27533 /*
27534 ** Wrapper around the pluggable caches xUnpin method. If the cache is
27535 ** being used for an in-memory database, this function is a no-op.
27536 */
27537 static void pcacheUnpin(PgHdr *p){
27538   PCache *pCache = p->pCache;
27539   if( pCache->bPurgeable ){
27540     if( p->pgno==1 ){
27541       pCache->pPage1 = 0;
27542     }
27543     sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
27544   }
27545 }
27546
27547 /*************************************************** General Interfaces ******
27548 **
27549 ** Initialize and shutdown the page cache subsystem. Neither of these 
27550 ** functions are threadsafe.
27551 */
27552 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
27553   if( sqlite3GlobalConfig.pcache.xInit==0 ){
27554     sqlite3PCacheSetDefault();
27555   }
27556   return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
27557 }
27558 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
27559   if( sqlite3GlobalConfig.pcache.xShutdown ){
27560     sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
27561   }
27562 }
27563
27564 /*
27565 ** Return the size in bytes of a PCache object.
27566 */
27567 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
27568
27569 /*
27570 ** Create a new PCache object. Storage space to hold the object
27571 ** has already been allocated and is passed in as the p pointer. 
27572 ** The caller discovers how much space needs to be allocated by 
27573 ** calling sqlite3PcacheSize().
27574 */
27575 SQLITE_PRIVATE void sqlite3PcacheOpen(
27576   int szPage,                  /* Size of every page */
27577   int szExtra,                 /* Extra space associated with each page */
27578   int bPurgeable,              /* True if pages are on backing store */
27579   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
27580   void *pStress,               /* Argument to xStress */
27581   PCache *p                    /* Preallocated space for the PCache */
27582 ){
27583   memset(p, 0, sizeof(PCache));
27584   p->szPage = szPage;
27585   p->szExtra = szExtra;
27586   p->bPurgeable = bPurgeable;
27587   p->xStress = xStress;
27588   p->pStress = pStress;
27589   p->nMax = 100;
27590   p->nMin = 10;
27591 }
27592
27593 /*
27594 ** Change the page size for PCache object. The caller must ensure that there
27595 ** are no outstanding page references when this function is called.
27596 */
27597 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
27598   assert( pCache->nRef==0 && pCache->pDirty==0 );
27599   if( pCache->pCache ){
27600     sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
27601     pCache->pCache = 0;
27602   }
27603   pCache->szPage = szPage;
27604 }
27605
27606 /*
27607 ** Try to obtain a page from the cache.
27608 */
27609 SQLITE_PRIVATE int sqlite3PcacheFetch(
27610   PCache *pCache,       /* Obtain the page from this cache */
27611   Pgno pgno,            /* Page number to obtain */
27612   int createFlag,       /* If true, create page if it does not exist already */
27613   PgHdr **ppPage        /* Write the page here */
27614 ){
27615   PgHdr *pPage = 0;
27616   int eCreate;
27617
27618   assert( pCache!=0 );
27619   assert( pgno>0 );
27620
27621   /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
27622   ** allocate it now.
27623   */
27624   if( !pCache->pCache && createFlag ){
27625     sqlite3_pcache *p;
27626     int nByte;
27627     nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
27628     p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
27629     if( !p ){
27630       return SQLITE_NOMEM;
27631     }
27632     sqlite3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
27633     pCache->pCache = p;
27634   }
27635
27636   eCreate = createFlag ? 1 : 0;
27637   if( eCreate && (!pCache->bPurgeable || !pCache->pDirty) ){
27638     eCreate = 2;
27639   }
27640   if( pCache->pCache ){
27641     pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
27642   }
27643
27644   if( !pPage && eCreate==1 ){
27645     PgHdr *pPg;
27646
27647     /* Find a dirty page to write-out and recycle. First try to find a 
27648     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
27649     ** cleared), but if that is not possible settle for any other 
27650     ** unreferenced dirty page.
27651     */
27652     expensive_assert( pcacheCheckSynced(pCache) );
27653     for(pPg=pCache->pSynced; 
27654         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 
27655         pPg=pPg->pDirtyPrev
27656     );
27657     if( !pPg ){
27658       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
27659     }
27660     if( pPg ){
27661       int rc;
27662       rc = pCache->xStress(pCache->pStress, pPg);
27663       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
27664         return rc;
27665       }
27666     }
27667
27668     pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
27669   }
27670
27671   if( pPage ){
27672     if( 0==pPage->nRef ){
27673       pCache->nRef++;
27674     }
27675     pPage->nRef++;
27676     pPage->pData = (void*)&pPage[1];
27677     pPage->pExtra = (void*)&((char*)pPage->pData)[pCache->szPage];
27678     pPage->pCache = pCache;
27679     pPage->pgno = pgno;
27680     if( pgno==1 ){
27681       pCache->pPage1 = pPage;
27682     }
27683   }
27684   *ppPage = pPage;
27685   return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
27686 }
27687
27688 /*
27689 ** Decrement the reference count on a page. If the page is clean and the
27690 ** reference count drops to 0, then it is made elible for recycling.
27691 */
27692 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
27693   assert( p->nRef>0 );
27694   p->nRef--;
27695   if( p->nRef==0 ){
27696     PCache *pCache = p->pCache;
27697     pCache->nRef--;
27698     if( (p->flags&PGHDR_DIRTY)==0 ){
27699       pcacheUnpin(p);
27700     }else{
27701       /* Move the page to the head of the dirty list. */
27702       pcacheRemoveFromDirtyList(p);
27703       pcacheAddToDirtyList(p);
27704     }
27705   }
27706 }
27707
27708 /*
27709 ** Increase the reference count of a supplied page by 1.
27710 */
27711 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
27712   assert(p->nRef>0);
27713   p->nRef++;
27714 }
27715
27716 /*
27717 ** Drop a page from the cache. There must be exactly one reference to the
27718 ** page. This function deletes that reference, so after it returns the
27719 ** page pointed to by p is invalid.
27720 */
27721 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
27722   PCache *pCache;
27723   assert( p->nRef==1 );
27724   if( p->flags&PGHDR_DIRTY ){
27725     pcacheRemoveFromDirtyList(p);
27726   }
27727   pCache = p->pCache;
27728   pCache->nRef--;
27729   if( p->pgno==1 ){
27730     pCache->pPage1 = 0;
27731   }
27732   sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
27733 }
27734
27735 /*
27736 ** Make sure the page is marked as dirty. If it isn't dirty already,
27737 ** make it so.
27738 */
27739 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
27740   PCache *pCache;
27741   p->flags &= ~PGHDR_DONT_WRITE;
27742   assert( p->nRef>0 );
27743   if( 0==(p->flags & PGHDR_DIRTY) ){
27744     pCache = p->pCache;
27745     p->flags |= PGHDR_DIRTY;
27746     pcacheAddToDirtyList( p);
27747   }
27748 }
27749
27750 /*
27751 ** Make sure the page is marked as clean. If it isn't clean already,
27752 ** make it so.
27753 */
27754 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
27755   if( (p->flags & PGHDR_DIRTY) ){
27756     pcacheRemoveFromDirtyList(p);
27757     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
27758     if( p->nRef==0 ){
27759       pcacheUnpin(p);
27760     }
27761   }
27762 }
27763
27764 /*
27765 ** Make every page in the cache clean.
27766 */
27767 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
27768   PgHdr *p;
27769   while( (p = pCache->pDirty)!=0 ){
27770     sqlite3PcacheMakeClean(p);
27771   }
27772 }
27773
27774 /*
27775 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
27776 */
27777 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
27778   PgHdr *p;
27779   for(p=pCache->pDirty; p; p=p->pDirtyNext){
27780     p->flags &= ~PGHDR_NEED_SYNC;
27781   }
27782   pCache->pSynced = pCache->pDirtyTail;
27783 }
27784
27785 /*
27786 ** Change the page number of page p to newPgno. 
27787 */
27788 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
27789   PCache *pCache = p->pCache;
27790   assert( p->nRef>0 );
27791   assert( newPgno>0 );
27792   sqlite3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
27793   p->pgno = newPgno;
27794   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
27795     pcacheRemoveFromDirtyList(p);
27796     pcacheAddToDirtyList(p);
27797   }
27798 }
27799
27800 /*
27801 ** Drop every cache entry whose page number is greater than "pgno". The
27802 ** caller must ensure that there are no outstanding references to any pages
27803 ** other than page 1 with a page number greater than pgno.
27804 **
27805 ** If there is a reference to page 1 and the pgno parameter passed to this
27806 ** function is 0, then the data area associated with page 1 is zeroed, but
27807 ** the page object is not dropped.
27808 */
27809 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
27810   if( pCache->pCache ){
27811     PgHdr *p;
27812     PgHdr *pNext;
27813     for(p=pCache->pDirty; p; p=pNext){
27814       pNext = p->pDirtyNext;
27815       if( p->pgno>pgno ){
27816         assert( p->flags&PGHDR_DIRTY );
27817         sqlite3PcacheMakeClean(p);
27818       }
27819     }
27820     if( pgno==0 && pCache->pPage1 ){
27821       memset(pCache->pPage1->pData, 0, pCache->szPage);
27822       pgno = 1;
27823     }
27824     sqlite3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
27825   }
27826 }
27827
27828 /*
27829 ** Close a cache.
27830 */
27831 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
27832   if( pCache->pCache ){
27833     sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
27834   }
27835 }
27836
27837 /* 
27838 ** Discard the contents of the cache.
27839 */
27840 SQLITE_PRIVATE int sqlite3PcacheClear(PCache *pCache){
27841   sqlite3PcacheTruncate(pCache, 0);
27842   return SQLITE_OK;
27843 }
27844
27845 /*
27846 ** Merge two lists of pages connected by pDirty and in pgno order.
27847 ** Do not both fixing the pDirtyPrev pointers.
27848 */
27849 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
27850   PgHdr result, *pTail;
27851   pTail = &result;
27852   while( pA && pB ){
27853     if( pA->pgno<pB->pgno ){
27854       pTail->pDirty = pA;
27855       pTail = pA;
27856       pA = pA->pDirty;
27857     }else{
27858       pTail->pDirty = pB;
27859       pTail = pB;
27860       pB = pB->pDirty;
27861     }
27862   }
27863   if( pA ){
27864     pTail->pDirty = pA;
27865   }else if( pB ){
27866     pTail->pDirty = pB;
27867   }else{
27868     pTail->pDirty = 0;
27869   }
27870   return result.pDirty;
27871 }
27872
27873 /*
27874 ** Sort the list of pages in accending order by pgno.  Pages are
27875 ** connected by pDirty pointers.  The pDirtyPrev pointers are
27876 ** corrupted by this sort.
27877 */
27878 #define N_SORT_BUCKET_ALLOC 25
27879 #define N_SORT_BUCKET       25
27880 #ifdef SQLITE_TEST
27881   int sqlite3_pager_n_sort_bucket = 0;
27882   #undef N_SORT_BUCKET
27883   #define N_SORT_BUCKET \
27884    (sqlite3_pager_n_sort_bucket?sqlite3_pager_n_sort_bucket:N_SORT_BUCKET_ALLOC)
27885 #endif
27886 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
27887   PgHdr *a[N_SORT_BUCKET_ALLOC], *p;
27888   int i;
27889   memset(a, 0, sizeof(a));
27890   while( pIn ){
27891     p = pIn;
27892     pIn = p->pDirty;
27893     p->pDirty = 0;
27894     for(i=0; i<N_SORT_BUCKET-1; i++){
27895       if( a[i]==0 ){
27896         a[i] = p;
27897         break;
27898       }else{
27899         p = pcacheMergeDirtyList(a[i], p);
27900         a[i] = 0;
27901       }
27902     }
27903     if( i==N_SORT_BUCKET-1 ){
27904       /* Coverage: To get here, there need to be 2^(N_SORT_BUCKET) 
27905       ** elements in the input list. This is possible, but impractical.
27906       ** Testing this line is the point of global variable
27907       ** sqlite3_pager_n_sort_bucket.
27908       */
27909       a[i] = pcacheMergeDirtyList(a[i], p);
27910     }
27911   }
27912   p = a[0];
27913   for(i=1; i<N_SORT_BUCKET; i++){
27914     p = pcacheMergeDirtyList(p, a[i]);
27915   }
27916   return p;
27917 }
27918
27919 /*
27920 ** Return a list of all dirty pages in the cache, sorted by page number.
27921 */
27922 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
27923   PgHdr *p;
27924   for(p=pCache->pDirty; p; p=p->pDirtyNext){
27925     p->pDirty = p->pDirtyNext;
27926   }
27927   return pcacheSortDirtyList(pCache->pDirty);
27928 }
27929
27930 /* 
27931 ** Return the total number of referenced pages held by the cache.
27932 */
27933 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
27934   return pCache->nRef;
27935 }
27936
27937 /*
27938 ** Return the number of references to the page supplied as an argument.
27939 */
27940 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
27941   return p->nRef;
27942 }
27943
27944 /* 
27945 ** Return the total number of pages in the cache.
27946 */
27947 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
27948   int nPage = 0;
27949   if( pCache->pCache ){
27950     nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache);
27951   }
27952   return nPage;
27953 }
27954
27955 #ifdef SQLITE_TEST
27956 /*
27957 ** Get the suggested cache-size value.
27958 */
27959 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
27960   return pCache->nMax;
27961 }
27962 #endif
27963
27964 /*
27965 ** Set the suggested cache-size value.
27966 */
27967 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
27968   pCache->nMax = mxPage;
27969   if( pCache->pCache ){
27970     sqlite3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
27971   }
27972 }
27973
27974 #ifdef SQLITE_CHECK_PAGES
27975 /*
27976 ** For all dirty pages currently in the cache, invoke the specified
27977 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
27978 ** defined.
27979 */
27980 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
27981   PgHdr *pDirty;
27982   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
27983     xIter(pDirty);
27984   }
27985 }
27986 #endif
27987
27988
27989 /************** End of pcache.c **********************************************/
27990 /************** Begin file pcache1.c *****************************************/
27991 /*
27992 ** 2008 November 05
27993 **
27994 ** The author disclaims copyright to this source code.  In place of
27995 ** a legal notice, here is a blessing:
27996 **
27997 **    May you do good and not evil.
27998 **    May you find forgiveness for yourself and forgive others.
27999 **    May you share freely, never taking more than you give.
28000 **
28001 *************************************************************************
28002 **
28003 ** This file implements the default page cache implementation (the
28004 ** sqlite3_pcache interface). It also contains part of the implementation
28005 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
28006 ** If the default page cache implementation is overriden, then neither of
28007 ** these two features are available.
28008 **
28009 ** @(#) $Id: pcache1.c,v 1.3 2008/11/19 09:05:27 danielk1977 Exp $
28010 */
28011
28012
28013 typedef struct PCache1 PCache1;
28014 typedef struct PgHdr1 PgHdr1;
28015 typedef struct PgFreeslot PgFreeslot;
28016
28017 /* Pointers to structures of this type are cast and returned as 
28018 ** opaque sqlite3_pcache* handles
28019 */
28020 struct PCache1 {
28021   /* Cache configuration parameters. Page size (szPage) and the purgeable
28022   ** flag (bPurgeable) are set when the cache is created. nMax may be 
28023   ** modified at any time by a call to the pcache1CacheSize() method.
28024   ** The global mutex must be held when accessing nMax.
28025   */
28026   int szPage;                         /* Size of allocated pages in bytes */
28027   int bPurgeable;                     /* True if cache is purgeable */
28028   unsigned int nMin;                  /* Minimum number of pages reserved */
28029   unsigned int nMax;                  /* Configured "cache_size" value */
28030
28031   /* Hash table of all pages. The following variables may only be accessed
28032   ** when the accessor is holding the global mutex (see pcache1EnterMutex() 
28033   ** and pcache1LeaveMutex()).
28034   */
28035   unsigned int nRecyclable;           /* Number of pages in the LRU list */
28036   unsigned int nPage;                 /* Total number of pages in apHash */
28037   unsigned int nHash;                 /* Number of slots in apHash[] */
28038   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
28039 };
28040
28041 /*
28042 ** Each cache entry is represented by an instance of the following 
28043 ** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated 
28044 ** directly after the structure in memory (see the PGHDR1_TO_PAGE() 
28045 ** macro below).
28046 */
28047 struct PgHdr1 {
28048   unsigned int iKey;             /* Key value (page number) */
28049   PgHdr1 *pNext;                 /* Next in hash table chain */
28050   PCache1 *pCache;               /* Cache that currently owns this page */
28051   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
28052   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
28053 };
28054
28055 /*
28056 ** Free slots in the allocator used to divide up the buffer provided using
28057 ** the SQLITE_CONFIG_PAGECACHE mechanism.
28058 */
28059 struct PgFreeslot {
28060   PgFreeslot *pNext;  /* Next free slot */
28061 };
28062
28063 /*
28064 ** Global data used by this cache.
28065 */
28066 static SQLITE_WSD struct PCacheGlobal {
28067   sqlite3_mutex *mutex;               /* static mutex MUTEX_STATIC_LRU */
28068
28069   int nMaxPage;                       /* Sum of nMaxPage for purgeable caches */
28070   int nMinPage;                       /* Sum of nMinPage for purgeable caches */
28071   int nCurrentPage;                   /* Number of purgeable pages allocated */
28072   PgHdr1 *pLruHead, *pLruTail;        /* LRU list of unpinned pages */
28073
28074   /* Variables related to SQLITE_CONFIG_PAGECACHE settings. */
28075   int szSlot;                         /* Size of each free slot */
28076   void *pStart, *pEnd;                /* Bounds of pagecache malloc range */
28077   PgFreeslot *pFree;                  /* Free page blocks */
28078 } pcache1_g;
28079
28080 /*
28081 ** All code in this file should access the global structure above via the
28082 ** alias "pcache1". This ensures that the WSD emulation is used when
28083 ** compiling for systems that do not support real WSD.
28084 */
28085 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
28086
28087 /*
28088 ** When a PgHdr1 structure is allocated, the associated PCache1.szPage
28089 ** bytes of data are located directly after it in memory (i.e. the total
28090 ** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
28091 ** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
28092 ** an argument and returns a pointer to the associated block of szPage
28093 ** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
28094 ** a pointer to a block of szPage bytes of data and the return value is
28095 ** a pointer to the associated PgHdr1 structure.
28096 **
28097 **   assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(X))==X );
28098 */
28099 #define PGHDR1_TO_PAGE(p) (void *)(&((unsigned char *)p)[sizeof(PgHdr1)])
28100 #define PAGE_TO_PGHDR1(p) (PgHdr1 *)(&((unsigned char *)p)[-1*sizeof(PgHdr1)])
28101
28102 /*
28103 ** Macros to enter and leave the global LRU mutex.
28104 */
28105 #define pcache1EnterMutex() sqlite3_mutex_enter(pcache1.mutex)
28106 #define pcache1LeaveMutex() sqlite3_mutex_leave(pcache1.mutex)
28107
28108 /******************************************************************************/
28109 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
28110
28111 /*
28112 ** This function is called during initialization if a static buffer is 
28113 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
28114 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
28115 ** enough to contain 'n' buffers of 'sz' bytes each.
28116 */
28117 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
28118   PgFreeslot *p;
28119   sz &= ~7;
28120   pcache1.szSlot = sz;
28121   pcache1.pStart = pBuf;
28122   pcache1.pFree = 0;
28123   while( n-- ){
28124     p = (PgFreeslot*)pBuf;
28125     p->pNext = pcache1.pFree;
28126     pcache1.pFree = p;
28127     pBuf = (void*)&((char*)pBuf)[sz];
28128   }
28129   pcache1.pEnd = pBuf;
28130 }
28131
28132 /*
28133 ** Malloc function used within this file to allocate space from the buffer
28134 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no 
28135 ** such buffer exists or there is no space left in it, this function falls 
28136 ** back to sqlite3Malloc().
28137 */
28138 static void *pcache1Alloc(int nByte){
28139   void *p;
28140   assert( sqlite3_mutex_held(pcache1.mutex) );
28141   if( nByte<=pcache1.szSlot && pcache1.pFree ){
28142     p = (PgHdr1 *)pcache1.pFree;
28143     pcache1.pFree = pcache1.pFree->pNext;
28144     sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
28145     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
28146   }else{
28147
28148     /* Allocate a new buffer using sqlite3Malloc. Before doing so, exit the
28149     ** global pcache mutex and unlock the pager-cache object pCache. This is 
28150     ** so that if the attempt to allocate a new buffer causes the the 
28151     ** configured soft-heap-limit to be breached, it will be possible to
28152     ** reclaim memory from this pager-cache.
28153     */
28154     pcache1LeaveMutex();
28155     p = sqlite3Malloc(nByte);
28156     pcache1EnterMutex();
28157     if( p ){
28158       int sz = sqlite3MallocSize(p);
28159       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
28160     }
28161   }
28162   return p;
28163 }
28164
28165 /*
28166 ** Free an allocated buffer obtained from pcache1Alloc().
28167 */
28168 static void pcache1Free(void *p){
28169   assert( sqlite3_mutex_held(pcache1.mutex) );
28170   if( p==0 ) return;
28171   if( p>=pcache1.pStart && p<pcache1.pEnd ){
28172     PgFreeslot *pSlot;
28173     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
28174     pSlot = (PgFreeslot*)p;
28175     pSlot->pNext = pcache1.pFree;
28176     pcache1.pFree = pSlot;
28177   }else{
28178     int iSize = sqlite3MallocSize(p);
28179     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
28180     sqlite3_free(p);
28181   }
28182 }
28183
28184 /*
28185 ** Allocate a new page object initially associated with cache pCache.
28186 */
28187 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
28188   int nByte = sizeof(PgHdr1) + pCache->szPage;
28189   PgHdr1 *p = (PgHdr1 *)pcache1Alloc(nByte);
28190   if( p ){
28191     memset(p, 0, nByte);
28192     if( pCache->bPurgeable ){
28193       pcache1.nCurrentPage++;
28194     }
28195   }
28196   return p;
28197 }
28198
28199 /*
28200 ** Free a page object allocated by pcache1AllocPage().
28201 */
28202 static void pcache1FreePage(PgHdr1 *p){
28203   if( p ){
28204     if( p->pCache->bPurgeable ){
28205       pcache1.nCurrentPage--;
28206     }
28207     pcache1Free(p);
28208   }
28209 }
28210
28211 /*
28212 ** Malloc function used by SQLite to obtain space from the buffer configured
28213 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
28214 ** exists, this function falls back to sqlite3Malloc().
28215 */
28216 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
28217   void *p;
28218   pcache1EnterMutex();
28219   p = pcache1Alloc(sz);
28220   pcache1LeaveMutex();
28221   return p;
28222 }
28223
28224 /*
28225 ** Free an allocated buffer obtained from sqlite3PageMalloc().
28226 */
28227 SQLITE_PRIVATE void sqlite3PageFree(void *p){
28228   pcache1EnterMutex();
28229   pcache1Free(p);
28230   pcache1LeaveMutex();
28231 }
28232
28233 /******************************************************************************/
28234 /******** General Implementation Functions ************************************/
28235
28236 /*
28237 ** This function is used to resize the hash table used by the cache passed
28238 ** as the first argument.
28239 **
28240 ** The global mutex must be held when this function is called.
28241 */
28242 static int pcache1ResizeHash(PCache1 *p){
28243   PgHdr1 **apNew;
28244   unsigned int nNew;
28245   unsigned int i;
28246
28247   assert( sqlite3_mutex_held(pcache1.mutex) );
28248
28249   nNew = p->nHash*2;
28250   if( nNew<256 ){
28251     nNew = 256;
28252   }
28253
28254   pcache1LeaveMutex();
28255   apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
28256   pcache1EnterMutex();
28257   if( apNew ){
28258     memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
28259     for(i=0; i<p->nHash; i++){
28260       PgHdr1 *pPage;
28261       PgHdr1 *pNext = p->apHash[i];
28262       while( (pPage = pNext) ){
28263         unsigned int h = pPage->iKey % nNew;
28264         pNext = pPage->pNext;
28265         pPage->pNext = apNew[h];
28266         apNew[h] = pPage;
28267       }
28268     }
28269     sqlite3_free(p->apHash);
28270     p->apHash = apNew;
28271     p->nHash = nNew;
28272   }
28273
28274   return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
28275 }
28276
28277 /*
28278 ** This function is used internally to remove the page pPage from the 
28279 ** global LRU list, if is part of it. If pPage is not part of the global
28280 ** LRU list, then this function is a no-op.
28281 **
28282 ** The global mutex must be held when this function is called.
28283 */
28284 static void pcache1PinPage(PgHdr1 *pPage){
28285   assert( sqlite3_mutex_held(pcache1.mutex) );
28286   if( pPage && (pPage->pLruNext || pPage==pcache1.pLruTail) ){
28287     if( pPage->pLruPrev ){
28288       pPage->pLruPrev->pLruNext = pPage->pLruNext;
28289     }
28290     if( pPage->pLruNext ){
28291       pPage->pLruNext->pLruPrev = pPage->pLruPrev;
28292     }
28293     if( pcache1.pLruHead==pPage ){
28294       pcache1.pLruHead = pPage->pLruNext;
28295     }
28296     if( pcache1.pLruTail==pPage ){
28297       pcache1.pLruTail = pPage->pLruPrev;
28298     }
28299     pPage->pLruNext = 0;
28300     pPage->pLruPrev = 0;
28301     pPage->pCache->nRecyclable--;
28302   }
28303 }
28304
28305
28306 /*
28307 ** Remove the page supplied as an argument from the hash table 
28308 ** (PCache1.apHash structure) that it is currently stored in.
28309 **
28310 ** The global mutex must be held when this function is called.
28311 */
28312 static void pcache1RemoveFromHash(PgHdr1 *pPage){
28313   unsigned int h;
28314   PCache1 *pCache = pPage->pCache;
28315   PgHdr1 **pp;
28316
28317   h = pPage->iKey % pCache->nHash;
28318   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
28319   *pp = (*pp)->pNext;
28320
28321   pCache->nPage--;
28322 }
28323
28324 /*
28325 ** If there are currently more than pcache.nMaxPage pages allocated, try
28326 ** to recycle pages to reduce the number allocated to pcache.nMaxPage.
28327 */
28328 static void pcache1EnforceMaxPage(void){
28329   assert( sqlite3_mutex_held(pcache1.mutex) );
28330   while( pcache1.nCurrentPage>pcache1.nMaxPage && pcache1.pLruTail ){
28331     PgHdr1 *p = pcache1.pLruTail;
28332     pcache1PinPage(p);
28333     pcache1RemoveFromHash(p);
28334     pcache1FreePage(p);
28335   }
28336 }
28337
28338 /*
28339 ** Discard all pages from cache pCache with a page number (key value) 
28340 ** greater than or equal to iLimit. Any pinned pages that meet this 
28341 ** criteria are unpinned before they are discarded.
28342 **
28343 ** The global mutex must be held when this function is called.
28344 */
28345 static void pcache1TruncateUnsafe(
28346   PCache1 *pCache, 
28347   unsigned int iLimit 
28348 ){
28349   unsigned int h;
28350   assert( sqlite3_mutex_held(pcache1.mutex) );
28351   for(h=0; h<pCache->nHash; h++){
28352     PgHdr1 **pp = &pCache->apHash[h]; 
28353     PgHdr1 *pPage;
28354     while( (pPage = *pp) ){
28355       if( pPage->iKey>=iLimit ){
28356         pcache1PinPage(pPage);
28357         *pp = pPage->pNext;
28358         pcache1FreePage(pPage);
28359       }else{
28360         pp = &pPage->pNext;
28361       }
28362     }
28363   }
28364 }
28365
28366 /******************************************************************************/
28367 /******** sqlite3_pcache Methods **********************************************/
28368
28369 /*
28370 ** Implementation of the sqlite3_pcache.xInit method.
28371 */
28372 static int pcache1Init(void *NotUsed){
28373   UNUSED_PARAMETER(NotUsed);
28374   memset(&pcache1, 0, sizeof(pcache1));
28375   if( sqlite3GlobalConfig.bCoreMutex ){
28376     pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
28377   }
28378   return SQLITE_OK;
28379 }
28380
28381 /*
28382 ** Implementation of the sqlite3_pcache.xShutdown method.
28383 */
28384 static void pcache1Shutdown(void *NotUsed){
28385   UNUSED_PARAMETER(NotUsed);
28386   /* no-op */
28387 }
28388
28389 /*
28390 ** Implementation of the sqlite3_pcache.xCreate method.
28391 **
28392 ** Allocate a new cache.
28393 */
28394 static sqlite3_pcache *pcache1Create(int szPage, int bPurgeable){
28395   PCache1 *pCache;
28396
28397   pCache = (PCache1 *)sqlite3_malloc(sizeof(PCache1));
28398   if( pCache ){
28399     memset(pCache, 0, sizeof(PCache1));
28400     pCache->szPage = szPage;
28401     pCache->bPurgeable = (bPurgeable ? 1 : 0);
28402     if( bPurgeable ){
28403       pCache->nMin = 10;
28404       pcache1EnterMutex();
28405       pcache1.nMinPage += pCache->nMin;
28406       pcache1LeaveMutex();
28407     }
28408   }
28409   return (sqlite3_pcache *)pCache;
28410 }
28411
28412 /*
28413 ** Implementation of the sqlite3_pcache.xCachesize method. 
28414 **
28415 ** Configure the cache_size limit for a cache.
28416 */
28417 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
28418   PCache1 *pCache = (PCache1 *)p;
28419   if( pCache->bPurgeable ){
28420     pcache1EnterMutex();
28421     pcache1.nMaxPage += (nMax - pCache->nMax);
28422     pCache->nMax = nMax;
28423     pcache1EnforceMaxPage();
28424     pcache1LeaveMutex();
28425   }
28426 }
28427
28428 /*
28429 ** Implementation of the sqlite3_pcache.xPagecount method. 
28430 */
28431 static int pcache1Pagecount(sqlite3_pcache *p){
28432   int n;
28433   pcache1EnterMutex();
28434   n = ((PCache1 *)p)->nPage;
28435   pcache1LeaveMutex();
28436   return n;
28437 }
28438
28439 /*
28440 ** Implementation of the sqlite3_pcache.xFetch method. 
28441 **
28442 ** Fetch a page by key value.
28443 **
28444 ** Whether or not a new page may be allocated by this function depends on
28445 ** the value of the createFlag argument.
28446 **
28447 ** There are three different approaches to obtaining space for a page,
28448 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
28449 **
28450 **   1. Regardless of the value of createFlag, the cache is searched for a 
28451 **      copy of the requested page. If one is found, it is returned.
28452 **
28453 **   2. If createFlag==0 and the page is not already in the cache, NULL is
28454 **      returned.
28455 **
28456 **   3. If createFlag is 1, the cache is marked as purgeable and the page is 
28457 **      not already in the cache, and if either of the following are true, 
28458 **      return NULL:
28459 **
28460 **       (a) the number of pages pinned by the cache is greater than
28461 **           PCache1.nMax, or
28462 **       (b) the number of pages pinned by the cache is greater than
28463 **           the sum of nMax for all purgeable caches, less the sum of 
28464 **           nMin for all other purgeable caches. 
28465 **
28466 **   4. If none of the first three conditions apply and the cache is marked
28467 **      as purgeable, and if one of the following is true:
28468 **
28469 **       (a) The number of pages allocated for the cache is already 
28470 **           PCache1.nMax, or
28471 **
28472 **       (b) The number of pages allocated for all purgeable caches is
28473 **           already equal to or greater than the sum of nMax for all
28474 **           purgeable caches,
28475 **
28476 **      then attempt to recycle a page from the LRU list. If it is the right
28477 **      size, return the recycled buffer. Otherwise, free the buffer and
28478 **      proceed to step 5. 
28479 **
28480 **   5. Otherwise, allocate and return a new page buffer.
28481 */
28482 static void *pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag){
28483   unsigned int nPinned;
28484   PCache1 *pCache = (PCache1 *)p;
28485   PgHdr1 *pPage = 0;
28486
28487   pcache1EnterMutex();
28488   if( createFlag==1 ) sqlite3BeginBenignMalloc();
28489
28490   /* Search the hash table for an existing entry. */
28491   if( pCache->nHash>0 ){
28492     unsigned int h = iKey % pCache->nHash;
28493     for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
28494   }
28495
28496   if( pPage || createFlag==0 ){
28497     pcache1PinPage(pPage);
28498     goto fetch_out;
28499   }
28500
28501   /* Step 3 of header comment. */
28502   nPinned = pCache->nPage - pCache->nRecyclable;
28503   if( createFlag==1 && pCache->bPurgeable && (
28504         nPinned>=(pcache1.nMaxPage+pCache->nMin-pcache1.nMinPage)
28505      || nPinned>=(pCache->nMax)
28506   )){
28507     goto fetch_out;
28508   }
28509
28510   if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
28511     goto fetch_out;
28512   }
28513
28514   /* Step 4. Try to recycle a page buffer if appropriate. */
28515   if( pCache->bPurgeable && pcache1.pLruTail && (
28516       pCache->nPage>=pCache->nMax-1 || pcache1.nCurrentPage>=pcache1.nMaxPage
28517   )){
28518     pPage = pcache1.pLruTail;
28519     pcache1RemoveFromHash(pPage);
28520     pcache1PinPage(pPage);
28521     if( pPage->pCache->szPage!=pCache->szPage ){
28522       pcache1FreePage(pPage);
28523       pPage = 0;
28524     }else{
28525       pcache1.nCurrentPage -= (pPage->pCache->bPurgeable - pCache->bPurgeable);
28526     }
28527   }
28528
28529   /* Step 5. If a usable page buffer has still not been found, 
28530   ** attempt to allocate a new one. 
28531   */
28532   if( !pPage ){
28533     pPage = pcache1AllocPage(pCache);
28534   }
28535
28536   if( pPage ){
28537     unsigned int h = iKey % pCache->nHash;
28538     memset(pPage, 0, pCache->szPage + sizeof(PgHdr1));
28539     pCache->nPage++;
28540     pPage->iKey = iKey;
28541     pPage->pNext = pCache->apHash[h];
28542     pPage->pCache = pCache;
28543     pCache->apHash[h] = pPage;
28544   }
28545
28546 fetch_out:
28547   if( createFlag==1 ) sqlite3EndBenignMalloc();
28548   pcache1LeaveMutex();
28549   return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
28550 }
28551
28552
28553 /*
28554 ** Implementation of the sqlite3_pcache.xUnpin method.
28555 **
28556 ** Mark a page as unpinned (eligible for asynchronous recycling).
28557 */
28558 static void pcache1Unpin(sqlite3_pcache *p, void *pPg, int reuseUnlikely){
28559   PCache1 *pCache = (PCache1 *)p;
28560   PgHdr1 *pPage = PAGE_TO_PGHDR1(pPg);
28561
28562   pcache1EnterMutex();
28563
28564   /* It is an error to call this function if the page is already 
28565   ** part of the global LRU list.
28566   */
28567   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
28568   assert( pcache1.pLruHead!=pPage && pcache1.pLruTail!=pPage );
28569
28570   if( reuseUnlikely || pcache1.nCurrentPage>pcache1.nMaxPage ){
28571     pcache1RemoveFromHash(pPage);
28572     pcache1FreePage(pPage);
28573   }else{
28574     /* Add the page to the global LRU list. Normally, the page is added to
28575     ** the head of the list (last page to be recycled). However, if the 
28576     ** reuseUnlikely flag passed to this function is true, the page is added
28577     ** to the tail of the list (first page to be recycled).
28578     */
28579     if( pcache1.pLruHead ){
28580       pcache1.pLruHead->pLruPrev = pPage;
28581       pPage->pLruNext = pcache1.pLruHead;
28582       pcache1.pLruHead = pPage;
28583     }else{
28584       pcache1.pLruTail = pPage;
28585       pcache1.pLruHead = pPage;
28586     }
28587     pCache->nRecyclable++;
28588   }
28589
28590   pcache1LeaveMutex();
28591 }
28592
28593 /*
28594 ** Implementation of the sqlite3_pcache.xRekey method. 
28595 */
28596 static void pcache1Rekey(
28597   sqlite3_pcache *p,
28598   void *pPg,
28599   unsigned int iOld,
28600   unsigned int iNew
28601 ){
28602   PCache1 *pCache = (PCache1 *)p;
28603   PgHdr1 *pPage = PAGE_TO_PGHDR1(pPg);
28604   PgHdr1 **pp;
28605   unsigned int h; 
28606   assert( pPage->iKey==iOld );
28607
28608   pcache1EnterMutex();
28609
28610   h = iOld%pCache->nHash;
28611   pp = &pCache->apHash[h];
28612   while( (*pp)!=pPage ){
28613     pp = &(*pp)->pNext;
28614   }
28615   *pp = pPage->pNext;
28616
28617   h = iNew%pCache->nHash;
28618   pPage->iKey = iNew;
28619   pPage->pNext = pCache->apHash[h];
28620   pCache->apHash[h] = pPage;
28621
28622   pcache1LeaveMutex();
28623 }
28624
28625 /*
28626 ** Implementation of the sqlite3_pcache.xTruncate method. 
28627 **
28628 ** Discard all unpinned pages in the cache with a page number equal to
28629 ** or greater than parameter iLimit. Any pinned pages with a page number
28630 ** equal to or greater than iLimit are implicitly unpinned.
28631 */
28632 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
28633   PCache1 *pCache = (PCache1 *)p;
28634   pcache1EnterMutex();
28635   pcache1TruncateUnsafe(pCache, iLimit);
28636   pcache1LeaveMutex();
28637 }
28638
28639 /*
28640 ** Implementation of the sqlite3_pcache.xDestroy method. 
28641 **
28642 ** Destroy a cache allocated using pcache1Create().
28643 */
28644 static void pcache1Destroy(sqlite3_pcache *p){
28645   PCache1 *pCache = (PCache1 *)p;
28646   pcache1EnterMutex();
28647   pcache1TruncateUnsafe(pCache, 0);
28648   pcache1.nMaxPage -= pCache->nMax;
28649   pcache1.nMinPage -= pCache->nMin;
28650   pcache1EnforceMaxPage();
28651   pcache1LeaveMutex();
28652   sqlite3_free(pCache->apHash);
28653   sqlite3_free(pCache);
28654 }
28655
28656 /*
28657 ** This function is called during initialization (sqlite3_initialize()) to
28658 ** install the default pluggable cache module, assuming the user has not
28659 ** already provided an alternative.
28660 */
28661 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
28662   static sqlite3_pcache_methods defaultMethods = {
28663     0,                       /* pArg */
28664     pcache1Init,             /* xInit */
28665     pcache1Shutdown,         /* xShutdown */
28666     pcache1Create,           /* xCreate */
28667     pcache1Cachesize,        /* xCachesize */
28668     pcache1Pagecount,        /* xPagecount */
28669     pcache1Fetch,            /* xFetch */
28670     pcache1Unpin,            /* xUnpin */
28671     pcache1Rekey,            /* xRekey */
28672     pcache1Truncate,         /* xTruncate */
28673     pcache1Destroy           /* xDestroy */
28674   };
28675   sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
28676 }
28677
28678 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
28679 /*
28680 ** This function is called to free superfluous dynamically allocated memory
28681 ** held by the pager system. Memory in use by any SQLite pager allocated
28682 ** by the current thread may be sqlite3_free()ed.
28683 **
28684 ** nReq is the number of bytes of memory required. Once this much has
28685 ** been released, the function returns. The return value is the total number 
28686 ** of bytes of memory released.
28687 */
28688 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
28689   int nFree = 0;
28690   if( pcache1.pStart==0 ){
28691     PgHdr1 *p;
28692     pcache1EnterMutex();
28693     while( (nReq<0 || nFree<nReq) && (p=pcache1.pLruTail) ){
28694       nFree += sqlite3MallocSize(p);
28695       pcache1PinPage(p);
28696       pcache1RemoveFromHash(p);
28697       pcache1FreePage(p);
28698     }
28699     pcache1LeaveMutex();
28700   }
28701   return nFree;
28702 }
28703 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
28704
28705 #ifdef SQLITE_TEST
28706 /*
28707 ** This function is used by test procedures to inspect the internal state
28708 ** of the global cache.
28709 */
28710 SQLITE_PRIVATE void sqlite3PcacheStats(
28711   int *pnCurrent,      /* OUT: Total number of pages cached */
28712   int *pnMax,          /* OUT: Global maximum cache size */
28713   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
28714   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
28715 ){
28716   PgHdr1 *p;
28717   int nRecyclable = 0;
28718   for(p=pcache1.pLruHead; p; p=p->pLruNext){
28719     nRecyclable++;
28720   }
28721   *pnCurrent = pcache1.nCurrentPage;
28722   *pnMax = pcache1.nMaxPage;
28723   *pnMin = pcache1.nMinPage;
28724   *pnRecyclable = nRecyclable;
28725 }
28726 #endif
28727
28728 /************** End of pcache1.c *********************************************/
28729 /************** Begin file pager.c *******************************************/
28730 /*
28731 ** 2001 September 15
28732 **
28733 ** The author disclaims copyright to this source code.  In place of
28734 ** a legal notice, here is a blessing:
28735 **
28736 **    May you do good and not evil.
28737 **    May you find forgiveness for yourself and forgive others.
28738 **    May you share freely, never taking more than you give.
28739 **
28740 *************************************************************************
28741 ** This is the implementation of the page cache subsystem or "pager".
28742 ** 
28743 ** The pager is used to access a database disk file.  It implements
28744 ** atomic commit and rollback through the use of a journal file that
28745 ** is separate from the database file.  The pager also implements file
28746 ** locking to prevent two processes from writing the same database
28747 ** file simultaneously, or one process from reading the database while
28748 ** another is writing.
28749 **
28750 ** @(#) $Id: pager.c,v 1.506.2.1 2008/11/26 14:55:02 drh Exp $
28751 */
28752 #ifndef SQLITE_OMIT_DISKIO
28753
28754 /*
28755 ** Macros for troubleshooting.  Normally turned off
28756 */
28757 #if 0
28758 #define sqlite3DebugPrintf printf
28759 #define PAGERTRACE1(X)       sqlite3DebugPrintf(X)
28760 #define PAGERTRACE2(X,Y)     sqlite3DebugPrintf(X,Y)
28761 #define PAGERTRACE3(X,Y,Z)   sqlite3DebugPrintf(X,Y,Z)
28762 #define PAGERTRACE4(X,Y,Z,W) sqlite3DebugPrintf(X,Y,Z,W)
28763 #define PAGERTRACE5(X,Y,Z,W,V) sqlite3DebugPrintf(X,Y,Z,W,V)
28764 #else
28765 #define PAGERTRACE1(X)
28766 #define PAGERTRACE2(X,Y)
28767 #define PAGERTRACE3(X,Y,Z)
28768 #define PAGERTRACE4(X,Y,Z,W)
28769 #define PAGERTRACE5(X,Y,Z,W,V)
28770 #endif
28771
28772 /*
28773 ** The following two macros are used within the PAGERTRACEX() macros above
28774 ** to print out file-descriptors. 
28775 **
28776 ** PAGERID() takes a pointer to a Pager struct as its argument. The
28777 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
28778 ** struct as its argument.
28779 */
28780 #define PAGERID(p) ((int)(p->fd))
28781 #define FILEHANDLEID(fd) ((int)fd)
28782
28783 /*
28784 ** The page cache as a whole is always in one of the following
28785 ** states:
28786 **
28787 **   PAGER_UNLOCK        The page cache is not currently reading or 
28788 **                       writing the database file.  There is no
28789 **                       data held in memory.  This is the initial
28790 **                       state.
28791 **
28792 **   PAGER_SHARED        The page cache is reading the database.
28793 **                       Writing is not permitted.  There can be
28794 **                       multiple readers accessing the same database
28795 **                       file at the same time.
28796 **
28797 **   PAGER_RESERVED      This process has reserved the database for writing
28798 **                       but has not yet made any changes.  Only one process
28799 **                       at a time can reserve the database.  The original
28800 **                       database file has not been modified so other
28801 **                       processes may still be reading the on-disk
28802 **                       database file.
28803 **
28804 **   PAGER_EXCLUSIVE     The page cache is writing the database.
28805 **                       Access is exclusive.  No other processes or
28806 **                       threads can be reading or writing while one
28807 **                       process is writing.
28808 **
28809 **   PAGER_SYNCED        The pager moves to this state from PAGER_EXCLUSIVE
28810 **                       after all dirty pages have been written to the
28811 **                       database file and the file has been synced to
28812 **                       disk. All that remains to do is to remove or
28813 **                       truncate the journal file and the transaction 
28814 **                       will be committed.
28815 **
28816 ** The page cache comes up in PAGER_UNLOCK.  The first time a
28817 ** sqlite3PagerGet() occurs, the state transitions to PAGER_SHARED.
28818 ** After all pages have been released using sqlite_page_unref(),
28819 ** the state transitions back to PAGER_UNLOCK.  The first time
28820 ** that sqlite3PagerWrite() is called, the state transitions to
28821 ** PAGER_RESERVED.  (Note that sqlite3PagerWrite() can only be
28822 ** called on an outstanding page which means that the pager must
28823 ** be in PAGER_SHARED before it transitions to PAGER_RESERVED.)
28824 ** PAGER_RESERVED means that there is an open rollback journal.
28825 ** The transition to PAGER_EXCLUSIVE occurs before any changes
28826 ** are made to the database file, though writes to the rollback
28827 ** journal occurs with just PAGER_RESERVED.  After an sqlite3PagerRollback()
28828 ** or sqlite3PagerCommitPhaseTwo(), the state can go back to PAGER_SHARED,
28829 ** or it can stay at PAGER_EXCLUSIVE if we are in exclusive access mode.
28830 */
28831 #define PAGER_UNLOCK      0
28832 #define PAGER_SHARED      1   /* same as SHARED_LOCK */
28833 #define PAGER_RESERVED    2   /* same as RESERVED_LOCK */
28834 #define PAGER_EXCLUSIVE   4   /* same as EXCLUSIVE_LOCK */
28835 #define PAGER_SYNCED      5
28836
28837 /*
28838 ** If the SQLITE_BUSY_RESERVED_LOCK macro is set to true at compile-time,
28839 ** then failed attempts to get a reserved lock will invoke the busy callback.
28840 ** This is off by default.  To see why, consider the following scenario:
28841 ** 
28842 ** Suppose thread A already has a shared lock and wants a reserved lock.
28843 ** Thread B already has a reserved lock and wants an exclusive lock.  If
28844 ** both threads are using their busy callbacks, it might be a long time
28845 ** be for one of the threads give up and allows the other to proceed.
28846 ** But if the thread trying to get the reserved lock gives up quickly
28847 ** (if it never invokes its busy callback) then the contention will be
28848 ** resolved quickly.
28849 */
28850 #ifndef SQLITE_BUSY_RESERVED_LOCK
28851 # define SQLITE_BUSY_RESERVED_LOCK 0
28852 #endif
28853
28854 /*
28855 ** This macro rounds values up so that if the value is an address it
28856 ** is guaranteed to be an address that is aligned to an 8-byte boundary.
28857 */
28858 #define FORCE_ALIGNMENT(X)   (((X)+7)&~7)
28859
28860 /*
28861 ** A macro used for invoking the codec if there is one
28862 */
28863 #ifdef SQLITE_HAS_CODEC
28864 # define CODEC1(P,D,N,X) if( P->xCodec!=0 ){ P->xCodec(P->pCodecArg,D,N,X); }
28865 # define CODEC2(P,D,N,X) ((char*)(P->xCodec!=0?P->xCodec(P->pCodecArg,D,N,X):D))
28866 #else
28867 # define CODEC1(P,D,N,X) /* NO-OP */
28868 # define CODEC2(P,D,N,X) ((char*)D)
28869 #endif
28870
28871 /*
28872 ** A open page cache is an instance of the following structure.
28873 **
28874 ** Pager.errCode may be set to SQLITE_IOERR, SQLITE_CORRUPT, or
28875 ** or SQLITE_FULL. Once one of the first three errors occurs, it persists
28876 ** and is returned as the result of every major pager API call.  The
28877 ** SQLITE_FULL return code is slightly different. It persists only until the
28878 ** next successful rollback is performed on the pager cache. Also,
28879 ** SQLITE_FULL does not affect the sqlite3PagerGet() and sqlite3PagerLookup()
28880 ** APIs, they may still be used successfully.
28881 */
28882 struct Pager {
28883   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
28884   u8 journalOpen;             /* True if journal file descriptors is valid */
28885   u8 journalStarted;          /* True if header of journal is synced */
28886   u8 useJournal;              /* Use a rollback journal on this file */
28887   u8 noReadlock;              /* Do not bother to obtain readlocks */
28888   u8 stmtOpen;                /* True if the statement subjournal is open */
28889   u8 stmtInUse;               /* True we are in a statement subtransaction */
28890   u8 stmtAutoopen;            /* Open stmt journal when main journal is opened*/
28891   u8 noSync;                  /* Do not sync the journal if true */
28892   u8 fullSync;                /* Do extra syncs of the journal for robustness */
28893   u8 sync_flags;              /* One of SYNC_NORMAL or SYNC_FULL */
28894   u8 state;                   /* PAGER_UNLOCK, _SHARED, _RESERVED, etc. */
28895   u8 tempFile;                /* zFilename is a temporary file */
28896   u8 readOnly;                /* True for a read-only database */
28897   u8 needSync;                /* True if an fsync() is needed on the journal */
28898   u8 dirtyCache;              /* True if cached pages have changed */
28899   u8 alwaysRollback;          /* Disable DontRollback() for all pages */
28900   u8 memDb;                   /* True to inhibit all file I/O */
28901   u8 setMaster;               /* True if a m-j name has been written to jrnl */
28902   u8 doNotSync;               /* Boolean. While true, do not spill the cache */
28903   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
28904   u8 journalMode;             /* On of the PAGER_JOURNALMODE_* values */
28905   u8 dbModified;              /* True if there are any changes to the Db */
28906   u8 changeCountDone;         /* Set after incrementing the change-counter */
28907   u8 dbSizeValid;             /* Set when dbSize is correct */
28908   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
28909   int errCode;                /* One of several kinds of errors */
28910   Pgno dbSize;                /* Number of pages in the file */
28911   Pgno origDbSize;            /* dbSize before the current change */
28912   Pgno stmtSize;              /* Size of database (in pages) at stmt_begin() */
28913   int nRec;                   /* Number of pages written to the journal */
28914   u32 cksumInit;              /* Quasi-random value added to every checksum */
28915   int stmtNRec;               /* Number of records in stmt subjournal */
28916   int nExtra;                 /* Add this many bytes to each in-memory page */
28917   int pageSize;               /* Number of bytes in a page */
28918   int nPage;                  /* Total number of in-memory pages */
28919   int mxPage;                 /* Maximum number of pages to hold in cache */
28920   Pgno mxPgno;                /* Maximum allowed size of the database */
28921   Bitvec *pInJournal;         /* One bit for each page in the database file */
28922   Bitvec *pInStmt;            /* One bit for each page in the database */
28923   Bitvec *pAlwaysRollback;    /* One bit for each page marked always-rollback */
28924   char *zFilename;            /* Name of the database file */
28925   char *zJournal;             /* Name of the journal file */
28926   char *zDirectory;           /* Directory hold database and journal files */
28927   sqlite3_file *fd, *jfd;     /* File descriptors for database and journal */
28928   sqlite3_file *stfd;         /* File descriptor for the statement subjournal*/
28929   int (*xBusyHandler)(void*); /* Function to call when busy */
28930   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
28931   i64 journalOff;             /* Current byte offset in the journal file */
28932   i64 journalHdr;             /* Byte offset to previous journal header */
28933   i64 stmtHdrOff;             /* First journal header written this statement */
28934   i64 stmtCksum;              /* cksumInit when statement was started */
28935   i64 stmtJSize;              /* Size of journal at stmt_begin() */
28936   u32 sectorSize;             /* Assumed sector size during rollback */
28937 #ifdef SQLITE_TEST
28938   int nHit, nMiss;            /* Cache hits and missing */
28939   int nRead, nWrite;          /* Database pages read/written */
28940 #endif
28941   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
28942 #ifdef SQLITE_HAS_CODEC
28943   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
28944   void *pCodecArg;            /* First argument to xCodec() */
28945 #endif
28946   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
28947   char dbFileVers[16];        /* Changes whenever database file changes */
28948   i64 journalSizeLimit;       /* Size limit for persistent journal files */
28949   PCache *pPCache;            /* Pointer to page cache object */
28950 };
28951
28952 /*
28953 ** The following global variables hold counters used for
28954 ** testing purposes only.  These variables do not exist in
28955 ** a non-testing build.  These variables are not thread-safe.
28956 */
28957 #ifdef SQLITE_TEST
28958 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
28959 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
28960 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
28961 # define PAGER_INCR(v)  v++
28962 #else
28963 # define PAGER_INCR(v)
28964 #endif
28965
28966
28967
28968 /*
28969 ** Journal files begin with the following magic string.  The data
28970 ** was obtained from /dev/random.  It is used only as a sanity check.
28971 **
28972 ** Since version 2.8.0, the journal format contains additional sanity
28973 ** checking information.  If the power fails while the journal is begin
28974 ** written, semi-random garbage data might appear in the journal
28975 ** file after power is restored.  If an attempt is then made
28976 ** to roll the journal back, the database could be corrupted.  The additional
28977 ** sanity checking data is an attempt to discover the garbage in the
28978 ** journal and ignore it.
28979 **
28980 ** The sanity checking information for the new journal format consists
28981 ** of a 32-bit checksum on each page of data.  The checksum covers both
28982 ** the page number and the pPager->pageSize bytes of data for the page.
28983 ** This cksum is initialized to a 32-bit random value that appears in the
28984 ** journal file right after the header.  The random initializer is important,
28985 ** because garbage data that appears at the end of a journal is likely
28986 ** data that was once in other files that have now been deleted.  If the
28987 ** garbage data came from an obsolete journal file, the checksums might
28988 ** be correct.  But by initializing the checksum to random value which
28989 ** is different for every journal, we minimize that risk.
28990 */
28991 static const unsigned char aJournalMagic[] = {
28992   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
28993 };
28994
28995 /*
28996 ** The size of the header and of each page in the journal is determined
28997 ** by the following macros.
28998 */
28999 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
29000
29001 /*
29002 ** The journal header size for this pager. In the future, this could be
29003 ** set to some value read from the disk controller. The important
29004 ** characteristic is that it is the same size as a disk sector.
29005 */
29006 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
29007
29008 /*
29009 ** The macro MEMDB is true if we are dealing with an in-memory database.
29010 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
29011 ** the value of MEMDB will be a constant and the compiler will optimize
29012 ** out code that would never execute.
29013 */
29014 #ifdef SQLITE_OMIT_MEMORYDB
29015 # define MEMDB 0
29016 #else
29017 # define MEMDB pPager->memDb
29018 #endif
29019
29020 /*
29021 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
29022 ** reserved for working around a windows/posix incompatibility). It is
29023 ** used in the journal to signify that the remainder of the journal file 
29024 ** is devoted to storing a master journal name - there are no more pages to
29025 ** roll back. See comments for function writeMasterJournal() for details.
29026 */
29027 /* #define PAGER_MJ_PGNO(x) (PENDING_BYTE/((x)->pageSize)) */
29028 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
29029
29030 /*
29031 ** The maximum legal page number is (2^31 - 1).
29032 */
29033 #define PAGER_MAX_PGNO 2147483647
29034
29035 /*
29036 ** Return true if page *pPg has already been written to the statement
29037 ** journal (or statement snapshot has been created, if *pPg is part
29038 ** of an in-memory database).
29039 */
29040 static int pageInStatement(PgHdr *pPg){
29041   Pager *pPager = pPg->pPager;
29042   return sqlite3BitvecTest(pPager->pInStmt, pPg->pgno);
29043 }
29044
29045 static int pageInJournal(PgHdr *pPg){
29046   return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
29047 }
29048
29049 /*
29050 ** Read a 32-bit integer from the given file descriptor.  Store the integer
29051 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
29052 ** error code is something goes wrong.
29053 **
29054 ** All values are stored on disk as big-endian.
29055 */
29056 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
29057   unsigned char ac[4];
29058   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
29059   if( rc==SQLITE_OK ){
29060     *pRes = sqlite3Get4byte(ac);
29061   }
29062   return rc;
29063 }
29064
29065 /*
29066 ** Write a 32-bit integer into a string buffer in big-endian byte order.
29067 */
29068 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
29069
29070 /*
29071 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
29072 ** on success or an error code is something goes wrong.
29073 */
29074 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
29075   char ac[4];
29076   put32bits(ac, val);
29077   return sqlite3OsWrite(fd, ac, 4, offset);
29078 }
29079
29080 /*
29081 ** If file pFd is open, call sqlite3OsUnlock() on it.
29082 */
29083 static int osUnlock(sqlite3_file *pFd, int eLock){
29084   if( !pFd->pMethods ){
29085     return SQLITE_OK;
29086   }
29087   return sqlite3OsUnlock(pFd, eLock);
29088 }
29089
29090 /*
29091 ** This function determines whether or not the atomic-write optimization
29092 ** can be used with this pager. The optimization can be used if:
29093 **
29094 **  (a) the value returned by OsDeviceCharacteristics() indicates that
29095 **      a database page may be written atomically, and
29096 **  (b) the value returned by OsSectorSize() is less than or equal
29097 **      to the page size.
29098 **
29099 ** If the optimization cannot be used, 0 is returned. If it can be used,
29100 ** then the value returned is the size of the journal file when it
29101 ** contains rollback data for exactly one page.
29102 */
29103 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
29104 static int jrnlBufferSize(Pager *pPager){
29105   int dc;           /* Device characteristics */
29106   int nSector;      /* Sector size */
29107   int szPage;        /* Page size */
29108   sqlite3_file *fd = pPager->fd;
29109
29110   if( fd->pMethods ){
29111     dc = sqlite3OsDeviceCharacteristics(fd);
29112     nSector = sqlite3OsSectorSize(fd);
29113     szPage = pPager->pageSize;
29114   }
29115
29116   assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
29117   assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
29118
29119   if( !fd->pMethods || 
29120        (dc & (SQLITE_IOCAP_ATOMIC|(szPage>>8)) && nSector<=szPage) ){
29121     return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
29122   }
29123   return 0;
29124 }
29125 #endif
29126
29127 /*
29128 ** This function should be called when an error occurs within the pager
29129 ** code. The first argument is a pointer to the pager structure, the
29130 ** second the error-code about to be returned by a pager API function. 
29131 ** The value returned is a copy of the second argument to this function. 
29132 **
29133 ** If the second argument is SQLITE_IOERR, SQLITE_CORRUPT, or SQLITE_FULL
29134 ** the error becomes persistent. Until the persisten error is cleared,
29135 ** subsequent API calls on this Pager will immediately return the same 
29136 ** error code.
29137 **
29138 ** A persistent error indicates that the contents of the pager-cache 
29139 ** cannot be trusted. This state can be cleared by completely discarding 
29140 ** the contents of the pager-cache. If a transaction was active when
29141 ** the persistent error occured, then the rollback journal may need
29142 ** to be replayed.
29143 */
29144 static void pager_unlock(Pager *pPager);
29145 static int pager_error(Pager *pPager, int rc){
29146   int rc2 = rc & 0xff;
29147   assert(
29148        pPager->errCode==SQLITE_FULL ||
29149        pPager->errCode==SQLITE_OK ||
29150        (pPager->errCode & 0xff)==SQLITE_IOERR
29151   );
29152   if(
29153     rc2==SQLITE_FULL ||
29154     rc2==SQLITE_IOERR ||
29155     rc2==SQLITE_CORRUPT
29156   ){
29157     pPager->errCode = rc;
29158     if( pPager->state==PAGER_UNLOCK 
29159      && sqlite3PcacheRefCount(pPager->pPCache)==0 
29160     ){
29161       /* If the pager is already unlocked, call pager_unlock() now to
29162       ** clear the error state and ensure that the pager-cache is 
29163       ** completely empty.
29164       */
29165       pager_unlock(pPager);
29166     }
29167   }
29168   return rc;
29169 }
29170
29171 /*
29172 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
29173 ** on the cache using a hash function.  This is used for testing
29174 ** and debugging only.
29175 */
29176 #ifdef SQLITE_CHECK_PAGES
29177 /*
29178 ** Return a 32-bit hash of the page data for pPage.
29179 */
29180 static u32 pager_datahash(int nByte, unsigned char *pData){
29181   u32 hash = 0;
29182   int i;
29183   for(i=0; i<nByte; i++){
29184     hash = (hash*1039) + pData[i];
29185   }
29186   return hash;
29187 }
29188 static u32 pager_pagehash(PgHdr *pPage){
29189   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
29190 }
29191 static void pager_set_pagehash(PgHdr *pPage){
29192   pPage->pageHash = pager_pagehash(pPage);
29193 }
29194
29195 /*
29196 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
29197 ** is defined, and NDEBUG is not defined, an assert() statement checks
29198 ** that the page is either dirty or still matches the calculated page-hash.
29199 */
29200 #define CHECK_PAGE(x) checkPage(x)
29201 static void checkPage(PgHdr *pPg){
29202   Pager *pPager = pPg->pPager;
29203   assert( !pPg->pageHash || pPager->errCode
29204       || (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
29205 }
29206
29207 #else
29208 #define pager_datahash(X,Y)  0
29209 #define pager_pagehash(X)  0
29210 #define CHECK_PAGE(x)
29211 #endif  /* SQLITE_CHECK_PAGES */
29212
29213 /*
29214 ** When this is called the journal file for pager pPager must be open.
29215 ** The master journal file name is read from the end of the file and 
29216 ** written into memory supplied by the caller. 
29217 **
29218 ** zMaster must point to a buffer of at least nMaster bytes allocated by
29219 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
29220 ** enough space to write the master journal name). If the master journal
29221 ** name in the journal is longer than nMaster bytes (including a
29222 ** nul-terminator), then this is handled as if no master journal name
29223 ** were present in the journal.
29224 **
29225 ** If no master journal file name is present zMaster[0] is set to 0 and
29226 ** SQLITE_OK returned.
29227 */
29228 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
29229   int rc;
29230   u32 len;
29231   i64 szJ;
29232   u32 cksum;
29233   u32 u;                   /* Unsigned loop counter */
29234   unsigned char aMagic[8]; /* A buffer to hold the magic header */
29235
29236   zMaster[0] = '\0';
29237
29238   rc = sqlite3OsFileSize(pJrnl, &szJ);
29239   if( rc!=SQLITE_OK || szJ<16 ) return rc;
29240
29241   rc = read32bits(pJrnl, szJ-16, &len);
29242   if( rc!=SQLITE_OK ) return rc;
29243
29244   if( len>=nMaster ){
29245     return SQLITE_OK;
29246   }
29247
29248   rc = read32bits(pJrnl, szJ-12, &cksum);
29249   if( rc!=SQLITE_OK ) return rc;
29250
29251   rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8);
29252   if( rc!=SQLITE_OK || memcmp(aMagic, aJournalMagic, 8) ) return rc;
29253
29254   rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len);
29255   if( rc!=SQLITE_OK ){
29256     return rc;
29257   }
29258   zMaster[len] = '\0';
29259
29260   /* See if the checksum matches the master journal name */
29261   for(u=0; u<len; u++){
29262     cksum -= zMaster[u];
29263    }
29264   if( cksum ){
29265     /* If the checksum doesn't add up, then one or more of the disk sectors
29266     ** containing the master journal filename is corrupted. This means
29267     ** definitely roll back, so just return SQLITE_OK and report a (nul)
29268     ** master-journal filename.
29269     */
29270     zMaster[0] = '\0';
29271   }
29272    
29273   return SQLITE_OK;
29274 }
29275
29276 /*
29277 ** Seek the journal file descriptor to the next sector boundary where a
29278 ** journal header may be read or written. Pager.journalOff is updated with
29279 ** the new seek offset.
29280 **
29281 ** i.e for a sector size of 512:
29282 **
29283 ** Input Offset              Output Offset
29284 ** ---------------------------------------
29285 ** 0                         0
29286 ** 512                       512
29287 ** 100                       512
29288 ** 2000                      2048
29289 ** 
29290 */
29291 static void seekJournalHdr(Pager *pPager){
29292   i64 offset = 0;
29293   i64 c = pPager->journalOff;
29294   if( c ){
29295     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
29296   }
29297   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
29298   assert( offset>=c );
29299   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
29300   pPager->journalOff = offset;
29301 }
29302
29303 /*
29304 ** Write zeros over the header of the journal file.  This has the
29305 ** effect of invalidating the journal file and committing the
29306 ** transaction.
29307 */
29308 static int zeroJournalHdr(Pager *pPager, int doTruncate){
29309   int rc = SQLITE_OK;
29310   static const char zeroHdr[28] = {0};
29311
29312   if( pPager->journalOff ){
29313     i64 iLimit = pPager->journalSizeLimit;
29314
29315     IOTRACE(("JZEROHDR %p\n", pPager))
29316     if( doTruncate || iLimit==0 ){
29317       rc = sqlite3OsTruncate(pPager->jfd, 0);
29318     }else{
29319       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
29320     }
29321     if( rc==SQLITE_OK && !pPager->noSync ){
29322       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->sync_flags);
29323     }
29324
29325     /* At this point the transaction is committed but the write lock 
29326     ** is still held on the file. If there is a size limit configured for 
29327     ** the persistent journal and the journal file currently consumes more
29328     ** space than that limit allows for, truncate it now. There is no need
29329     ** to sync the file following this operation.
29330     */
29331     if( rc==SQLITE_OK && iLimit>0 ){
29332       i64 sz;
29333       rc = sqlite3OsFileSize(pPager->jfd, &sz);
29334       if( rc==SQLITE_OK && sz>iLimit ){
29335         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
29336       }
29337     }
29338   }
29339   return rc;
29340 }
29341
29342 /*
29343 ** The journal file must be open when this routine is called. A journal
29344 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
29345 ** current location.
29346 **
29347 ** The format for the journal header is as follows:
29348 ** - 8 bytes: Magic identifying journal format.
29349 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
29350 ** - 4 bytes: Random number used for page hash.
29351 ** - 4 bytes: Initial database page count.
29352 ** - 4 bytes: Sector size used by the process that wrote this journal.
29353 ** - 4 bytes: Database page size.
29354 ** 
29355 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
29356 */
29357 static int writeJournalHdr(Pager *pPager){
29358   int rc = SQLITE_OK;
29359   char *zHeader = pPager->pTmpSpace;
29360   u32 nHeader = pPager->pageSize;
29361   u32 nWrite;
29362
29363   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
29364     nHeader = JOURNAL_HDR_SZ(pPager);
29365   }
29366
29367   if( pPager->stmtHdrOff==0 ){
29368     pPager->stmtHdrOff = pPager->journalOff;
29369   }
29370
29371   seekJournalHdr(pPager);
29372   pPager->journalHdr = pPager->journalOff;
29373
29374   memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
29375
29376   /* 
29377   ** Write the nRec Field - the number of page records that follow this
29378   ** journal header. Normally, zero is written to this value at this time.
29379   ** After the records are added to the journal (and the journal synced, 
29380   ** if in full-sync mode), the zero is overwritten with the true number
29381   ** of records (see syncJournal()).
29382   **
29383   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
29384   ** reading the journal this value tells SQLite to assume that the
29385   ** rest of the journal file contains valid page records. This assumption
29386   ** is dangerous, as if a failure occured whilst writing to the journal
29387   ** file it may contain some garbage data. There are two scenarios
29388   ** where this risk can be ignored:
29389   **
29390   **   * When the pager is in no-sync mode. Corruption can follow a
29391   **     power failure in this case anyway.
29392   **
29393   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
29394   **     that garbage data is never appended to the journal file.
29395   */
29396   assert(pPager->fd->pMethods||pPager->noSync);
29397   if( (pPager->noSync) || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
29398    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
29399   ){
29400     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
29401   }else{
29402     put32bits(&zHeader[sizeof(aJournalMagic)], 0);
29403   }
29404
29405   /* The random check-hash initialiser */ 
29406   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
29407   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
29408   /* The initial database size */
29409   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbSize);
29410   /* The assumed sector size for this process */
29411   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
29412   if( pPager->journalHdr==0 ){
29413     /* The page size */
29414     put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
29415   }
29416
29417   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
29418     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
29419     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
29420     pPager->journalOff += nHeader;
29421   }
29422
29423   return rc;
29424 }
29425
29426 /*
29427 ** The journal file must be open when this is called. A journal header file
29428 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
29429 ** file. See comments above function writeJournalHdr() for a description of
29430 ** the journal header format.
29431 **
29432 ** If the header is read successfully, *nRec is set to the number of
29433 ** page records following this header and *dbSize is set to the size of the
29434 ** database before the transaction began, in pages. Also, pPager->cksumInit
29435 ** is set to the value read from the journal header. SQLITE_OK is returned
29436 ** in this case.
29437 **
29438 ** If the journal header file appears to be corrupted, SQLITE_DONE is
29439 ** returned and *nRec and *dbSize are not set.  If JOURNAL_HDR_SZ bytes
29440 ** cannot be read from the journal file an error code is returned.
29441 */
29442 static int readJournalHdr(
29443   Pager *pPager, 
29444   i64 journalSize,
29445   u32 *pNRec, 
29446   u32 *pDbSize
29447 ){
29448   int rc;
29449   unsigned char aMagic[8]; /* A buffer to hold the magic header */
29450   i64 jrnlOff;
29451   int iPageSize;
29452
29453   seekJournalHdr(pPager);
29454   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
29455     return SQLITE_DONE;
29456   }
29457   jrnlOff = pPager->journalOff;
29458
29459   rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), jrnlOff);
29460   if( rc ) return rc;
29461   jrnlOff += sizeof(aMagic);
29462
29463   if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
29464     return SQLITE_DONE;
29465   }
29466
29467   rc = read32bits(pPager->jfd, jrnlOff, pNRec);
29468   if( rc ) return rc;
29469
29470   rc = read32bits(pPager->jfd, jrnlOff+4, &pPager->cksumInit);
29471   if( rc ) return rc;
29472
29473   rc = read32bits(pPager->jfd, jrnlOff+8, pDbSize);
29474   if( rc ) return rc;
29475
29476   rc = read32bits(pPager->jfd, jrnlOff+16, (u32 *)&iPageSize);
29477   if( rc==SQLITE_OK 
29478    && iPageSize>=512 
29479    && iPageSize<=SQLITE_MAX_PAGE_SIZE 
29480    && ((iPageSize-1)&iPageSize)==0 
29481   ){
29482     u16 pagesize = iPageSize;
29483     rc = sqlite3PagerSetPagesize(pPager, &pagesize);
29484   }
29485   if( rc ) return rc;
29486
29487   /* Update the assumed sector-size to match the value used by 
29488   ** the process that created this journal. If this journal was
29489   ** created by a process other than this one, then this routine
29490   ** is being called from within pager_playback(). The local value
29491   ** of Pager.sectorSize is restored at the end of that routine.
29492   */
29493   rc = read32bits(pPager->jfd, jrnlOff+12, &pPager->sectorSize);
29494   if( rc ) return rc;
29495   if( (pPager->sectorSize & (pPager->sectorSize-1))!=0
29496          || pPager->sectorSize>0x1000000 ){
29497     return SQLITE_DONE;
29498   }
29499
29500   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
29501   return SQLITE_OK;
29502 }
29503
29504
29505 /*
29506 ** Write the supplied master journal name into the journal file for pager
29507 ** pPager at the current location. The master journal name must be the last
29508 ** thing written to a journal file. If the pager is in full-sync mode, the
29509 ** journal file descriptor is advanced to the next sector boundary before
29510 ** anything is written. The format is:
29511 **
29512 ** + 4 bytes: PAGER_MJ_PGNO.
29513 ** + N bytes: length of master journal name.
29514 ** + 4 bytes: N
29515 ** + 4 bytes: Master journal name checksum.
29516 ** + 8 bytes: aJournalMagic[].
29517 **
29518 ** The master journal page checksum is the sum of the bytes in the master
29519 ** journal name.
29520 **
29521 ** If zMaster is a NULL pointer (occurs for a single database transaction), 
29522 ** this call is a no-op.
29523 */
29524 static int writeMasterJournal(Pager *pPager, const char *zMaster){
29525   int rc;
29526   int len; 
29527   int i; 
29528   i64 jrnlOff;
29529   i64 jrnlSize;
29530   u32 cksum = 0;
29531   char zBuf[sizeof(aJournalMagic)+2*4];
29532
29533   if( !zMaster || pPager->setMaster ) return SQLITE_OK;
29534   if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ) return SQLITE_OK;
29535   pPager->setMaster = 1;
29536
29537   len = strlen(zMaster);
29538   for(i=0; i<len; i++){
29539     cksum += zMaster[i];
29540   }
29541
29542   /* If in full-sync mode, advance to the next disk sector before writing
29543   ** the master journal name. This is in case the previous page written to
29544   ** the journal has already been synced.
29545   */
29546   if( pPager->fullSync ){
29547     seekJournalHdr(pPager);
29548   }
29549   jrnlOff = pPager->journalOff;
29550   pPager->journalOff += (len+20);
29551
29552   rc = write32bits(pPager->jfd, jrnlOff, PAGER_MJ_PGNO(pPager));
29553   if( rc!=SQLITE_OK ) return rc;
29554   jrnlOff += 4;
29555
29556   rc = sqlite3OsWrite(pPager->jfd, zMaster, len, jrnlOff);
29557   if( rc!=SQLITE_OK ) return rc;
29558   jrnlOff += len;
29559
29560   put32bits(zBuf, len);
29561   put32bits(&zBuf[4], cksum);
29562   memcpy(&zBuf[8], aJournalMagic, sizeof(aJournalMagic));
29563   rc = sqlite3OsWrite(pPager->jfd, zBuf, 8+sizeof(aJournalMagic), jrnlOff);
29564   jrnlOff += 8+sizeof(aJournalMagic);
29565   pPager->needSync = !pPager->noSync;
29566
29567   /* If the pager is in peristent-journal mode, then the physical 
29568   ** journal-file may extend past the end of the master-journal name
29569   ** and 8 bytes of magic data just written to the file. This is 
29570   ** dangerous because the code to rollback a hot-journal file
29571   ** will not be able to find the master-journal name to determine 
29572   ** whether or not the journal is hot. 
29573   **
29574   ** Easiest thing to do in this scenario is to truncate the journal 
29575   ** file to the required size.
29576   */ 
29577   if( (rc==SQLITE_OK)
29578    && (rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))==SQLITE_OK
29579    && jrnlSize>jrnlOff
29580   ){
29581     rc = sqlite3OsTruncate(pPager->jfd, jrnlOff);
29582   }
29583   return rc;
29584 }
29585
29586 /*
29587 ** Find a page in the hash table given its page number.  Return
29588 ** a pointer to the page or NULL if not found.
29589 */
29590 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
29591   PgHdr *p;
29592   sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
29593   return p;
29594 }
29595
29596 /*
29597 ** Clear the in-memory cache.  This routine
29598 ** sets the state of the pager back to what it was when it was first
29599 ** opened.  Any outstanding pages are invalidated and subsequent attempts
29600 ** to access those pages will likely result in a coredump.
29601 */
29602 static void pager_reset(Pager *pPager){
29603   if( pPager->errCode ) return;
29604   sqlite3PcacheClear(pPager->pPCache);
29605 }
29606
29607 /*
29608 ** Unlock the database file. 
29609 **
29610 ** If the pager is currently in error state, discard the contents of 
29611 ** the cache and reset the Pager structure internal state. If there is
29612 ** an open journal-file, then the next time a shared-lock is obtained
29613 ** on the pager file (by this or any other process), it will be
29614 ** treated as a hot-journal and rolled back.
29615 */
29616 static void pager_unlock(Pager *pPager){
29617   if( !pPager->exclusiveMode ){
29618     int rc = osUnlock(pPager->fd, NO_LOCK);
29619     if( rc ) pPager->errCode = rc;
29620     pPager->dbSizeValid = 0;
29621     IOTRACE(("UNLOCK %p\n", pPager))
29622
29623     /* Always close the journal file when dropping the database lock.
29624     ** Otherwise, another connection with journal_mode=delete might
29625     ** delete the file out from under us.
29626     */
29627     if( pPager->journalOpen ){
29628       sqlite3OsClose(pPager->jfd);
29629       pPager->journalOpen = 0;
29630       sqlite3BitvecDestroy(pPager->pInJournal);
29631       pPager->pInJournal = 0;
29632       sqlite3BitvecDestroy(pPager->pAlwaysRollback);
29633       pPager->pAlwaysRollback = 0;
29634     }
29635
29636     /* If Pager.errCode is set, the contents of the pager cache cannot be
29637     ** trusted. Now that the pager file is unlocked, the contents of the
29638     ** cache can be discarded and the error code safely cleared.
29639     */
29640     if( pPager->errCode ){
29641       if( rc==SQLITE_OK ) pPager->errCode = SQLITE_OK;
29642       pager_reset(pPager);
29643       if( pPager->stmtOpen ){
29644         sqlite3OsClose(pPager->stfd);
29645         sqlite3BitvecDestroy(pPager->pInStmt);
29646         pPager->pInStmt = 0;
29647       }
29648       pPager->stmtOpen = 0;
29649       pPager->stmtInUse = 0;
29650       pPager->journalOff = 0;
29651       pPager->journalStarted = 0;
29652       pPager->stmtAutoopen = 0;
29653       pPager->origDbSize = 0;
29654     }
29655
29656     pPager->state = PAGER_UNLOCK;
29657     pPager->changeCountDone = 0;
29658   }
29659 }
29660
29661 /*
29662 ** Execute a rollback if a transaction is active and unlock the 
29663 ** database file. If the pager has already entered the error state, 
29664 ** do not attempt the rollback.
29665 */
29666 static void pagerUnlockAndRollback(Pager *p){
29667   if( p->errCode==SQLITE_OK && p->state>=PAGER_RESERVED ){
29668     sqlite3BeginBenignMalloc();
29669     sqlite3PagerRollback(p);
29670     sqlite3EndBenignMalloc();
29671   }
29672   pager_unlock(p);
29673 }
29674
29675 /*
29676 ** This routine ends a transaction.  A transaction is ended by either
29677 ** a COMMIT or a ROLLBACK.
29678 **
29679 ** When this routine is called, the pager has the journal file open and
29680 ** a RESERVED or EXCLUSIVE lock on the database.  This routine will release
29681 ** the database lock and acquires a SHARED lock in its place if that is
29682 ** the appropriate thing to do.  Release locks usually is appropriate,
29683 ** unless we are in exclusive access mode or unless this is a 
29684 ** COMMIT AND BEGIN or ROLLBACK AND BEGIN operation.
29685 **
29686 ** The journal file is either deleted or truncated.
29687 **
29688 ** TODO: Consider keeping the journal file open for temporary databases.
29689 ** This might give a performance improvement on windows where opening
29690 ** a file is an expensive operation.
29691 */
29692 static int pager_end_transaction(Pager *pPager, int hasMaster){
29693   int rc = SQLITE_OK;
29694   int rc2 = SQLITE_OK;
29695   if( pPager->state<PAGER_RESERVED ){
29696     return SQLITE_OK;
29697   }
29698   sqlite3PagerStmtCommit(pPager);
29699   if( pPager->stmtOpen && !pPager->exclusiveMode ){
29700     sqlite3OsClose(pPager->stfd);
29701     pPager->stmtOpen = 0;
29702   }
29703   if( pPager->journalOpen ){
29704     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
29705       int isMemoryJournal = sqlite3IsMemJournal(pPager->jfd);
29706       sqlite3OsClose(pPager->jfd);
29707       pPager->journalOpen = 0;
29708       if( !isMemoryJournal ){
29709         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
29710       }
29711     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE
29712          && (rc = sqlite3OsTruncate(pPager->jfd, 0))==SQLITE_OK ){
29713       pPager->journalOff = 0;
29714       pPager->journalStarted = 0;
29715     }else if( pPager->exclusiveMode 
29716      || pPager->journalMode==PAGER_JOURNALMODE_PERSIST
29717     ){
29718       rc = zeroJournalHdr(pPager, hasMaster);
29719       pager_error(pPager, rc);
29720       pPager->journalOff = 0;
29721       pPager->journalStarted = 0;
29722     }else{
29723       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE || rc );
29724       sqlite3OsClose(pPager->jfd);
29725       pPager->journalOpen = 0;
29726       if( rc==SQLITE_OK && !pPager->tempFile ){
29727         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
29728       }
29729     }
29730     sqlite3BitvecDestroy(pPager->pInJournal);
29731     pPager->pInJournal = 0;
29732     sqlite3BitvecDestroy(pPager->pAlwaysRollback);
29733     pPager->pAlwaysRollback = 0;
29734 #ifdef SQLITE_CHECK_PAGES
29735     sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
29736 #endif
29737     sqlite3PcacheCleanAll(pPager->pPCache);
29738     pPager->dirtyCache = 0;
29739     pPager->nRec = 0;
29740   }else{
29741     assert( pPager->pInJournal==0 );
29742   }
29743
29744   if( !pPager->exclusiveMode ){
29745     rc2 = osUnlock(pPager->fd, SHARED_LOCK);
29746     pPager->state = PAGER_SHARED;
29747   }else if( pPager->state==PAGER_SYNCED ){
29748     pPager->state = PAGER_EXCLUSIVE;
29749   }
29750   pPager->origDbSize = 0;
29751   pPager->setMaster = 0;
29752   pPager->needSync = 0;
29753   /* lruListSetFirstSynced(pPager); */
29754   if( !MEMDB ){
29755     pPager->dbSizeValid = 0;
29756   }
29757   pPager->dbModified = 0;
29758
29759   return (rc==SQLITE_OK?rc2:rc);
29760 }
29761
29762 /*
29763 ** Compute and return a checksum for the page of data.
29764 **
29765 ** This is not a real checksum.  It is really just the sum of the 
29766 ** random initial value and the page number.  We experimented with
29767 ** a checksum of the entire data, but that was found to be too slow.
29768 **
29769 ** Note that the page number is stored at the beginning of data and
29770 ** the checksum is stored at the end.  This is important.  If journal
29771 ** corruption occurs due to a power failure, the most likely scenario
29772 ** is that one end or the other of the record will be changed.  It is
29773 ** much less likely that the two ends of the journal record will be
29774 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
29775 ** though fast and simple, catches the mostly likely kind of corruption.
29776 **
29777 ** FIX ME:  Consider adding every 200th (or so) byte of the data to the
29778 ** checksum.  That way if a single page spans 3 or more disk sectors and
29779 ** only the middle sector is corrupt, we will still have a reasonable
29780 ** chance of failing the checksum and thus detecting the problem.
29781 */
29782 static u32 pager_cksum(Pager *pPager, const u8 *aData){
29783   u32 cksum = pPager->cksumInit;
29784   int i = pPager->pageSize-200;
29785   while( i>0 ){
29786     cksum += aData[i];
29787     i -= 200;
29788   }
29789   return cksum;
29790 }
29791
29792 /*
29793 ** Read a single page from the journal file opened on file descriptor
29794 ** jfd.  Playback this one page.
29795 **
29796 ** The isMainJrnl flag is true if this is the main rollback journal and
29797 ** false for the statement journal.  The main rollback journal uses
29798 ** checksums - the statement journal does not.
29799 */
29800 static int pager_playback_one_page(
29801   Pager *pPager,       /* The pager being played back */
29802   sqlite3_file *jfd,   /* The file that is the journal being rolled back */
29803   i64 offset,          /* Offset of the page within the journal */
29804   int isMainJrnl       /* True for main rollback journal. False for Stmt jrnl */
29805 ){
29806   int rc;
29807   PgHdr *pPg;                   /* An existing page in the cache */
29808   Pgno pgno;                    /* The page number of a page in journal */
29809   u32 cksum;                    /* Checksum used for sanity checking */
29810   u8 *aData = (u8 *)pPager->pTmpSpace;   /* Temp storage for a page */
29811
29812   /* isMainJrnl should be true for the main journal and false for
29813   ** statement journals.  Verify that this is always the case
29814   */
29815   assert( jfd == (isMainJrnl ? pPager->jfd : pPager->stfd) );
29816   assert( aData );
29817
29818   rc = read32bits(jfd, offset, &pgno);
29819   if( rc!=SQLITE_OK ) return rc;
29820   rc = sqlite3OsRead(jfd, aData, pPager->pageSize, offset+4);
29821   if( rc!=SQLITE_OK ) return rc;
29822   pPager->journalOff += pPager->pageSize + 4;
29823
29824   /* Sanity checking on the page.  This is more important that I originally
29825   ** thought.  If a power failure occurs while the journal is being written,
29826   ** it could cause invalid data to be written into the journal.  We need to
29827   ** detect this invalid data (with high probability) and ignore it.
29828   */
29829   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
29830     return SQLITE_DONE;
29831   }
29832   if( pgno>(unsigned)pPager->dbSize ){
29833     return SQLITE_OK;
29834   }
29835   if( isMainJrnl ){
29836     rc = read32bits(jfd, offset+pPager->pageSize+4, &cksum);
29837     if( rc ) return rc;
29838     pPager->journalOff += 4;
29839     if( pager_cksum(pPager, aData)!=cksum ){
29840       return SQLITE_DONE;
29841     }
29842   }
29843
29844   assert( pPager->state==PAGER_RESERVED || pPager->state>=PAGER_EXCLUSIVE );
29845
29846   /* If the pager is in RESERVED state, then there must be a copy of this
29847   ** page in the pager cache. In this case just update the pager cache,
29848   ** not the database file. The page is left marked dirty in this case.
29849   **
29850   ** An exception to the above rule: If the database is in no-sync mode
29851   ** and a page is moved during an incremental vacuum then the page may
29852   ** not be in the pager cache. Later: if a malloc() or IO error occurs
29853   ** during a Movepage() call, then the page may not be in the cache
29854   ** either. So the condition described in the above paragraph is not
29855   ** assert()able.
29856   **
29857   ** If in EXCLUSIVE state, then we update the pager cache if it exists
29858   ** and the main file. The page is then marked not dirty.
29859   **
29860   ** Ticket #1171:  The statement journal might contain page content that is
29861   ** different from the page content at the start of the transaction.
29862   ** This occurs when a page is changed prior to the start of a statement
29863   ** then changed again within the statement.  When rolling back such a
29864   ** statement we must not write to the original database unless we know
29865   ** for certain that original page contents are synced into the main rollback
29866   ** journal.  Otherwise, a power loss might leave modified data in the
29867   ** database file without an entry in the rollback journal that can
29868   ** restore the database to its original form.  Two conditions must be
29869   ** met before writing to the database files. (1) the database must be
29870   ** locked.  (2) we know that the original page content is fully synced
29871   ** in the main journal either because the page is not in cache or else
29872   ** the page is marked as needSync==0.
29873   **
29874   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
29875   ** is possible to fail a statement on a database that does not yet exist.
29876   ** Do not attempt to write if database file has never been opened.
29877   */
29878   pPg = pager_lookup(pPager, pgno);
29879   PAGERTRACE4("PLAYBACK %d page %d hash(%08x)\n",
29880                PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, aData));
29881   if( (pPager->state>=PAGER_EXCLUSIVE)
29882    && (pPg==0 || 0==(pPg->flags&PGHDR_NEED_SYNC))
29883    && (pPager->fd->pMethods)
29884   ){
29885     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
29886     rc = sqlite3OsWrite(pPager->fd, aData, pPager->pageSize, ofst);
29887   }
29888   if( pPg ){
29889     /* No page should ever be explicitly rolled back that is in use, except
29890     ** for page 1 which is held in use in order to keep the lock on the
29891     ** database active. However such a page may be rolled back as a result
29892     ** of an internal error resulting in an automatic call to
29893     ** sqlite3PagerRollback().
29894     */
29895     void *pData;
29896     pData = pPg->pData;
29897     memcpy(pData, aData, pPager->pageSize);
29898     if( pPager->xReiniter ){
29899       pPager->xReiniter(pPg);
29900     }
29901     if( isMainJrnl ){
29902       sqlite3PcacheMakeClean(pPg);
29903     }
29904 #ifdef SQLITE_CHECK_PAGES
29905     pPg->pageHash = pager_pagehash(pPg);
29906 #endif
29907     /* If this was page 1, then restore the value of Pager.dbFileVers.
29908     ** Do this before any decoding. */
29909     if( pgno==1 ){
29910       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
29911     }
29912
29913     /* Decode the page just read from disk */
29914     CODEC1(pPager, pData, pPg->pgno, 3);
29915     sqlite3PcacheRelease(pPg);
29916   }
29917   return rc;
29918 }
29919
29920 /*
29921 ** Parameter zMaster is the name of a master journal file. A single journal
29922 ** file that referred to the master journal file has just been rolled back.
29923 ** This routine checks if it is possible to delete the master journal file,
29924 ** and does so if it is.
29925 **
29926 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
29927 ** available for use within this function.
29928 **
29929 **
29930 ** The master journal file contains the names of all child journals.
29931 ** To tell if a master journal can be deleted, check to each of the
29932 ** children.  If all children are either missing or do not refer to
29933 ** a different master journal, then this master journal can be deleted.
29934 */
29935 static int pager_delmaster(Pager *pPager, const char *zMaster){
29936   sqlite3_vfs *pVfs = pPager->pVfs;
29937   int rc;
29938   int master_open = 0;
29939   sqlite3_file *pMaster;
29940   sqlite3_file *pJournal;
29941   char *zMasterJournal = 0; /* Contents of master journal file */
29942   i64 nMasterJournal;       /* Size of master journal file */
29943
29944   /* Open the master journal file exclusively in case some other process
29945   ** is running this routine also. Not that it makes too much difference.
29946   */
29947   pMaster = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile * 2);
29948   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
29949   if( !pMaster ){
29950     rc = SQLITE_NOMEM;
29951   }else{
29952     int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
29953     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
29954   }
29955   if( rc!=SQLITE_OK ) goto delmaster_out;
29956   master_open = 1;
29957
29958   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
29959   if( rc!=SQLITE_OK ) goto delmaster_out;
29960
29961   if( nMasterJournal>0 ){
29962     char *zJournal;
29963     char *zMasterPtr = 0;
29964     int nMasterPtr = pPager->pVfs->mxPathname+1;
29965
29966     /* Load the entire master journal file into space obtained from
29967     ** sqlite3_malloc() and pointed to by zMasterJournal. 
29968     */
29969     zMasterJournal = (char *)sqlite3Malloc(nMasterJournal + nMasterPtr);
29970     if( !zMasterJournal ){
29971       rc = SQLITE_NOMEM;
29972       goto delmaster_out;
29973     }
29974     zMasterPtr = &zMasterJournal[nMasterJournal];
29975     rc = sqlite3OsRead(pMaster, zMasterJournal, nMasterJournal, 0);
29976     if( rc!=SQLITE_OK ) goto delmaster_out;
29977
29978     zJournal = zMasterJournal;
29979     while( (zJournal-zMasterJournal)<nMasterJournal ){
29980       int exists;
29981       rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
29982       if( rc!=SQLITE_OK ){
29983         goto delmaster_out;
29984       }
29985       if( exists ){
29986         /* One of the journals pointed to by the master journal exists.
29987         ** Open it and check if it points at the master journal. If
29988         ** so, return without deleting the master journal file.
29989         */
29990         int c;
29991         int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
29992         rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
29993         if( rc!=SQLITE_OK ){
29994           goto delmaster_out;
29995         }
29996
29997         rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
29998         sqlite3OsClose(pJournal);
29999         if( rc!=SQLITE_OK ){
30000           goto delmaster_out;
30001         }
30002
30003         c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
30004         if( c ){
30005           /* We have a match. Do not delete the master journal file. */
30006           goto delmaster_out;
30007         }
30008       }
30009       zJournal += (strlen(zJournal)+1);
30010     }
30011   }
30012   
30013   rc = sqlite3OsDelete(pVfs, zMaster, 0);
30014
30015 delmaster_out:
30016   if( zMasterJournal ){
30017     sqlite3_free(zMasterJournal);
30018   }  
30019   if( master_open ){
30020     sqlite3OsClose(pMaster);
30021   }
30022   sqlite3_free(pMaster);
30023   return rc;
30024 }
30025
30026
30027 static void pager_truncate_cache(Pager *pPager);
30028
30029 /*
30030 ** Truncate the main file of the given pager to the number of pages
30031 ** indicated. Also truncate the cached representation of the file.
30032 **
30033 ** Might might be the case that the file on disk is smaller than nPage.
30034 ** This can happen, for example, if we are in the middle of a transaction
30035 ** which has extended the file size and the new pages are still all held
30036 ** in cache, then an INSERT or UPDATE does a statement rollback.  Some
30037 ** operating system implementations can get confused if you try to
30038 ** truncate a file to some size that is larger than it currently is,
30039 ** so detect this case and write a single zero byte to the end of the new
30040 ** file instead.
30041 */
30042 static int pager_truncate(Pager *pPager, Pgno nPage){
30043   int rc = SQLITE_OK;
30044   if( pPager->state>=PAGER_EXCLUSIVE && pPager->fd->pMethods ){
30045     i64 currentSize, newSize;
30046     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
30047     newSize = pPager->pageSize*(i64)nPage;
30048     if( rc==SQLITE_OK && currentSize!=newSize ){
30049       if( currentSize>newSize ){
30050         rc = sqlite3OsTruncate(pPager->fd, newSize);
30051       }else{
30052         rc = sqlite3OsWrite(pPager->fd, "", 1, newSize-1);
30053       }
30054     }
30055   }
30056   if( rc==SQLITE_OK ){
30057     pPager->dbSize = nPage;
30058     pager_truncate_cache(pPager);
30059   }
30060   return rc;
30061 }
30062
30063 /*
30064 ** Set the sectorSize for the given pager.
30065 **
30066 ** The sector size is at least as big as the sector size reported
30067 ** by sqlite3OsSectorSize().  The minimum sector size is 512.
30068 */
30069 static void setSectorSize(Pager *pPager){
30070   assert(pPager->fd->pMethods||pPager->tempFile);
30071   if( !pPager->tempFile ){
30072     /* Sector size doesn't matter for temporary files. Also, the file
30073     ** may not have been opened yet, in whcih case the OsSectorSize()
30074     ** call will segfault.
30075     */
30076     pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
30077   }
30078   if( pPager->sectorSize<512 ){
30079     pPager->sectorSize = 512;
30080   }
30081 }
30082
30083 /*
30084 ** Playback the journal and thus restore the database file to
30085 ** the state it was in before we started making changes.  
30086 **
30087 ** The journal file format is as follows: 
30088 **
30089 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
30090 **  (2)  4 byte big-endian integer which is the number of valid page records
30091 **       in the journal.  If this value is 0xffffffff, then compute the
30092 **       number of page records from the journal size.
30093 **  (3)  4 byte big-endian integer which is the initial value for the 
30094 **       sanity checksum.
30095 **  (4)  4 byte integer which is the number of pages to truncate the
30096 **       database to during a rollback.
30097 **  (5)  4 byte big-endian integer which is the sector size.  The header
30098 **       is this many bytes in size.
30099 **  (6)  4 byte big-endian integer which is the page case.
30100 **  (7)  4 byte integer which is the number of bytes in the master journal
30101 **       name.  The value may be zero (indicate that there is no master
30102 **       journal.)
30103 **  (8)  N bytes of the master journal name.  The name will be nul-terminated
30104 **       and might be shorter than the value read from (5).  If the first byte
30105 **       of the name is \000 then there is no master journal.  The master
30106 **       journal name is stored in UTF-8.
30107 **  (9)  Zero or more pages instances, each as follows:
30108 **        +  4 byte page number.
30109 **        +  pPager->pageSize bytes of data.
30110 **        +  4 byte checksum
30111 **
30112 ** When we speak of the journal header, we mean the first 8 items above.
30113 ** Each entry in the journal is an instance of the 9th item.
30114 **
30115 ** Call the value from the second bullet "nRec".  nRec is the number of
30116 ** valid page entries in the journal.  In most cases, you can compute the
30117 ** value of nRec from the size of the journal file.  But if a power
30118 ** failure occurred while the journal was being written, it could be the
30119 ** case that the size of the journal file had already been increased but
30120 ** the extra entries had not yet made it safely to disk.  In such a case,
30121 ** the value of nRec computed from the file size would be too large.  For
30122 ** that reason, we always use the nRec value in the header.
30123 **
30124 ** If the nRec value is 0xffffffff it means that nRec should be computed
30125 ** from the file size.  This value is used when the user selects the
30126 ** no-sync option for the journal.  A power failure could lead to corruption
30127 ** in this case.  But for things like temporary table (which will be
30128 ** deleted when the power is restored) we don't care.  
30129 **
30130 ** If the file opened as the journal file is not a well-formed
30131 ** journal file then all pages up to the first corrupted page are rolled
30132 ** back (or no pages if the journal header is corrupted). The journal file
30133 ** is then deleted and SQLITE_OK returned, just as if no corruption had
30134 ** been encountered.
30135 **
30136 ** If an I/O or malloc() error occurs, the journal-file is not deleted
30137 ** and an error code is returned.
30138 */
30139 static int pager_playback(Pager *pPager, int isHot){
30140   sqlite3_vfs *pVfs = pPager->pVfs;
30141   i64 szJ;                 /* Size of the journal file in bytes */
30142   u32 nRec;                /* Number of Records in the journal */
30143   u32 u;                   /* Unsigned loop counter */
30144   Pgno mxPg = 0;           /* Size of the original file in pages */
30145   int rc;                  /* Result code of a subroutine */
30146   int res = 1;             /* Value returned by sqlite3OsAccess() */
30147   char *zMaster = 0;       /* Name of master journal file if any */
30148
30149   /* Figure out how many records are in the journal.  Abort early if
30150   ** the journal is empty.
30151   */
30152   assert( pPager->journalOpen );
30153   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
30154   if( rc!=SQLITE_OK || szJ==0 ){
30155     goto end_playback;
30156   }
30157
30158   /* Read the master journal name from the journal, if it is present.
30159   ** If a master journal file name is specified, but the file is not
30160   ** present on disk, then the journal is not hot and does not need to be
30161   ** played back.
30162   */
30163   zMaster = pPager->pTmpSpace;
30164   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
30165   if( rc==SQLITE_OK && zMaster[0] ){
30166     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
30167   }
30168   zMaster = 0;
30169   if( rc!=SQLITE_OK || !res ){
30170     goto end_playback;
30171   }
30172   pPager->journalOff = 0;
30173
30174   /* This loop terminates either when the readJournalHdr() call returns
30175   ** SQLITE_DONE or an IO error occurs. */
30176   while( 1 ){
30177
30178     /* Read the next journal header from the journal file.  If there are
30179     ** not enough bytes left in the journal file for a complete header, or
30180     ** it is corrupted, then a process must of failed while writing it.
30181     ** This indicates nothing more needs to be rolled back.
30182     */
30183     rc = readJournalHdr(pPager, szJ, &nRec, &mxPg);
30184     if( rc!=SQLITE_OK ){ 
30185       if( rc==SQLITE_DONE ){
30186         rc = SQLITE_OK;
30187       }
30188       goto end_playback;
30189     }
30190
30191     /* If nRec is 0xffffffff, then this journal was created by a process
30192     ** working in no-sync mode. This means that the rest of the journal
30193     ** file consists of pages, there are no more journal headers. Compute
30194     ** the value of nRec based on this assumption.
30195     */
30196     if( nRec==0xffffffff ){
30197       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
30198       nRec = (szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager);
30199     }
30200
30201     /* If nRec is 0 and this rollback is of a transaction created by this
30202     ** process and if this is the final header in the journal, then it means
30203     ** that this part of the journal was being filled but has not yet been
30204     ** synced to disk.  Compute the number of pages based on the remaining
30205     ** size of the file.
30206     **
30207     ** The third term of the test was added to fix ticket #2565.
30208     */
30209     if( nRec==0 && !isHot &&
30210         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
30211       nRec = (szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager);
30212     }
30213
30214     /* If this is the first header read from the journal, truncate the
30215     ** database file back to its original size.
30216     */
30217     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
30218       rc = pager_truncate(pPager, mxPg);
30219       if( rc!=SQLITE_OK ){
30220         goto end_playback;
30221       }
30222     }
30223
30224     /* Copy original pages out of the journal and back into the database file.
30225     */
30226     for(u=0; u<nRec; u++){
30227       rc = pager_playback_one_page(pPager, pPager->jfd, pPager->journalOff, 1);
30228       if( rc!=SQLITE_OK ){
30229         if( rc==SQLITE_DONE ){
30230           rc = SQLITE_OK;
30231           pPager->journalOff = szJ;
30232           break;
30233         }else{
30234           /* If we are unable to rollback, then the database is probably
30235           ** going to end up being corrupt.  It is corrupt to us, anyhow.
30236           ** Perhaps the next process to come along can fix it....
30237           */
30238           rc = SQLITE_CORRUPT_BKPT;
30239           goto end_playback;
30240         }
30241       }
30242     }
30243   }
30244   /*NOTREACHED*/
30245   assert( 0 );
30246
30247 end_playback:
30248   if( rc==SQLITE_OK ){
30249     zMaster = pPager->pTmpSpace;
30250     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
30251   }
30252   if( rc==SQLITE_OK ){
30253     rc = pager_end_transaction(pPager, zMaster[0]!='\0');
30254   }
30255   if( rc==SQLITE_OK && zMaster[0] && res ){
30256     /* If there was a master journal and this routine will return success,
30257     ** see if it is possible to delete the master journal.
30258     */
30259     rc = pager_delmaster(pPager, zMaster);
30260   }
30261
30262   /* The Pager.sectorSize variable may have been updated while rolling
30263   ** back a journal created by a process with a different sector size
30264   ** value. Reset it to the correct value for this process.
30265   */
30266   setSectorSize(pPager);
30267   return rc;
30268 }
30269
30270 /*
30271 ** Playback the statement journal.
30272 **
30273 ** This is similar to playing back the transaction journal but with
30274 ** a few extra twists.
30275 **
30276 **    (1)  The number of pages in the database file at the start of
30277 **         the statement is stored in pPager->stmtSize, not in the
30278 **         journal file itself.
30279 **
30280 **    (2)  In addition to playing back the statement journal, also
30281 **         playback all pages of the transaction journal beginning
30282 **         at offset pPager->stmtJSize.
30283 */
30284 static int pager_stmt_playback(Pager *pPager){
30285   i64 szJ;                 /* Size of the full journal */
30286   i64 hdrOff;
30287   int nRec;                /* Number of Records */
30288   int i;                   /* Loop counter */
30289   int rc;
30290
30291   szJ = pPager->journalOff;
30292
30293   /* Set hdrOff to be the offset just after the end of the last journal
30294   ** page written before the first journal-header for this statement
30295   ** transaction was written, or the end of the file if no journal
30296   ** header was written.
30297   */
30298   hdrOff = pPager->stmtHdrOff;
30299   assert( pPager->fullSync || !hdrOff );
30300   if( !hdrOff ){
30301     hdrOff = szJ;
30302   }
30303   
30304   /* Truncate the database back to its original size.
30305   */
30306   rc = pager_truncate(pPager, pPager->stmtSize);
30307   assert( pPager->state>=PAGER_SHARED );
30308
30309   /* Figure out how many records are in the statement journal.
30310   */
30311   assert( pPager->stmtInUse && pPager->journalOpen );
30312   nRec = pPager->stmtNRec;
30313   
30314   /* Copy original pages out of the statement journal and back into the
30315   ** database file.  Note that the statement journal omits checksums from
30316   ** each record since power-failure recovery is not important to statement
30317   ** journals.
30318   */
30319   for(i=0; i<nRec; i++){
30320     i64 offset = i*(4+pPager->pageSize);
30321     rc = pager_playback_one_page(pPager, pPager->stfd, offset, 0);
30322     assert( rc!=SQLITE_DONE );
30323     if( rc!=SQLITE_OK ) goto end_stmt_playback;
30324   }
30325
30326   /* Now roll some pages back from the transaction journal. Pager.stmtJSize
30327   ** was the size of the journal file when this statement was started, so
30328   ** everything after that needs to be rolled back, either into the
30329   ** database, the memory cache, or both.
30330   **
30331   ** If it is not zero, then Pager.stmtHdrOff is the offset to the start
30332   ** of the first journal header written during this statement transaction.
30333   */
30334   pPager->journalOff = pPager->stmtJSize;
30335   pPager->cksumInit = pPager->stmtCksum;
30336   while( pPager->journalOff < hdrOff ){
30337     rc = pager_playback_one_page(pPager, pPager->jfd, pPager->journalOff, 1);
30338     assert( rc!=SQLITE_DONE );
30339     if( rc!=SQLITE_OK ) goto end_stmt_playback;
30340   }
30341
30342   while( pPager->journalOff < szJ ){
30343     u32 nJRec;         /* Number of Journal Records */
30344     u32 dummy;
30345     rc = readJournalHdr(pPager, szJ, &nJRec, &dummy);
30346     if( rc!=SQLITE_OK ){
30347       assert( rc!=SQLITE_DONE );
30348       goto end_stmt_playback;
30349     }
30350     if( nJRec==0 ){
30351       nJRec = (szJ - pPager->journalOff) / (pPager->pageSize+8);
30352     }
30353     for(i=nJRec-1; i>=0 && pPager->journalOff < szJ; i--){
30354       rc = pager_playback_one_page(pPager, pPager->jfd, pPager->journalOff, 1);
30355       assert( rc!=SQLITE_DONE );
30356       if( rc!=SQLITE_OK ) goto end_stmt_playback;
30357     }
30358   }
30359
30360   pPager->journalOff = szJ;
30361   
30362 end_stmt_playback:
30363   if( rc==SQLITE_OK) {
30364     pPager->journalOff = szJ;
30365     /* pager_reload_cache(pPager); */
30366   }
30367   return rc;
30368 }
30369
30370 /*
30371 ** Change the maximum number of in-memory pages that are allowed.
30372 */
30373 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
30374   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
30375 }
30376
30377 /*
30378 ** Adjust the robustness of the database to damage due to OS crashes
30379 ** or power failures by changing the number of syncs()s when writing
30380 ** the rollback journal.  There are three levels:
30381 **
30382 **    OFF       sqlite3OsSync() is never called.  This is the default
30383 **              for temporary and transient files.
30384 **
30385 **    NORMAL    The journal is synced once before writes begin on the
30386 **              database.  This is normally adequate protection, but
30387 **              it is theoretically possible, though very unlikely,
30388 **              that an inopertune power failure could leave the journal
30389 **              in a state which would cause damage to the database
30390 **              when it is rolled back.
30391 **
30392 **    FULL      The journal is synced twice before writes begin on the
30393 **              database (with some additional information - the nRec field
30394 **              of the journal header - being written in between the two
30395 **              syncs).  If we assume that writing a
30396 **              single disk sector is atomic, then this mode provides
30397 **              assurance that the journal will not be corrupted to the
30398 **              point of causing damage to the database during rollback.
30399 **
30400 ** Numeric values associated with these states are OFF==1, NORMAL=2,
30401 ** and FULL=3.
30402 */
30403 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
30404 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager *pPager, int level, int bFullFsync){
30405   pPager->noSync =  level==1 || pPager->tempFile;
30406   pPager->fullSync = level==3 && !pPager->tempFile;
30407   pPager->sync_flags = (bFullFsync?SQLITE_SYNC_FULL:SQLITE_SYNC_NORMAL);
30408   if( pPager->noSync ) pPager->needSync = 0;
30409 }
30410 #endif
30411
30412 /*
30413 ** The following global variable is incremented whenever the library
30414 ** attempts to open a temporary file.  This information is used for
30415 ** testing and analysis only.  
30416 */
30417 #ifdef SQLITE_TEST
30418 SQLITE_API int sqlite3_opentemp_count = 0;
30419 #endif
30420
30421 /*
30422 ** Open a temporary file. 
30423 **
30424 ** Write the file descriptor into *fd.  Return SQLITE_OK on success or some
30425 ** other error code if we fail. The OS will automatically delete the temporary
30426 ** file when it is closed.
30427 */
30428 static int sqlite3PagerOpentemp(
30429   Pager *pPager,        /* The pager object */
30430   sqlite3_file *pFile,  /* Write the file descriptor here */
30431   int vfsFlags          /* Flags passed through to the VFS */
30432 ){
30433   int rc;
30434
30435 #ifdef SQLITE_TEST
30436   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
30437 #endif
30438
30439   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
30440             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
30441   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
30442   assert( rc!=SQLITE_OK || pFile->pMethods );
30443   return rc;
30444 }
30445
30446 static int pagerStress(void *,PgHdr *);
30447
30448 /*
30449 ** Create a new page cache and put a pointer to the page cache in *ppPager.
30450 ** The file to be cached need not exist.  The file is not locked until
30451 ** the first call to sqlite3PagerGet() and is only held open until the
30452 ** last page is released using sqlite3PagerUnref().
30453 **
30454 ** If zFilename is NULL then a randomly-named temporary file is created
30455 ** and used as the file to be cached.  The file will be deleted
30456 ** automatically when it is closed.
30457 **
30458 ** If zFilename is ":memory:" then all information is held in cache.
30459 ** It is never written to disk.  This can be used to implement an
30460 ** in-memory database.
30461 */
30462 SQLITE_PRIVATE int sqlite3PagerOpen(
30463   sqlite3_vfs *pVfs,       /* The virtual file system to use */
30464   Pager **ppPager,         /* Return the Pager structure here */
30465   const char *zFilename,   /* Name of the database file to open */
30466   int nExtra,              /* Extra bytes append to each in-memory page */
30467   int flags,               /* flags controlling this file */
30468   int vfsFlags             /* flags passed through to sqlite3_vfs.xOpen() */
30469 ){
30470   u8 *pPtr;
30471   Pager *pPager = 0;
30472   int rc = SQLITE_OK;
30473   int i;
30474   int tempFile = 0;
30475   int memDb = 0;
30476   int readOnly = 0;
30477   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0;
30478   int noReadlock = (flags & PAGER_NO_READLOCK)!=0;
30479   int journalFileSize;
30480   int pcacheSize = sqlite3PcacheSize();
30481   int szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;
30482   char *zPathname = 0;
30483   int nPathname = 0;
30484
30485   if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
30486     journalFileSize = sqlite3JournalSize(pVfs);
30487   }else{
30488     journalFileSize = sqlite3MemJournalSize();
30489   }
30490
30491   /* The default return is a NULL pointer */
30492   *ppPager = 0;
30493
30494   /* Compute and store the full pathname in an allocated buffer pointed
30495   ** to by zPathname, length nPathname. Or, if this is a temporary file,
30496   ** leave both nPathname and zPathname set to 0.
30497   */
30498   if( zFilename && zFilename[0] ){
30499     nPathname = pVfs->mxPathname+1;
30500     zPathname = sqlite3Malloc(nPathname*2);
30501     if( zPathname==0 ){
30502       return SQLITE_NOMEM;
30503     }
30504 #ifndef SQLITE_OMIT_MEMORYDB
30505     if( strcmp(zFilename,":memory:")==0 ){
30506       memDb = 1;
30507       zPathname[0] = 0;
30508     }else
30509 #endif
30510     {
30511       rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
30512     }
30513     if( rc!=SQLITE_OK ){
30514       sqlite3_free(zPathname);
30515       return rc;
30516     }
30517     nPathname = strlen(zPathname);
30518   }
30519
30520   /* Allocate memory for the pager structure */
30521   pPager = sqlite3MallocZero(
30522     sizeof(*pPager) +           /* Pager structure */
30523     pcacheSize      +           /* PCache object */
30524     journalFileSize +           /* The journal file structure */ 
30525     pVfs->szOsFile  +           /* The main db file */
30526     journalFileSize * 2 +       /* The two journal files */ 
30527     3*nPathname + 40            /* zFilename, zDirectory, zJournal */
30528   );
30529   if( !pPager ){
30530     sqlite3_free(zPathname);
30531     return SQLITE_NOMEM;
30532   }
30533   pPager->pPCache = (PCache *)&pPager[1];
30534   pPtr = ((u8 *)&pPager[1]) + pcacheSize;
30535   pPager->vfsFlags = vfsFlags;
30536   pPager->fd = (sqlite3_file*)&pPtr[pVfs->szOsFile*0];
30537   pPager->stfd = (sqlite3_file*)&pPtr[pVfs->szOsFile];
30538   pPager->jfd = (sqlite3_file*)&pPtr[pVfs->szOsFile+journalFileSize];
30539   pPager->zFilename = (char*)&pPtr[pVfs->szOsFile+2*journalFileSize];
30540   pPager->zDirectory = &pPager->zFilename[nPathname+1];
30541   pPager->zJournal = &pPager->zDirectory[nPathname+1];
30542   pPager->pVfs = pVfs;
30543   if( zPathname ){
30544     memcpy(pPager->zFilename, zPathname, nPathname+1);
30545     sqlite3_free(zPathname);
30546   }
30547
30548   /* Open the pager file.
30549   */
30550   if( zFilename && zFilename[0] && !memDb ){
30551     if( nPathname>(pVfs->mxPathname - (int)sizeof("-journal")) ){
30552       rc = SQLITE_CANTOPEN;
30553     }else{
30554       int fout = 0;
30555       rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd,
30556                          pPager->vfsFlags, &fout);
30557       readOnly = (fout&SQLITE_OPEN_READONLY);
30558
30559       /* If the file was successfully opened for read/write access,
30560       ** choose a default page size in case we have to create the
30561       ** database file. The default page size is the maximum of:
30562       **
30563       **    + SQLITE_DEFAULT_PAGE_SIZE,
30564       **    + The value returned by sqlite3OsSectorSize()
30565       **    + The largest page size that can be written atomically.
30566       */
30567       if( rc==SQLITE_OK && !readOnly ){
30568         int iSectorSize = sqlite3OsSectorSize(pPager->fd);
30569         if( szPageDflt<iSectorSize ){
30570           szPageDflt = iSectorSize;
30571         }
30572 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
30573         {
30574           int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
30575           int ii;
30576           assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
30577           assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
30578           assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
30579           for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
30580             if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ) szPageDflt = ii;
30581           }
30582         }
30583 #endif
30584         if( szPageDflt>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
30585           szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
30586         }
30587       }
30588     }
30589   }else{
30590     /* If a temporary file is requested, it is not opened immediately.
30591     ** In this case we accept the default page size and delay actually
30592     ** opening the file until the first call to OsWrite().
30593     **
30594     ** This branch is also run for an in-memory database. An in-memory
30595     ** database is the same as a temp-file that is never written out to
30596     ** disk and uses an in-memory rollback journal.
30597     */ 
30598     tempFile = 1;
30599     pPager->state = PAGER_EXCLUSIVE;
30600   }
30601
30602   if( pPager && rc==SQLITE_OK ){
30603     pPager->pTmpSpace = sqlite3PageMalloc(szPageDflt);
30604   }
30605
30606   /* If an error occured in either of the blocks above.
30607   ** Free the Pager structure and close the file.
30608   ** Since the pager is not allocated there is no need to set 
30609   ** any Pager.errMask variables.
30610   */
30611   if( !pPager || !pPager->pTmpSpace ){
30612     sqlite3OsClose(pPager->fd);
30613     sqlite3_free(pPager);
30614     return ((rc==SQLITE_OK)?SQLITE_NOMEM:rc);
30615   }
30616   nExtra = FORCE_ALIGNMENT(nExtra);
30617   sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
30618                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
30619
30620   PAGERTRACE3("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename);
30621   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
30622
30623   /* Fill in Pager.zDirectory[] */
30624   memcpy(pPager->zDirectory, pPager->zFilename, nPathname+1);
30625   for(i=strlen(pPager->zDirectory); i>0 && pPager->zDirectory[i-1]!='/'; i--){}
30626   if( i>0 ) pPager->zDirectory[i-1] = 0;
30627
30628   /* Fill in Pager.zJournal[] */
30629   if( zPathname ){
30630     memcpy(pPager->zJournal, pPager->zFilename, nPathname);
30631     memcpy(&pPager->zJournal[nPathname], "-journal", 9);
30632   }else{
30633     pPager->zJournal = 0;
30634   }
30635
30636   /* pPager->journalOpen = 0; */
30637   pPager->useJournal = useJournal;
30638   pPager->noReadlock = noReadlock && readOnly;
30639   /* pPager->stmtOpen = 0; */
30640   /* pPager->stmtInUse = 0; */
30641   /* pPager->nRef = 0; */
30642   pPager->dbSizeValid = memDb;
30643   pPager->pageSize = szPageDflt;
30644   /* pPager->stmtSize = 0; */
30645   /* pPager->stmtJSize = 0; */
30646   /* pPager->nPage = 0; */
30647   pPager->mxPage = 100;
30648   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
30649   /* pPager->state = PAGER_UNLOCK; */
30650   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
30651   /* pPager->errMask = 0; */
30652   pPager->tempFile = tempFile;
30653   assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
30654           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
30655   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
30656   pPager->exclusiveMode = tempFile; 
30657   pPager->memDb = memDb;
30658   pPager->readOnly = readOnly;
30659   /* pPager->needSync = 0; */
30660   pPager->noSync = pPager->tempFile || !useJournal;
30661   pPager->fullSync = (pPager->noSync?0:1);
30662   pPager->sync_flags = SQLITE_SYNC_NORMAL;
30663   /* pPager->pFirst = 0; */
30664   /* pPager->pFirstSynced = 0; */
30665   /* pPager->pLast = 0; */
30666   pPager->nExtra = nExtra;
30667   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
30668   assert(pPager->fd->pMethods||tempFile);
30669   setSectorSize(pPager);
30670   if( memDb ){
30671     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
30672   }
30673   /* pPager->xBusyHandler = 0; */
30674   /* pPager->pBusyHandlerArg = 0; */
30675   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
30676   *ppPager = pPager;
30677   return SQLITE_OK;
30678 }
30679
30680 /*
30681 ** Set the busy handler function.
30682 */
30683 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
30684   Pager *pPager, 
30685   int (*xBusyHandler)(void *),
30686   void *pBusyHandlerArg
30687 ){  
30688   pPager->xBusyHandler = xBusyHandler;
30689   pPager->pBusyHandlerArg = pBusyHandlerArg;
30690 }
30691
30692 /*
30693 ** Set the reinitializer for this pager.  If not NULL, the reinitializer
30694 ** is called when the content of a page in cache is restored to its original
30695 ** value as a result of a rollback.  The callback gives higher-level code
30696 ** an opportunity to restore the EXTRA section to agree with the restored
30697 ** page data.
30698 */
30699 SQLITE_PRIVATE void sqlite3PagerSetReiniter(Pager *pPager, void (*xReinit)(DbPage*)){
30700   pPager->xReiniter = xReinit;
30701 }
30702
30703 /*
30704 ** Set the page size to *pPageSize. If the suggest new page size is
30705 ** inappropriate, then an alternative page size is set to that
30706 ** value before returning.
30707 */
30708 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u16 *pPageSize){
30709   int rc = pPager->errCode;
30710   if( rc==SQLITE_OK ){
30711     u16 pageSize = *pPageSize;
30712     assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
30713     if( pageSize && pageSize!=pPager->pageSize 
30714      && (pPager->memDb==0 || pPager->dbSize==0)
30715      && sqlite3PcacheRefCount(pPager->pPCache)==0 
30716     ){
30717       char *pNew = (char *)sqlite3PageMalloc(pageSize);
30718       if( !pNew ){
30719         rc = SQLITE_NOMEM;
30720       }else{
30721         pager_reset(pPager);
30722         pPager->pageSize = pageSize;
30723         if( !pPager->memDb ) setSectorSize(pPager);
30724         sqlite3PageFree(pPager->pTmpSpace);
30725         pPager->pTmpSpace = pNew;
30726         sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
30727       }
30728     }
30729     *pPageSize = pPager->pageSize;
30730   }
30731   return rc;
30732 }
30733
30734 /*
30735 ** Return a pointer to the "temporary page" buffer held internally
30736 ** by the pager.  This is a buffer that is big enough to hold the
30737 ** entire content of a database page.  This buffer is used internally
30738 ** during rollback and will be overwritten whenever a rollback
30739 ** occurs.  But other modules are free to use it too, as long as
30740 ** no rollbacks are happening.
30741 */
30742 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
30743   return pPager->pTmpSpace;
30744 }
30745
30746 /*
30747 ** Attempt to set the maximum database page count if mxPage is positive. 
30748 ** Make no changes if mxPage is zero or negative.  And never reduce the
30749 ** maximum page count below the current size of the database.
30750 **
30751 ** Regardless of mxPage, return the current maximum page count.
30752 */
30753 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
30754   if( mxPage>0 ){
30755     pPager->mxPgno = mxPage;
30756   }
30757   sqlite3PagerPagecount(pPager, 0);
30758   return pPager->mxPgno;
30759 }
30760
30761 /*
30762 ** The following set of routines are used to disable the simulated
30763 ** I/O error mechanism.  These routines are used to avoid simulated
30764 ** errors in places where we do not care about errors.
30765 **
30766 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
30767 ** and generate no code.
30768 */
30769 #ifdef SQLITE_TEST
30770 SQLITE_API extern int sqlite3_io_error_pending;
30771 SQLITE_API extern int sqlite3_io_error_hit;
30772 static int saved_cnt;
30773 void disable_simulated_io_errors(void){
30774   saved_cnt = sqlite3_io_error_pending;
30775   sqlite3_io_error_pending = -1;
30776 }
30777 void enable_simulated_io_errors(void){
30778   sqlite3_io_error_pending = saved_cnt;
30779 }
30780 #else
30781 # define disable_simulated_io_errors()
30782 # define enable_simulated_io_errors()
30783 #endif
30784
30785 /*
30786 ** Read the first N bytes from the beginning of the file into memory
30787 ** that pDest points to. 
30788 **
30789 ** No error checking is done. The rational for this is that this function 
30790 ** may be called even if the file does not exist or contain a header. In 
30791 ** these cases sqlite3OsRead() will return an error, to which the correct 
30792 ** response is to zero the memory at pDest and continue.  A real IO error 
30793 ** will presumably recur and be picked up later (Todo: Think about this).
30794 */
30795 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
30796   int rc = SQLITE_OK;
30797   memset(pDest, 0, N);
30798   assert(pPager->fd->pMethods||pPager->tempFile);
30799   if( pPager->fd->pMethods ){
30800     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
30801     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
30802     if( rc==SQLITE_IOERR_SHORT_READ ){
30803       rc = SQLITE_OK;
30804     }
30805   }
30806   return rc;
30807 }
30808
30809 /*
30810 ** Return the total number of pages in the disk file associated with
30811 ** pPager. 
30812 **
30813 ** If the PENDING_BYTE lies on the page directly after the end of the
30814 ** file, then consider this page part of the file too. For example, if
30815 ** PENDING_BYTE is byte 4096 (the first byte of page 5) and the size of the
30816 ** file is 4096 bytes, 5 is returned instead of 4.
30817 */
30818 SQLITE_PRIVATE int sqlite3PagerPagecount(Pager *pPager, int *pnPage){
30819   i64 n = 0;
30820   int rc;
30821   assert( pPager!=0 );
30822   if( pPager->errCode ){
30823     rc = pPager->errCode;
30824     return rc;
30825   }
30826   if( pPager->dbSizeValid ){
30827     n = pPager->dbSize;
30828   } else {
30829     assert(pPager->fd->pMethods||pPager->tempFile);
30830     if( (pPager->fd->pMethods)
30831      && (rc = sqlite3OsFileSize(pPager->fd, &n))!=SQLITE_OK ){
30832       pager_error(pPager, rc);
30833       return rc;
30834     }
30835     if( n>0 && n<pPager->pageSize ){
30836       n = 1;
30837     }else{
30838       n /= pPager->pageSize;
30839     }
30840     if( pPager->state!=PAGER_UNLOCK ){
30841       pPager->dbSize = n;
30842       pPager->dbSizeValid = 1;
30843     }
30844   }
30845   if( n==(PENDING_BYTE/pPager->pageSize) ){
30846     n++;
30847   }
30848   if( n>pPager->mxPgno ){
30849     pPager->mxPgno = n;
30850   }
30851   if( pnPage ){
30852     *pnPage = n;
30853   }
30854   return SQLITE_OK;
30855 }
30856
30857 /*
30858 ** Forward declaration
30859 */
30860 static int syncJournal(Pager*);
30861
30862 /*
30863 ** This routine is used to truncate the cache when a database
30864 ** is truncated.  Drop from the cache all pages whose pgno is
30865 ** larger than pPager->dbSize and is unreferenced.
30866 **
30867 ** Referenced pages larger than pPager->dbSize are zeroed.
30868 **
30869 ** Actually, at the point this routine is called, it would be
30870 ** an error to have a referenced page.  But rather than delete
30871 ** that page and guarantee a subsequent segfault, it seems better
30872 ** to zero it and hope that we error out sanely.
30873 */
30874 static void pager_truncate_cache(Pager *pPager){
30875   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
30876 }
30877
30878 /*
30879 ** Try to obtain a lock on a file.  Invoke the busy callback if the lock
30880 ** is currently not available.  Repeat until the busy callback returns
30881 ** false or until the lock succeeds.
30882 **
30883 ** Return SQLITE_OK on success and an error code if we cannot obtain
30884 ** the lock.
30885 */
30886 static int pager_wait_on_lock(Pager *pPager, int locktype){
30887   int rc;
30888
30889   /* The OS lock values must be the same as the Pager lock values */
30890   assert( PAGER_SHARED==SHARED_LOCK );
30891   assert( PAGER_RESERVED==RESERVED_LOCK );
30892   assert( PAGER_EXCLUSIVE==EXCLUSIVE_LOCK );
30893
30894   /* If the file is currently unlocked then the size must be unknown */
30895   assert( pPager->state>=PAGER_SHARED || pPager->dbSizeValid==0 );
30896
30897   if( pPager->state>=locktype ){
30898     rc = SQLITE_OK;
30899   }else{
30900     do {
30901       rc = sqlite3OsLock(pPager->fd, locktype);
30902     }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
30903     if( rc==SQLITE_OK ){
30904       pPager->state = locktype;
30905       IOTRACE(("LOCK %p %d\n", pPager, locktype))
30906     }
30907   }
30908   return rc;
30909 }
30910
30911 /*
30912 ** Truncate the file to the number of pages specified.
30913 */
30914 SQLITE_PRIVATE int sqlite3PagerTruncate(Pager *pPager, Pgno nPage){
30915   int rc = SQLITE_OK;
30916   assert( pPager->state>=PAGER_SHARED );
30917
30918   sqlite3PagerPagecount(pPager, 0);
30919   if( pPager->errCode ){
30920     rc = pPager->errCode;
30921   }else if( nPage<pPager->dbSize ){
30922     rc = syncJournal(pPager);
30923     if( rc==SQLITE_OK ){
30924       /* Get an exclusive lock on the database before truncating. */
30925       rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
30926     }
30927     if( rc==SQLITE_OK ){
30928       rc = pager_truncate(pPager, nPage);
30929     }
30930   }
30931
30932   return rc;
30933 }
30934
30935 /*
30936 ** Shutdown the page cache.  Free all memory and close all files.
30937 **
30938 ** If a transaction was in progress when this routine is called, that
30939 ** transaction is rolled back.  All outstanding pages are invalidated
30940 ** and their memory is freed.  Any attempt to use a page associated
30941 ** with this page cache after this function returns will likely
30942 ** result in a coredump.
30943 **
30944 ** This function always succeeds. If a transaction is active an attempt
30945 ** is made to roll it back. If an error occurs during the rollback 
30946 ** a hot journal may be left in the filesystem but no error is returned
30947 ** to the caller.
30948 */
30949 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
30950
30951   disable_simulated_io_errors();
30952   sqlite3BeginBenignMalloc();
30953   pPager->errCode = 0;
30954   pPager->exclusiveMode = 0;
30955   pager_reset(pPager);
30956   if( !MEMDB ){
30957     pagerUnlockAndRollback(pPager);
30958   }
30959   enable_simulated_io_errors();
30960   sqlite3EndBenignMalloc();
30961   PAGERTRACE2("CLOSE %d\n", PAGERID(pPager));
30962   IOTRACE(("CLOSE %p\n", pPager))
30963   if( pPager->journalOpen ){
30964     sqlite3OsClose(pPager->jfd);
30965   }
30966   sqlite3BitvecDestroy(pPager->pInJournal);
30967   sqlite3BitvecDestroy(pPager->pAlwaysRollback);
30968   if( pPager->stmtOpen ){
30969     sqlite3OsClose(pPager->stfd);
30970   }
30971   sqlite3OsClose(pPager->fd);
30972   /* Temp files are automatically deleted by the OS
30973   ** if( pPager->tempFile ){
30974   **   sqlite3OsDelete(pPager->zFilename);
30975   ** }
30976   */
30977
30978   sqlite3PageFree(pPager->pTmpSpace);
30979   sqlite3PcacheClose(pPager->pPCache);
30980   sqlite3_free(pPager);
30981   return SQLITE_OK;
30982 }
30983
30984 #if !defined(NDEBUG) || defined(SQLITE_TEST)
30985 /*
30986 ** Return the page number for the given page data.
30987 */
30988 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *p){
30989   return p->pgno;
30990 }
30991 #endif
30992
30993 /*
30994 ** Increment the reference count for a page.  The input pointer is
30995 ** a reference to the page data.
30996 */
30997 SQLITE_PRIVATE int sqlite3PagerRef(DbPage *pPg){
30998   sqlite3PcacheRef(pPg);
30999   return SQLITE_OK;
31000 }
31001
31002 /*
31003 ** Sync the journal.  In other words, make sure all the pages that have
31004 ** been written to the journal have actually reached the surface of the
31005 ** disk.  It is not safe to modify the original database file until after
31006 ** the journal has been synced.  If the original database is modified before
31007 ** the journal is synced and a power failure occurs, the unsynced journal
31008 ** data would be lost and we would be unable to completely rollback the
31009 ** database changes.  Database corruption would occur.
31010 ** 
31011 ** This routine also updates the nRec field in the header of the journal.
31012 ** (See comments on the pager_playback() routine for additional information.)
31013 ** If the sync mode is FULL, two syncs will occur.  First the whole journal
31014 ** is synced, then the nRec field is updated, then a second sync occurs.
31015 **
31016 ** For temporary databases, we do not care if we are able to rollback
31017 ** after a power failure, so no sync occurs.
31018 **
31019 ** If the IOCAP_SEQUENTIAL flag is set for the persistent media on which
31020 ** the database is stored, then OsSync() is never called on the journal
31021 ** file. In this case all that is required is to update the nRec field in
31022 ** the journal header.
31023 **
31024 ** This routine clears the needSync field of every page current held in
31025 ** memory.
31026 */
31027 static int syncJournal(Pager *pPager){
31028   int rc = SQLITE_OK;
31029
31030   /* Sync the journal before modifying the main database
31031   ** (assuming there is a journal and it needs to be synced.)
31032   */
31033   if( pPager->needSync ){
31034     assert( !pPager->tempFile );
31035     if( pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
31036       int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
31037       assert( pPager->journalOpen );
31038
31039       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
31040         /* Write the nRec value into the journal file header. If in
31041         ** full-synchronous mode, sync the journal first. This ensures that
31042         ** all data has really hit the disk before nRec is updated to mark
31043         ** it as a candidate for rollback.
31044         **
31045         ** This is not required if the persistent media supports the
31046         ** SAFE_APPEND property. Because in this case it is not possible 
31047         ** for garbage data to be appended to the file, the nRec field
31048         ** is populated with 0xFFFFFFFF when the journal header is written
31049         ** and never needs to be updated.
31050         */
31051         i64 jrnlOff;
31052         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
31053           PAGERTRACE2("SYNC journal of %d\n", PAGERID(pPager));
31054           IOTRACE(("JSYNC %p\n", pPager))
31055           rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags);
31056           if( rc!=0 ) return rc;
31057         }
31058
31059         jrnlOff = pPager->journalHdr + sizeof(aJournalMagic);
31060         IOTRACE(("JHDR %p %lld %d\n", pPager, jrnlOff, 4));
31061         rc = write32bits(pPager->jfd, jrnlOff, pPager->nRec);
31062         if( rc ) return rc;
31063       }
31064       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
31065         PAGERTRACE2("SYNC journal of %d\n", PAGERID(pPager));
31066         IOTRACE(("JSYNC %p\n", pPager))
31067         rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags| 
31068           (pPager->sync_flags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
31069         );
31070         if( rc!=0 ) return rc;
31071       }
31072       pPager->journalStarted = 1;
31073     }
31074     pPager->needSync = 0;
31075
31076     /* Erase the needSync flag from every page.
31077     */
31078     sqlite3PcacheClearSyncFlags(pPager->pPCache);
31079   }
31080
31081   return rc;
31082 }
31083
31084 /*
31085 ** Given a list of pages (connected by the PgHdr.pDirty pointer) write
31086 ** every one of those pages out to the database file. No calls are made
31087 ** to the page-cache to mark the pages as clean. It is the responsibility
31088 ** of the caller to use PcacheCleanAll() or PcacheMakeClean() to mark
31089 ** the pages as clean.
31090 */
31091 static int pager_write_pagelist(PgHdr *pList){
31092   Pager *pPager;
31093   int rc;
31094
31095   if( pList==0 ) return SQLITE_OK;
31096   pPager = pList->pPager;
31097
31098   /* At this point there may be either a RESERVED or EXCLUSIVE lock on the
31099   ** database file. If there is already an EXCLUSIVE lock, the following
31100   ** calls to sqlite3OsLock() are no-ops.
31101   **
31102   ** Moving the lock from RESERVED to EXCLUSIVE actually involves going
31103   ** through an intermediate state PENDING.   A PENDING lock prevents new
31104   ** readers from attaching to the database but is unsufficient for us to
31105   ** write.  The idea of a PENDING lock is to prevent new readers from
31106   ** coming in while we wait for existing readers to clear.
31107   **
31108   ** While the pager is in the RESERVED state, the original database file
31109   ** is unchanged and we can rollback without having to playback the
31110   ** journal into the original database file.  Once we transition to
31111   ** EXCLUSIVE, it means the database file has been changed and any rollback
31112   ** will require a journal playback.
31113   */
31114   rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
31115   if( rc!=SQLITE_OK ){
31116     return rc;
31117   }
31118
31119   while( pList ){
31120
31121     /* If the file has not yet been opened, open it now. */
31122     if( !pPager->fd->pMethods ){
31123       assert(pPager->tempFile);
31124       rc = sqlite3PagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
31125       if( rc ) return rc;
31126     }
31127
31128     /* If there are dirty pages in the page cache with page numbers greater
31129     ** than Pager.dbSize, this means sqlite3PagerTruncate() was called to
31130     ** make the file smaller (presumably by auto-vacuum code). Do not write
31131     ** any such pages to the file.
31132     */
31133     if( pList->pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
31134       i64 offset = (pList->pgno-1)*(i64)pPager->pageSize;
31135       char *pData = CODEC2(pPager, pList->pData, pList->pgno, 6);
31136       PAGERTRACE4("STORE %d page %d hash(%08x)\n",
31137                    PAGERID(pPager), pList->pgno, pager_pagehash(pList));
31138       IOTRACE(("PGOUT %p %d\n", pPager, pList->pgno));
31139       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
31140       PAGER_INCR(sqlite3_pager_writedb_count);
31141       PAGER_INCR(pPager->nWrite);
31142       if( pList->pgno==1 ){
31143         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
31144       }
31145     }
31146 #ifndef NDEBUG
31147     else{
31148       PAGERTRACE3("NOSTORE %d page %d\n", PAGERID(pPager), pList->pgno);
31149     }
31150 #endif
31151     if( rc ) return rc;
31152 #ifdef SQLITE_CHECK_PAGES
31153     pList->pageHash = pager_pagehash(pList);
31154 #endif
31155     pList = pList->pDirty;
31156   }
31157
31158   return SQLITE_OK;
31159 }
31160
31161 /*
31162 ** This function is called by the pcache layer when it has reached some
31163 ** soft memory limit. The argument is a pointer to a purgeable Pager 
31164 ** object. This function attempts to make a single dirty page that has no
31165 ** outstanding references (if one exists) clean so that it can be recycled 
31166 ** by the pcache layer.
31167 */
31168 static int pagerStress(void *p, PgHdr *pPg){
31169   Pager *pPager = (Pager *)p;
31170   int rc = SQLITE_OK;
31171
31172   if( pPager->doNotSync ){
31173     return SQLITE_OK;
31174   }
31175
31176   assert( pPg->flags&PGHDR_DIRTY );
31177   if( pPager->errCode==SQLITE_OK ){
31178     if( pPg->flags&PGHDR_NEED_SYNC ){
31179       rc = syncJournal(pPager);
31180       if( rc==SQLITE_OK && pPager->fullSync && 
31181         !(pPager->journalMode==PAGER_JOURNALMODE_MEMORY) &&
31182         !(sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
31183       ){
31184         pPager->nRec = 0;
31185         rc = writeJournalHdr(pPager);
31186       }
31187     }
31188     if( rc==SQLITE_OK ){
31189       pPg->pDirty = 0;
31190       rc = pager_write_pagelist(pPg);
31191     }
31192     if( rc!=SQLITE_OK ){
31193       pager_error(pPager, rc);
31194     }
31195   }
31196
31197   if( rc==SQLITE_OK ){
31198     sqlite3PcacheMakeClean(pPg);
31199   }
31200   return rc;
31201 }
31202
31203
31204 /*
31205 ** Return 1 if there is a hot journal on the given pager.
31206 ** A hot journal is one that needs to be played back.
31207 **
31208 ** If the current size of the database file is 0 but a journal file
31209 ** exists, that is probably an old journal left over from a prior
31210 ** database with the same name.  Just delete the journal.
31211 **
31212 ** Return negative if unable to determine the status of the journal.
31213 **
31214 ** This routine does not open the journal file to examine its
31215 ** content.  Hence, the journal might contain the name of a master
31216 ** journal file that has been deleted, and hence not be hot.  Or
31217 ** the header of the journal might be zeroed out.  This routine
31218 ** does not discover these cases of a non-hot journal - if the
31219 ** journal file exists and is not empty this routine assumes it
31220 ** is hot.  The pager_playback() routine will discover that the
31221 ** journal file is not really hot and will no-op.
31222 */
31223 static int hasHotJournal(Pager *pPager, int *pExists){
31224   sqlite3_vfs *pVfs = pPager->pVfs;
31225   int rc = SQLITE_OK;
31226   int exists;
31227   int locked;
31228   assert( pPager!=0 );
31229   assert( pPager->useJournal );
31230   assert( pPager->fd->pMethods );
31231   *pExists = 0;
31232   rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
31233   if( rc==SQLITE_OK && exists ){
31234     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
31235   }
31236   if( rc==SQLITE_OK && exists && !locked ){
31237     int nPage;
31238     rc = sqlite3PagerPagecount(pPager, &nPage);
31239     if( rc==SQLITE_OK ){
31240      if( nPage==0 ){
31241         sqlite3OsDelete(pVfs, pPager->zJournal, 0);
31242       }else{
31243         *pExists = 1;
31244       }
31245     }
31246   }
31247   return rc;
31248 }
31249
31250 /*
31251 ** Read the content of page pPg out of the database file.
31252 */
31253 static int readDbPage(Pager *pPager, PgHdr *pPg, Pgno pgno){
31254   int rc;
31255   i64 offset;
31256   assert( MEMDB==0 );
31257   assert(pPager->fd->pMethods||pPager->tempFile);
31258   if( !pPager->fd->pMethods ){
31259     return SQLITE_IOERR_SHORT_READ;
31260   }
31261   offset = (pgno-1)*(i64)pPager->pageSize;
31262   rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, offset);
31263   PAGER_INCR(sqlite3_pager_readdb_count);
31264   PAGER_INCR(pPager->nRead);
31265   IOTRACE(("PGIN %p %d\n", pPager, pgno));
31266   if( pgno==1 ){
31267     memcpy(&pPager->dbFileVers, &((u8*)pPg->pData)[24],
31268                                               sizeof(pPager->dbFileVers));
31269   }
31270   CODEC1(pPager, pPg->pData, pPg->pgno, 3);
31271   PAGERTRACE4("FETCH %d page %d hash(%08x)\n",
31272                PAGERID(pPager), pPg->pgno, pager_pagehash(pPg));
31273   return rc;
31274 }
31275
31276
31277 /*
31278 ** This function is called to obtain the shared lock required before
31279 ** data may be read from the pager cache. If the shared lock has already
31280 ** been obtained, this function is a no-op.
31281 **
31282 ** Immediately after obtaining the shared lock (if required), this function
31283 ** checks for a hot-journal file. If one is found, an emergency rollback
31284 ** is performed immediately.
31285 */
31286 static int pagerSharedLock(Pager *pPager){
31287   int rc = SQLITE_OK;
31288   int isErrorReset = 0;
31289
31290   /* If this database is opened for exclusive access, has no outstanding 
31291   ** page references and is in an error-state, now is the chance to clear
31292   ** the error. Discard the contents of the pager-cache and treat any
31293   ** open journal file as a hot-journal.
31294   */
31295   if( !MEMDB && pPager->exclusiveMode 
31296    && sqlite3PcacheRefCount(pPager->pPCache)==0 && pPager->errCode 
31297   ){
31298     if( pPager->journalOpen ){
31299       isErrorReset = 1;
31300     }
31301     pPager->errCode = SQLITE_OK;
31302     pager_reset(pPager);
31303   }
31304
31305   /* If the pager is still in an error state, do not proceed. The error 
31306   ** state will be cleared at some point in the future when all page 
31307   ** references are dropped and the cache can be discarded.
31308   */
31309   if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
31310     return pPager->errCode;
31311   }
31312
31313   if( pPager->state==PAGER_UNLOCK || isErrorReset ){
31314     sqlite3_vfs *pVfs = pPager->pVfs;
31315     int isHotJournal;
31316     assert( !MEMDB );
31317     assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
31318     if( !pPager->noReadlock ){
31319       rc = pager_wait_on_lock(pPager, SHARED_LOCK);
31320       if( rc!=SQLITE_OK ){
31321         assert( pPager->state==PAGER_UNLOCK );
31322         return pager_error(pPager, rc);
31323       }
31324       assert( pPager->state>=SHARED_LOCK );
31325     }
31326
31327     /* If a journal file exists, and there is no RESERVED lock on the
31328     ** database file, then it either needs to be played back or deleted.
31329     */
31330     if( !isErrorReset ){
31331       rc = hasHotJournal(pPager, &isHotJournal);
31332       if( rc!=SQLITE_OK ){
31333         goto failed;
31334       }
31335     }
31336     if( isErrorReset || isHotJournal ){
31337       /* Get an EXCLUSIVE lock on the database file. At this point it is
31338       ** important that a RESERVED lock is not obtained on the way to the
31339       ** EXCLUSIVE lock. If it were, another process might open the
31340       ** database file, detect the RESERVED lock, and conclude that the
31341       ** database is safe to read while this process is still rolling it 
31342       ** back.
31343       ** 
31344       ** Because the intermediate RESERVED lock is not requested, the
31345       ** second process will get to this point in the code and fail to
31346       ** obtain its own EXCLUSIVE lock on the database file.
31347       */
31348       if( pPager->state<EXCLUSIVE_LOCK ){
31349         rc = sqlite3OsLock(pPager->fd, EXCLUSIVE_LOCK);
31350         if( rc!=SQLITE_OK ){
31351           rc = pager_error(pPager, rc);
31352           goto failed;
31353         }
31354         pPager->state = PAGER_EXCLUSIVE;
31355       }
31356  
31357       /* Open the journal for read/write access. This is because in 
31358       ** exclusive-access mode the file descriptor will be kept open and
31359       ** possibly used for a transaction later on. On some systems, the
31360       ** OsTruncate() call used in exclusive-access mode also requires
31361       ** a read/write file handle.
31362       */
31363       if( !isErrorReset && pPager->journalOpen==0 ){
31364         int res;
31365         rc = sqlite3OsAccess(pVfs,pPager->zJournal,SQLITE_ACCESS_EXISTS,&res);
31366         if( rc==SQLITE_OK ){
31367           if( res ){
31368             int fout = 0;
31369             int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
31370             assert( !pPager->tempFile );
31371             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
31372             assert( rc!=SQLITE_OK || pPager->jfd->pMethods );
31373             if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
31374               rc = SQLITE_CANTOPEN;
31375               sqlite3OsClose(pPager->jfd);
31376             }
31377           }else{
31378             /* If the journal does not exist, that means some other process
31379             ** has already rolled it back */
31380             rc = SQLITE_BUSY;
31381           }
31382         }
31383       }
31384       if( rc!=SQLITE_OK ){
31385         goto failed;
31386       }
31387       pPager->journalOpen = 1;
31388       pPager->journalStarted = 0;
31389       pPager->journalOff = 0;
31390       pPager->setMaster = 0;
31391       pPager->journalHdr = 0;
31392  
31393       /* Playback and delete the journal.  Drop the database write
31394       ** lock and reacquire the read lock.
31395       */
31396       rc = pager_playback(pPager, 1);
31397       if( rc!=SQLITE_OK ){
31398         rc = pager_error(pPager, rc);
31399         goto failed;
31400       }
31401       assert(pPager->state==PAGER_SHARED || 
31402           (pPager->exclusiveMode && pPager->state>PAGER_SHARED)
31403       );
31404     }
31405
31406     if( sqlite3PcachePagecount(pPager->pPCache)>0 ){
31407       /* The shared-lock has just been acquired on the database file
31408       ** and there are already pages in the cache (from a previous
31409       ** read or write transaction).  Check to see if the database
31410       ** has been modified.  If the database has changed, flush the
31411       ** cache.
31412       **
31413       ** Database changes is detected by looking at 15 bytes beginning
31414       ** at offset 24 into the file.  The first 4 of these 16 bytes are
31415       ** a 32-bit counter that is incremented with each change.  The
31416       ** other bytes change randomly with each file change when
31417       ** a codec is in use.
31418       ** 
31419       ** There is a vanishingly small chance that a change will not be 
31420       ** detected.  The chance of an undetected change is so small that
31421       ** it can be neglected.
31422       */
31423       char dbFileVers[sizeof(pPager->dbFileVers)];
31424       sqlite3PagerPagecount(pPager, 0);
31425
31426       if( pPager->errCode ){
31427         rc = pPager->errCode;
31428         goto failed;
31429       }
31430
31431       assert( pPager->dbSizeValid );
31432       if( pPager->dbSize>0 ){
31433         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
31434         rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
31435         if( rc!=SQLITE_OK ){
31436           goto failed;
31437         }
31438       }else{
31439         memset(dbFileVers, 0, sizeof(dbFileVers));
31440       }
31441
31442       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
31443         pager_reset(pPager);
31444       }
31445     }
31446     assert( pPager->exclusiveMode || pPager->state<=PAGER_SHARED );
31447     if( pPager->state==PAGER_UNLOCK ){
31448       pPager->state = PAGER_SHARED;
31449     }
31450   }
31451
31452  failed:
31453   if( rc!=SQLITE_OK ){
31454     /* pager_unlock() is a no-op for exclusive mode and in-memory databases. */
31455     pager_unlock(pPager);
31456   }
31457   return rc;
31458 }
31459
31460 /*
31461 ** Make sure we have the content for a page.  If the page was
31462 ** previously acquired with noContent==1, then the content was
31463 ** just initialized to zeros instead of being read from disk.
31464 ** But now we need the real data off of disk.  So make sure we
31465 ** have it.  Read it in if we do not have it already.
31466 */
31467 static int pager_get_content(PgHdr *pPg){
31468   if( pPg->flags&PGHDR_NEED_READ ){
31469     int rc = readDbPage(pPg->pPager, pPg, pPg->pgno);
31470     if( rc==SQLITE_OK ){
31471       pPg->flags &= ~PGHDR_NEED_READ;
31472     }else{
31473       return rc;
31474     }
31475   }
31476   return SQLITE_OK;
31477 }
31478
31479 /*
31480 ** If the reference count has reached zero, and the pager is not in the
31481 ** middle of a write transaction or opened in exclusive mode, unlock it.
31482 */ 
31483 static void pagerUnlockIfUnused(Pager *pPager){
31484   if( (sqlite3PcacheRefCount(pPager->pPCache)==0)
31485     && (!pPager->exclusiveMode || pPager->journalOff>0) 
31486   ){
31487     pagerUnlockAndRollback(pPager);
31488   }
31489 }
31490
31491 /*
31492 ** Drop a page from the cache using sqlite3PcacheDrop().
31493 **
31494 ** If this means there are now no pages with references to them, a rollback
31495 ** occurs and the lock on the database is removed.
31496 */
31497 static void pagerDropPage(DbPage *pPg){
31498   Pager *pPager = pPg->pPager;
31499   sqlite3PcacheDrop(pPg);
31500   pagerUnlockIfUnused(pPager);
31501 }
31502
31503 /*
31504 ** Acquire a page.
31505 **
31506 ** A read lock on the disk file is obtained when the first page is acquired. 
31507 ** This read lock is dropped when the last page is released.
31508 **
31509 ** This routine works for any page number greater than 0.  If the database
31510 ** file is smaller than the requested page, then no actual disk
31511 ** read occurs and the memory image of the page is initialized to
31512 ** all zeros.  The extra data appended to a page is always initialized
31513 ** to zeros the first time a page is loaded into memory.
31514 **
31515 ** The acquisition might fail for several reasons.  In all cases,
31516 ** an appropriate error code is returned and *ppPage is set to NULL.
31517 **
31518 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
31519 ** to find a page in the in-memory cache first.  If the page is not already
31520 ** in memory, this routine goes to disk to read it in whereas Lookup()
31521 ** just returns 0.  This routine acquires a read-lock the first time it
31522 ** has to go to disk, and could also playback an old journal if necessary.
31523 ** Since Lookup() never goes to disk, it never has to deal with locks
31524 ** or journal files.
31525 **
31526 ** If noContent is false, the page contents are actually read from disk.
31527 ** If noContent is true, it means that we do not care about the contents
31528 ** of the page at this time, so do not do a disk read.  Just fill in the
31529 ** page content with zeros.  But mark the fact that we have not read the
31530 ** content by setting the PgHdr.needRead flag.  Later on, if 
31531 ** sqlite3PagerWrite() is called on this page or if this routine is
31532 ** called again with noContent==0, that means that the content is needed
31533 ** and the disk read should occur at that point.
31534 */
31535 SQLITE_PRIVATE int sqlite3PagerAcquire(
31536   Pager *pPager,      /* The pager open on the database file */
31537   Pgno pgno,          /* Page number to fetch */
31538   DbPage **ppPage,    /* Write a pointer to the page here */
31539   int noContent       /* Do not bother reading content from disk if true */
31540 ){
31541   PgHdr *pPg = 0;
31542   int rc;
31543
31544   assert( pPager->state==PAGER_UNLOCK 
31545        || sqlite3PcacheRefCount(pPager->pPCache)>0 
31546        || pgno==1
31547   );
31548
31549   /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
31550   ** number greater than this, or zero, is requested.
31551   */
31552   if( pgno>PAGER_MAX_PGNO || pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
31553     return SQLITE_CORRUPT_BKPT;
31554   }
31555
31556   /* Make sure we have not hit any critical errors.
31557   */ 
31558   assert( pPager!=0 );
31559   *ppPage = 0;
31560
31561   /* If this is the first page accessed, then get a SHARED lock
31562   ** on the database file. pagerSharedLock() is a no-op if 
31563   ** a database lock is already held.
31564   */
31565   rc = pagerSharedLock(pPager);
31566   if( rc!=SQLITE_OK ){
31567     return rc;
31568   }
31569   assert( pPager->state!=PAGER_UNLOCK );
31570
31571   rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, &pPg);
31572   if( rc!=SQLITE_OK ){
31573     return rc;
31574   }
31575   if( pPg->pPager==0 ){
31576     /* The pager cache has created a new page. Its content needs to 
31577     ** be initialized.
31578     */
31579     int nMax;
31580     PAGER_INCR(pPager->nMiss);
31581     pPg->pPager = pPager;
31582     memset(pPg->pExtra, 0, pPager->nExtra);
31583
31584     rc = sqlite3PagerPagecount(pPager, &nMax);
31585     if( rc!=SQLITE_OK ){
31586       sqlite3PagerUnref(pPg);
31587       return rc;
31588     }
31589
31590     if( nMax<(int)pgno || MEMDB || noContent ){
31591       if( pgno>pPager->mxPgno ){
31592         sqlite3PagerUnref(pPg);
31593         return SQLITE_FULL;
31594       }
31595       memset(pPg->pData, 0, pPager->pageSize);
31596       if( noContent ){
31597         pPg->flags |= PGHDR_NEED_READ;
31598       }
31599       IOTRACE(("ZERO %p %d\n", pPager, pgno));
31600     }else{
31601       rc = readDbPage(pPager, pPg, pgno);
31602       if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
31603         /* sqlite3PagerUnref(pPg); */
31604         pagerDropPage(pPg);
31605         return rc;
31606       }
31607     }
31608 #ifdef SQLITE_CHECK_PAGES
31609     pPg->pageHash = pager_pagehash(pPg);
31610 #endif
31611   }else{
31612     /* The requested page is in the page cache. */
31613     assert(sqlite3PcacheRefCount(pPager->pPCache)>0 || pgno==1);
31614     PAGER_INCR(pPager->nHit);
31615     if( !noContent ){
31616       rc = pager_get_content(pPg);
31617       if( rc ){
31618         sqlite3PagerUnref(pPg);
31619         return rc;
31620       }
31621     }
31622   }
31623
31624   *ppPage = pPg;
31625   return SQLITE_OK;
31626 }
31627
31628 /*
31629 ** Acquire a page if it is already in the in-memory cache.  Do
31630 ** not read the page from disk.  Return a pointer to the page,
31631 ** or 0 if the page is not in cache.
31632 **
31633 ** See also sqlite3PagerGet().  The difference between this routine
31634 ** and sqlite3PagerGet() is that _get() will go to the disk and read
31635 ** in the page if the page is not already in cache.  This routine
31636 ** returns NULL if the page is not in cache or if a disk I/O error 
31637 ** has ever happened.
31638 */
31639 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
31640   PgHdr *pPg = 0;
31641   assert( pPager!=0 );
31642   assert( pgno!=0 );
31643
31644   if( (pPager->state!=PAGER_UNLOCK)
31645    && (pPager->errCode==SQLITE_OK || pPager->errCode==SQLITE_FULL)
31646   ){
31647     sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
31648   }
31649
31650   return pPg;
31651 }
31652
31653 /*
31654 ** Release a page.
31655 **
31656 ** If the number of references to the page drop to zero, then the
31657 ** page is added to the LRU list.  When all references to all pages
31658 ** are released, a rollback occurs and the lock on the database is
31659 ** removed.
31660 */
31661 SQLITE_PRIVATE int sqlite3PagerUnref(DbPage *pPg){
31662   if( pPg ){
31663     Pager *pPager = pPg->pPager;
31664     sqlite3PcacheRelease(pPg);
31665     pagerUnlockIfUnused(pPager);
31666   }
31667   return SQLITE_OK;
31668 }
31669
31670 /*
31671 ** Create a journal file for pPager.  There should already be a RESERVED
31672 ** or EXCLUSIVE lock on the database file when this routine is called.
31673 **
31674 ** Return SQLITE_OK if everything.  Return an error code and release the
31675 ** write lock if anything goes wrong.
31676 */
31677 static int pager_open_journal(Pager *pPager){
31678   sqlite3_vfs *pVfs = pPager->pVfs;
31679   int flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_CREATE);
31680
31681   int rc;
31682   assert( pPager->state>=PAGER_RESERVED );
31683   assert( pPager->useJournal );
31684   assert( pPager->pInJournal==0 );
31685   sqlite3PagerPagecount(pPager, 0);
31686   pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
31687   if( pPager->pInJournal==0 ){
31688     rc = SQLITE_NOMEM;
31689     goto failed_to_open_journal;
31690   }
31691
31692   if( pPager->journalOpen==0 ){
31693     if( pPager->tempFile ){
31694       flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
31695     }else{
31696       flags |= (SQLITE_OPEN_MAIN_JOURNAL);
31697     }
31698     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
31699       sqlite3MemJournalOpen(pPager->jfd);
31700       rc = SQLITE_OK;
31701     }else{
31702 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
31703       rc = sqlite3JournalOpen(
31704           pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
31705       );
31706 #else
31707       rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
31708 #endif
31709     }
31710     assert( rc!=SQLITE_OK || pPager->jfd->pMethods );
31711     pPager->journalOff = 0;
31712     pPager->setMaster = 0;
31713     pPager->journalHdr = 0;
31714     if( rc!=SQLITE_OK ){
31715       if( rc==SQLITE_NOMEM ){
31716         sqlite3OsDelete(pVfs, pPager->zJournal, 0);
31717       }
31718       goto failed_to_open_journal;
31719     }
31720   }
31721   pPager->journalOpen = 1;
31722   pPager->journalStarted = 0;
31723   pPager->needSync = 0;
31724   pPager->nRec = 0;
31725   if( pPager->errCode ){
31726     rc = pPager->errCode;
31727     goto failed_to_open_journal;
31728   }
31729   pPager->origDbSize = pPager->dbSize;
31730
31731   rc = writeJournalHdr(pPager);
31732
31733   if( pPager->stmtAutoopen && rc==SQLITE_OK ){
31734     rc = sqlite3PagerStmtBegin(pPager);
31735   }
31736   if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && rc!=SQLITE_IOERR_NOMEM ){
31737     rc = pager_end_transaction(pPager, 0);
31738     if( rc==SQLITE_OK ){
31739       rc = SQLITE_FULL;
31740     }
31741   }
31742   return rc;
31743
31744 failed_to_open_journal:
31745   sqlite3BitvecDestroy(pPager->pInJournal);
31746   pPager->pInJournal = 0;
31747   return rc;
31748 }
31749
31750 /*
31751 ** Acquire a write-lock on the database.  The lock is removed when
31752 ** the any of the following happen:
31753 **
31754 **   *  sqlite3PagerCommitPhaseTwo() is called.
31755 **   *  sqlite3PagerRollback() is called.
31756 **   *  sqlite3PagerClose() is called.
31757 **   *  sqlite3PagerUnref() is called to on every outstanding page.
31758 **
31759 ** The first parameter to this routine is a pointer to any open page of the
31760 ** database file.  Nothing changes about the page - it is used merely to
31761 ** acquire a pointer to the Pager structure and as proof that there is
31762 ** already a read-lock on the database.
31763 **
31764 ** The second parameter indicates how much space in bytes to reserve for a
31765 ** master journal file-name at the start of the journal when it is created.
31766 **
31767 ** A journal file is opened if this is not a temporary file.  For temporary
31768 ** files, the opening of the journal file is deferred until there is an
31769 ** actual need to write to the journal.
31770 **
31771 ** If the database is already reserved for writing, this routine is a no-op.
31772 **
31773 ** If exFlag is true, go ahead and get an EXCLUSIVE lock on the file
31774 ** immediately instead of waiting until we try to flush the cache.  The
31775 ** exFlag is ignored if a transaction is already active.
31776 */
31777 SQLITE_PRIVATE int sqlite3PagerBegin(DbPage *pPg, int exFlag){
31778   Pager *pPager = pPg->pPager;
31779   int rc = SQLITE_OK;
31780   assert( pPg->nRef>0 );
31781   assert( pPager->state!=PAGER_UNLOCK );
31782   if( pPager->state==PAGER_SHARED ){
31783     assert( pPager->pInJournal==0 );
31784     assert( !MEMDB );
31785     rc = sqlite3OsLock(pPager->fd, RESERVED_LOCK);
31786     if( rc==SQLITE_OK ){
31787       pPager->state = PAGER_RESERVED;
31788       if( exFlag ){
31789         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
31790       }
31791     }
31792     if( rc!=SQLITE_OK ){
31793       return rc;
31794     }
31795     pPager->dirtyCache = 0;
31796     PAGERTRACE2("TRANSACTION %d\n", PAGERID(pPager));
31797     if( pPager->useJournal && !pPager->tempFile
31798            && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
31799       rc = pager_open_journal(pPager);
31800     }
31801   }else if( pPager->journalOpen && pPager->journalOff==0 ){
31802     /* This happens when the pager was in exclusive-access mode the last
31803     ** time a (read or write) transaction was successfully concluded
31804     ** by this connection. Instead of deleting the journal file it was 
31805     ** kept open and either was truncated to 0 bytes or its header was
31806     ** overwritten with zeros.
31807     */
31808     assert( pPager->nRec==0 );
31809     assert( pPager->origDbSize==0 );
31810     assert( pPager->pInJournal==0 );
31811     sqlite3PagerPagecount(pPager, 0);
31812     pPager->pInJournal = sqlite3BitvecCreate( pPager->dbSize );
31813     if( !pPager->pInJournal ){
31814       rc = SQLITE_NOMEM;
31815     }else{
31816       pPager->origDbSize = pPager->dbSize;
31817       rc = writeJournalHdr(pPager);
31818     }
31819   }
31820   assert( !pPager->journalOpen || pPager->journalOff>0 || rc!=SQLITE_OK );
31821   return rc;
31822 }
31823
31824 /*
31825 ** Mark a data page as writeable.  The page is written into the journal 
31826 ** if it is not there already.  This routine must be called before making
31827 ** changes to a page.
31828 **
31829 ** The first time this routine is called, the pager creates a new
31830 ** journal and acquires a RESERVED lock on the database.  If the RESERVED
31831 ** lock could not be acquired, this routine returns SQLITE_BUSY.  The
31832 ** calling routine must check for that return value and be careful not to
31833 ** change any page data until this routine returns SQLITE_OK.
31834 **
31835 ** If the journal file could not be written because the disk is full,
31836 ** then this routine returns SQLITE_FULL and does an immediate rollback.
31837 ** All subsequent write attempts also return SQLITE_FULL until there
31838 ** is a call to sqlite3PagerCommit() or sqlite3PagerRollback() to
31839 ** reset.
31840 */
31841 static int pager_write(PgHdr *pPg){
31842   void *pData = pPg->pData;
31843   Pager *pPager = pPg->pPager;
31844   int rc = SQLITE_OK;
31845
31846   /* Check for errors
31847   */
31848   if( pPager->errCode ){ 
31849     return pPager->errCode;
31850   }
31851   if( pPager->readOnly ){
31852     return SQLITE_PERM;
31853   }
31854
31855   assert( !pPager->setMaster );
31856
31857   CHECK_PAGE(pPg);
31858
31859   /* If this page was previously acquired with noContent==1, that means
31860   ** we didn't really read in the content of the page.  This can happen
31861   ** (for example) when the page is being moved to the freelist.  But
31862   ** now we are (perhaps) moving the page off of the freelist for
31863   ** reuse and we need to know its original content so that content
31864   ** can be stored in the rollback journal.  So do the read at this
31865   ** time.
31866   */
31867   rc = pager_get_content(pPg);
31868   if( rc ){
31869     return rc;
31870   }
31871
31872   /* Mark the page as dirty.  If the page has already been written
31873   ** to the journal then we can return right away.
31874   */
31875   sqlite3PcacheMakeDirty(pPg);
31876   if( pageInJournal(pPg) && (pageInStatement(pPg) || pPager->stmtInUse==0) ){
31877     pPager->dirtyCache = 1;
31878     pPager->dbModified = 1;
31879   }else{
31880
31881     /* If we get this far, it means that the page needs to be
31882     ** written to the transaction journal or the ckeckpoint journal
31883     ** or both.
31884     **
31885     ** First check to see that the transaction journal exists and
31886     ** create it if it does not.
31887     */
31888     assert( pPager->state!=PAGER_UNLOCK );
31889     rc = sqlite3PagerBegin(pPg, 0);
31890     if( rc!=SQLITE_OK ){
31891       return rc;
31892     }
31893     assert( pPager->state>=PAGER_RESERVED );
31894     if( !pPager->journalOpen && pPager->useJournal
31895           && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
31896       rc = pager_open_journal(pPager);
31897       if( rc!=SQLITE_OK ) return rc;
31898     }
31899     pPager->dirtyCache = 1;
31900     pPager->dbModified = 1;
31901   
31902     /* The transaction journal now exists and we have a RESERVED or an
31903     ** EXCLUSIVE lock on the main database file.  Write the current page to
31904     ** the transaction journal if it is not there already.
31905     */
31906     if( !pageInJournal(pPg) && pPager->journalOpen ){
31907       if( pPg->pgno<=pPager->origDbSize ){
31908         u32 cksum;
31909         char *pData2;
31910
31911         /* We should never write to the journal file the page that
31912         ** contains the database locks.  The following assert verifies
31913         ** that we do not. */
31914         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
31915         pData2 = CODEC2(pPager, pData, pPg->pgno, 7);
31916         cksum = pager_cksum(pPager, (u8*)pData2);
31917         rc = write32bits(pPager->jfd, pPager->journalOff, pPg->pgno);
31918         if( rc==SQLITE_OK ){
31919           rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize,
31920                               pPager->journalOff + 4);
31921           pPager->journalOff += pPager->pageSize+4;
31922         }
31923         if( rc==SQLITE_OK ){
31924           rc = write32bits(pPager->jfd, pPager->journalOff, cksum);
31925           pPager->journalOff += 4;
31926         }
31927         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
31928                  pPager->journalOff, pPager->pageSize));
31929         PAGER_INCR(sqlite3_pager_writej_count);
31930         PAGERTRACE5("JOURNAL %d page %d needSync=%d hash(%08x)\n",
31931              PAGERID(pPager), pPg->pgno, 
31932              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg));
31933
31934         /* An error has occured writing to the journal file. The 
31935         ** transaction will be rolled back by the layer above.
31936         */
31937         if( rc!=SQLITE_OK ){
31938           return rc;
31939         }
31940
31941         pPager->nRec++;
31942         assert( pPager->pInJournal!=0 );
31943         sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
31944         if( !pPager->noSync ){
31945           pPg->flags |= PGHDR_NEED_SYNC;
31946         }
31947         if( pPager->stmtInUse ){
31948           sqlite3BitvecSet(pPager->pInStmt, pPg->pgno);
31949         }
31950       }else{
31951         if( !pPager->journalStarted && !pPager->noSync ){
31952           pPg->flags |= PGHDR_NEED_SYNC;
31953         }
31954         PAGERTRACE4("APPEND %d page %d needSync=%d\n",
31955                 PAGERID(pPager), pPg->pgno,
31956                ((pPg->flags&PGHDR_NEED_SYNC)?1:0));
31957       }
31958       if( pPg->flags&PGHDR_NEED_SYNC ){
31959         pPager->needSync = 1;
31960       }
31961     }
31962   
31963     /* If the statement journal is open and the page is not in it,
31964     ** then write the current page to the statement journal.  Note that
31965     ** the statement journal format differs from the standard journal format
31966     ** in that it omits the checksums and the header.
31967     */
31968     if( pPager->stmtInUse 
31969      && !pageInStatement(pPg) 
31970      && pPg->pgno<=pPager->stmtSize 
31971     ){
31972       i64 offset = pPager->stmtNRec*(4+pPager->pageSize);
31973       char *pData2 = CODEC2(pPager, pData, pPg->pgno, 7);
31974       assert( pageInJournal(pPg) || pPg->pgno>pPager->origDbSize );
31975       rc = write32bits(pPager->stfd, offset, pPg->pgno);
31976       if( rc==SQLITE_OK ){
31977         rc = sqlite3OsWrite(pPager->stfd, pData2, pPager->pageSize, offset+4);
31978       }
31979       PAGERTRACE3("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno);
31980       if( rc!=SQLITE_OK ){
31981         return rc;
31982       }
31983       pPager->stmtNRec++;
31984       assert( pPager->pInStmt!=0 );
31985       sqlite3BitvecSet(pPager->pInStmt, pPg->pgno);
31986     }
31987   }
31988
31989   /* Update the database size and return.
31990   */
31991   assert( pPager->state>=PAGER_SHARED );
31992   if( pPager->dbSize<pPg->pgno ){
31993     pPager->dbSize = pPg->pgno;
31994     if( pPager->dbSize==(PAGER_MJ_PGNO(pPager)-1) ){
31995       pPager->dbSize++;
31996     }
31997   }
31998   return rc;
31999 }
32000
32001 /*
32002 ** This function is used to mark a data-page as writable. It uses 
32003 ** pager_write() to open a journal file (if it is not already open)
32004 ** and write the page *pData to the journal.
32005 **
32006 ** The difference between this function and pager_write() is that this
32007 ** function also deals with the special case where 2 or more pages
32008 ** fit on a single disk sector. In this case all co-resident pages
32009 ** must have been written to the journal file before returning.
32010 */
32011 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
32012   int rc = SQLITE_OK;
32013
32014   PgHdr *pPg = pDbPage;
32015   Pager *pPager = pPg->pPager;
32016   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
32017
32018   if( nPagePerSector>1 ){
32019     Pgno nPageCount;          /* Total number of pages in database file */
32020     Pgno pg1;                 /* First page of the sector pPg is located on. */
32021     int nPage;                /* Number of pages starting at pg1 to journal */
32022     int ii;
32023     int needSync = 0;
32024
32025     /* Set the doNotSync flag to 1. This is because we cannot allow a journal
32026     ** header to be written between the pages journaled by this function.
32027     */
32028     assert( !MEMDB );
32029     assert( pPager->doNotSync==0 );
32030     pPager->doNotSync = 1;
32031
32032     /* This trick assumes that both the page-size and sector-size are
32033     ** an integer power of 2. It sets variable pg1 to the identifier
32034     ** of the first page of the sector pPg is located on.
32035     */
32036     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
32037
32038     sqlite3PagerPagecount(pPager, (int *)&nPageCount);
32039     if( pPg->pgno>nPageCount ){
32040       nPage = (pPg->pgno - pg1)+1;
32041     }else if( (pg1+nPagePerSector-1)>nPageCount ){
32042       nPage = nPageCount+1-pg1;
32043     }else{
32044       nPage = nPagePerSector;
32045     }
32046     assert(nPage>0);
32047     assert(pg1<=pPg->pgno);
32048     assert((pg1+nPage)>pPg->pgno);
32049
32050     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
32051       Pgno pg = pg1+ii;
32052       PgHdr *pPage;
32053       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
32054         if( pg!=PAGER_MJ_PGNO(pPager) ){
32055           rc = sqlite3PagerGet(pPager, pg, &pPage);
32056           if( rc==SQLITE_OK ){
32057             rc = pager_write(pPage);
32058             if( pPage->flags&PGHDR_NEED_SYNC ){
32059               needSync = 1;
32060             }
32061             sqlite3PagerUnref(pPage);
32062           }
32063         }
32064       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
32065         if( pPage->flags&PGHDR_NEED_SYNC ){
32066           needSync = 1;
32067         }
32068         sqlite3PagerUnref(pPage);
32069       }
32070     }
32071
32072     /* If the PgHdr.needSync flag is set for any of the nPage pages 
32073     ** starting at pg1, then it needs to be set for all of them. Because
32074     ** writing to any of these nPage pages may damage the others, the
32075     ** journal file must contain sync()ed copies of all of them
32076     ** before any of them can be written out to the database file.
32077     */
32078     if( needSync ){
32079       assert( !MEMDB && pPager->noSync==0 );
32080       for(ii=0; ii<nPage && needSync; ii++){
32081         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
32082         if( pPage ) pPage->flags |= PGHDR_NEED_SYNC;
32083         sqlite3PagerUnref(pPage);
32084       }
32085       assert(pPager->needSync);
32086     }
32087
32088     assert( pPager->doNotSync==1 );
32089     pPager->doNotSync = 0;
32090   }else{
32091     rc = pager_write(pDbPage);
32092   }
32093   return rc;
32094 }
32095
32096 /*
32097 ** Return TRUE if the page given in the argument was previously passed
32098 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
32099 ** to change the content of the page.
32100 */
32101 #ifndef NDEBUG
32102 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
32103   return pPg->flags&PGHDR_DIRTY;
32104 }
32105 #endif
32106
32107 /*
32108 ** A call to this routine tells the pager that it is not necessary to
32109 ** write the information on page pPg back to the disk, even though
32110 ** that page might be marked as dirty.  This happens, for example, when
32111 ** the page has been added as a leaf of the freelist and so its
32112 ** content no longer matters.
32113 **
32114 ** The overlying software layer calls this routine when all of the data
32115 ** on the given page is unused.  The pager marks the page as clean so
32116 ** that it does not get written to disk.
32117 **
32118 ** Tests show that this optimization, together with the
32119 ** sqlite3PagerDontRollback() below, more than double the speed
32120 ** of large INSERT operations and quadruple the speed of large DELETEs.
32121 **
32122 ** When this routine is called, set the alwaysRollback flag to true.
32123 ** Subsequent calls to sqlite3PagerDontRollback() for the same page
32124 ** will thereafter be ignored.  This is necessary to avoid a problem
32125 ** where a page with data is added to the freelist during one part of
32126 ** a transaction then removed from the freelist during a later part
32127 ** of the same transaction and reused for some other purpose.  When it
32128 ** is first added to the freelist, this routine is called.  When reused,
32129 ** the sqlite3PagerDontRollback() routine is called.  But because the
32130 ** page contains critical data, we still need to be sure it gets
32131 ** rolled back in spite of the sqlite3PagerDontRollback() call.
32132 */
32133 SQLITE_PRIVATE int sqlite3PagerDontWrite(DbPage *pDbPage){
32134   PgHdr *pPg = pDbPage;
32135   Pager *pPager = pPg->pPager;
32136   int rc;
32137
32138   if( pPg->pgno>pPager->origDbSize ){
32139     return SQLITE_OK;
32140   }
32141   if( pPager->pAlwaysRollback==0 ){
32142     assert( pPager->pInJournal );
32143     pPager->pAlwaysRollback = sqlite3BitvecCreate(pPager->origDbSize);
32144     if( !pPager->pAlwaysRollback ){
32145       return SQLITE_NOMEM;
32146     }
32147   }
32148   rc = sqlite3BitvecSet(pPager->pAlwaysRollback, pPg->pgno);
32149
32150   if( rc==SQLITE_OK && (pPg->flags&PGHDR_DIRTY) && !pPager->stmtInUse ){
32151     assert( pPager->state>=PAGER_SHARED );
32152     if( pPager->dbSize==pPg->pgno && pPager->origDbSize<pPager->dbSize ){
32153       /* If this pages is the last page in the file and the file has grown
32154       ** during the current transaction, then do NOT mark the page as clean.
32155       ** When the database file grows, we must make sure that the last page
32156       ** gets written at least once so that the disk file will be the correct
32157       ** size. If you do not write this page and the size of the file
32158       ** on the disk ends up being too small, that can lead to database
32159       ** corruption during the next transaction.
32160       */
32161     }else{
32162       PAGERTRACE3("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager));
32163       IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
32164       pPg->flags |= PGHDR_DONT_WRITE;
32165 #ifdef SQLITE_CHECK_PAGES
32166       pPg->pageHash = pager_pagehash(pPg);
32167 #endif
32168     }
32169   }
32170   return rc;
32171 }
32172
32173 /*
32174 ** A call to this routine tells the pager that if a rollback occurs,
32175 ** it is not necessary to restore the data on the given page.  This
32176 ** means that the pager does not have to record the given page in the
32177 ** rollback journal.
32178 **
32179 ** If we have not yet actually read the content of this page (if
32180 ** the PgHdr.needRead flag is set) then this routine acts as a promise
32181 ** that we will never need to read the page content in the future.
32182 ** so the needRead flag can be cleared at this point.
32183 */
32184 SQLITE_PRIVATE void sqlite3PagerDontRollback(DbPage *pPg){
32185   Pager *pPager = pPg->pPager;
32186
32187   assert( pPager->state>=PAGER_RESERVED );
32188
32189   /* If the journal file is not open, or DontWrite() has been called on
32190   ** this page (DontWrite() sets the alwaysRollback flag), then this
32191   ** function is a no-op.
32192   */
32193   if( pPager->journalOpen==0 
32194    || sqlite3BitvecTest(pPager->pAlwaysRollback, pPg->pgno)
32195    || pPg->pgno>pPager->origDbSize
32196   ){
32197     return;
32198   }
32199
32200 #ifdef SQLITE_SECURE_DELETE
32201   if( sqlite3BitvecTest(pPager->pInJournal, pPg->pgno)!=0
32202    || pPg->pgno>pPager->origDbSize ){
32203     return;
32204   }
32205 #endif
32206
32207   /* If SECURE_DELETE is disabled, then there is no way that this
32208   ** routine can be called on a page for which sqlite3PagerDontWrite()
32209   ** has not been previously called during the same transaction.
32210   ** And if DontWrite() has previously been called, the following
32211   ** conditions must be met.
32212   **
32213   ** (Later:)  Not true.  If the database is corrupted by having duplicate
32214   ** pages on the freelist (ex: corrupt9.test) then the following is not
32215   ** necessarily true:
32216   */
32217   /* assert( !pPg->inJournal && (int)pPg->pgno <= pPager->origDbSize ); */
32218
32219   assert( pPager->pInJournal!=0 );
32220   sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
32221   pPg->flags &= ~PGHDR_NEED_READ;
32222   if( pPager->stmtInUse ){
32223     assert( pPager->stmtSize >= pPager->origDbSize );
32224     sqlite3BitvecSet(pPager->pInStmt, pPg->pgno);
32225   }
32226   PAGERTRACE3("DONT_ROLLBACK page %d of %d\n", pPg->pgno, PAGERID(pPager));
32227   IOTRACE(("GARBAGE %p %d\n", pPager, pPg->pgno))
32228 }
32229
32230
32231 /*
32232 ** This routine is called to increment the database file change-counter,
32233 ** stored at byte 24 of the pager file.
32234 */
32235 static int pager_incr_changecounter(Pager *pPager, int isDirect){
32236   PgHdr *pPgHdr;
32237   u32 change_counter;
32238   int rc = SQLITE_OK;
32239
32240 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
32241   assert( isDirect==0 );  /* isDirect is only true for atomic writes */
32242 #endif
32243   if( !pPager->changeCountDone ){
32244     /* Open page 1 of the file for writing. */
32245     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
32246     if( rc!=SQLITE_OK ) return rc;
32247
32248     if( !isDirect ){
32249       rc = sqlite3PagerWrite(pPgHdr);
32250       if( rc!=SQLITE_OK ){
32251         sqlite3PagerUnref(pPgHdr);
32252         return rc;
32253       }
32254     }
32255
32256     /* Increment the value just read and write it back to byte 24. */
32257     change_counter = sqlite3Get4byte((u8*)pPager->dbFileVers);
32258     change_counter++;
32259     put32bits(((char*)pPgHdr->pData)+24, change_counter);
32260
32261 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
32262     if( isDirect && pPager->fd->pMethods ){
32263       const void *zBuf = pPgHdr->pData;
32264       rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
32265     }
32266 #endif
32267
32268     /* Release the page reference. */
32269     sqlite3PagerUnref(pPgHdr);
32270     pPager->changeCountDone = 1;
32271   }
32272   return rc;
32273 }
32274
32275 /*
32276 ** Sync the pager file to disk.
32277 */
32278 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
32279   int rc;
32280   if( MEMDB ){
32281     rc = SQLITE_OK;
32282   }else{
32283     rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
32284   }
32285   return rc;
32286 }
32287
32288 /*
32289 ** Sync the database file for the pager pPager. zMaster points to the name
32290 ** of a master journal file that should be written into the individual
32291 ** journal file. zMaster may be NULL, which is interpreted as no master
32292 ** journal (a single database transaction).
32293 **
32294 ** This routine ensures that the journal is synced, all dirty pages written
32295 ** to the database file and the database file synced. The only thing that
32296 ** remains to commit the transaction is to delete the journal file (or
32297 ** master journal file if specified).
32298 **
32299 ** Note that if zMaster==NULL, this does not overwrite a previous value
32300 ** passed to an sqlite3PagerCommitPhaseOne() call.
32301 **
32302 ** If parameter nTrunc is non-zero, then the pager file is truncated to
32303 ** nTrunc pages (this is used by auto-vacuum databases).
32304 **
32305 ** If the final parameter - noSync - is true, then the database file itself
32306 ** is not synced. The caller must call sqlite3PagerSync() directly to
32307 ** sync the database file before calling CommitPhaseTwo() to delete the
32308 ** journal file in this case.
32309 */
32310 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
32311   Pager *pPager, 
32312   const char *zMaster, 
32313   Pgno nTrunc,
32314   int noSync
32315 ){
32316   int rc = SQLITE_OK;
32317
32318   if( pPager->errCode ){
32319     return pPager->errCode;
32320   }
32321
32322   /* If no changes have been made, we can leave the transaction early.
32323   */
32324   if( pPager->dbModified==0 &&
32325         (pPager->journalMode!=PAGER_JOURNALMODE_DELETE ||
32326           pPager->exclusiveMode!=0) ){
32327     assert( pPager->dirtyCache==0 || pPager->journalOpen==0 );
32328     return SQLITE_OK;
32329   }
32330
32331   PAGERTRACE4("DATABASE SYNC: File=%s zMaster=%s nTrunc=%d\n", 
32332       pPager->zFilename, zMaster, nTrunc);
32333
32334   /* If this is an in-memory db, or no pages have been written to, or this
32335   ** function has already been called, it is a no-op.
32336   */
32337   if( pPager->state!=PAGER_SYNCED && !MEMDB && pPager->dirtyCache ){
32338     PgHdr *pPg;
32339
32340 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
32341     /* The atomic-write optimization can be used if all of the
32342     ** following are true:
32343     **
32344     **    + The file-system supports the atomic-write property for
32345     **      blocks of size page-size, and
32346     **    + This commit is not part of a multi-file transaction, and
32347     **    + Exactly one page has been modified and store in the journal file.
32348     **
32349     ** If the optimization can be used, then the journal file will never
32350     ** be created for this transaction.
32351     */
32352     int useAtomicWrite;
32353     pPg = sqlite3PcacheDirtyList(pPager->pPCache);
32354     useAtomicWrite = (
32355         !zMaster && 
32356         pPager->journalOpen &&
32357         pPager->journalOff==jrnlBufferSize(pPager) && 
32358         nTrunc==0 && 
32359         (pPg==0 || pPg->pDirty==0)
32360     );
32361     assert( pPager->journalOpen || pPager->journalMode==PAGER_JOURNALMODE_OFF );
32362     if( useAtomicWrite ){
32363       /* Update the nRec field in the journal file. */
32364       int offset = pPager->journalHdr + sizeof(aJournalMagic);
32365       assert(pPager->nRec==1);
32366       rc = write32bits(pPager->jfd, offset, pPager->nRec);
32367
32368       /* Update the db file change counter. The following call will modify
32369       ** the in-memory representation of page 1 to include the updated
32370       ** change counter and then write page 1 directly to the database
32371       ** file. Because of the atomic-write property of the host file-system, 
32372       ** this is safe.
32373       */
32374       if( rc==SQLITE_OK ){
32375         rc = pager_incr_changecounter(pPager, 1);
32376       }
32377     }else{
32378       rc = sqlite3JournalCreate(pPager->jfd);
32379     }
32380
32381     if( !useAtomicWrite && rc==SQLITE_OK )
32382 #endif
32383
32384     /* If a master journal file name has already been written to the
32385     ** journal file, then no sync is required. This happens when it is
32386     ** written, then the process fails to upgrade from a RESERVED to an
32387     ** EXCLUSIVE lock. The next time the process tries to commit the
32388     ** transaction the m-j name will have already been written.
32389     */
32390     if( !pPager->setMaster ){
32391       rc = pager_incr_changecounter(pPager, 0);
32392       if( rc!=SQLITE_OK ) goto sync_exit;
32393       if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
32394 #ifndef SQLITE_OMIT_AUTOVACUUM
32395         if( nTrunc!=0 ){
32396           /* If this transaction has made the database smaller, then all pages
32397           ** being discarded by the truncation must be written to the journal
32398           ** file.
32399           */
32400           Pgno i;
32401           Pgno iSkip = PAGER_MJ_PGNO(pPager);
32402           for( i=nTrunc+1; i<=pPager->origDbSize; i++ ){
32403             if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
32404               rc = sqlite3PagerGet(pPager, i, &pPg);
32405               if( rc!=SQLITE_OK ) goto sync_exit;
32406               rc = sqlite3PagerWrite(pPg);
32407               sqlite3PagerUnref(pPg);
32408               if( rc!=SQLITE_OK ) goto sync_exit;
32409             }
32410           } 
32411         }
32412 #endif
32413         rc = writeMasterJournal(pPager, zMaster);
32414         if( rc!=SQLITE_OK ) goto sync_exit;
32415         rc = syncJournal(pPager);
32416       }
32417     }
32418     if( rc!=SQLITE_OK ) goto sync_exit;
32419
32420 #ifndef SQLITE_OMIT_AUTOVACUUM
32421     if( nTrunc!=0 ){
32422       rc = sqlite3PagerTruncate(pPager, nTrunc);
32423       if( rc!=SQLITE_OK ) goto sync_exit;
32424     }
32425 #endif
32426
32427     /* Write all dirty pages to the database file */
32428     pPg = sqlite3PcacheDirtyList(pPager->pPCache);
32429     rc = pager_write_pagelist(pPg);
32430     if( rc!=SQLITE_OK ){
32431       assert( rc!=SQLITE_IOERR_BLOCKED );
32432       /* The error might have left the dirty list all fouled up here,
32433       ** but that does not matter because if the if the dirty list did
32434       ** get corrupted, then the transaction will roll back and
32435       ** discard the dirty list.  There is an assert in
32436       ** pager_get_all_dirty_pages() that verifies that no attempt
32437       ** is made to use an invalid dirty list.
32438       */
32439       goto sync_exit;
32440     }
32441     sqlite3PcacheCleanAll(pPager->pPCache);
32442
32443     /* Sync the database file. */
32444     if( !pPager->noSync && !noSync ){
32445       rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
32446     }
32447     IOTRACE(("DBSYNC %p\n", pPager))
32448
32449     pPager->state = PAGER_SYNCED;
32450   }else if( MEMDB && nTrunc!=0 ){
32451     rc = sqlite3PagerTruncate(pPager, nTrunc);
32452   }
32453
32454 sync_exit:
32455   if( rc==SQLITE_IOERR_BLOCKED ){
32456     /* pager_incr_changecounter() may attempt to obtain an exclusive
32457      * lock to spill the cache and return IOERR_BLOCKED. But since 
32458      * there is no chance the cache is inconsistent, it is
32459      * better to return SQLITE_BUSY.
32460      */
32461     rc = SQLITE_BUSY;
32462   }
32463   return rc;
32464 }
32465
32466
32467 /*
32468 ** Commit all changes to the database and release the write lock.
32469 **
32470 ** If the commit fails for any reason, a rollback attempt is made
32471 ** and an error code is returned.  If the commit worked, SQLITE_OK
32472 ** is returned.
32473 */
32474 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
32475   int rc = SQLITE_OK;
32476
32477   if( pPager->errCode ){
32478     return pPager->errCode;
32479   }
32480   if( pPager->state<PAGER_RESERVED ){
32481     return SQLITE_ERROR;
32482   }
32483   if( pPager->dbModified==0 &&
32484         (pPager->journalMode!=PAGER_JOURNALMODE_DELETE ||
32485           pPager->exclusiveMode!=0) ){
32486     assert( pPager->dirtyCache==0 || pPager->journalOpen==0 );
32487     return SQLITE_OK;
32488   }
32489   PAGERTRACE2("COMMIT %d\n", PAGERID(pPager));
32490   assert( pPager->state==PAGER_SYNCED || MEMDB || !pPager->dirtyCache );
32491   rc = pager_end_transaction(pPager, pPager->setMaster);
32492   rc = pager_error(pPager, rc);
32493   return rc;
32494 }
32495
32496 /*
32497 ** Rollback all changes.  The database falls back to PAGER_SHARED mode.
32498 ** All in-memory cache pages revert to their original data contents.
32499 ** The journal is deleted.
32500 **
32501 ** This routine cannot fail unless some other process is not following
32502 ** the correct locking protocol or unless some other
32503 ** process is writing trash into the journal file (SQLITE_CORRUPT) or
32504 ** unless a prior malloc() failed (SQLITE_NOMEM).  Appropriate error
32505 ** codes are returned for all these occasions.  Otherwise,
32506 ** SQLITE_OK is returned.
32507 */
32508 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
32509   int rc = SQLITE_OK;
32510   PAGERTRACE2("ROLLBACK %d\n", PAGERID(pPager));
32511   if( !pPager->dirtyCache || !pPager->journalOpen ){
32512     rc = pager_end_transaction(pPager, pPager->setMaster);
32513   }else if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
32514     if( pPager->state>=PAGER_EXCLUSIVE ){
32515       pager_playback(pPager, 0);
32516     }
32517     rc = pPager->errCode;
32518   }else{
32519     if( pPager->state==PAGER_RESERVED ){
32520       int rc2;
32521       rc = pager_playback(pPager, 0);
32522       rc2 = pager_end_transaction(pPager, pPager->setMaster);
32523       if( rc==SQLITE_OK ){
32524         rc = rc2;
32525       }
32526     }else{
32527       rc = pager_playback(pPager, 0);
32528     }
32529
32530     if( !MEMDB ){
32531       pPager->dbSizeValid = 0;
32532     }
32533
32534     /* If an error occurs during a ROLLBACK, we can no longer trust the pager
32535     ** cache. So call pager_error() on the way out to make any error 
32536     ** persistent.
32537     */
32538     rc = pager_error(pPager, rc);
32539   }
32540   return rc;
32541 }
32542
32543 /*
32544 ** Return TRUE if the database file is opened read-only.  Return FALSE
32545 ** if the database is (in theory) writable.
32546 */
32547 SQLITE_PRIVATE int sqlite3PagerIsreadonly(Pager *pPager){
32548   return pPager->readOnly;
32549 }
32550
32551 /*
32552 ** Return the number of references to the pager.
32553 */
32554 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
32555   return sqlite3PcacheRefCount(pPager->pPCache);
32556 }
32557
32558 /*
32559 ** Return the number of references to the specified page.
32560 */
32561 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
32562   return sqlite3PcachePageRefcount(pPage);
32563 }
32564
32565 #ifdef SQLITE_TEST
32566 /*
32567 ** This routine is used for testing and analysis only.
32568 */
32569 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
32570   static int a[11];
32571   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
32572   a[1] = sqlite3PcachePagecount(pPager->pPCache);
32573   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
32574   a[3] = pPager->dbSizeValid ? (int) pPager->dbSize : -1;
32575   a[4] = pPager->state;
32576   a[5] = pPager->errCode;
32577   a[6] = pPager->nHit;
32578   a[7] = pPager->nMiss;
32579   a[8] = 0;  /* Used to be pPager->nOvfl */
32580   a[9] = pPager->nRead;
32581   a[10] = pPager->nWrite;
32582   return a;
32583 }
32584 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
32585   return MEMDB;
32586 }
32587 #endif
32588
32589 /*
32590 ** Set the statement rollback point.
32591 **
32592 ** This routine should be called with the transaction journal already
32593 ** open.  A new statement journal is created that can be used to rollback
32594 ** changes of a single SQL command within a larger transaction.
32595 */
32596 static int pagerStmtBegin(Pager *pPager){
32597   int rc;
32598   assert( !pPager->stmtInUse );
32599   assert( pPager->state>=PAGER_SHARED );
32600   assert( pPager->dbSizeValid );
32601   PAGERTRACE2("STMT-BEGIN %d\n", PAGERID(pPager));
32602   if( !pPager->journalOpen ){
32603     pPager->stmtAutoopen = 1;
32604     return SQLITE_OK;
32605   }
32606   assert( pPager->journalOpen );
32607   assert( pPager->pInStmt==0 );
32608   pPager->pInStmt = sqlite3BitvecCreate(pPager->dbSize);
32609   if( pPager->pInStmt==0 ){
32610     /* sqlite3OsLock(pPager->fd, SHARED_LOCK); */
32611     return SQLITE_NOMEM;
32612   }
32613   pPager->stmtJSize = pPager->journalOff;
32614   pPager->stmtSize = pPager->dbSize;
32615   pPager->stmtHdrOff = 0;
32616   pPager->stmtCksum = pPager->cksumInit;
32617   if( !pPager->stmtOpen ){
32618     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
32619       sqlite3MemJournalOpen(pPager->stfd);
32620     }else{
32621       rc = sqlite3PagerOpentemp(pPager, pPager->stfd, SQLITE_OPEN_SUBJOURNAL);
32622       if( rc ){
32623         goto stmt_begin_failed;
32624       }
32625     }
32626     pPager->stmtOpen = 1;
32627     pPager->stmtNRec = 0;
32628   }
32629   pPager->stmtInUse = 1;
32630   return SQLITE_OK;
32631  
32632 stmt_begin_failed:
32633   if( pPager->pInStmt ){
32634     sqlite3BitvecDestroy(pPager->pInStmt);
32635     pPager->pInStmt = 0;
32636   }
32637   return rc;
32638 }
32639 SQLITE_PRIVATE int sqlite3PagerStmtBegin(Pager *pPager){
32640   int rc;
32641   rc = pagerStmtBegin(pPager);
32642   return rc;
32643 }
32644
32645 /*
32646 ** Commit a statement.
32647 */
32648 SQLITE_PRIVATE int sqlite3PagerStmtCommit(Pager *pPager){
32649   if( pPager->stmtInUse ){
32650     PAGERTRACE2("STMT-COMMIT %d\n", PAGERID(pPager));
32651     sqlite3BitvecDestroy(pPager->pInStmt);
32652     pPager->pInStmt = 0;
32653     pPager->stmtNRec = 0;
32654     pPager->stmtInUse = 0;
32655     if( sqlite3IsMemJournal(pPager->stfd) ){
32656       sqlite3OsTruncate(pPager->stfd, 0);
32657     }
32658   }
32659   pPager->stmtAutoopen = 0;
32660   return SQLITE_OK;
32661 }
32662
32663 /*
32664 ** Rollback a statement.
32665 */
32666 SQLITE_PRIVATE int sqlite3PagerStmtRollback(Pager *pPager){
32667   int rc;
32668   if( pPager->stmtInUse ){
32669     PAGERTRACE2("STMT-ROLLBACK %d\n", PAGERID(pPager));
32670     rc = pager_stmt_playback(pPager);
32671     sqlite3PagerStmtCommit(pPager);
32672   }else{
32673     rc = SQLITE_OK;
32674   }
32675   pPager->stmtAutoopen = 0;
32676   return rc;
32677 }
32678
32679 /*
32680 ** Return the full pathname of the database file.
32681 */
32682 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
32683   return pPager->zFilename;
32684 }
32685
32686 /*
32687 ** Return the VFS structure for the pager.
32688 */
32689 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
32690   return pPager->pVfs;
32691 }
32692
32693 /*
32694 ** Return the file handle for the database file associated
32695 ** with the pager.  This might return NULL if the file has
32696 ** not yet been opened.
32697 */
32698 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
32699   return pPager->fd;
32700 }
32701
32702 /*
32703 ** Return the directory of the database file.
32704 */
32705 SQLITE_PRIVATE const char *sqlite3PagerDirname(Pager *pPager){
32706   return pPager->zDirectory;
32707 }
32708
32709 /*
32710 ** Return the full pathname of the journal file.
32711 */
32712 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
32713   return pPager->zJournal;
32714 }
32715
32716 /*
32717 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
32718 ** if fsync()s are executed normally.
32719 */
32720 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
32721   return pPager->noSync;
32722 }
32723
32724 #ifdef SQLITE_HAS_CODEC
32725 /*
32726 ** Set the codec for this pager
32727 */
32728 SQLITE_PRIVATE void sqlite3PagerSetCodec(
32729   Pager *pPager,
32730   void *(*xCodec)(void*,void*,Pgno,int),
32731   void *pCodecArg
32732 ){
32733   pPager->xCodec = xCodec;
32734   pPager->pCodecArg = pCodecArg;
32735 }
32736 #endif
32737
32738 #ifndef SQLITE_OMIT_AUTOVACUUM
32739 /*
32740 ** Move the page pPg to location pgno in the file.
32741 **
32742 ** There must be no references to the page previously located at
32743 ** pgno (which we call pPgOld) though that page is allowed to be
32744 ** in cache.  If the page previously located at pgno is not already
32745 ** in the rollback journal, it is not put there by by this routine.
32746 **
32747 ** References to the page pPg remain valid. Updating any
32748 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
32749 ** allocated along with the page) is the responsibility of the caller.
32750 **
32751 ** A transaction must be active when this routine is called. It used to be
32752 ** required that a statement transaction was not active, but this restriction
32753 ** has been removed (CREATE INDEX needs to move a page when a statement
32754 ** transaction is active).
32755 **
32756 ** If the fourth argument, isCommit, is non-zero, then this page is being
32757 ** moved as part of a database reorganization just before the transaction 
32758 ** is being committed. In this case, it is guaranteed that the database page 
32759 ** pPg refers to will not be written to again within this transaction.
32760 */
32761 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
32762   PgHdr *pPgOld;  /* The page being overwritten. */
32763   Pgno needSyncPgno = 0;
32764
32765   assert( pPg->nRef>0 );
32766
32767   PAGERTRACE5("MOVE %d page %d (needSync=%d) moves to %d\n", 
32768       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno);
32769   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
32770
32771   pager_get_content(pPg);
32772
32773   /* If the journal needs to be sync()ed before page pPg->pgno can
32774   ** be written to, store pPg->pgno in local variable needSyncPgno.
32775   **
32776   ** If the isCommit flag is set, there is no need to remember that
32777   ** the journal needs to be sync()ed before database page pPg->pgno 
32778   ** can be written to. The caller has already promised not to write to it.
32779   */
32780   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
32781     needSyncPgno = pPg->pgno;
32782     assert( pageInJournal(pPg) || pPg->pgno>pPager->origDbSize );
32783     assert( pPg->flags&PGHDR_DIRTY );
32784     assert( pPager->needSync );
32785   }
32786
32787   /* If the cache contains a page with page-number pgno, remove it
32788   ** from its hash chain. Also, if the PgHdr.needSync was set for 
32789   ** page pgno before the 'move' operation, it needs to be retained 
32790   ** for the page moved there.
32791   */
32792   pPg->flags &= ~PGHDR_NEED_SYNC;
32793   pPgOld = pager_lookup(pPager, pgno);
32794   assert( !pPgOld || pPgOld->nRef==1 );
32795   if( pPgOld ){
32796     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
32797   }
32798
32799   sqlite3PcacheMove(pPg, pgno);
32800   if( pPgOld ){
32801     sqlite3PcacheDrop(pPgOld);
32802   }
32803
32804   sqlite3PcacheMakeDirty(pPg);
32805   pPager->dirtyCache = 1;
32806   pPager->dbModified = 1;
32807
32808   if( needSyncPgno ){
32809     /* If needSyncPgno is non-zero, then the journal file needs to be 
32810     ** sync()ed before any data is written to database file page needSyncPgno.
32811     ** Currently, no such page exists in the page-cache and the 
32812     ** "is journaled" bitvec flag has been set. This needs to be remedied by
32813     ** loading the page into the pager-cache and setting the PgHdr.needSync 
32814     ** flag.
32815     **
32816     ** If the attempt to load the page into the page-cache fails, (due
32817     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
32818     ** array. Otherwise, if the page is loaded and written again in
32819     ** this transaction, it may be written to the database file before
32820     ** it is synced into the journal file. This way, it may end up in
32821     ** the journal file twice, but that is not a problem.
32822     **
32823     ** The sqlite3PagerGet() call may cause the journal to sync. So make
32824     ** sure the Pager.needSync flag is set too.
32825     */
32826     int rc;
32827     PgHdr *pPgHdr;
32828     assert( pPager->needSync );
32829     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
32830     if( rc!=SQLITE_OK ){
32831       if( pPager->pInJournal && needSyncPgno<=pPager->origDbSize ){
32832         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno);
32833       }
32834       return rc;
32835     }
32836     pPager->needSync = 1;
32837     assert( pPager->noSync==0 && !MEMDB );
32838     pPgHdr->flags |= PGHDR_NEED_SYNC;
32839     sqlite3PcacheMakeDirty(pPgHdr);
32840     sqlite3PagerUnref(pPgHdr);
32841   }
32842
32843   return SQLITE_OK;
32844 }
32845 #endif
32846
32847 /*
32848 ** Return a pointer to the data for the specified page.
32849 */
32850 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
32851   assert( pPg->nRef>0 || pPg->pPager->memDb );
32852   return pPg->pData;
32853 }
32854
32855 /*
32856 ** Return a pointer to the Pager.nExtra bytes of "extra" space 
32857 ** allocated along with the specified page.
32858 */
32859 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
32860   Pager *pPager = pPg->pPager;
32861   return (pPager?pPg->pExtra:0);
32862 }
32863
32864 /*
32865 ** Get/set the locking-mode for this pager. Parameter eMode must be one
32866 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
32867 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
32868 ** the locking-mode is set to the value specified.
32869 **
32870 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
32871 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
32872 ** locking-mode.
32873 */
32874 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
32875   assert( eMode==PAGER_LOCKINGMODE_QUERY
32876             || eMode==PAGER_LOCKINGMODE_NORMAL
32877             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
32878   assert( PAGER_LOCKINGMODE_QUERY<0 );
32879   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
32880   if( eMode>=0 && !pPager->tempFile ){
32881     pPager->exclusiveMode = eMode;
32882   }
32883   return (int)pPager->exclusiveMode;
32884 }
32885
32886 /*
32887 ** Get/set the journal-mode for this pager. Parameter eMode must be one of:
32888 **
32889 **    PAGER_JOURNALMODE_QUERY
32890 **    PAGER_JOURNALMODE_DELETE
32891 **    PAGER_JOURNALMODE_TRUNCATE
32892 **    PAGER_JOURNALMODE_PERSIST
32893 **    PAGER_JOURNALMODE_OFF
32894 **
32895 ** If the parameter is not _QUERY, then the journal-mode is set to the
32896 ** value specified.
32897 **
32898 ** The returned indicate the current (possibly updated)
32899 ** journal-mode.
32900 */
32901 SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *pPager, int eMode){
32902   if( !MEMDB ){
32903     assert( eMode==PAGER_JOURNALMODE_QUERY
32904               || eMode==PAGER_JOURNALMODE_DELETE
32905               || eMode==PAGER_JOURNALMODE_TRUNCATE
32906               || eMode==PAGER_JOURNALMODE_PERSIST
32907               || eMode==PAGER_JOURNALMODE_OFF 
32908               || eMode==PAGER_JOURNALMODE_MEMORY );
32909     assert( PAGER_JOURNALMODE_QUERY<0 );
32910     if( eMode>=0 ){
32911       pPager->journalMode = eMode;
32912     }else{
32913       assert( eMode==PAGER_JOURNALMODE_QUERY );
32914     }
32915   }
32916   return (int)pPager->journalMode;
32917 }
32918
32919 /*
32920 ** Get/set the size-limit used for persistent journal files.
32921 */
32922 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
32923   if( iLimit>=-1 ){
32924     pPager->journalSizeLimit = iLimit;
32925   }
32926   return pPager->journalSizeLimit;
32927 }
32928
32929 #endif /* SQLITE_OMIT_DISKIO */
32930
32931 /************** End of pager.c ***********************************************/
32932 /************** Begin file btmutex.c *****************************************/
32933 /*
32934 ** 2007 August 27
32935 **
32936 ** The author disclaims copyright to this source code.  In place of
32937 ** a legal notice, here is a blessing:
32938 **
32939 **    May you do good and not evil.
32940 **    May you find forgiveness for yourself and forgive others.
32941 **    May you share freely, never taking more than you give.
32942 **
32943 *************************************************************************
32944 **
32945 ** $Id: btmutex.c,v 1.12 2008/11/17 19:18:55 danielk1977 Exp $
32946 **
32947 ** This file contains code used to implement mutexes on Btree objects.
32948 ** This code really belongs in btree.c.  But btree.c is getting too
32949 ** big and we want to break it down some.  This packaged seemed like
32950 ** a good breakout.
32951 */
32952 /************** Include btreeInt.h in the middle of btmutex.c ****************/
32953 /************** Begin file btreeInt.h ****************************************/
32954 /*
32955 ** 2004 April 6
32956 **
32957 ** The author disclaims copyright to this source code.  In place of
32958 ** a legal notice, here is a blessing:
32959 **
32960 **    May you do good and not evil.
32961 **    May you find forgiveness for yourself and forgive others.
32962 **    May you share freely, never taking more than you give.
32963 **
32964 *************************************************************************
32965 ** $Id: btreeInt.h,v 1.36 2008/11/19 10:22:33 danielk1977 Exp $
32966 **
32967 ** This file implements a external (disk-based) database using BTrees.
32968 ** For a detailed discussion of BTrees, refer to
32969 **
32970 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
32971 **     "Sorting And Searching", pages 473-480. Addison-Wesley
32972 **     Publishing Company, Reading, Massachusetts.
32973 **
32974 ** The basic idea is that each page of the file contains N database
32975 ** entries and N+1 pointers to subpages.
32976 **
32977 **   ----------------------------------------------------------------
32978 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
32979 **   ----------------------------------------------------------------
32980 **
32981 ** All of the keys on the page that Ptr(0) points to have values less
32982 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
32983 ** values greater than Key(0) and less than Key(1).  All of the keys
32984 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
32985 ** so forth.
32986 **
32987 ** Finding a particular key requires reading O(log(M)) pages from the 
32988 ** disk where M is the number of entries in the tree.
32989 **
32990 ** In this implementation, a single file can hold one or more separate 
32991 ** BTrees.  Each BTree is identified by the index of its root page.  The
32992 ** key and data for any entry are combined to form the "payload".  A
32993 ** fixed amount of payload can be carried directly on the database
32994 ** page.  If the payload is larger than the preset amount then surplus
32995 ** bytes are stored on overflow pages.  The payload for an entry
32996 ** and the preceding pointer are combined to form a "Cell".  Each 
32997 ** page has a small header which contains the Ptr(N) pointer and other
32998 ** information such as the size of key and data.
32999 **
33000 ** FORMAT DETAILS
33001 **
33002 ** The file is divided into pages.  The first page is called page 1,
33003 ** the second is page 2, and so forth.  A page number of zero indicates
33004 ** "no such page".  The page size can be anything between 512 and 65536.
33005 ** Each page can be either a btree page, a freelist page or an overflow
33006 ** page.
33007 **
33008 ** The first page is always a btree page.  The first 100 bytes of the first
33009 ** page contain a special header (the "file header") that describes the file.
33010 ** The format of the file header is as follows:
33011 **
33012 **   OFFSET   SIZE    DESCRIPTION
33013 **      0      16     Header string: "SQLite format 3\000"
33014 **     16       2     Page size in bytes.  
33015 **     18       1     File format write version
33016 **     19       1     File format read version
33017 **     20       1     Bytes of unused space at the end of each page
33018 **     21       1     Max embedded payload fraction
33019 **     22       1     Min embedded payload fraction
33020 **     23       1     Min leaf payload fraction
33021 **     24       4     File change counter
33022 **     28       4     Reserved for future use
33023 **     32       4     First freelist page
33024 **     36       4     Number of freelist pages in the file
33025 **     40      60     15 4-byte meta values passed to higher layers
33026 **
33027 ** All of the integer values are big-endian (most significant byte first).
33028 **
33029 ** The file change counter is incremented when the database is changed
33030 ** This counter allows other processes to know when the file has changed
33031 ** and thus when they need to flush their cache.
33032 **
33033 ** The max embedded payload fraction is the amount of the total usable
33034 ** space in a page that can be consumed by a single cell for standard
33035 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
33036 ** is to limit the maximum cell size so that at least 4 cells will fit
33037 ** on one page.  Thus the default max embedded payload fraction is 64.
33038 **
33039 ** If the payload for a cell is larger than the max payload, then extra
33040 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
33041 ** as many bytes as possible are moved into the overflow pages without letting
33042 ** the cell size drop below the min embedded payload fraction.
33043 **
33044 ** The min leaf payload fraction is like the min embedded payload fraction
33045 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
33046 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
33047 ** not specified in the header.
33048 **
33049 ** Each btree pages is divided into three sections:  The header, the
33050 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
33051 ** file header that occurs before the page header.
33052 **
33053 **      |----------------|
33054 **      | file header    |   100 bytes.  Page 1 only.
33055 **      |----------------|
33056 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
33057 **      |----------------|
33058 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
33059 **      | array          |   |  Grows downward
33060 **      |                |   v
33061 **      |----------------|
33062 **      | unallocated    |
33063 **      | space          |
33064 **      |----------------|   ^  Grows upwards
33065 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
33066 **      | area           |   |  and free space fragments.
33067 **      |----------------|
33068 **
33069 ** The page headers looks like this:
33070 **
33071 **   OFFSET   SIZE     DESCRIPTION
33072 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
33073 **      1       2      byte offset to the first freeblock
33074 **      3       2      number of cells on this page
33075 **      5       2      first byte of the cell content area
33076 **      7       1      number of fragmented free bytes
33077 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
33078 **
33079 ** The flags define the format of this btree page.  The leaf flag means that
33080 ** this page has no children.  The zerodata flag means that this page carries
33081 ** only keys and no data.  The intkey flag means that the key is a integer
33082 ** which is stored in the key size entry of the cell header rather than in
33083 ** the payload area.
33084 **
33085 ** The cell pointer array begins on the first byte after the page header.
33086 ** The cell pointer array contains zero or more 2-byte numbers which are
33087 ** offsets from the beginning of the page to the cell content in the cell
33088 ** content area.  The cell pointers occur in sorted order.  The system strives
33089 ** to keep free space after the last cell pointer so that new cells can
33090 ** be easily added without having to defragment the page.
33091 **
33092 ** Cell content is stored at the very end of the page and grows toward the
33093 ** beginning of the page.
33094 **
33095 ** Unused space within the cell content area is collected into a linked list of
33096 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
33097 ** to the first freeblock is given in the header.  Freeblocks occur in
33098 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
33099 ** any group of 3 or fewer unused bytes in the cell content area cannot
33100 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
33101 ** a fragment.  The total number of bytes in all fragments is recorded.
33102 ** in the page header at offset 7.
33103 **
33104 **    SIZE    DESCRIPTION
33105 **      2     Byte offset of the next freeblock
33106 **      2     Bytes in this freeblock
33107 **
33108 ** Cells are of variable length.  Cells are stored in the cell content area at
33109 ** the end of the page.  Pointers to the cells are in the cell pointer array
33110 ** that immediately follows the page header.  Cells is not necessarily
33111 ** contiguous or in order, but cell pointers are contiguous and in order.
33112 **
33113 ** Cell content makes use of variable length integers.  A variable
33114 ** length integer is 1 to 9 bytes where the lower 7 bits of each 
33115 ** byte are used.  The integer consists of all bytes that have bit 8 set and
33116 ** the first byte with bit 8 clear.  The most significant byte of the integer
33117 ** appears first.  A variable-length integer may not be more than 9 bytes long.
33118 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
33119 ** allows a 64-bit integer to be encoded in 9 bytes.
33120 **
33121 **    0x00                      becomes  0x00000000
33122 **    0x7f                      becomes  0x0000007f
33123 **    0x81 0x00                 becomes  0x00000080
33124 **    0x82 0x00                 becomes  0x00000100
33125 **    0x80 0x7f                 becomes  0x0000007f
33126 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
33127 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
33128 **
33129 ** Variable length integers are used for rowids and to hold the number of
33130 ** bytes of key and data in a btree cell.
33131 **
33132 ** The content of a cell looks like this:
33133 **
33134 **    SIZE    DESCRIPTION
33135 **      4     Page number of the left child. Omitted if leaf flag is set.
33136 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
33137 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
33138 **      *     Payload
33139 **      4     First page of the overflow chain.  Omitted if no overflow
33140 **
33141 ** Overflow pages form a linked list.  Each page except the last is completely
33142 ** filled with data (pagesize - 4 bytes).  The last page can have as little
33143 ** as 1 byte of data.
33144 **
33145 **    SIZE    DESCRIPTION
33146 **      4     Page number of next overflow page
33147 **      *     Data
33148 **
33149 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
33150 ** file header points to the first in a linked list of trunk page.  Each trunk
33151 ** page points to multiple leaf pages.  The content of a leaf page is
33152 ** unspecified.  A trunk page looks like this:
33153 **
33154 **    SIZE    DESCRIPTION
33155 **      4     Page number of next trunk page
33156 **      4     Number of leaf pointers on this page
33157 **      *     zero or more pages numbers of leaves
33158 */
33159
33160 /* Round up a number to the next larger multiple of 8.  This is used
33161 ** to force 8-byte alignment on 64-bit architectures.
33162 */
33163 #define ROUND8(x)   ((x+7)&~7)
33164
33165
33166 /* The following value is the maximum cell size assuming a maximum page
33167 ** size give above.
33168 */
33169 #define MX_CELL_SIZE(pBt)  (pBt->pageSize-8)
33170
33171 /* The maximum number of cells on a single page of the database.  This
33172 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
33173 ** plus 2 bytes for the index to the cell in the page header).  Such
33174 ** small cells will be rare, but they are possible.
33175 */
33176 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
33177
33178 /* Forward declarations */
33179 typedef struct MemPage MemPage;
33180 typedef struct BtLock BtLock;
33181
33182 /*
33183 ** This is a magic string that appears at the beginning of every
33184 ** SQLite database in order to identify the file as a real database.
33185 **
33186 ** You can change this value at compile-time by specifying a
33187 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
33188 ** header must be exactly 16 bytes including the zero-terminator so
33189 ** the string itself should be 15 characters long.  If you change
33190 ** the header, then your custom library will not be able to read 
33191 ** databases generated by the standard tools and the standard tools
33192 ** will not be able to read databases created by your custom library.
33193 */
33194 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
33195 #  define SQLITE_FILE_HEADER "SQLite format 3"
33196 #endif
33197
33198 /*
33199 ** Page type flags.  An ORed combination of these flags appear as the
33200 ** first byte of on-disk image of every BTree page.
33201 */
33202 #define PTF_INTKEY    0x01
33203 #define PTF_ZERODATA  0x02
33204 #define PTF_LEAFDATA  0x04
33205 #define PTF_LEAF      0x08
33206
33207 /*
33208 ** As each page of the file is loaded into memory, an instance of the following
33209 ** structure is appended and initialized to zero.  This structure stores
33210 ** information about the page that is decoded from the raw file page.
33211 **
33212 ** The pParent field points back to the parent page.  This allows us to
33213 ** walk up the BTree from any leaf to the root.  Care must be taken to
33214 ** unref() the parent page pointer when this page is no longer referenced.
33215 ** The pageDestructor() routine handles that chore.
33216 **
33217 ** Access to all fields of this structure is controlled by the mutex
33218 ** stored in MemPage.pBt->mutex.
33219 */
33220 struct MemPage {
33221   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
33222   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
33223   u8 intKey;           /* True if intkey flag is set */
33224   u8 leaf;             /* True if leaf flag is set */
33225   u8 hasData;          /* True if this page stores data */
33226   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
33227   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
33228   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
33229   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
33230   u16 cellOffset;      /* Index in aData of first cell pointer */
33231   u16 nFree;           /* Number of free bytes on the page */
33232   u16 nCell;           /* Number of cells on this page, local and ovfl */
33233   u16 maskPage;        /* Mask for page offset */
33234   struct _OvflCell {   /* Cells that will not fit on aData[] */
33235     u8 *pCell;          /* Pointers to the body of the overflow cell */
33236     u16 idx;            /* Insert this cell before idx-th non-overflow cell */
33237   } aOvfl[5];
33238   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
33239   u8 *aData;           /* Pointer to disk image of the page data */
33240   DbPage *pDbPage;     /* Pager page handle */
33241   Pgno pgno;           /* Page number for this page */
33242 };
33243
33244 /*
33245 ** The in-memory image of a disk page has the auxiliary information appended
33246 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
33247 ** that extra information.
33248 */
33249 #define EXTRA_SIZE sizeof(MemPage)
33250
33251 /* A Btree handle
33252 **
33253 ** A database connection contains a pointer to an instance of
33254 ** this object for every database file that it has open.  This structure
33255 ** is opaque to the database connection.  The database connection cannot
33256 ** see the internals of this structure and only deals with pointers to
33257 ** this structure.
33258 **
33259 ** For some database files, the same underlying database cache might be 
33260 ** shared between multiple connections.  In that case, each contection
33261 ** has it own pointer to this object.  But each instance of this object
33262 ** points to the same BtShared object.  The database cache and the
33263 ** schema associated with the database file are all contained within
33264 ** the BtShared object.
33265 **
33266 ** All fields in this structure are accessed under sqlite3.mutex.
33267 ** The pBt pointer itself may not be changed while there exists cursors 
33268 ** in the referenced BtShared that point back to this Btree since those
33269 ** cursors have to do go through this Btree to find their BtShared and
33270 ** they often do so without holding sqlite3.mutex.
33271 */
33272 struct Btree {
33273   sqlite3 *db;       /* The database connection holding this btree */
33274   BtShared *pBt;     /* Sharable content of this btree */
33275   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
33276   u8 sharable;       /* True if we can share pBt with another db */
33277   u8 locked;         /* True if db currently has pBt locked */
33278   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
33279   Btree *pNext;      /* List of other sharable Btrees from the same db */
33280   Btree *pPrev;      /* Back pointer of the same list */
33281 };
33282
33283 /*
33284 ** Btree.inTrans may take one of the following values.
33285 **
33286 ** If the shared-data extension is enabled, there may be multiple users
33287 ** of the Btree structure. At most one of these may open a write transaction,
33288 ** but any number may have active read transactions.
33289 */
33290 #define TRANS_NONE  0
33291 #define TRANS_READ  1
33292 #define TRANS_WRITE 2
33293
33294 /*
33295 ** An instance of this object represents a single database file.
33296 ** 
33297 ** A single database file can be in use as the same time by two
33298 ** or more database connections.  When two or more connections are
33299 ** sharing the same database file, each connection has it own
33300 ** private Btree object for the file and each of those Btrees points
33301 ** to this one BtShared object.  BtShared.nRef is the number of
33302 ** connections currently sharing this database file.
33303 **
33304 ** Fields in this structure are accessed under the BtShared.mutex
33305 ** mutex, except for nRef and pNext which are accessed under the
33306 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
33307 ** may not be modified once it is initially set as long as nRef>0.
33308 ** The pSchema field may be set once under BtShared.mutex and
33309 ** thereafter is unchanged as long as nRef>0.
33310 */
33311 struct BtShared {
33312   Pager *pPager;        /* The page cache */
33313   sqlite3 *db;          /* Database connection currently using this Btree */
33314   BtCursor *pCursor;    /* A list of all open cursors */
33315   MemPage *pPage1;      /* First page of the database */
33316   u8 inStmt;            /* True if we are in a statement subtransaction */
33317   u8 readOnly;          /* True if the underlying file is readonly */
33318   u8 pageSizeFixed;     /* True if the page size can no longer be changed */
33319 #ifndef SQLITE_OMIT_AUTOVACUUM
33320   u8 autoVacuum;        /* True if auto-vacuum is enabled */
33321   u8 incrVacuum;        /* True if incr-vacuum is enabled */
33322   Pgno nTrunc;          /* Non-zero if the db will be truncated (incr vacuum) */
33323 #endif
33324   u16 pageSize;         /* Total number of bytes on a page */
33325   u16 usableSize;       /* Number of usable bytes on each page */
33326   int maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
33327   int minLocal;         /* Minimum local payload in non-LEAFDATA tables */
33328   int maxLeaf;          /* Maximum local payload in a LEAFDATA table */
33329   int minLeaf;          /* Minimum local payload in a LEAFDATA table */
33330   u8 inTransaction;     /* Transaction state */
33331   int nTransaction;     /* Number of open transactions (read + write) */
33332   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
33333   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
33334   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */
33335 #ifndef SQLITE_OMIT_SHARED_CACHE
33336   int nRef;             /* Number of references to this structure */
33337   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
33338   BtLock *pLock;        /* List of locks held on this shared-btree struct */
33339   Btree *pExclusive;    /* Btree with an EXCLUSIVE lock on the whole db */
33340 #endif
33341   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
33342 };
33343
33344 /*
33345 ** An instance of the following structure is used to hold information
33346 ** about a cell.  The parseCellPtr() function fills in this structure
33347 ** based on information extract from the raw disk page.
33348 */
33349 typedef struct CellInfo CellInfo;
33350 struct CellInfo {
33351   u8 *pCell;     /* Pointer to the start of cell content */
33352   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
33353   u32 nData;     /* Number of bytes of data */
33354   u32 nPayload;  /* Total amount of payload */
33355   u16 nHeader;   /* Size of the cell content header in bytes */
33356   u16 nLocal;    /* Amount of payload held locally */
33357   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
33358   u16 nSize;     /* Size of the cell content on the main b-tree page */
33359 };
33360
33361 /*
33362 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
33363 ** this will be declared corrupt. This value is calculated based on a
33364 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
33365 ** root-node and 3 for all other internal nodes.
33366 **
33367 ** If a tree that appears to be taller than this is encountered, it is
33368 ** assumed that the database is corrupt.
33369 */
33370 #define BTCURSOR_MAX_DEPTH 20
33371
33372 /*
33373 ** A cursor is a pointer to a particular entry within a particular
33374 ** b-tree within a database file.
33375 **
33376 ** The entry is identified by its MemPage and the index in
33377 ** MemPage.aCell[] of the entry.
33378 **
33379 ** When a single database file can shared by two more database connections,
33380 ** but cursors cannot be shared.  Each cursor is associated with a
33381 ** particular database connection identified BtCursor.pBtree.db.
33382 **
33383 ** Fields in this structure are accessed under the BtShared.mutex
33384 ** found at self->pBt->mutex. 
33385 */
33386 struct BtCursor {
33387   Btree *pBtree;            /* The Btree to which this cursor belongs */
33388   BtShared *pBt;            /* The BtShared this cursor points to */
33389   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
33390   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
33391   Pgno pgnoRoot;            /* The root page of this tree */
33392   CellInfo info;            /* A parse of the cell we are pointing at */
33393   u8 wrFlag;                /* True if writable */
33394   u8 atLast;                /* Cursor pointing to the last entry */
33395   u8 validNKey;             /* True if info.nKey is valid */
33396   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
33397   void *pKey;      /* Saved key that was cursor's last known position */
33398   i64 nKey;        /* Size of pKey, or last integer key */
33399   int skip;        /* (skip<0) -> Prev() is a no-op. (skip>0) -> Next() is */
33400 #ifndef SQLITE_OMIT_INCRBLOB
33401   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
33402   Pgno *aOverflow;          /* Cache of overflow page locations */
33403 #endif
33404 #ifndef NDEBUG
33405   u8 pagesShuffled;         /* True if Btree pages are rearranged by balance()*/
33406 #endif
33407   i16 iPage;                            /* Index of current page in apPage */
33408   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
33409   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
33410 };
33411
33412 /*
33413 ** Potential values for BtCursor.eState.
33414 **
33415 ** CURSOR_VALID:
33416 **   Cursor points to a valid entry. getPayload() etc. may be called.
33417 **
33418 ** CURSOR_INVALID:
33419 **   Cursor does not point to a valid entry. This can happen (for example) 
33420 **   because the table is empty or because BtreeCursorFirst() has not been
33421 **   called.
33422 **
33423 ** CURSOR_REQUIRESEEK:
33424 **   The table that this cursor was opened on still exists, but has been 
33425 **   modified since the cursor was last used. The cursor position is saved
33426 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
33427 **   this state, restoreCursorPosition() can be called to attempt to
33428 **   seek the cursor to the saved position.
33429 **
33430 ** CURSOR_FAULT:
33431 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
33432 **   on a different connection that shares the BtShared cache with this
33433 **   cursor.  The error has left the cache in an inconsistent state.
33434 **   Do nothing else with this cursor.  Any attempt to use the cursor
33435 **   should return the error code stored in BtCursor.skip
33436 */
33437 #define CURSOR_INVALID           0
33438 #define CURSOR_VALID             1
33439 #define CURSOR_REQUIRESEEK       2
33440 #define CURSOR_FAULT             3
33441
33442 /* The database page the PENDING_BYTE occupies. This page is never used.
33443 ** TODO: This macro is very similary to PAGER_MJ_PGNO() in pager.c. They
33444 ** should possibly be consolidated (presumably in pager.h).
33445 **
33446 ** If disk I/O is omitted (meaning that the database is stored purely
33447 ** in memory) then there is no pending byte.
33448 */
33449 #ifdef SQLITE_OMIT_DISKIO
33450 # define PENDING_BYTE_PAGE(pBt)  0x7fffffff
33451 #else
33452 # define PENDING_BYTE_PAGE(pBt) ((Pgno)((PENDING_BYTE/(pBt)->pageSize)+1))
33453 #endif
33454
33455 /*
33456 ** A linked list of the following structures is stored at BtShared.pLock.
33457 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
33458 ** is opened on the table with root page BtShared.iTable. Locks are removed
33459 ** from this list when a transaction is committed or rolled back, or when
33460 ** a btree handle is closed.
33461 */
33462 struct BtLock {
33463   Btree *pBtree;        /* Btree handle holding this lock */
33464   Pgno iTable;          /* Root page of table */
33465   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
33466   BtLock *pNext;        /* Next in BtShared.pLock list */
33467 };
33468
33469 /* Candidate values for BtLock.eLock */
33470 #define READ_LOCK     1
33471 #define WRITE_LOCK    2
33472
33473 /*
33474 ** These macros define the location of the pointer-map entry for a 
33475 ** database page. The first argument to each is the number of usable
33476 ** bytes on each page of the database (often 1024). The second is the
33477 ** page number to look up in the pointer map.
33478 **
33479 ** PTRMAP_PAGENO returns the database page number of the pointer-map
33480 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
33481 ** the offset of the requested map entry.
33482 **
33483 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
33484 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
33485 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
33486 ** this test.
33487 */
33488 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
33489 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
33490 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
33491
33492 /*
33493 ** The pointer map is a lookup table that identifies the parent page for
33494 ** each child page in the database file.  The parent page is the page that
33495 ** contains a pointer to the child.  Every page in the database contains
33496 ** 0 or 1 parent pages.  (In this context 'database page' refers
33497 ** to any page that is not part of the pointer map itself.)  Each pointer map
33498 ** entry consists of a single byte 'type' and a 4 byte parent page number.
33499 ** The PTRMAP_XXX identifiers below are the valid types.
33500 **
33501 ** The purpose of the pointer map is to facility moving pages from one
33502 ** position in the file to another as part of autovacuum.  When a page
33503 ** is moved, the pointer in its parent must be updated to point to the
33504 ** new location.  The pointer map is used to locate the parent page quickly.
33505 **
33506 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
33507 **                  used in this case.
33508 **
33509 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
33510 **                  is not used in this case.
33511 **
33512 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
33513 **                   overflow pages. The page number identifies the page that
33514 **                   contains the cell with a pointer to this overflow page.
33515 **
33516 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
33517 **                   overflow pages. The page-number identifies the previous
33518 **                   page in the overflow page list.
33519 **
33520 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
33521 **               identifies the parent page in the btree.
33522 */
33523 #define PTRMAP_ROOTPAGE 1
33524 #define PTRMAP_FREEPAGE 2
33525 #define PTRMAP_OVERFLOW1 3
33526 #define PTRMAP_OVERFLOW2 4
33527 #define PTRMAP_BTREE 5
33528
33529 /* A bunch of assert() statements to check the transaction state variables
33530 ** of handle p (type Btree*) are internally consistent.
33531 */
33532 #define btreeIntegrity(p) \
33533   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
33534   assert( p->pBt->inTransaction>=p->inTrans ); 
33535
33536
33537 /*
33538 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
33539 ** if the database supports auto-vacuum or not. Because it is used
33540 ** within an expression that is an argument to another macro 
33541 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
33542 ** So, this macro is defined instead.
33543 */
33544 #ifndef SQLITE_OMIT_AUTOVACUUM
33545 #define ISAUTOVACUUM (pBt->autoVacuum)
33546 #else
33547 #define ISAUTOVACUUM 0
33548 #endif
33549
33550
33551 /*
33552 ** This structure is passed around through all the sanity checking routines
33553 ** in order to keep track of some global state information.
33554 */
33555 typedef struct IntegrityCk IntegrityCk;
33556 struct IntegrityCk {
33557   BtShared *pBt;    /* The tree being checked out */
33558   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
33559   Pgno nPage;       /* Number of pages in the database */
33560   int *anRef;       /* Number of times each page is referenced */
33561   int mxErr;        /* Stop accumulating errors when this reaches zero */
33562   int nErr;         /* Number of messages written to zErrMsg so far */
33563   int mallocFailed; /* A memory allocation error has occurred */
33564   StrAccum errMsg;  /* Accumulate the error message text here */
33565 };
33566
33567 /*
33568 ** Read or write a two- and four-byte big-endian integer values.
33569 */
33570 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
33571 #define put2byte(p,v) ((p)[0] = (v)>>8, (p)[1] = (v))
33572 #define get4byte sqlite3Get4byte
33573 #define put4byte sqlite3Put4byte
33574
33575 /*
33576 ** Internal routines that should be accessed by the btree layer only.
33577 */
33578 SQLITE_PRIVATE int sqlite3BtreeGetPage(BtShared*, Pgno, MemPage**, int);
33579 SQLITE_PRIVATE int sqlite3BtreeInitPage(MemPage *pPage);
33580 SQLITE_PRIVATE void sqlite3BtreeParseCellPtr(MemPage*, u8*, CellInfo*);
33581 SQLITE_PRIVATE void sqlite3BtreeParseCell(MemPage*, int, CellInfo*);
33582 SQLITE_PRIVATE int sqlite3BtreeRestoreCursorPosition(BtCursor *pCur);
33583 SQLITE_PRIVATE void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur);
33584 SQLITE_PRIVATE void sqlite3BtreeReleaseTempCursor(BtCursor *pCur);
33585 SQLITE_PRIVATE void sqlite3BtreeMoveToParent(BtCursor *pCur);
33586
33587 /************** End of btreeInt.h ********************************************/
33588 /************** Continuing where we left off in btmutex.c ********************/
33589 #if SQLITE_THREADSAFE && !defined(SQLITE_OMIT_SHARED_CACHE)
33590
33591
33592 /*
33593 ** Enter a mutex on the given BTree object.
33594 **
33595 ** If the object is not sharable, then no mutex is ever required
33596 ** and this routine is a no-op.  The underlying mutex is non-recursive.
33597 ** But we keep a reference count in Btree.wantToLock so the behavior
33598 ** of this interface is recursive.
33599 **
33600 ** To avoid deadlocks, multiple Btrees are locked in the same order
33601 ** by all database connections.  The p->pNext is a list of other
33602 ** Btrees belonging to the same database connection as the p Btree
33603 ** which need to be locked after p.  If we cannot get a lock on
33604 ** p, then first unlock all of the others on p->pNext, then wait
33605 ** for the lock to become available on p, then relock all of the
33606 ** subsequent Btrees that desire a lock.
33607 */
33608 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
33609   Btree *pLater;
33610
33611   /* Some basic sanity checking on the Btree.  The list of Btrees
33612   ** connected by pNext and pPrev should be in sorted order by
33613   ** Btree.pBt value. All elements of the list should belong to
33614   ** the same connection. Only shared Btrees are on the list. */
33615   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
33616   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
33617   assert( p->pNext==0 || p->pNext->db==p->db );
33618   assert( p->pPrev==0 || p->pPrev->db==p->db );
33619   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
33620
33621   /* Check for locking consistency */
33622   assert( !p->locked || p->wantToLock>0 );
33623   assert( p->sharable || p->wantToLock==0 );
33624
33625   /* We should already hold a lock on the database connection */
33626   assert( sqlite3_mutex_held(p->db->mutex) );
33627
33628   if( !p->sharable ) return;
33629   p->wantToLock++;
33630   if( p->locked ) return;
33631
33632   /* In most cases, we should be able to acquire the lock we
33633   ** want without having to go throught the ascending lock
33634   ** procedure that follows.  Just be sure not to block.
33635   */
33636   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
33637     p->locked = 1;
33638     return;
33639   }
33640
33641   /* To avoid deadlock, first release all locks with a larger
33642   ** BtShared address.  Then acquire our lock.  Then reacquire
33643   ** the other BtShared locks that we used to hold in ascending
33644   ** order.
33645   */
33646   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
33647     assert( pLater->sharable );
33648     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
33649     assert( !pLater->locked || pLater->wantToLock>0 );
33650     if( pLater->locked ){
33651       sqlite3_mutex_leave(pLater->pBt->mutex);
33652       pLater->locked = 0;
33653     }
33654   }
33655   sqlite3_mutex_enter(p->pBt->mutex);
33656   p->locked = 1;
33657   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
33658     if( pLater->wantToLock ){
33659       sqlite3_mutex_enter(pLater->pBt->mutex);
33660       pLater->locked = 1;
33661     }
33662   }
33663 }
33664
33665 /*
33666 ** Exit the recursive mutex on a Btree.
33667 */
33668 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
33669   if( p->sharable ){
33670     assert( p->wantToLock>0 );
33671     p->wantToLock--;
33672     if( p->wantToLock==0 ){
33673       assert( p->locked );
33674       sqlite3_mutex_leave(p->pBt->mutex);
33675       p->locked = 0;
33676     }
33677   }
33678 }
33679
33680 #ifndef NDEBUG
33681 /*
33682 ** Return true if the BtShared mutex is held on the btree.  
33683 **
33684 ** This routine makes no determination one why or another if the
33685 ** database connection mutex is held.
33686 **
33687 ** This routine is used only from within assert() statements.
33688 */
33689 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
33690   return (p->sharable==0 ||
33691              (p->locked && p->wantToLock && sqlite3_mutex_held(p->pBt->mutex)));
33692 }
33693 #endif
33694
33695
33696 #ifndef SQLITE_OMIT_INCRBLOB
33697 /*
33698 ** Enter and leave a mutex on a Btree given a cursor owned by that
33699 ** Btree.  These entry points are used by incremental I/O and can be
33700 ** omitted if that module is not used.
33701 */
33702 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
33703   sqlite3BtreeEnter(pCur->pBtree);
33704 }
33705 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
33706   sqlite3BtreeLeave(pCur->pBtree);
33707 }
33708 #endif /* SQLITE_OMIT_INCRBLOB */
33709
33710
33711 /*
33712 ** Enter the mutex on every Btree associated with a database
33713 ** connection.  This is needed (for example) prior to parsing
33714 ** a statement since we will be comparing table and column names
33715 ** against all schemas and we do not want those schemas being
33716 ** reset out from under us.
33717 **
33718 ** There is a corresponding leave-all procedures.
33719 **
33720 ** Enter the mutexes in accending order by BtShared pointer address
33721 ** to avoid the possibility of deadlock when two threads with
33722 ** two or more btrees in common both try to lock all their btrees
33723 ** at the same instant.
33724 */
33725 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
33726   int i;
33727   Btree *p, *pLater;
33728   assert( sqlite3_mutex_held(db->mutex) );
33729   for(i=0; i<db->nDb; i++){
33730     p = db->aDb[i].pBt;
33731     if( p && p->sharable ){
33732       p->wantToLock++;
33733       if( !p->locked ){
33734         assert( p->wantToLock==1 );
33735         while( p->pPrev ) p = p->pPrev;
33736         while( p->locked && p->pNext ) p = p->pNext;
33737         for(pLater = p->pNext; pLater; pLater=pLater->pNext){
33738           if( pLater->locked ){
33739             sqlite3_mutex_leave(pLater->pBt->mutex);
33740             pLater->locked = 0;
33741           }
33742         }
33743         while( p ){
33744           sqlite3_mutex_enter(p->pBt->mutex);
33745           p->locked++;
33746           p = p->pNext;
33747         }
33748       }
33749     }
33750   }
33751 }
33752 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
33753   int i;
33754   Btree *p;
33755   assert( sqlite3_mutex_held(db->mutex) );
33756   for(i=0; i<db->nDb; i++){
33757     p = db->aDb[i].pBt;
33758     if( p && p->sharable ){
33759       assert( p->wantToLock>0 );
33760       p->wantToLock--;
33761       if( p->wantToLock==0 ){
33762         assert( p->locked );
33763         sqlite3_mutex_leave(p->pBt->mutex);
33764         p->locked = 0;
33765       }
33766     }
33767   }
33768 }
33769
33770 #ifndef NDEBUG
33771 /*
33772 ** Return true if the current thread holds the database connection
33773 ** mutex and all required BtShared mutexes.
33774 **
33775 ** This routine is used inside assert() statements only.
33776 */
33777 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
33778   int i;
33779   if( !sqlite3_mutex_held(db->mutex) ){
33780     return 0;
33781   }
33782   for(i=0; i<db->nDb; i++){
33783     Btree *p;
33784     p = db->aDb[i].pBt;
33785     if( p && p->sharable &&
33786          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
33787       return 0;
33788     }
33789   }
33790   return 1;
33791 }
33792 #endif /* NDEBUG */
33793
33794 /*
33795 ** Add a new Btree pointer to a BtreeMutexArray. 
33796 ** if the pointer can possibly be shared with
33797 ** another database connection.
33798 **
33799 ** The pointers are kept in sorted order by pBtree->pBt.  That
33800 ** way when we go to enter all the mutexes, we can enter them
33801 ** in order without every having to backup and retry and without
33802 ** worrying about deadlock.
33803 **
33804 ** The number of shared btrees will always be small (usually 0 or 1)
33805 ** so an insertion sort is an adequate algorithm here.
33806 */
33807 SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray *pArray, Btree *pBtree){
33808   int i, j;
33809   BtShared *pBt;
33810   if( pBtree==0 || pBtree->sharable==0 ) return;
33811 #ifndef NDEBUG
33812   {
33813     for(i=0; i<pArray->nMutex; i++){
33814       assert( pArray->aBtree[i]!=pBtree );
33815     }
33816   }
33817 #endif
33818   assert( pArray->nMutex>=0 );
33819   assert( pArray->nMutex<ArraySize(pArray->aBtree)-1 );
33820   pBt = pBtree->pBt;
33821   for(i=0; i<pArray->nMutex; i++){
33822     assert( pArray->aBtree[i]!=pBtree );
33823     if( pArray->aBtree[i]->pBt>pBt ){
33824       for(j=pArray->nMutex; j>i; j--){
33825         pArray->aBtree[j] = pArray->aBtree[j-1];
33826       }
33827       pArray->aBtree[i] = pBtree;
33828       pArray->nMutex++;
33829       return;
33830     }
33831   }
33832   pArray->aBtree[pArray->nMutex++] = pBtree;
33833 }
33834
33835 /*
33836 ** Enter the mutex of every btree in the array.  This routine is
33837 ** called at the beginning of sqlite3VdbeExec().  The mutexes are
33838 ** exited at the end of the same function.
33839 */
33840 SQLITE_PRIVATE void sqlite3BtreeMutexArrayEnter(BtreeMutexArray *pArray){
33841   int i;
33842   for(i=0; i<pArray->nMutex; i++){
33843     Btree *p = pArray->aBtree[i];
33844     /* Some basic sanity checking */
33845     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
33846     assert( !p->locked || p->wantToLock>0 );
33847
33848     /* We should already hold a lock on the database connection */
33849     assert( sqlite3_mutex_held(p->db->mutex) );
33850
33851     p->wantToLock++;
33852     if( !p->locked && p->sharable ){
33853       sqlite3_mutex_enter(p->pBt->mutex);
33854       p->locked = 1;
33855     }
33856   }
33857 }
33858
33859 /*
33860 ** Leave the mutex of every btree in the group.
33861 */
33862 SQLITE_PRIVATE void sqlite3BtreeMutexArrayLeave(BtreeMutexArray *pArray){
33863   int i;
33864   for(i=0; i<pArray->nMutex; i++){
33865     Btree *p = pArray->aBtree[i];
33866     /* Some basic sanity checking */
33867     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
33868     assert( p->locked || !p->sharable );
33869     assert( p->wantToLock>0 );
33870
33871     /* We should already hold a lock on the database connection */
33872     assert( sqlite3_mutex_held(p->db->mutex) );
33873
33874     p->wantToLock--;
33875     if( p->wantToLock==0 && p->locked ){
33876       sqlite3_mutex_leave(p->pBt->mutex);
33877       p->locked = 0;
33878     }
33879   }
33880 }
33881
33882
33883 #endif  /* SQLITE_THREADSAFE && !SQLITE_OMIT_SHARED_CACHE */
33884
33885 /************** End of btmutex.c *********************************************/
33886 /************** Begin file btree.c *******************************************/
33887 /*
33888 ** 2004 April 6
33889 **
33890 ** The author disclaims copyright to this source code.  In place of
33891 ** a legal notice, here is a blessing:
33892 **
33893 **    May you do good and not evil.
33894 **    May you find forgiveness for yourself and forgive others.
33895 **    May you share freely, never taking more than you give.
33896 **
33897 *************************************************************************
33898 ** $Id: btree.c,v 1.539.2.2 2008/11/26 14:55:02 drh Exp $
33899 **
33900 ** This file implements a external (disk-based) database using BTrees.
33901 ** See the header comment on "btreeInt.h" for additional information.
33902 ** Including a description of file format and an overview of operation.
33903 */
33904
33905 /*
33906 ** The header string that appears at the beginning of every
33907 ** SQLite database.
33908 */
33909 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
33910
33911 /*
33912 ** Set this global variable to 1 to enable tracing using the TRACE
33913 ** macro.
33914 */
33915 #if 0
33916 int sqlite3BtreeTrace=0;  /* True to enable tracing */
33917 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
33918 #else
33919 # define TRACE(X)
33920 #endif
33921
33922 /*
33923 ** Sometimes we need a small amount of code such as a variable initialization
33924 ** to setup for a later assert() statement.  We do not want this code to
33925 ** appear when assert() is disabled.  The following macro is therefore
33926 ** used to contain that setup code.  The "VVA" acronym stands for
33927 ** "Verification, Validation, and Accreditation".  In other words, the
33928 ** code within VVA_ONLY() will only run during verification processes.
33929 */
33930 #ifndef NDEBUG
33931 # define VVA_ONLY(X)  X
33932 #else
33933 # define VVA_ONLY(X)
33934 #endif
33935
33936
33937
33938 #ifndef SQLITE_OMIT_SHARED_CACHE
33939 /*
33940 ** A list of BtShared objects that are eligible for participation
33941 ** in shared cache.  This variable has file scope during normal builds,
33942 ** but the test harness needs to access it so we make it global for 
33943 ** test builds.
33944 */
33945 #ifdef SQLITE_TEST
33946 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
33947 #else
33948 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
33949 #endif
33950 #endif /* SQLITE_OMIT_SHARED_CACHE */
33951
33952 #ifndef SQLITE_OMIT_SHARED_CACHE
33953 /*
33954 ** Enable or disable the shared pager and schema features.
33955 **
33956 ** This routine has no effect on existing database connections.
33957 ** The shared cache setting effects only future calls to
33958 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
33959 */
33960 SQLITE_API int sqlite3_enable_shared_cache(int enable){
33961   sqlite3GlobalConfig.sharedCacheEnabled = enable;
33962   return SQLITE_OK;
33963 }
33964 #endif
33965
33966
33967 /*
33968 ** Forward declaration
33969 */
33970 static int checkReadLocks(Btree*, Pgno, BtCursor*, i64);
33971
33972
33973 #ifdef SQLITE_OMIT_SHARED_CACHE
33974   /*
33975   ** The functions queryTableLock(), lockTable() and unlockAllTables()
33976   ** manipulate entries in the BtShared.pLock linked list used to store
33977   ** shared-cache table level locks. If the library is compiled with the
33978   ** shared-cache feature disabled, then there is only ever one user
33979   ** of each BtShared structure and so this locking is not necessary. 
33980   ** So define the lock related functions as no-ops.
33981   */
33982   #define queryTableLock(a,b,c) SQLITE_OK
33983   #define lockTable(a,b,c) SQLITE_OK
33984   #define unlockAllTables(a)
33985 #endif
33986
33987 #ifndef SQLITE_OMIT_SHARED_CACHE
33988 /*
33989 ** Query to see if btree handle p may obtain a lock of type eLock 
33990 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
33991 ** SQLITE_OK if the lock may be obtained (by calling lockTable()), or
33992 ** SQLITE_LOCKED if not.
33993 */
33994 static int queryTableLock(Btree *p, Pgno iTab, u8 eLock){
33995   BtShared *pBt = p->pBt;
33996   BtLock *pIter;
33997
33998   assert( sqlite3BtreeHoldsMutex(p) );
33999   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
34000   assert( p->db!=0 );
34001   
34002   /* This is a no-op if the shared-cache is not enabled */
34003   if( !p->sharable ){
34004     return SQLITE_OK;
34005   }
34006
34007   /* If some other connection is holding an exclusive lock, the
34008   ** requested lock may not be obtained.
34009   */
34010   if( pBt->pExclusive && pBt->pExclusive!=p ){
34011     return SQLITE_LOCKED;
34012   }
34013
34014   /* This (along with lockTable()) is where the ReadUncommitted flag is
34015   ** dealt with. If the caller is querying for a read-lock and the flag is
34016   ** set, it is unconditionally granted - even if there are write-locks
34017   ** on the table. If a write-lock is requested, the ReadUncommitted flag
34018   ** is not considered.
34019   **
34020   ** In function lockTable(), if a read-lock is demanded and the 
34021   ** ReadUncommitted flag is set, no entry is added to the locks list 
34022   ** (BtShared.pLock).
34023   **
34024   ** To summarize: If the ReadUncommitted flag is set, then read cursors do
34025   ** not create or respect table locks. The locking procedure for a 
34026   ** write-cursor does not change.
34027   */
34028   if( 
34029     0==(p->db->flags&SQLITE_ReadUncommitted) || 
34030     eLock==WRITE_LOCK ||
34031     iTab==MASTER_ROOT
34032   ){
34033     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
34034       if( pIter->pBtree!=p && pIter->iTable==iTab && 
34035           (pIter->eLock!=eLock || eLock!=READ_LOCK) ){
34036         return SQLITE_LOCKED;
34037       }
34038     }
34039   }
34040   return SQLITE_OK;
34041 }
34042 #endif /* !SQLITE_OMIT_SHARED_CACHE */
34043
34044 #ifndef SQLITE_OMIT_SHARED_CACHE
34045 /*
34046 ** Add a lock on the table with root-page iTable to the shared-btree used
34047 ** by Btree handle p. Parameter eLock must be either READ_LOCK or 
34048 ** WRITE_LOCK.
34049 **
34050 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_BUSY and
34051 ** SQLITE_NOMEM may also be returned.
34052 */
34053 static int lockTable(Btree *p, Pgno iTable, u8 eLock){
34054   BtShared *pBt = p->pBt;
34055   BtLock *pLock = 0;
34056   BtLock *pIter;
34057
34058   assert( sqlite3BtreeHoldsMutex(p) );
34059   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
34060   assert( p->db!=0 );
34061
34062   /* This is a no-op if the shared-cache is not enabled */
34063   if( !p->sharable ){
34064     return SQLITE_OK;
34065   }
34066
34067   assert( SQLITE_OK==queryTableLock(p, iTable, eLock) );
34068
34069   /* If the read-uncommitted flag is set and a read-lock is requested,
34070   ** return early without adding an entry to the BtShared.pLock list. See
34071   ** comment in function queryTableLock() for more info on handling 
34072   ** the ReadUncommitted flag.
34073   */
34074   if( 
34075     (p->db->flags&SQLITE_ReadUncommitted) && 
34076     (eLock==READ_LOCK) &&
34077     iTable!=MASTER_ROOT
34078   ){
34079     return SQLITE_OK;
34080   }
34081
34082   /* First search the list for an existing lock on this table. */
34083   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
34084     if( pIter->iTable==iTable && pIter->pBtree==p ){
34085       pLock = pIter;
34086       break;
34087     }
34088   }
34089
34090   /* If the above search did not find a BtLock struct associating Btree p
34091   ** with table iTable, allocate one and link it into the list.
34092   */
34093   if( !pLock ){
34094     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
34095     if( !pLock ){
34096       return SQLITE_NOMEM;
34097     }
34098     pLock->iTable = iTable;
34099     pLock->pBtree = p;
34100     pLock->pNext = pBt->pLock;
34101     pBt->pLock = pLock;
34102   }
34103
34104   /* Set the BtLock.eLock variable to the maximum of the current lock
34105   ** and the requested lock. This means if a write-lock was already held
34106   ** and a read-lock requested, we don't incorrectly downgrade the lock.
34107   */
34108   assert( WRITE_LOCK>READ_LOCK );
34109   if( eLock>pLock->eLock ){
34110     pLock->eLock = eLock;
34111   }
34112
34113   return SQLITE_OK;
34114 }
34115 #endif /* !SQLITE_OMIT_SHARED_CACHE */
34116
34117 #ifndef SQLITE_OMIT_SHARED_CACHE
34118 /*
34119 ** Release all the table locks (locks obtained via calls to the lockTable()
34120 ** procedure) held by Btree handle p.
34121 */
34122 static void unlockAllTables(Btree *p){
34123   BtShared *pBt = p->pBt;
34124   BtLock **ppIter = &pBt->pLock;
34125
34126   assert( sqlite3BtreeHoldsMutex(p) );
34127   assert( p->sharable || 0==*ppIter );
34128
34129   while( *ppIter ){
34130     BtLock *pLock = *ppIter;
34131     assert( pBt->pExclusive==0 || pBt->pExclusive==pLock->pBtree );
34132     if( pLock->pBtree==p ){
34133       *ppIter = pLock->pNext;
34134       sqlite3_free(pLock);
34135     }else{
34136       ppIter = &pLock->pNext;
34137     }
34138   }
34139
34140   if( pBt->pExclusive==p ){
34141     pBt->pExclusive = 0;
34142   }
34143 }
34144 #endif /* SQLITE_OMIT_SHARED_CACHE */
34145
34146 static void releasePage(MemPage *pPage);  /* Forward reference */
34147
34148 /*
34149 ** Verify that the cursor holds a mutex on the BtShared
34150 */
34151 #ifndef NDEBUG
34152 static int cursorHoldsMutex(BtCursor *p){
34153   return sqlite3_mutex_held(p->pBt->mutex);
34154 }
34155 #endif
34156
34157
34158 #ifndef SQLITE_OMIT_INCRBLOB
34159 /*
34160 ** Invalidate the overflow page-list cache for cursor pCur, if any.
34161 */
34162 static void invalidateOverflowCache(BtCursor *pCur){
34163   assert( cursorHoldsMutex(pCur) );
34164   sqlite3_free(pCur->aOverflow);
34165   pCur->aOverflow = 0;
34166 }
34167
34168 /*
34169 ** Invalidate the overflow page-list cache for all cursors opened
34170 ** on the shared btree structure pBt.
34171 */
34172 static void invalidateAllOverflowCache(BtShared *pBt){
34173   BtCursor *p;
34174   assert( sqlite3_mutex_held(pBt->mutex) );
34175   for(p=pBt->pCursor; p; p=p->pNext){
34176     invalidateOverflowCache(p);
34177   }
34178 }
34179 #else
34180   #define invalidateOverflowCache(x)
34181   #define invalidateAllOverflowCache(x)
34182 #endif
34183
34184 /*
34185 ** Save the current cursor position in the variables BtCursor.nKey 
34186 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
34187 */
34188 static int saveCursorPosition(BtCursor *pCur){
34189   int rc;
34190
34191   assert( CURSOR_VALID==pCur->eState );
34192   assert( 0==pCur->pKey );
34193   assert( cursorHoldsMutex(pCur) );
34194
34195   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
34196
34197   /* If this is an intKey table, then the above call to BtreeKeySize()
34198   ** stores the integer key in pCur->nKey. In this case this value is
34199   ** all that is required. Otherwise, if pCur is not open on an intKey
34200   ** table, then malloc space for and store the pCur->nKey bytes of key 
34201   ** data.
34202   */
34203   if( rc==SQLITE_OK && 0==pCur->apPage[0]->intKey){
34204     void *pKey = sqlite3Malloc(pCur->nKey);
34205     if( pKey ){
34206       rc = sqlite3BtreeKey(pCur, 0, pCur->nKey, pKey);
34207       if( rc==SQLITE_OK ){
34208         pCur->pKey = pKey;
34209       }else{
34210         sqlite3_free(pKey);
34211       }
34212     }else{
34213       rc = SQLITE_NOMEM;
34214     }
34215   }
34216   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
34217
34218   if( rc==SQLITE_OK ){
34219     int i;
34220     for(i=0; i<=pCur->iPage; i++){
34221       releasePage(pCur->apPage[i]);
34222       pCur->apPage[i] = 0;
34223     }
34224     pCur->iPage = -1;
34225     pCur->eState = CURSOR_REQUIRESEEK;
34226   }
34227
34228   invalidateOverflowCache(pCur);
34229   return rc;
34230 }
34231
34232 /*
34233 ** Save the positions of all cursors except pExcept open on the table 
34234 ** with root-page iRoot. Usually, this is called just before cursor
34235 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
34236 */
34237 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
34238   BtCursor *p;
34239   assert( sqlite3_mutex_held(pBt->mutex) );
34240   assert( pExcept==0 || pExcept->pBt==pBt );
34241   for(p=pBt->pCursor; p; p=p->pNext){
34242     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) && 
34243         p->eState==CURSOR_VALID ){
34244       int rc = saveCursorPosition(p);
34245       if( SQLITE_OK!=rc ){
34246         return rc;
34247       }
34248     }
34249   }
34250   return SQLITE_OK;
34251 }
34252
34253 /*
34254 ** Clear the current cursor position.
34255 */
34256 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
34257   assert( cursorHoldsMutex(pCur) );
34258   sqlite3_free(pCur->pKey);
34259   pCur->pKey = 0;
34260   pCur->eState = CURSOR_INVALID;
34261 }
34262
34263 /*
34264 ** Restore the cursor to the position it was in (or as close to as possible)
34265 ** when saveCursorPosition() was called. Note that this call deletes the 
34266 ** saved position info stored by saveCursorPosition(), so there can be
34267 ** at most one effective restoreCursorPosition() call after each 
34268 ** saveCursorPosition().
34269 */
34270 SQLITE_PRIVATE int sqlite3BtreeRestoreCursorPosition(BtCursor *pCur){
34271   int rc;
34272   assert( cursorHoldsMutex(pCur) );
34273   assert( pCur->eState>=CURSOR_REQUIRESEEK );
34274   if( pCur->eState==CURSOR_FAULT ){
34275     return pCur->skip;
34276   }
34277   pCur->eState = CURSOR_INVALID;
34278   rc = sqlite3BtreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skip);
34279   if( rc==SQLITE_OK ){
34280     sqlite3_free(pCur->pKey);
34281     pCur->pKey = 0;
34282     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
34283   }
34284   return rc;
34285 }
34286
34287 #define restoreCursorPosition(p) \
34288   (p->eState>=CURSOR_REQUIRESEEK ? \
34289          sqlite3BtreeRestoreCursorPosition(p) : \
34290          SQLITE_OK)
34291
34292 /*
34293 ** Determine whether or not a cursor has moved from the position it
34294 ** was last placed at.  Cursors can move when the row they are pointing
34295 ** at is deleted out from under them.
34296 **
34297 ** This routine returns an error code if something goes wrong.  The
34298 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
34299 */
34300 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
34301   int rc;
34302
34303   rc = restoreCursorPosition(pCur);
34304   if( rc ){
34305     *pHasMoved = 1;
34306     return rc;
34307   }
34308   if( pCur->eState!=CURSOR_VALID || pCur->skip!=0 ){
34309     *pHasMoved = 1;
34310   }else{
34311     *pHasMoved = 0;
34312   }
34313   return SQLITE_OK;
34314 }
34315
34316 #ifndef SQLITE_OMIT_AUTOVACUUM
34317 /*
34318 ** Given a page number of a regular database page, return the page
34319 ** number for the pointer-map page that contains the entry for the
34320 ** input page number.
34321 */
34322 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
34323   int nPagesPerMapPage;
34324   Pgno iPtrMap, ret;
34325   assert( sqlite3_mutex_held(pBt->mutex) );
34326   nPagesPerMapPage = (pBt->usableSize/5)+1;
34327   iPtrMap = (pgno-2)/nPagesPerMapPage;
34328   ret = (iPtrMap*nPagesPerMapPage) + 2; 
34329   if( ret==PENDING_BYTE_PAGE(pBt) ){
34330     ret++;
34331   }
34332   return ret;
34333 }
34334
34335 /*
34336 ** Write an entry into the pointer map.
34337 **
34338 ** This routine updates the pointer map entry for page number 'key'
34339 ** so that it maps to type 'eType' and parent page number 'pgno'.
34340 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
34341 */
34342 static int ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent){
34343   DbPage *pDbPage;  /* The pointer map page */
34344   u8 *pPtrmap;      /* The pointer map data */
34345   Pgno iPtrmap;     /* The pointer map page number */
34346   int offset;       /* Offset in pointer map page */
34347   int rc;
34348
34349   assert( sqlite3_mutex_held(pBt->mutex) );
34350   /* The master-journal page number must never be used as a pointer map page */
34351   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
34352
34353   assert( pBt->autoVacuum );
34354   if( key==0 ){
34355     return SQLITE_CORRUPT_BKPT;
34356   }
34357   iPtrmap = PTRMAP_PAGENO(pBt, key);
34358   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
34359   if( rc!=SQLITE_OK ){
34360     return rc;
34361   }
34362   offset = PTRMAP_PTROFFSET(iPtrmap, key);
34363   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
34364
34365   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
34366     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
34367     rc = sqlite3PagerWrite(pDbPage);
34368     if( rc==SQLITE_OK ){
34369       pPtrmap[offset] = eType;
34370       put4byte(&pPtrmap[offset+1], parent);
34371     }
34372   }
34373
34374   sqlite3PagerUnref(pDbPage);
34375   return rc;
34376 }
34377
34378 /*
34379 ** Read an entry from the pointer map.
34380 **
34381 ** This routine retrieves the pointer map entry for page 'key', writing
34382 ** the type and parent page number to *pEType and *pPgno respectively.
34383 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
34384 */
34385 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
34386   DbPage *pDbPage;   /* The pointer map page */
34387   int iPtrmap;       /* Pointer map page index */
34388   u8 *pPtrmap;       /* Pointer map page data */
34389   int offset;        /* Offset of entry in pointer map */
34390   int rc;
34391
34392   assert( sqlite3_mutex_held(pBt->mutex) );
34393
34394   iPtrmap = PTRMAP_PAGENO(pBt, key);
34395   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
34396   if( rc!=0 ){
34397     return rc;
34398   }
34399   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
34400
34401   offset = PTRMAP_PTROFFSET(iPtrmap, key);
34402   assert( pEType!=0 );
34403   *pEType = pPtrmap[offset];
34404   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
34405
34406   sqlite3PagerUnref(pDbPage);
34407   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
34408   return SQLITE_OK;
34409 }
34410
34411 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
34412   #define ptrmapPut(w,x,y,z) SQLITE_OK
34413   #define ptrmapGet(w,x,y,z) SQLITE_OK
34414   #define ptrmapPutOvfl(y,z) SQLITE_OK
34415 #endif
34416
34417 /*
34418 ** Given a btree page and a cell index (0 means the first cell on
34419 ** the page, 1 means the second cell, and so forth) return a pointer
34420 ** to the cell content.
34421 **
34422 ** This routine works only for pages that do not contain overflow cells.
34423 */
34424 #define findCell(P,I) \
34425   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
34426
34427 /*
34428 ** This a more complex version of findCell() that works for
34429 ** pages that do contain overflow cells.  See insert
34430 */
34431 static u8 *findOverflowCell(MemPage *pPage, int iCell){
34432   int i;
34433   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34434   for(i=pPage->nOverflow-1; i>=0; i--){
34435     int k;
34436     struct _OvflCell *pOvfl;
34437     pOvfl = &pPage->aOvfl[i];
34438     k = pOvfl->idx;
34439     if( k<=iCell ){
34440       if( k==iCell ){
34441         return pOvfl->pCell;
34442       }
34443       iCell--;
34444     }
34445   }
34446   return findCell(pPage, iCell);
34447 }
34448
34449 /*
34450 ** Parse a cell content block and fill in the CellInfo structure.  There
34451 ** are two versions of this function.  sqlite3BtreeParseCell() takes a 
34452 ** cell index as the second argument and sqlite3BtreeParseCellPtr() 
34453 ** takes a pointer to the body of the cell as its second argument.
34454 **
34455 ** Within this file, the parseCell() macro can be called instead of
34456 ** sqlite3BtreeParseCellPtr(). Using some compilers, this will be faster.
34457 */
34458 SQLITE_PRIVATE void sqlite3BtreeParseCellPtr(
34459   MemPage *pPage,         /* Page containing the cell */
34460   u8 *pCell,              /* Pointer to the cell text. */
34461   CellInfo *pInfo         /* Fill in this structure */
34462 ){
34463   int n;                  /* Number bytes in cell content header */
34464   u32 nPayload;           /* Number of bytes of cell payload */
34465
34466   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34467
34468   pInfo->pCell = pCell;
34469   assert( pPage->leaf==0 || pPage->leaf==1 );
34470   n = pPage->childPtrSize;
34471   assert( n==4-4*pPage->leaf );
34472   if( pPage->intKey ){
34473     if( pPage->hasData ){
34474       n += getVarint32(&pCell[n], nPayload);
34475     }else{
34476       nPayload = 0;
34477     }
34478     n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
34479     pInfo->nData = nPayload;
34480   }else{
34481     pInfo->nData = 0;
34482     n += getVarint32(&pCell[n], nPayload);
34483     pInfo->nKey = nPayload;
34484   }
34485   pInfo->nPayload = nPayload;
34486   pInfo->nHeader = n;
34487   if( likely(nPayload<=pPage->maxLocal) ){
34488     /* This is the (easy) common case where the entire payload fits
34489     ** on the local page.  No overflow is required.
34490     */
34491     int nSize;          /* Total size of cell content in bytes */
34492     nSize = nPayload + n;
34493     pInfo->nLocal = nPayload;
34494     pInfo->iOverflow = 0;
34495     if( (nSize & ~3)==0 ){
34496       nSize = 4;        /* Minimum cell size is 4 */
34497     }
34498     pInfo->nSize = nSize;
34499   }else{
34500     /* If the payload will not fit completely on the local page, we have
34501     ** to decide how much to store locally and how much to spill onto
34502     ** overflow pages.  The strategy is to minimize the amount of unused
34503     ** space on overflow pages while keeping the amount of local storage
34504     ** in between minLocal and maxLocal.
34505     **
34506     ** Warning:  changing the way overflow payload is distributed in any
34507     ** way will result in an incompatible file format.
34508     */
34509     int minLocal;  /* Minimum amount of payload held locally */
34510     int maxLocal;  /* Maximum amount of payload held locally */
34511     int surplus;   /* Overflow payload available for local storage */
34512
34513     minLocal = pPage->minLocal;
34514     maxLocal = pPage->maxLocal;
34515     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
34516     if( surplus <= maxLocal ){
34517       pInfo->nLocal = surplus;
34518     }else{
34519       pInfo->nLocal = minLocal;
34520     }
34521     pInfo->iOverflow = pInfo->nLocal + n;
34522     pInfo->nSize = pInfo->iOverflow + 4;
34523   }
34524 }
34525 #define parseCell(pPage, iCell, pInfo) \
34526   sqlite3BtreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
34527 SQLITE_PRIVATE void sqlite3BtreeParseCell(
34528   MemPage *pPage,         /* Page containing the cell */
34529   int iCell,              /* The cell index.  First cell is 0 */
34530   CellInfo *pInfo         /* Fill in this structure */
34531 ){
34532   parseCell(pPage, iCell, pInfo);
34533 }
34534
34535 /*
34536 ** Compute the total number of bytes that a Cell needs in the cell
34537 ** data area of the btree-page.  The return number includes the cell
34538 ** data header and the local payload, but not any overflow page or
34539 ** the space used by the cell pointer.
34540 */
34541 #ifndef NDEBUG
34542 static u16 cellSize(MemPage *pPage, int iCell){
34543   CellInfo info;
34544   sqlite3BtreeParseCell(pPage, iCell, &info);
34545   return info.nSize;
34546 }
34547 #endif
34548 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
34549   CellInfo info;
34550   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
34551   return info.nSize;
34552 }
34553
34554 #ifndef SQLITE_OMIT_AUTOVACUUM
34555 /*
34556 ** If the cell pCell, part of page pPage contains a pointer
34557 ** to an overflow page, insert an entry into the pointer-map
34558 ** for the overflow page.
34559 */
34560 static int ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell){
34561   CellInfo info;
34562   assert( pCell!=0 );
34563   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
34564   assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
34565   if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
34566     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
34567     return ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno);
34568   }
34569   return SQLITE_OK;
34570 }
34571 /*
34572 ** If the cell with index iCell on page pPage contains a pointer
34573 ** to an overflow page, insert an entry into the pointer-map
34574 ** for the overflow page.
34575 */
34576 static int ptrmapPutOvfl(MemPage *pPage, int iCell){
34577   u8 *pCell;
34578   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34579   pCell = findOverflowCell(pPage, iCell);
34580   return ptrmapPutOvflPtr(pPage, pCell);
34581 }
34582 #endif
34583
34584
34585 /*
34586 ** Defragment the page given.  All Cells are moved to the
34587 ** end of the page and all free space is collected into one
34588 ** big FreeBlk that occurs in between the header and cell
34589 ** pointer array and the cell content area.
34590 */
34591 static int defragmentPage(MemPage *pPage){
34592   int i;                     /* Loop counter */
34593   int pc;                    /* Address of a i-th cell */
34594   int addr;                  /* Offset of first byte after cell pointer array */
34595   int hdr;                   /* Offset to the page header */
34596   int size;                  /* Size of a cell */
34597   int usableSize;            /* Number of usable bytes on a page */
34598   int cellOffset;            /* Offset to the cell pointer array */
34599   int cbrk;                  /* Offset to the cell content area */
34600   int nCell;                 /* Number of cells on the page */
34601   unsigned char *data;       /* The page data */
34602   unsigned char *temp;       /* Temp area for cell content */
34603
34604   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
34605   assert( pPage->pBt!=0 );
34606   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
34607   assert( pPage->nOverflow==0 );
34608   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34609   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
34610   data = pPage->aData;
34611   hdr = pPage->hdrOffset;
34612   cellOffset = pPage->cellOffset;
34613   nCell = pPage->nCell;
34614   assert( nCell==get2byte(&data[hdr+3]) );
34615   usableSize = pPage->pBt->usableSize;
34616   cbrk = get2byte(&data[hdr+5]);
34617   memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
34618   cbrk = usableSize;
34619   for(i=0; i<nCell; i++){
34620     u8 *pAddr;     /* The i-th cell pointer */
34621     pAddr = &data[cellOffset + i*2];
34622     pc = get2byte(pAddr);
34623     if( pc>=usableSize ){
34624       return SQLITE_CORRUPT_BKPT;
34625     }
34626     size = cellSizePtr(pPage, &temp[pc]);
34627     cbrk -= size;
34628     if( cbrk<cellOffset+2*nCell || pc+size>usableSize ){
34629       return SQLITE_CORRUPT_BKPT;
34630     }
34631     assert( cbrk+size<=usableSize && cbrk>=0 );
34632     memcpy(&data[cbrk], &temp[pc], size);
34633     put2byte(pAddr, cbrk);
34634   }
34635   assert( cbrk>=cellOffset+2*nCell );
34636   put2byte(&data[hdr+5], cbrk);
34637   data[hdr+1] = 0;
34638   data[hdr+2] = 0;
34639   data[hdr+7] = 0;
34640   addr = cellOffset+2*nCell;
34641   memset(&data[addr], 0, cbrk-addr);
34642   if( cbrk-addr!=pPage->nFree ){
34643     return SQLITE_CORRUPT_BKPT;
34644   }
34645   return SQLITE_OK;
34646 }
34647
34648 /*
34649 ** Allocate nByte bytes of space on a page.
34650 **
34651 ** Return the index into pPage->aData[] of the first byte of
34652 ** the new allocation.  The caller guarantees that there is enough
34653 ** space.  This routine will never fail.
34654 **
34655 ** If the page contains nBytes of free space but does not contain
34656 ** nBytes of contiguous free space, then this routine automatically
34657 ** calls defragementPage() to consolidate all free space before 
34658 ** allocating the new chunk.
34659 */
34660 static int allocateSpace(MemPage *pPage, int nByte){
34661   int addr, pc, hdr;
34662   int size;
34663   int nFrag;
34664   int top;
34665   int nCell;
34666   int cellOffset;
34667   unsigned char *data;
34668   
34669   data = pPage->aData;
34670   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
34671   assert( pPage->pBt );
34672   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34673   assert( nByte>=0 );  /* Minimum cell size is 4 */
34674   assert( pPage->nFree>=nByte );
34675   assert( pPage->nOverflow==0 );
34676   pPage->nFree -= nByte;
34677   hdr = pPage->hdrOffset;
34678
34679   nFrag = data[hdr+7];
34680   if( nFrag<60 ){
34681     /* Search the freelist looking for a slot big enough to satisfy the
34682     ** space request. */
34683     addr = hdr+1;
34684     while( (pc = get2byte(&data[addr]))>0 ){
34685       size = get2byte(&data[pc+2]);
34686       if( size>=nByte ){
34687         if( size<nByte+4 ){
34688           memcpy(&data[addr], &data[pc], 2);
34689           data[hdr+7] = nFrag + size - nByte;
34690           return pc;
34691         }else{
34692           put2byte(&data[pc+2], size-nByte);
34693           return pc + size - nByte;
34694         }
34695       }
34696       addr = pc;
34697     }
34698   }
34699
34700   /* Allocate memory from the gap in between the cell pointer array
34701   ** and the cell content area.
34702   */
34703   top = get2byte(&data[hdr+5]);
34704   nCell = get2byte(&data[hdr+3]);
34705   cellOffset = pPage->cellOffset;
34706   if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
34707     defragmentPage(pPage);
34708     top = get2byte(&data[hdr+5]);
34709   }
34710   top -= nByte;
34711   assert( cellOffset + 2*nCell <= top );
34712   put2byte(&data[hdr+5], top);
34713   return top;
34714 }
34715
34716 /*
34717 ** Return a section of the pPage->aData to the freelist.
34718 ** The first byte of the new free block is pPage->aDisk[start]
34719 ** and the size of the block is "size" bytes.
34720 **
34721 ** Most of the effort here is involved in coalesing adjacent
34722 ** free blocks into a single big free block.
34723 */
34724 static int freeSpace(MemPage *pPage, int start, int size){
34725   int addr, pbegin, hdr;
34726   unsigned char *data = pPage->aData;
34727
34728   assert( pPage->pBt!=0 );
34729   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
34730   assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
34731   assert( (start + size)<=pPage->pBt->usableSize );
34732   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34733   assert( size>=0 );   /* Minimum cell size is 4 */
34734
34735 #ifdef SQLITE_SECURE_DELETE
34736   /* Overwrite deleted information with zeros when the SECURE_DELETE 
34737   ** option is enabled at compile-time */
34738   memset(&data[start], 0, size);
34739 #endif
34740
34741   /* Add the space back into the linked list of freeblocks */
34742   hdr = pPage->hdrOffset;
34743   addr = hdr + 1;
34744   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
34745     assert( pbegin<=pPage->pBt->usableSize-4 );
34746     if( pbegin<=addr ) {
34747       return SQLITE_CORRUPT_BKPT;
34748     }
34749     addr = pbegin;
34750   }
34751   if ( pbegin>pPage->pBt->usableSize-4 ) {
34752     return SQLITE_CORRUPT_BKPT;
34753   }
34754   assert( pbegin>addr || pbegin==0 );
34755   put2byte(&data[addr], start);
34756   put2byte(&data[start], pbegin);
34757   put2byte(&data[start+2], size);
34758   pPage->nFree += size;
34759
34760   /* Coalesce adjacent free blocks */
34761   addr = pPage->hdrOffset + 1;
34762   while( (pbegin = get2byte(&data[addr]))>0 ){
34763     int pnext, psize;
34764     assert( pbegin>addr );
34765     assert( pbegin<=pPage->pBt->usableSize-4 );
34766     pnext = get2byte(&data[pbegin]);
34767     psize = get2byte(&data[pbegin+2]);
34768     if( pbegin + psize + 3 >= pnext && pnext>0 ){
34769       int frag = pnext - (pbegin+psize);
34770       if( (frag<0) || (frag>data[pPage->hdrOffset+7]) ){
34771         return SQLITE_CORRUPT_BKPT;
34772       }
34773       data[pPage->hdrOffset+7] -= frag;
34774       put2byte(&data[pbegin], get2byte(&data[pnext]));
34775       put2byte(&data[pbegin+2], pnext+get2byte(&data[pnext+2])-pbegin);
34776     }else{
34777       addr = pbegin;
34778     }
34779   }
34780
34781   /* If the cell content area begins with a freeblock, remove it. */
34782   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
34783     int top;
34784     pbegin = get2byte(&data[hdr+1]);
34785     memcpy(&data[hdr+1], &data[pbegin], 2);
34786     top = get2byte(&data[hdr+5]);
34787     put2byte(&data[hdr+5], top + get2byte(&data[pbegin+2]));
34788   }
34789   return SQLITE_OK;
34790 }
34791
34792 /*
34793 ** Decode the flags byte (the first byte of the header) for a page
34794 ** and initialize fields of the MemPage structure accordingly.
34795 **
34796 ** Only the following combinations are supported.  Anything different
34797 ** indicates a corrupt database files:
34798 **
34799 **         PTF_ZERODATA
34800 **         PTF_ZERODATA | PTF_LEAF
34801 **         PTF_LEAFDATA | PTF_INTKEY
34802 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
34803 */
34804 static int decodeFlags(MemPage *pPage, int flagByte){
34805   BtShared *pBt;     /* A copy of pPage->pBt */
34806
34807   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
34808   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34809   pPage->leaf = flagByte>>3;  assert( PTF_LEAF == 1<<3 );
34810   flagByte &= ~PTF_LEAF;
34811   pPage->childPtrSize = 4-4*pPage->leaf;
34812   pBt = pPage->pBt;
34813   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
34814     pPage->intKey = 1;
34815     pPage->hasData = pPage->leaf;
34816     pPage->maxLocal = pBt->maxLeaf;
34817     pPage->minLocal = pBt->minLeaf;
34818   }else if( flagByte==PTF_ZERODATA ){
34819     pPage->intKey = 0;
34820     pPage->hasData = 0;
34821     pPage->maxLocal = pBt->maxLocal;
34822     pPage->minLocal = pBt->minLocal;
34823   }else{
34824     return SQLITE_CORRUPT_BKPT;
34825   }
34826   return SQLITE_OK;
34827 }
34828
34829 /*
34830 ** Initialize the auxiliary information for a disk block.
34831 **
34832 ** Return SQLITE_OK on success.  If we see that the page does
34833 ** not contain a well-formed database page, then return 
34834 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
34835 ** guarantee that the page is well-formed.  It only shows that
34836 ** we failed to detect any corruption.
34837 */
34838 SQLITE_PRIVATE int sqlite3BtreeInitPage(MemPage *pPage){
34839
34840   assert( pPage->pBt!=0 );
34841   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34842   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
34843   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
34844   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
34845
34846   if( !pPage->isInit ){
34847     int pc;            /* Address of a freeblock within pPage->aData[] */
34848     int hdr;           /* Offset to beginning of page header */
34849     u8 *data;          /* Equal to pPage->aData */
34850     BtShared *pBt;        /* The main btree structure */
34851     int usableSize;    /* Amount of usable space on each page */
34852     int cellOffset;    /* Offset from start of page to first cell pointer */
34853     int nFree;         /* Number of unused bytes on the page */
34854     int top;           /* First byte of the cell content area */
34855
34856     pBt = pPage->pBt;
34857
34858     hdr = pPage->hdrOffset;
34859     data = pPage->aData;
34860     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
34861     assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
34862     pPage->maskPage = pBt->pageSize - 1;
34863     pPage->nOverflow = 0;
34864     usableSize = pBt->usableSize;
34865     pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
34866     top = get2byte(&data[hdr+5]);
34867     pPage->nCell = get2byte(&data[hdr+3]);
34868     if( pPage->nCell>MX_CELL(pBt) ){
34869       /* To many cells for a single page.  The page must be corrupt */
34870       return SQLITE_CORRUPT_BKPT;
34871     }
34872   
34873     /* Compute the total free space on the page */
34874     pc = get2byte(&data[hdr+1]);
34875     nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
34876     while( pc>0 ){
34877       int next, size;
34878       if( pc>usableSize-4 ){
34879         /* Free block is off the page */
34880         return SQLITE_CORRUPT_BKPT; 
34881       }
34882       next = get2byte(&data[pc]);
34883       size = get2byte(&data[pc+2]);
34884       if( next>0 && next<=pc+size+3 ){
34885         /* Free blocks must be in accending order */
34886         return SQLITE_CORRUPT_BKPT; 
34887       }
34888       nFree += size;
34889       pc = next;
34890     }
34891     pPage->nFree = nFree;
34892     if( nFree>=usableSize ){
34893       /* Free space cannot exceed total page size */
34894       return SQLITE_CORRUPT_BKPT; 
34895     }
34896
34897 #if 0
34898   /* Check that all the offsets in the cell offset array are within range. 
34899   ** 
34900   ** Omitting this consistency check and using the pPage->maskPage mask
34901   ** to prevent overrunning the page buffer in findCell() results in a
34902   ** 2.5% performance gain.
34903   */
34904   {
34905     u8 *pOff;        /* Iterator used to check all cell offsets are in range */
34906     u8 *pEnd;        /* Pointer to end of cell offset array */
34907     u8 mask;         /* Mask of bits that must be zero in MSB of cell offsets */
34908     mask = ~(((u8)(pBt->pageSize>>8))-1);
34909     pEnd = &data[cellOffset + pPage->nCell*2];
34910     for(pOff=&data[cellOffset]; pOff!=pEnd && !((*pOff)&mask); pOff+=2);
34911     if( pOff!=pEnd ){
34912       return SQLITE_CORRUPT_BKPT;
34913     }
34914   }
34915 #endif
34916
34917     pPage->isInit = 1;
34918   }
34919   return SQLITE_OK;
34920 }
34921
34922 /*
34923 ** Set up a raw page so that it looks like a database page holding
34924 ** no entries.
34925 */
34926 static void zeroPage(MemPage *pPage, int flags){
34927   unsigned char *data = pPage->aData;
34928   BtShared *pBt = pPage->pBt;
34929   int hdr = pPage->hdrOffset;
34930   int first;
34931
34932   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
34933   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
34934   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
34935   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
34936   assert( sqlite3_mutex_held(pBt->mutex) );
34937   /*memset(&data[hdr], 0, pBt->usableSize - hdr);*/
34938   data[hdr] = flags;
34939   first = hdr + 8 + 4*((flags&PTF_LEAF)==0);
34940   memset(&data[hdr+1], 0, 4);
34941   data[hdr+7] = 0;
34942   put2byte(&data[hdr+5], pBt->usableSize);
34943   pPage->nFree = pBt->usableSize - first;
34944   decodeFlags(pPage, flags);
34945   pPage->hdrOffset = hdr;
34946   pPage->cellOffset = first;
34947   pPage->nOverflow = 0;
34948   assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
34949   pPage->maskPage = pBt->pageSize - 1;
34950   pPage->nCell = 0;
34951   pPage->isInit = 1;
34952 }
34953
34954
34955 /*
34956 ** Convert a DbPage obtained from the pager into a MemPage used by
34957 ** the btree layer.
34958 */
34959 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
34960   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
34961   pPage->aData = sqlite3PagerGetData(pDbPage);
34962   pPage->pDbPage = pDbPage;
34963   pPage->pBt = pBt;
34964   pPage->pgno = pgno;
34965   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
34966   return pPage; 
34967 }
34968
34969 /*
34970 ** Get a page from the pager.  Initialize the MemPage.pBt and
34971 ** MemPage.aData elements if needed.
34972 **
34973 ** If the noContent flag is set, it means that we do not care about
34974 ** the content of the page at this time.  So do not go to the disk
34975 ** to fetch the content.  Just fill in the content with zeros for now.
34976 ** If in the future we call sqlite3PagerWrite() on this page, that
34977 ** means we have started to be concerned about content and the disk
34978 ** read should occur at that point.
34979 */
34980 SQLITE_PRIVATE int sqlite3BtreeGetPage(
34981   BtShared *pBt,       /* The btree */
34982   Pgno pgno,           /* Number of the page to fetch */
34983   MemPage **ppPage,    /* Return the page in this parameter */
34984   int noContent        /* Do not load page content if true */
34985 ){
34986   int rc;
34987   DbPage *pDbPage;
34988
34989   assert( sqlite3_mutex_held(pBt->mutex) );
34990   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
34991   if( rc ) return rc;
34992   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
34993   return SQLITE_OK;
34994 }
34995
34996 /*
34997 ** Return the size of the database file in pages. If there is any kind of
34998 ** error, return ((unsigned int)-1).
34999 */
35000 static Pgno pagerPagecount(BtShared *pBt){
35001   int nPage = -1;
35002   int rc;
35003   assert( pBt->pPage1 );
35004   rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
35005   assert( rc==SQLITE_OK || nPage==-1 );
35006   return (Pgno)nPage;
35007 }
35008
35009 /*
35010 ** Get a page from the pager and initialize it.  This routine
35011 ** is just a convenience wrapper around separate calls to
35012 ** sqlite3BtreeGetPage() and sqlite3BtreeInitPage().
35013 */
35014 static int getAndInitPage(
35015   BtShared *pBt,          /* The database file */
35016   Pgno pgno,           /* Number of the page to get */
35017   MemPage **ppPage     /* Write the page pointer here */
35018 ){
35019   int rc;
35020   DbPage *pDbPage;
35021   MemPage *pPage;
35022
35023   assert( sqlite3_mutex_held(pBt->mutex) );
35024   if( pgno==0 ){
35025     return SQLITE_CORRUPT_BKPT; 
35026   }
35027
35028   /* It is often the case that the page we want is already in cache.
35029   ** If so, get it directly.  This saves us from having to call
35030   ** pagerPagecount() to make sure pgno is within limits, which results
35031   ** in a measureable performance improvements.
35032   */
35033   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
35034   if( pDbPage ){
35035     /* Page is already in cache */
35036     *ppPage = pPage = btreePageFromDbPage(pDbPage, pgno, pBt);
35037     rc = SQLITE_OK;
35038   }else{
35039     /* Page not in cache.  Acquire it. */
35040     if( pgno>pagerPagecount(pBt) ){
35041       return SQLITE_CORRUPT_BKPT; 
35042     }
35043     rc = sqlite3BtreeGetPage(pBt, pgno, ppPage, 0);
35044     if( rc ) return rc;
35045     pPage = *ppPage;
35046   }
35047   if( !pPage->isInit ){
35048     rc = sqlite3BtreeInitPage(pPage);
35049   }
35050   if( rc!=SQLITE_OK ){
35051     releasePage(pPage);
35052     *ppPage = 0;
35053   }
35054   return rc;
35055 }
35056
35057 /*
35058 ** Release a MemPage.  This should be called once for each prior
35059 ** call to sqlite3BtreeGetPage.
35060 */
35061 static void releasePage(MemPage *pPage){
35062   if( pPage ){
35063     assert( pPage->aData );
35064     assert( pPage->pBt );
35065     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
35066     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
35067     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
35068     sqlite3PagerUnref(pPage->pDbPage);
35069   }
35070 }
35071
35072 /*
35073 ** During a rollback, when the pager reloads information into the cache
35074 ** so that the cache is restored to its original state at the start of
35075 ** the transaction, for each page restored this routine is called.
35076 **
35077 ** This routine needs to reset the extra data section at the end of the
35078 ** page to agree with the restored data.
35079 */
35080 static void pageReinit(DbPage *pData){
35081   MemPage *pPage;
35082   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
35083   if( pPage->isInit ){
35084     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
35085     pPage->isInit = 0;
35086     if( sqlite3PagerPageRefcount(pData)>0 ){
35087       sqlite3BtreeInitPage(pPage);
35088     }
35089   }
35090 }
35091
35092 /*
35093 ** Invoke the busy handler for a btree.
35094 */
35095 static int btreeInvokeBusyHandler(void *pArg){
35096   BtShared *pBt = (BtShared*)pArg;
35097   assert( pBt->db );
35098   assert( sqlite3_mutex_held(pBt->db->mutex) );
35099   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
35100 }
35101
35102 /*
35103 ** Open a database file.
35104 ** 
35105 ** zFilename is the name of the database file.  If zFilename is NULL
35106 ** a new database with a random name is created.  This randomly named
35107 ** database file will be deleted when sqlite3BtreeClose() is called.
35108 ** If zFilename is ":memory:" then an in-memory database is created
35109 ** that is automatically destroyed when it is closed.
35110 */
35111 SQLITE_PRIVATE int sqlite3BtreeOpen(
35112   const char *zFilename,  /* Name of the file containing the BTree database */
35113   sqlite3 *db,            /* Associated database handle */
35114   Btree **ppBtree,        /* Pointer to new Btree object written here */
35115   int flags,              /* Options */
35116   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
35117 ){
35118   sqlite3_vfs *pVfs;      /* The VFS to use for this btree */
35119   BtShared *pBt = 0;      /* Shared part of btree structure */
35120   Btree *p;               /* Handle to return */
35121   int rc = SQLITE_OK;
35122   int nReserve;
35123   unsigned char zDbHeader[100];
35124
35125   /* Set the variable isMemdb to true for an in-memory database, or 
35126   ** false for a file-based database. This symbol is only required if
35127   ** either of the shared-data or autovacuum features are compiled 
35128   ** into the library.
35129   */
35130 #if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
35131   #ifdef SQLITE_OMIT_MEMORYDB
35132     const int isMemdb = 0;
35133   #else
35134     const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
35135   #endif
35136 #endif
35137
35138   assert( db!=0 );
35139   assert( sqlite3_mutex_held(db->mutex) );
35140
35141   pVfs = db->pVfs;
35142   p = sqlite3MallocZero(sizeof(Btree));
35143   if( !p ){
35144     return SQLITE_NOMEM;
35145   }
35146   p->inTrans = TRANS_NONE;
35147   p->db = db;
35148
35149 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
35150   /*
35151   ** If this Btree is a candidate for shared cache, try to find an
35152   ** existing BtShared object that we can share with
35153   */
35154   if( isMemdb==0
35155    && (db->flags & SQLITE_Vtab)==0
35156    && zFilename && zFilename[0]
35157   ){
35158     if( sqlite3GlobalConfig.sharedCacheEnabled ){
35159       int nFullPathname = pVfs->mxPathname+1;
35160       char *zFullPathname = sqlite3Malloc(nFullPathname);
35161       sqlite3_mutex *mutexShared;
35162       p->sharable = 1;
35163       db->flags |= SQLITE_SharedCache;
35164       if( !zFullPathname ){
35165         sqlite3_free(p);
35166         return SQLITE_NOMEM;
35167       }
35168       sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
35169       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
35170       sqlite3_mutex_enter(mutexShared);
35171       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
35172         assert( pBt->nRef>0 );
35173         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
35174                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
35175           p->pBt = pBt;
35176           pBt->nRef++;
35177           break;
35178         }
35179       }
35180       sqlite3_mutex_leave(mutexShared);
35181       sqlite3_free(zFullPathname);
35182     }
35183 #ifdef SQLITE_DEBUG
35184     else{
35185       /* In debug mode, we mark all persistent databases as sharable
35186       ** even when they are not.  This exercises the locking code and
35187       ** gives more opportunity for asserts(sqlite3_mutex_held())
35188       ** statements to find locking problems.
35189       */
35190       p->sharable = 1;
35191     }
35192 #endif
35193   }
35194 #endif
35195   if( pBt==0 ){
35196     /*
35197     ** The following asserts make sure that structures used by the btree are
35198     ** the right size.  This is to guard against size changes that result
35199     ** when compiling on a different architecture.
35200     */
35201     assert( sizeof(i64)==8 || sizeof(i64)==4 );
35202     assert( sizeof(u64)==8 || sizeof(u64)==4 );
35203     assert( sizeof(u32)==4 );
35204     assert( sizeof(u16)==2 );
35205     assert( sizeof(Pgno)==4 );
35206   
35207     pBt = sqlite3MallocZero( sizeof(*pBt) );
35208     if( pBt==0 ){
35209       rc = SQLITE_NOMEM;
35210       goto btree_open_out;
35211     }
35212     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
35213                           EXTRA_SIZE, flags, vfsFlags);
35214     if( rc==SQLITE_OK ){
35215       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
35216     }
35217     if( rc!=SQLITE_OK ){
35218       goto btree_open_out;
35219     }
35220     sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
35221     p->pBt = pBt;
35222   
35223     sqlite3PagerSetReiniter(pBt->pPager, pageReinit);
35224     pBt->pCursor = 0;
35225     pBt->pPage1 = 0;
35226     pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
35227     pBt->pageSize = get2byte(&zDbHeader[16]);
35228     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
35229          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
35230       pBt->pageSize = 0;
35231       sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
35232 #ifndef SQLITE_OMIT_AUTOVACUUM
35233       /* If the magic name ":memory:" will create an in-memory database, then
35234       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
35235       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
35236       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
35237       ** regular file-name. In this case the auto-vacuum applies as per normal.
35238       */
35239       if( zFilename && !isMemdb ){
35240         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
35241         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
35242       }
35243 #endif
35244       nReserve = 0;
35245     }else{
35246       nReserve = zDbHeader[20];
35247       pBt->pageSizeFixed = 1;
35248 #ifndef SQLITE_OMIT_AUTOVACUUM
35249       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
35250       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
35251 #endif
35252     }
35253     pBt->usableSize = pBt->pageSize - nReserve;
35254     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
35255     sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
35256    
35257 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
35258     /* Add the new BtShared object to the linked list sharable BtShareds.
35259     */
35260     if( p->sharable ){
35261       sqlite3_mutex *mutexShared;
35262       pBt->nRef = 1;
35263       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
35264       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
35265         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
35266         if( pBt->mutex==0 ){
35267           rc = SQLITE_NOMEM;
35268           db->mallocFailed = 0;
35269           goto btree_open_out;
35270         }
35271       }
35272       sqlite3_mutex_enter(mutexShared);
35273       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
35274       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
35275       sqlite3_mutex_leave(mutexShared);
35276     }
35277 #endif
35278   }
35279
35280 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
35281   /* If the new Btree uses a sharable pBtShared, then link the new
35282   ** Btree into the list of all sharable Btrees for the same connection.
35283   ** The list is kept in ascending order by pBt address.
35284   */
35285   if( p->sharable ){
35286     int i;
35287     Btree *pSib;
35288     for(i=0; i<db->nDb; i++){
35289       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
35290         while( pSib->pPrev ){ pSib = pSib->pPrev; }
35291         if( p->pBt<pSib->pBt ){
35292           p->pNext = pSib;
35293           p->pPrev = 0;
35294           pSib->pPrev = p;
35295         }else{
35296           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
35297             pSib = pSib->pNext;
35298           }
35299           p->pNext = pSib->pNext;
35300           p->pPrev = pSib;
35301           if( p->pNext ){
35302             p->pNext->pPrev = p;
35303           }
35304           pSib->pNext = p;
35305         }
35306         break;
35307       }
35308     }
35309   }
35310 #endif
35311   *ppBtree = p;
35312
35313 btree_open_out:
35314   if( rc!=SQLITE_OK ){
35315     if( pBt && pBt->pPager ){
35316       sqlite3PagerClose(pBt->pPager);
35317     }
35318     sqlite3_free(pBt);
35319     sqlite3_free(p);
35320     *ppBtree = 0;
35321   }
35322   return rc;
35323 }
35324
35325 /*
35326 ** Decrement the BtShared.nRef counter.  When it reaches zero,
35327 ** remove the BtShared structure from the sharing list.  Return
35328 ** true if the BtShared.nRef counter reaches zero and return
35329 ** false if it is still positive.
35330 */
35331 static int removeFromSharingList(BtShared *pBt){
35332 #ifndef SQLITE_OMIT_SHARED_CACHE
35333   sqlite3_mutex *pMaster;
35334   BtShared *pList;
35335   int removed = 0;
35336
35337   assert( sqlite3_mutex_notheld(pBt->mutex) );
35338   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
35339   sqlite3_mutex_enter(pMaster);
35340   pBt->nRef--;
35341   if( pBt->nRef<=0 ){
35342     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
35343       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
35344     }else{
35345       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
35346       while( ALWAYS(pList) && pList->pNext!=pBt ){
35347         pList=pList->pNext;
35348       }
35349       if( ALWAYS(pList) ){
35350         pList->pNext = pBt->pNext;
35351       }
35352     }
35353     if( SQLITE_THREADSAFE ){
35354       sqlite3_mutex_free(pBt->mutex);
35355     }
35356     removed = 1;
35357   }
35358   sqlite3_mutex_leave(pMaster);
35359   return removed;
35360 #else
35361   return 1;
35362 #endif
35363 }
35364
35365 /*
35366 ** Make sure pBt->pTmpSpace points to an allocation of 
35367 ** MX_CELL_SIZE(pBt) bytes.
35368 */
35369 static void allocateTempSpace(BtShared *pBt){
35370   if( !pBt->pTmpSpace ){
35371     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
35372   }
35373 }
35374
35375 /*
35376 ** Free the pBt->pTmpSpace allocation
35377 */
35378 static void freeTempSpace(BtShared *pBt){
35379   sqlite3PageFree( pBt->pTmpSpace);
35380   pBt->pTmpSpace = 0;
35381 }
35382
35383 /*
35384 ** Close an open database and invalidate all cursors.
35385 */
35386 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
35387   BtShared *pBt = p->pBt;
35388   BtCursor *pCur;
35389
35390   /* Close all cursors opened via this handle.  */
35391   assert( sqlite3_mutex_held(p->db->mutex) );
35392   sqlite3BtreeEnter(p);
35393   pBt->db = p->db;
35394   pCur = pBt->pCursor;
35395   while( pCur ){
35396     BtCursor *pTmp = pCur;
35397     pCur = pCur->pNext;
35398     if( pTmp->pBtree==p ){
35399       sqlite3BtreeCloseCursor(pTmp);
35400     }
35401   }
35402
35403   /* Rollback any active transaction and free the handle structure.
35404   ** The call to sqlite3BtreeRollback() drops any table-locks held by
35405   ** this handle.
35406   */
35407   sqlite3BtreeRollback(p);
35408   sqlite3BtreeLeave(p);
35409
35410   /* If there are still other outstanding references to the shared-btree
35411   ** structure, return now. The remainder of this procedure cleans 
35412   ** up the shared-btree.
35413   */
35414   assert( p->wantToLock==0 && p->locked==0 );
35415   if( !p->sharable || removeFromSharingList(pBt) ){
35416     /* The pBt is no longer on the sharing list, so we can access
35417     ** it without having to hold the mutex.
35418     **
35419     ** Clean out and delete the BtShared object.
35420     */
35421     assert( !pBt->pCursor );
35422     sqlite3PagerClose(pBt->pPager);
35423     if( pBt->xFreeSchema && pBt->pSchema ){
35424       pBt->xFreeSchema(pBt->pSchema);
35425     }
35426     sqlite3_free(pBt->pSchema);
35427     freeTempSpace(pBt);
35428     sqlite3_free(pBt);
35429   }
35430
35431 #ifndef SQLITE_OMIT_SHARED_CACHE
35432   assert( p->wantToLock==0 );
35433   assert( p->locked==0 );
35434   if( p->pPrev ) p->pPrev->pNext = p->pNext;
35435   if( p->pNext ) p->pNext->pPrev = p->pPrev;
35436 #endif
35437
35438   sqlite3_free(p);
35439   return SQLITE_OK;
35440 }
35441
35442 /*
35443 ** Change the limit on the number of pages allowed in the cache.
35444 **
35445 ** The maximum number of cache pages is set to the absolute
35446 ** value of mxPage.  If mxPage is negative, the pager will
35447 ** operate asynchronously - it will not stop to do fsync()s
35448 ** to insure data is written to the disk surface before
35449 ** continuing.  Transactions still work if synchronous is off,
35450 ** and the database cannot be corrupted if this program
35451 ** crashes.  But if the operating system crashes or there is
35452 ** an abrupt power failure when synchronous is off, the database
35453 ** could be left in an inconsistent and unrecoverable state.
35454 ** Synchronous is on by default so database corruption is not
35455 ** normally a worry.
35456 */
35457 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
35458   BtShared *pBt = p->pBt;
35459   assert( sqlite3_mutex_held(p->db->mutex) );
35460   sqlite3BtreeEnter(p);
35461   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
35462   sqlite3BtreeLeave(p);
35463   return SQLITE_OK;
35464 }
35465
35466 /*
35467 ** Change the way data is synced to disk in order to increase or decrease
35468 ** how well the database resists damage due to OS crashes and power
35469 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
35470 ** there is a high probability of damage)  Level 2 is the default.  There
35471 ** is a very low but non-zero probability of damage.  Level 3 reduces the
35472 ** probability of damage to near zero but with a write performance reduction.
35473 */
35474 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
35475 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
35476   BtShared *pBt = p->pBt;
35477   assert( sqlite3_mutex_held(p->db->mutex) );
35478   sqlite3BtreeEnter(p);
35479   sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
35480   sqlite3BtreeLeave(p);
35481   return SQLITE_OK;
35482 }
35483 #endif
35484
35485 /*
35486 ** Return TRUE if the given btree is set to safety level 1.  In other
35487 ** words, return TRUE if no sync() occurs on the disk files.
35488 */
35489 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
35490   BtShared *pBt = p->pBt;
35491   int rc;
35492   assert( sqlite3_mutex_held(p->db->mutex) );  
35493   sqlite3BtreeEnter(p);
35494   assert( pBt && pBt->pPager );
35495   rc = sqlite3PagerNosync(pBt->pPager);
35496   sqlite3BtreeLeave(p);
35497   return rc;
35498 }
35499
35500 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
35501 /*
35502 ** Change the default pages size and the number of reserved bytes per page.
35503 **
35504 ** The page size must be a power of 2 between 512 and 65536.  If the page
35505 ** size supplied does not meet this constraint then the page size is not
35506 ** changed.
35507 **
35508 ** Page sizes are constrained to be a power of two so that the region
35509 ** of the database file used for locking (beginning at PENDING_BYTE,
35510 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
35511 ** at the beginning of a page.
35512 **
35513 ** If parameter nReserve is less than zero, then the number of reserved
35514 ** bytes per page is left unchanged.
35515 */
35516 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve){
35517   int rc = SQLITE_OK;
35518   BtShared *pBt = p->pBt;
35519   sqlite3BtreeEnter(p);
35520   if( pBt->pageSizeFixed ){
35521     sqlite3BtreeLeave(p);
35522     return SQLITE_READONLY;
35523   }
35524   if( nReserve<0 ){
35525     nReserve = pBt->pageSize - pBt->usableSize;
35526   }
35527   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
35528         ((pageSize-1)&pageSize)==0 ){
35529     assert( (pageSize & 7)==0 );
35530     assert( !pBt->pPage1 && !pBt->pCursor );
35531     pBt->pageSize = pageSize;
35532     freeTempSpace(pBt);
35533     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
35534   }
35535   pBt->usableSize = pBt->pageSize - nReserve;
35536   sqlite3BtreeLeave(p);
35537   return rc;
35538 }
35539
35540 /*
35541 ** Return the currently defined page size
35542 */
35543 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
35544   return p->pBt->pageSize;
35545 }
35546 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
35547   int n;
35548   sqlite3BtreeEnter(p);
35549   n = p->pBt->pageSize - p->pBt->usableSize;
35550   sqlite3BtreeLeave(p);
35551   return n;
35552 }
35553
35554 /*
35555 ** Set the maximum page count for a database if mxPage is positive.
35556 ** No changes are made if mxPage is 0 or negative.
35557 ** Regardless of the value of mxPage, return the maximum page count.
35558 */
35559 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
35560   int n;
35561   sqlite3BtreeEnter(p);
35562   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
35563   sqlite3BtreeLeave(p);
35564   return n;
35565 }
35566 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
35567
35568 /*
35569 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
35570 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
35571 ** is disabled. The default value for the auto-vacuum property is 
35572 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
35573 */
35574 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
35575 #ifdef SQLITE_OMIT_AUTOVACUUM
35576   return SQLITE_READONLY;
35577 #else
35578   BtShared *pBt = p->pBt;
35579   int rc = SQLITE_OK;
35580   int av = (autoVacuum?1:0);
35581
35582   sqlite3BtreeEnter(p);
35583   if( pBt->pageSizeFixed && av!=pBt->autoVacuum ){
35584     rc = SQLITE_READONLY;
35585   }else{
35586     pBt->autoVacuum = av;
35587   }
35588   sqlite3BtreeLeave(p);
35589   return rc;
35590 #endif
35591 }
35592
35593 /*
35594 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
35595 ** enabled 1 is returned. Otherwise 0.
35596 */
35597 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
35598 #ifdef SQLITE_OMIT_AUTOVACUUM
35599   return BTREE_AUTOVACUUM_NONE;
35600 #else
35601   int rc;
35602   sqlite3BtreeEnter(p);
35603   rc = (
35604     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
35605     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
35606     BTREE_AUTOVACUUM_INCR
35607   );
35608   sqlite3BtreeLeave(p);
35609   return rc;
35610 #endif
35611 }
35612
35613
35614 /*
35615 ** Get a reference to pPage1 of the database file.  This will
35616 ** also acquire a readlock on that file.
35617 **
35618 ** SQLITE_OK is returned on success.  If the file is not a
35619 ** well-formed database file, then SQLITE_CORRUPT is returned.
35620 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
35621 ** is returned if we run out of memory. 
35622 */
35623 static int lockBtree(BtShared *pBt){
35624   int rc;
35625   MemPage *pPage1;
35626   int nPage;
35627
35628   assert( sqlite3_mutex_held(pBt->mutex) );
35629   if( pBt->pPage1 ) return SQLITE_OK;
35630   rc = sqlite3BtreeGetPage(pBt, 1, &pPage1, 0);
35631   if( rc!=SQLITE_OK ) return rc;
35632
35633   /* Do some checking to help insure the file we opened really is
35634   ** a valid database file. 
35635   */
35636   rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
35637   if( rc!=SQLITE_OK ){
35638     goto page1_init_failed;
35639   }else if( nPage>0 ){
35640     int pageSize;
35641     int usableSize;
35642     u8 *page1 = pPage1->aData;
35643     rc = SQLITE_NOTADB;
35644     if( memcmp(page1, zMagicHeader, 16)!=0 ){
35645       goto page1_init_failed;
35646     }
35647     if( page1[18]>1 ){
35648       pBt->readOnly = 1;
35649     }
35650     if( page1[19]>1 ){
35651       goto page1_init_failed;
35652     }
35653
35654     /* The maximum embedded fraction must be exactly 25%.  And the minimum
35655     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
35656     ** The original design allowed these amounts to vary, but as of
35657     ** version 3.6.0, we require them to be fixed.
35658     */
35659     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
35660       goto page1_init_failed;
35661     }
35662     pageSize = get2byte(&page1[16]);
35663     if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
35664         (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
35665     ){
35666       goto page1_init_failed;
35667     }
35668     assert( (pageSize & 7)==0 );
35669     usableSize = pageSize - page1[20];
35670     if( pageSize!=pBt->pageSize ){
35671       /* After reading the first page of the database assuming a page size
35672       ** of BtShared.pageSize, we have discovered that the page-size is
35673       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
35674       ** zero and return SQLITE_OK. The caller will call this function
35675       ** again with the correct page-size.
35676       */
35677       releasePage(pPage1);
35678       pBt->usableSize = usableSize;
35679       pBt->pageSize = pageSize;
35680       freeTempSpace(pBt);
35681       sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
35682       return SQLITE_OK;
35683     }
35684     if( usableSize<500 ){
35685       goto page1_init_failed;
35686     }
35687     pBt->pageSize = pageSize;
35688     pBt->usableSize = usableSize;
35689 #ifndef SQLITE_OMIT_AUTOVACUUM
35690     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
35691     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
35692 #endif
35693   }
35694
35695   /* maxLocal is the maximum amount of payload to store locally for
35696   ** a cell.  Make sure it is small enough so that at least minFanout
35697   ** cells can will fit on one page.  We assume a 10-byte page header.
35698   ** Besides the payload, the cell must store:
35699   **     2-byte pointer to the cell
35700   **     4-byte child pointer
35701   **     9-byte nKey value
35702   **     4-byte nData value
35703   **     4-byte overflow page pointer
35704   ** So a cell consists of a 2-byte poiner, a header which is as much as
35705   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
35706   ** page pointer.
35707   */
35708   pBt->maxLocal = (pBt->usableSize-12)*64/255 - 23;
35709   pBt->minLocal = (pBt->usableSize-12)*32/255 - 23;
35710   pBt->maxLeaf = pBt->usableSize - 35;
35711   pBt->minLeaf = (pBt->usableSize-12)*32/255 - 23;
35712   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
35713   pBt->pPage1 = pPage1;
35714   return SQLITE_OK;
35715
35716 page1_init_failed:
35717   releasePage(pPage1);
35718   pBt->pPage1 = 0;
35719   return rc;
35720 }
35721
35722 /*
35723 ** This routine works like lockBtree() except that it also invokes the
35724 ** busy callback if there is lock contention.
35725 */
35726 static int lockBtreeWithRetry(Btree *pRef){
35727   int rc = SQLITE_OK;
35728
35729   assert( sqlite3BtreeHoldsMutex(pRef) );
35730   if( pRef->inTrans==TRANS_NONE ){
35731     u8 inTransaction = pRef->pBt->inTransaction;
35732     btreeIntegrity(pRef);
35733     rc = sqlite3BtreeBeginTrans(pRef, 0);
35734     pRef->pBt->inTransaction = inTransaction;
35735     pRef->inTrans = TRANS_NONE;
35736     if( rc==SQLITE_OK ){
35737       pRef->pBt->nTransaction--;
35738     }
35739     btreeIntegrity(pRef);
35740   }
35741   return rc;
35742 }
35743        
35744
35745 /*
35746 ** If there are no outstanding cursors and we are not in the middle
35747 ** of a transaction but there is a read lock on the database, then
35748 ** this routine unrefs the first page of the database file which 
35749 ** has the effect of releasing the read lock.
35750 **
35751 ** If there are any outstanding cursors, this routine is a no-op.
35752 **
35753 ** If there is a transaction in progress, this routine is a no-op.
35754 */
35755 static void unlockBtreeIfUnused(BtShared *pBt){
35756   assert( sqlite3_mutex_held(pBt->mutex) );
35757   if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
35758     if( sqlite3PagerRefcount(pBt->pPager)>=1 ){
35759       assert( pBt->pPage1->aData );
35760 #if 0
35761       if( pBt->pPage1->aData==0 ){
35762         MemPage *pPage = pBt->pPage1;
35763         pPage->aData = sqlite3PagerGetData(pPage->pDbPage);
35764         pPage->pBt = pBt;
35765         pPage->pgno = 1;
35766       }
35767 #endif
35768       releasePage(pBt->pPage1);
35769     }
35770     pBt->pPage1 = 0;
35771     pBt->inStmt = 0;
35772   }
35773 }
35774
35775 /*
35776 ** Create a new database by initializing the first page of the
35777 ** file.
35778 */
35779 static int newDatabase(BtShared *pBt){
35780   MemPage *pP1;
35781   unsigned char *data;
35782   int rc;
35783   int nPage;
35784
35785   assert( sqlite3_mutex_held(pBt->mutex) );
35786   rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
35787   if( rc!=SQLITE_OK || nPage>0 ){
35788     return rc;
35789   }
35790   pP1 = pBt->pPage1;
35791   assert( pP1!=0 );
35792   data = pP1->aData;
35793   rc = sqlite3PagerWrite(pP1->pDbPage);
35794   if( rc ) return rc;
35795   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
35796   assert( sizeof(zMagicHeader)==16 );
35797   put2byte(&data[16], pBt->pageSize);
35798   data[18] = 1;
35799   data[19] = 1;
35800   data[20] = pBt->pageSize - pBt->usableSize;
35801   data[21] = 64;
35802   data[22] = 32;
35803   data[23] = 32;
35804   memset(&data[24], 0, 100-24);
35805   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
35806   pBt->pageSizeFixed = 1;
35807 #ifndef SQLITE_OMIT_AUTOVACUUM
35808   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
35809   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
35810   put4byte(&data[36 + 4*4], pBt->autoVacuum);
35811   put4byte(&data[36 + 7*4], pBt->incrVacuum);
35812 #endif
35813   return SQLITE_OK;
35814 }
35815
35816 /*
35817 ** Attempt to start a new transaction. A write-transaction
35818 ** is started if the second argument is nonzero, otherwise a read-
35819 ** transaction.  If the second argument is 2 or more and exclusive
35820 ** transaction is started, meaning that no other process is allowed
35821 ** to access the database.  A preexisting transaction may not be
35822 ** upgraded to exclusive by calling this routine a second time - the
35823 ** exclusivity flag only works for a new transaction.
35824 **
35825 ** A write-transaction must be started before attempting any 
35826 ** changes to the database.  None of the following routines 
35827 ** will work unless a transaction is started first:
35828 **
35829 **      sqlite3BtreeCreateTable()
35830 **      sqlite3BtreeCreateIndex()
35831 **      sqlite3BtreeClearTable()
35832 **      sqlite3BtreeDropTable()
35833 **      sqlite3BtreeInsert()
35834 **      sqlite3BtreeDelete()
35835 **      sqlite3BtreeUpdateMeta()
35836 **
35837 ** If an initial attempt to acquire the lock fails because of lock contention
35838 ** and the database was previously unlocked, then invoke the busy handler
35839 ** if there is one.  But if there was previously a read-lock, do not
35840 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
35841 ** returned when there is already a read-lock in order to avoid a deadlock.
35842 **
35843 ** Suppose there are two processes A and B.  A has a read lock and B has
35844 ** a reserved lock.  B tries to promote to exclusive but is blocked because
35845 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
35846 ** One or the other of the two processes must give way or there can be
35847 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
35848 ** when A already has a read lock, we encourage A to give up and let B
35849 ** proceed.
35850 */
35851 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
35852   BtShared *pBt = p->pBt;
35853   int rc = SQLITE_OK;
35854
35855   sqlite3BtreeEnter(p);
35856   pBt->db = p->db;
35857   btreeIntegrity(p);
35858
35859   /* If the btree is already in a write-transaction, or it
35860   ** is already in a read-transaction and a read-transaction
35861   ** is requested, this is a no-op.
35862   */
35863   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
35864     goto trans_begun;
35865   }
35866
35867   /* Write transactions are not possible on a read-only database */
35868   if( pBt->readOnly && wrflag ){
35869     rc = SQLITE_READONLY;
35870     goto trans_begun;
35871   }
35872
35873   /* If another database handle has already opened a write transaction 
35874   ** on this shared-btree structure and a second write transaction is
35875   ** requested, return SQLITE_BUSY.
35876   */
35877   if( pBt->inTransaction==TRANS_WRITE && wrflag ){
35878     rc = SQLITE_BUSY;
35879     goto trans_begun;
35880   }
35881
35882 #ifndef SQLITE_OMIT_SHARED_CACHE
35883   if( wrflag>1 ){
35884     BtLock *pIter;
35885     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
35886       if( pIter->pBtree!=p ){
35887         rc = SQLITE_BUSY;
35888         goto trans_begun;
35889       }
35890     }
35891   }
35892 #endif
35893
35894   do {
35895     if( pBt->pPage1==0 ){
35896       do{
35897         rc = lockBtree(pBt);
35898       }while( pBt->pPage1==0 && rc==SQLITE_OK );
35899     }
35900
35901     if( rc==SQLITE_OK && wrflag ){
35902       if( pBt->readOnly ){
35903         rc = SQLITE_READONLY;
35904       }else{
35905         rc = sqlite3PagerBegin(pBt->pPage1->pDbPage, wrflag>1);
35906         if( rc==SQLITE_OK ){
35907           rc = newDatabase(pBt);
35908         }
35909       }
35910     }
35911   
35912     if( rc==SQLITE_OK ){
35913       if( wrflag ) pBt->inStmt = 0;
35914     }else{
35915       unlockBtreeIfUnused(pBt);
35916     }
35917   }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
35918           btreeInvokeBusyHandler(pBt) );
35919
35920   if( rc==SQLITE_OK ){
35921     if( p->inTrans==TRANS_NONE ){
35922       pBt->nTransaction++;
35923     }
35924     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
35925     if( p->inTrans>pBt->inTransaction ){
35926       pBt->inTransaction = p->inTrans;
35927     }
35928 #ifndef SQLITE_OMIT_SHARED_CACHE
35929     if( wrflag>1 ){
35930       assert( !pBt->pExclusive );
35931       pBt->pExclusive = p;
35932     }
35933 #endif
35934   }
35935
35936
35937 trans_begun:
35938   btreeIntegrity(p);
35939   sqlite3BtreeLeave(p);
35940   return rc;
35941 }
35942
35943 #ifndef SQLITE_OMIT_AUTOVACUUM
35944
35945 /*
35946 ** Set the pointer-map entries for all children of page pPage. Also, if
35947 ** pPage contains cells that point to overflow pages, set the pointer
35948 ** map entries for the overflow pages as well.
35949 */
35950 static int setChildPtrmaps(MemPage *pPage){
35951   int i;                             /* Counter variable */
35952   int nCell;                         /* Number of cells in page pPage */
35953   int rc;                            /* Return code */
35954   BtShared *pBt = pPage->pBt;
35955   int isInitOrig = pPage->isInit;
35956   Pgno pgno = pPage->pgno;
35957
35958   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
35959   rc = sqlite3BtreeInitPage(pPage);
35960   if( rc!=SQLITE_OK ){
35961     goto set_child_ptrmaps_out;
35962   }
35963   nCell = pPage->nCell;
35964
35965   for(i=0; i<nCell; i++){
35966     u8 *pCell = findCell(pPage, i);
35967
35968     rc = ptrmapPutOvflPtr(pPage, pCell);
35969     if( rc!=SQLITE_OK ){
35970       goto set_child_ptrmaps_out;
35971     }
35972
35973     if( !pPage->leaf ){
35974       Pgno childPgno = get4byte(pCell);
35975       rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
35976       if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
35977     }
35978   }
35979
35980   if( !pPage->leaf ){
35981     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
35982     rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
35983   }
35984
35985 set_child_ptrmaps_out:
35986   pPage->isInit = isInitOrig;
35987   return rc;
35988 }
35989
35990 /*
35991 ** Somewhere on pPage, which is guarenteed to be a btree page, not an overflow
35992 ** page, is a pointer to page iFrom. Modify this pointer so that it points to
35993 ** iTo. Parameter eType describes the type of pointer to be modified, as 
35994 ** follows:
35995 **
35996 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
35997 **                   page of pPage.
35998 **
35999 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
36000 **                   page pointed to by one of the cells on pPage.
36001 **
36002 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
36003 **                   overflow page in the list.
36004 */
36005 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
36006   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
36007   if( eType==PTRMAP_OVERFLOW2 ){
36008     /* The pointer is always the first 4 bytes of the page in this case.  */
36009     if( get4byte(pPage->aData)!=iFrom ){
36010       return SQLITE_CORRUPT_BKPT;
36011     }
36012     put4byte(pPage->aData, iTo);
36013   }else{
36014     int isInitOrig = pPage->isInit;
36015     int i;
36016     int nCell;
36017
36018     sqlite3BtreeInitPage(pPage);
36019     nCell = pPage->nCell;
36020
36021     for(i=0; i<nCell; i++){
36022       u8 *pCell = findCell(pPage, i);
36023       if( eType==PTRMAP_OVERFLOW1 ){
36024         CellInfo info;
36025         sqlite3BtreeParseCellPtr(pPage, pCell, &info);
36026         if( info.iOverflow ){
36027           if( iFrom==get4byte(&pCell[info.iOverflow]) ){
36028             put4byte(&pCell[info.iOverflow], iTo);
36029             break;
36030           }
36031         }
36032       }else{
36033         if( get4byte(pCell)==iFrom ){
36034           put4byte(pCell, iTo);
36035           break;
36036         }
36037       }
36038     }
36039   
36040     if( i==nCell ){
36041       if( eType!=PTRMAP_BTREE || 
36042           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
36043         return SQLITE_CORRUPT_BKPT;
36044       }
36045       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
36046     }
36047
36048     pPage->isInit = isInitOrig;
36049   }
36050   return SQLITE_OK;
36051 }
36052
36053
36054 /*
36055 ** Move the open database page pDbPage to location iFreePage in the 
36056 ** database. The pDbPage reference remains valid.
36057 */
36058 static int relocatePage(
36059   BtShared *pBt,           /* Btree */
36060   MemPage *pDbPage,        /* Open page to move */
36061   u8 eType,                /* Pointer map 'type' entry for pDbPage */
36062   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
36063   Pgno iFreePage,          /* The location to move pDbPage to */
36064   int isCommit
36065 ){
36066   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
36067   Pgno iDbPage = pDbPage->pgno;
36068   Pager *pPager = pBt->pPager;
36069   int rc;
36070
36071   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
36072       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
36073   assert( sqlite3_mutex_held(pBt->mutex) );
36074   assert( pDbPage->pBt==pBt );
36075
36076   /* Move page iDbPage from its current location to page number iFreePage */
36077   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
36078       iDbPage, iFreePage, iPtrPage, eType));
36079   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
36080   if( rc!=SQLITE_OK ){
36081     return rc;
36082   }
36083   pDbPage->pgno = iFreePage;
36084
36085   /* If pDbPage was a btree-page, then it may have child pages and/or cells
36086   ** that point to overflow pages. The pointer map entries for all these
36087   ** pages need to be changed.
36088   **
36089   ** If pDbPage is an overflow page, then the first 4 bytes may store a
36090   ** pointer to a subsequent overflow page. If this is the case, then
36091   ** the pointer map needs to be updated for the subsequent overflow page.
36092   */
36093   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
36094     rc = setChildPtrmaps(pDbPage);
36095     if( rc!=SQLITE_OK ){
36096       return rc;
36097     }
36098   }else{
36099     Pgno nextOvfl = get4byte(pDbPage->aData);
36100     if( nextOvfl!=0 ){
36101       rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
36102       if( rc!=SQLITE_OK ){
36103         return rc;
36104       }
36105     }
36106   }
36107
36108   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
36109   ** that it points at iFreePage. Also fix the pointer map entry for
36110   ** iPtrPage.
36111   */
36112   if( eType!=PTRMAP_ROOTPAGE ){
36113     rc = sqlite3BtreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
36114     if( rc!=SQLITE_OK ){
36115       return rc;
36116     }
36117     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
36118     if( rc!=SQLITE_OK ){
36119       releasePage(pPtrPage);
36120       return rc;
36121     }
36122     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
36123     releasePage(pPtrPage);
36124     if( rc==SQLITE_OK ){
36125       rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
36126     }
36127   }
36128   return rc;
36129 }
36130
36131 /* Forward declaration required by incrVacuumStep(). */
36132 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
36133
36134 /*
36135 ** Perform a single step of an incremental-vacuum. If successful,
36136 ** return SQLITE_OK. If there is no work to do (and therefore no
36137 ** point in calling this function again), return SQLITE_DONE.
36138 **
36139 ** More specificly, this function attempts to re-organize the 
36140 ** database so that the last page of the file currently in use
36141 ** is no longer in use.
36142 **
36143 ** If the nFin parameter is non-zero, the implementation assumes
36144 ** that the caller will keep calling incrVacuumStep() until
36145 ** it returns SQLITE_DONE or an error, and that nFin is the
36146 ** number of pages the database file will contain after this 
36147 ** process is complete.
36148 */
36149 static int incrVacuumStep(BtShared *pBt, Pgno nFin){
36150   Pgno iLastPg;             /* Last page in the database */
36151   Pgno nFreeList;           /* Number of pages still on the free-list */
36152
36153   assert( sqlite3_mutex_held(pBt->mutex) );
36154   iLastPg = pBt->nTrunc;
36155   if( iLastPg==0 ){
36156     iLastPg = pagerPagecount(pBt);
36157   }
36158
36159   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
36160     int rc;
36161     u8 eType;
36162     Pgno iPtrPage;
36163
36164     nFreeList = get4byte(&pBt->pPage1->aData[36]);
36165     if( nFreeList==0 || nFin==iLastPg ){
36166       return SQLITE_DONE;
36167     }
36168
36169     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
36170     if( rc!=SQLITE_OK ){
36171       return rc;
36172     }
36173     if( eType==PTRMAP_ROOTPAGE ){
36174       return SQLITE_CORRUPT_BKPT;
36175     }
36176
36177     if( eType==PTRMAP_FREEPAGE ){
36178       if( nFin==0 ){
36179         /* Remove the page from the files free-list. This is not required
36180         ** if nFin is non-zero. In that case, the free-list will be
36181         ** truncated to zero after this function returns, so it doesn't 
36182         ** matter if it still contains some garbage entries.
36183         */
36184         Pgno iFreePg;
36185         MemPage *pFreePg;
36186         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
36187         if( rc!=SQLITE_OK ){
36188           return rc;
36189         }
36190         assert( iFreePg==iLastPg );
36191         releasePage(pFreePg);
36192       }
36193     } else {
36194       Pgno iFreePg;             /* Index of free page to move pLastPg to */
36195       MemPage *pLastPg;
36196
36197       rc = sqlite3BtreeGetPage(pBt, iLastPg, &pLastPg, 0);
36198       if( rc!=SQLITE_OK ){
36199         return rc;
36200       }
36201
36202       /* If nFin is zero, this loop runs exactly once and page pLastPg
36203       ** is swapped with the first free page pulled off the free list.
36204       **
36205       ** On the other hand, if nFin is greater than zero, then keep
36206       ** looping until a free-page located within the first nFin pages
36207       ** of the file is found.
36208       */
36209       do {
36210         MemPage *pFreePg;
36211         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
36212         if( rc!=SQLITE_OK ){
36213           releasePage(pLastPg);
36214           return rc;
36215         }
36216         releasePage(pFreePg);
36217       }while( nFin!=0 && iFreePg>nFin );
36218       assert( iFreePg<iLastPg );
36219       
36220       rc = sqlite3PagerWrite(pLastPg->pDbPage);
36221       if( rc==SQLITE_OK ){
36222         rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
36223       }
36224       releasePage(pLastPg);
36225       if( rc!=SQLITE_OK ){
36226         return rc;
36227       }
36228     }
36229   }
36230
36231   pBt->nTrunc = iLastPg - 1;
36232   while( pBt->nTrunc==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, pBt->nTrunc) ){
36233     pBt->nTrunc--;
36234   }
36235   return SQLITE_OK;
36236 }
36237
36238 /*
36239 ** A write-transaction must be opened before calling this function.
36240 ** It performs a single unit of work towards an incremental vacuum.
36241 **
36242 ** If the incremental vacuum is finished after this function has run,
36243 ** SQLITE_DONE is returned. If it is not finished, but no error occured,
36244 ** SQLITE_OK is returned. Otherwise an SQLite error code. 
36245 */
36246 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
36247   int rc;
36248   BtShared *pBt = p->pBt;
36249
36250   sqlite3BtreeEnter(p);
36251   pBt->db = p->db;
36252   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
36253   if( !pBt->autoVacuum ){
36254     rc = SQLITE_DONE;
36255   }else{
36256     invalidateAllOverflowCache(pBt);
36257     rc = incrVacuumStep(pBt, 0);
36258   }
36259   sqlite3BtreeLeave(p);
36260   return rc;
36261 }
36262
36263 /*
36264 ** This routine is called prior to sqlite3PagerCommit when a transaction
36265 ** is commited for an auto-vacuum database.
36266 **
36267 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
36268 ** the database file should be truncated to during the commit process. 
36269 ** i.e. the database has been reorganized so that only the first *pnTrunc
36270 ** pages are in use.
36271 */
36272 static int autoVacuumCommit(BtShared *pBt, Pgno *pnTrunc){
36273   int rc = SQLITE_OK;
36274   Pager *pPager = pBt->pPager;
36275   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
36276
36277   assert( sqlite3_mutex_held(pBt->mutex) );
36278   invalidateAllOverflowCache(pBt);
36279   assert(pBt->autoVacuum);
36280   if( !pBt->incrVacuum ){
36281     Pgno nFin = 0;
36282
36283     if( pBt->nTrunc==0 ){
36284       Pgno nFree;
36285       Pgno nPtrmap;
36286       const int pgsz = pBt->pageSize;
36287       Pgno nOrig = pagerPagecount(pBt);
36288
36289       if( PTRMAP_ISPAGE(pBt, nOrig) ){
36290         return SQLITE_CORRUPT_BKPT;
36291       }
36292       if( nOrig==PENDING_BYTE_PAGE(pBt) ){
36293         nOrig--;
36294       }
36295       nFree = get4byte(&pBt->pPage1->aData[36]);
36296       nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+pgsz/5)/(pgsz/5);
36297       nFin = nOrig - nFree - nPtrmap;
36298       if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<=PENDING_BYTE_PAGE(pBt) ){
36299         nFin--;
36300       }
36301       while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
36302         nFin--;
36303       }
36304     }
36305
36306     while( rc==SQLITE_OK ){
36307       rc = incrVacuumStep(pBt, nFin);
36308     }
36309     if( rc==SQLITE_DONE ){
36310       assert(nFin==0 || pBt->nTrunc==0 || nFin<=pBt->nTrunc);
36311       rc = SQLITE_OK;
36312       if( pBt->nTrunc && nFin ){
36313         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
36314         put4byte(&pBt->pPage1->aData[32], 0);
36315         put4byte(&pBt->pPage1->aData[36], 0);
36316         pBt->nTrunc = nFin;
36317       }
36318     }
36319     if( rc!=SQLITE_OK ){
36320       sqlite3PagerRollback(pPager);
36321     }
36322   }
36323
36324   if( rc==SQLITE_OK ){
36325     *pnTrunc = pBt->nTrunc;
36326     pBt->nTrunc = 0;
36327   }
36328   assert( nRef==sqlite3PagerRefcount(pPager) );
36329   return rc;
36330 }
36331
36332 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
36333
36334 /*
36335 ** This routine does the first phase of a two-phase commit.  This routine
36336 ** causes a rollback journal to be created (if it does not already exist)
36337 ** and populated with enough information so that if a power loss occurs
36338 ** the database can be restored to its original state by playing back
36339 ** the journal.  Then the contents of the journal are flushed out to
36340 ** the disk.  After the journal is safely on oxide, the changes to the
36341 ** database are written into the database file and flushed to oxide.
36342 ** At the end of this call, the rollback journal still exists on the
36343 ** disk and we are still holding all locks, so the transaction has not
36344 ** committed.  See sqlite3BtreeCommit() for the second phase of the
36345 ** commit process.
36346 **
36347 ** This call is a no-op if no write-transaction is currently active on pBt.
36348 **
36349 ** Otherwise, sync the database file for the btree pBt. zMaster points to
36350 ** the name of a master journal file that should be written into the
36351 ** individual journal file, or is NULL, indicating no master journal file 
36352 ** (single database transaction).
36353 **
36354 ** When this is called, the master journal should already have been
36355 ** created, populated with this journal pointer and synced to disk.
36356 **
36357 ** Once this is routine has returned, the only thing required to commit
36358 ** the write-transaction for this database file is to delete the journal.
36359 */
36360 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
36361   int rc = SQLITE_OK;
36362   if( p->inTrans==TRANS_WRITE ){
36363     BtShared *pBt = p->pBt;
36364     Pgno nTrunc = 0;
36365     sqlite3BtreeEnter(p);
36366     pBt->db = p->db;
36367 #ifndef SQLITE_OMIT_AUTOVACUUM
36368     if( pBt->autoVacuum ){
36369       rc = autoVacuumCommit(pBt, &nTrunc); 
36370       if( rc!=SQLITE_OK ){
36371         sqlite3BtreeLeave(p);
36372         return rc;
36373       }
36374     }
36375 #endif
36376     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, nTrunc, 0);
36377     sqlite3BtreeLeave(p);
36378   }
36379   return rc;
36380 }
36381
36382 /*
36383 ** Commit the transaction currently in progress.
36384 **
36385 ** This routine implements the second phase of a 2-phase commit.  The
36386 ** sqlite3BtreeSync() routine does the first phase and should be invoked
36387 ** prior to calling this routine.  The sqlite3BtreeSync() routine did
36388 ** all the work of writing information out to disk and flushing the
36389 ** contents so that they are written onto the disk platter.  All this
36390 ** routine has to do is delete or truncate the rollback journal
36391 ** (which causes the transaction to commit) and drop locks.
36392 **
36393 ** This will release the write lock on the database file.  If there
36394 ** are no active cursors, it also releases the read lock.
36395 */
36396 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p){
36397   BtShared *pBt = p->pBt;
36398
36399   sqlite3BtreeEnter(p);
36400   pBt->db = p->db;
36401   btreeIntegrity(p);
36402
36403   /* If the handle has a write-transaction open, commit the shared-btrees 
36404   ** transaction and set the shared state to TRANS_READ.
36405   */
36406   if( p->inTrans==TRANS_WRITE ){
36407     int rc;
36408     assert( pBt->inTransaction==TRANS_WRITE );
36409     assert( pBt->nTransaction>0 );
36410     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
36411     if( rc!=SQLITE_OK ){
36412       sqlite3BtreeLeave(p);
36413       return rc;
36414     }
36415     pBt->inTransaction = TRANS_READ;
36416     pBt->inStmt = 0;
36417   }
36418   unlockAllTables(p);
36419
36420   /* If the handle has any kind of transaction open, decrement the transaction
36421   ** count of the shared btree. If the transaction count reaches 0, set
36422   ** the shared state to TRANS_NONE. The unlockBtreeIfUnused() call below
36423   ** will unlock the pager.
36424   */
36425   if( p->inTrans!=TRANS_NONE ){
36426     pBt->nTransaction--;
36427     if( 0==pBt->nTransaction ){
36428       pBt->inTransaction = TRANS_NONE;
36429     }
36430   }
36431
36432   /* Set the handles current transaction state to TRANS_NONE and unlock
36433   ** the pager if this call closed the only read or write transaction.
36434   */
36435   p->inTrans = TRANS_NONE;
36436   unlockBtreeIfUnused(pBt);
36437
36438   btreeIntegrity(p);
36439   sqlite3BtreeLeave(p);
36440   return SQLITE_OK;
36441 }
36442
36443 /*
36444 ** Do both phases of a commit.
36445 */
36446 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
36447   int rc;
36448   sqlite3BtreeEnter(p);
36449   rc = sqlite3BtreeCommitPhaseOne(p, 0);
36450   if( rc==SQLITE_OK ){
36451     rc = sqlite3BtreeCommitPhaseTwo(p);
36452   }
36453   sqlite3BtreeLeave(p);
36454   return rc;
36455 }
36456
36457 #ifndef NDEBUG
36458 /*
36459 ** Return the number of write-cursors open on this handle. This is for use
36460 ** in assert() expressions, so it is only compiled if NDEBUG is not
36461 ** defined.
36462 **
36463 ** For the purposes of this routine, a write-cursor is any cursor that
36464 ** is capable of writing to the databse.  That means the cursor was
36465 ** originally opened for writing and the cursor has not be disabled
36466 ** by having its state changed to CURSOR_FAULT.
36467 */
36468 static int countWriteCursors(BtShared *pBt){
36469   BtCursor *pCur;
36470   int r = 0;
36471   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
36472     if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++; 
36473   }
36474   return r;
36475 }
36476 #endif
36477
36478 /*
36479 ** This routine sets the state to CURSOR_FAULT and the error
36480 ** code to errCode for every cursor on BtShared that pBtree
36481 ** references.
36482 **
36483 ** Every cursor is tripped, including cursors that belong
36484 ** to other database connections that happen to be sharing
36485 ** the cache with pBtree.
36486 **
36487 ** This routine gets called when a rollback occurs.
36488 ** All cursors using the same cache must be tripped
36489 ** to prevent them from trying to use the btree after
36490 ** the rollback.  The rollback may have deleted tables
36491 ** or moved root pages, so it is not sufficient to
36492 ** save the state of the cursor.  The cursor must be
36493 ** invalidated.
36494 */
36495 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
36496   BtCursor *p;
36497   sqlite3BtreeEnter(pBtree);
36498   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
36499     int i;
36500     sqlite3BtreeClearCursor(p);
36501     p->eState = CURSOR_FAULT;
36502     p->skip = errCode;
36503     for(i=0; i<=p->iPage; i++){
36504       releasePage(p->apPage[i]);
36505       p->apPage[i] = 0;
36506     }
36507   }
36508   sqlite3BtreeLeave(pBtree);
36509 }
36510
36511 /*
36512 ** Rollback the transaction in progress.  All cursors will be
36513 ** invalided by this operation.  Any attempt to use a cursor
36514 ** that was open at the beginning of this operation will result
36515 ** in an error.
36516 **
36517 ** This will release the write lock on the database file.  If there
36518 ** are no active cursors, it also releases the read lock.
36519 */
36520 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
36521   int rc;
36522   BtShared *pBt = p->pBt;
36523   MemPage *pPage1;
36524
36525   sqlite3BtreeEnter(p);
36526   pBt->db = p->db;
36527   rc = saveAllCursors(pBt, 0, 0);
36528 #ifndef SQLITE_OMIT_SHARED_CACHE
36529   if( rc!=SQLITE_OK ){
36530     /* This is a horrible situation. An IO or malloc() error occured whilst
36531     ** trying to save cursor positions. If this is an automatic rollback (as
36532     ** the result of a constraint, malloc() failure or IO error) then 
36533     ** the cache may be internally inconsistent (not contain valid trees) so
36534     ** we cannot simply return the error to the caller. Instead, abort 
36535     ** all queries that may be using any of the cursors that failed to save.
36536     */
36537     sqlite3BtreeTripAllCursors(p, rc);
36538   }
36539 #endif
36540   btreeIntegrity(p);
36541   unlockAllTables(p);
36542
36543   if( p->inTrans==TRANS_WRITE ){
36544     int rc2;
36545
36546 #ifndef SQLITE_OMIT_AUTOVACUUM
36547     pBt->nTrunc = 0;
36548 #endif
36549
36550     assert( TRANS_WRITE==pBt->inTransaction );
36551     rc2 = sqlite3PagerRollback(pBt->pPager);
36552     if( rc2!=SQLITE_OK ){
36553       rc = rc2;
36554     }
36555
36556     /* The rollback may have destroyed the pPage1->aData value.  So
36557     ** call sqlite3BtreeGetPage() on page 1 again to make
36558     ** sure pPage1->aData is set correctly. */
36559     if( sqlite3BtreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
36560       releasePage(pPage1);
36561     }
36562     assert( countWriteCursors(pBt)==0 );
36563     pBt->inTransaction = TRANS_READ;
36564   }
36565
36566   if( p->inTrans!=TRANS_NONE ){
36567     assert( pBt->nTransaction>0 );
36568     pBt->nTransaction--;
36569     if( 0==pBt->nTransaction ){
36570       pBt->inTransaction = TRANS_NONE;
36571     }
36572   }
36573
36574   p->inTrans = TRANS_NONE;
36575   pBt->inStmt = 0;
36576   unlockBtreeIfUnused(pBt);
36577
36578   btreeIntegrity(p);
36579   sqlite3BtreeLeave(p);
36580   return rc;
36581 }
36582
36583 /*
36584 ** Start a statement subtransaction.  The subtransaction can
36585 ** can be rolled back independently of the main transaction.
36586 ** You must start a transaction before starting a subtransaction.
36587 ** The subtransaction is ended automatically if the main transaction
36588 ** commits or rolls back.
36589 **
36590 ** Only one subtransaction may be active at a time.  It is an error to try
36591 ** to start a new subtransaction if another subtransaction is already active.
36592 **
36593 ** Statement subtransactions are used around individual SQL statements
36594 ** that are contained within a BEGIN...COMMIT block.  If a constraint
36595 ** error occurs within the statement, the effect of that one statement
36596 ** can be rolled back without having to rollback the entire transaction.
36597 */
36598 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p){
36599   int rc;
36600   BtShared *pBt = p->pBt;
36601   sqlite3BtreeEnter(p);
36602   pBt->db = p->db;
36603   if( (p->inTrans!=TRANS_WRITE) || pBt->inStmt ){
36604     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
36605   }else{
36606     assert( pBt->inTransaction==TRANS_WRITE );
36607     rc = pBt->readOnly ? SQLITE_OK : sqlite3PagerStmtBegin(pBt->pPager);
36608     pBt->inStmt = 1;
36609   }
36610   sqlite3BtreeLeave(p);
36611   return rc;
36612 }
36613
36614
36615 /*
36616 ** Commit the statment subtransaction currently in progress.  If no
36617 ** subtransaction is active, this is a no-op.
36618 */
36619 SQLITE_PRIVATE int sqlite3BtreeCommitStmt(Btree *p){
36620   int rc;
36621   BtShared *pBt = p->pBt;
36622   sqlite3BtreeEnter(p);
36623   pBt->db = p->db;
36624   if( pBt->inStmt && !pBt->readOnly ){
36625     rc = sqlite3PagerStmtCommit(pBt->pPager);
36626   }else{
36627     rc = SQLITE_OK;
36628   }
36629   pBt->inStmt = 0;
36630   sqlite3BtreeLeave(p);
36631   return rc;
36632 }
36633
36634 /*
36635 ** Rollback the active statement subtransaction.  If no subtransaction
36636 ** is active this routine is a no-op.
36637 **
36638 ** All cursors will be invalidated by this operation.  Any attempt
36639 ** to use a cursor that was open at the beginning of this operation
36640 ** will result in an error.
36641 */
36642 SQLITE_PRIVATE int sqlite3BtreeRollbackStmt(Btree *p){
36643   int rc = SQLITE_OK;
36644   BtShared *pBt = p->pBt;
36645   sqlite3BtreeEnter(p);
36646   pBt->db = p->db;
36647   if( pBt->inStmt && !pBt->readOnly ){
36648     rc = sqlite3PagerStmtRollback(pBt->pPager);
36649     pBt->inStmt = 0;
36650   }
36651   sqlite3BtreeLeave(p);
36652   return rc;
36653 }
36654
36655 /*
36656 ** Create a new cursor for the BTree whose root is on the page
36657 ** iTable.  The act of acquiring a cursor gets a read lock on 
36658 ** the database file.
36659 **
36660 ** If wrFlag==0, then the cursor can only be used for reading.
36661 ** If wrFlag==1, then the cursor can be used for reading or for
36662 ** writing if other conditions for writing are also met.  These
36663 ** are the conditions that must be met in order for writing to
36664 ** be allowed:
36665 **
36666 ** 1:  The cursor must have been opened with wrFlag==1
36667 **
36668 ** 2:  Other database connections that share the same pager cache
36669 **     but which are not in the READ_UNCOMMITTED state may not have
36670 **     cursors open with wrFlag==0 on the same table.  Otherwise
36671 **     the changes made by this write cursor would be visible to
36672 **     the read cursors in the other database connection.
36673 **
36674 ** 3:  The database must be writable (not on read-only media)
36675 **
36676 ** 4:  There must be an active transaction.
36677 **
36678 ** No checking is done to make sure that page iTable really is the
36679 ** root page of a b-tree.  If it is not, then the cursor acquired
36680 ** will not work correctly.
36681 **
36682 ** It is assumed that the sqlite3BtreeCursorSize() bytes of memory 
36683 ** pointed to by pCur have been zeroed by the caller.
36684 */
36685 static int btreeCursor(
36686   Btree *p,                              /* The btree */
36687   int iTable,                            /* Root page of table to open */
36688   int wrFlag,                            /* 1 to write. 0 read-only */
36689   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
36690   BtCursor *pCur                         /* Space for new cursor */
36691 ){
36692   int rc;
36693   Pgno nPage;
36694   BtShared *pBt = p->pBt;
36695
36696   assert( sqlite3BtreeHoldsMutex(p) );
36697   if( wrFlag ){
36698     if( pBt->readOnly ){
36699       return SQLITE_READONLY;
36700     }
36701     if( checkReadLocks(p, iTable, 0, 0) ){
36702       return SQLITE_LOCKED;
36703     }
36704   }
36705
36706   if( pBt->pPage1==0 ){
36707     rc = lockBtreeWithRetry(p);
36708     if( rc!=SQLITE_OK ){
36709       return rc;
36710     }
36711     if( pBt->readOnly && wrFlag ){
36712       return SQLITE_READONLY;
36713     }
36714   }
36715   pCur->pgnoRoot = (Pgno)iTable;
36716   rc = sqlite3PagerPagecount(pBt->pPager, (int *)&nPage); 
36717   if( rc!=SQLITE_OK ){
36718     return rc;
36719   }
36720   if( iTable==1 && nPage==0 ){
36721     rc = SQLITE_EMPTY;
36722     goto create_cursor_exception;
36723   }
36724   rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
36725   if( rc!=SQLITE_OK ){
36726     goto create_cursor_exception;
36727   }
36728
36729   /* Now that no other errors can occur, finish filling in the BtCursor
36730   ** variables, link the cursor into the BtShared list and set *ppCur (the
36731   ** output argument to this function).
36732   */
36733   pCur->pKeyInfo = pKeyInfo;
36734   pCur->pBtree = p;
36735   pCur->pBt = pBt;
36736   pCur->wrFlag = wrFlag;
36737   pCur->pNext = pBt->pCursor;
36738   if( pCur->pNext ){
36739     pCur->pNext->pPrev = pCur;
36740   }
36741   pBt->pCursor = pCur;
36742   pCur->eState = CURSOR_INVALID;
36743
36744   return SQLITE_OK;
36745
36746 create_cursor_exception:
36747   releasePage(pCur->apPage[0]);
36748   unlockBtreeIfUnused(pBt);
36749   return rc;
36750 }
36751 SQLITE_PRIVATE int sqlite3BtreeCursor(
36752   Btree *p,                                   /* The btree */
36753   int iTable,                                 /* Root page of table to open */
36754   int wrFlag,                                 /* 1 to write. 0 read-only */
36755   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
36756   BtCursor *pCur                              /* Write new cursor here */
36757 ){
36758   int rc;
36759   sqlite3BtreeEnter(p);
36760   p->pBt->db = p->db;
36761   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
36762   sqlite3BtreeLeave(p);
36763   return rc;
36764 }
36765 SQLITE_PRIVATE int sqlite3BtreeCursorSize(){
36766   return sizeof(BtCursor);
36767 }
36768
36769
36770
36771 /*
36772 ** Close a cursor.  The read lock on the database file is released
36773 ** when the last cursor is closed.
36774 */
36775 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
36776   Btree *pBtree = pCur->pBtree;
36777   if( pBtree ){
36778     int i;
36779     BtShared *pBt = pCur->pBt;
36780     sqlite3BtreeEnter(pBtree);
36781     pBt->db = pBtree->db;
36782     sqlite3BtreeClearCursor(pCur);
36783     if( pCur->pPrev ){
36784       pCur->pPrev->pNext = pCur->pNext;
36785     }else{
36786       pBt->pCursor = pCur->pNext;
36787     }
36788     if( pCur->pNext ){
36789       pCur->pNext->pPrev = pCur->pPrev;
36790     }
36791     for(i=0; i<=pCur->iPage; i++){
36792       releasePage(pCur->apPage[i]);
36793     }
36794     unlockBtreeIfUnused(pBt);
36795     invalidateOverflowCache(pCur);
36796     /* sqlite3_free(pCur); */
36797     sqlite3BtreeLeave(pBtree);
36798   }
36799   return SQLITE_OK;
36800 }
36801
36802 /*
36803 ** Make a temporary cursor by filling in the fields of pTempCur.
36804 ** The temporary cursor is not on the cursor list for the Btree.
36805 */
36806 SQLITE_PRIVATE void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur){
36807   int i;
36808   assert( cursorHoldsMutex(pCur) );
36809   memcpy(pTempCur, pCur, sizeof(BtCursor));
36810   pTempCur->pNext = 0;
36811   pTempCur->pPrev = 0;
36812   for(i=0; i<=pTempCur->iPage; i++){
36813     sqlite3PagerRef(pTempCur->apPage[i]->pDbPage);
36814   }
36815   assert( pTempCur->pKey==0 );
36816 }
36817
36818 /*
36819 ** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
36820 ** function above.
36821 */
36822 SQLITE_PRIVATE void sqlite3BtreeReleaseTempCursor(BtCursor *pCur){
36823   int i;
36824   assert( cursorHoldsMutex(pCur) );
36825   for(i=0; i<=pCur->iPage; i++){
36826     sqlite3PagerUnref(pCur->apPage[i]->pDbPage);
36827   }
36828   sqlite3_free(pCur->pKey);
36829 }
36830
36831 /*
36832 ** Make sure the BtCursor* given in the argument has a valid
36833 ** BtCursor.info structure.  If it is not already valid, call
36834 ** sqlite3BtreeParseCell() to fill it in.
36835 **
36836 ** BtCursor.info is a cache of the information in the current cell.
36837 ** Using this cache reduces the number of calls to sqlite3BtreeParseCell().
36838 **
36839 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
36840 ** compiler to crash when getCellInfo() is implemented as a macro.
36841 ** But there is a measureable speed advantage to using the macro on gcc
36842 ** (when less compiler optimizations like -Os or -O0 are used and the
36843 ** compiler is not doing agressive inlining.)  So we use a real function
36844 ** for MSVC and a macro for everything else.  Ticket #2457.
36845 */
36846 #ifndef NDEBUG
36847   static void assertCellInfo(BtCursor *pCur){
36848     CellInfo info;
36849     int iPage = pCur->iPage;
36850     memset(&info, 0, sizeof(info));
36851     sqlite3BtreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
36852     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
36853   }
36854 #else
36855   #define assertCellInfo(x)
36856 #endif
36857 #ifdef _MSC_VER
36858   /* Use a real function in MSVC to work around bugs in that compiler. */
36859   static void getCellInfo(BtCursor *pCur){
36860     if( pCur->info.nSize==0 ){
36861       int iPage = pCur->iPage;
36862       sqlite3BtreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
36863       pCur->validNKey = 1;
36864     }else{
36865       assertCellInfo(pCur);
36866     }
36867   }
36868 #else /* if not _MSC_VER */
36869   /* Use a macro in all other compilers so that the function is inlined */
36870 #define getCellInfo(pCur)                                                      \
36871   if( pCur->info.nSize==0 ){                                                   \
36872     int iPage = pCur->iPage;                                                   \
36873     sqlite3BtreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
36874     pCur->validNKey = 1;                                                       \
36875   }else{                                                                       \
36876     assertCellInfo(pCur);                                                      \
36877   }
36878 #endif /* _MSC_VER */
36879
36880 /*
36881 ** Set *pSize to the size of the buffer needed to hold the value of
36882 ** the key for the current entry.  If the cursor is not pointing
36883 ** to a valid entry, *pSize is set to 0. 
36884 **
36885 ** For a table with the INTKEY flag set, this routine returns the key
36886 ** itself, not the number of bytes in the key.
36887 */
36888 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
36889   int rc;
36890
36891   assert( cursorHoldsMutex(pCur) );
36892   rc = restoreCursorPosition(pCur);
36893   if( rc==SQLITE_OK ){
36894     assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
36895     if( pCur->eState==CURSOR_INVALID ){
36896       *pSize = 0;
36897     }else{
36898       getCellInfo(pCur);
36899       *pSize = pCur->info.nKey;
36900     }
36901   }
36902   return rc;
36903 }
36904
36905 /*
36906 ** Set *pSize to the number of bytes of data in the entry the
36907 ** cursor currently points to.  Always return SQLITE_OK.
36908 ** Failure is not possible.  If the cursor is not currently
36909 ** pointing to an entry (which can happen, for example, if
36910 ** the database is empty) then *pSize is set to 0.
36911 */
36912 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
36913   int rc;
36914
36915   assert( cursorHoldsMutex(pCur) );
36916   rc = restoreCursorPosition(pCur);
36917   if( rc==SQLITE_OK ){
36918     assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
36919     if( pCur->eState==CURSOR_INVALID ){
36920       /* Not pointing at a valid entry - set *pSize to 0. */
36921       *pSize = 0;
36922     }else{
36923       getCellInfo(pCur);
36924       *pSize = pCur->info.nData;
36925     }
36926   }
36927   return rc;
36928 }
36929
36930 /*
36931 ** Given the page number of an overflow page in the database (parameter
36932 ** ovfl), this function finds the page number of the next page in the 
36933 ** linked list of overflow pages. If possible, it uses the auto-vacuum
36934 ** pointer-map data instead of reading the content of page ovfl to do so. 
36935 **
36936 ** If an error occurs an SQLite error code is returned. Otherwise:
36937 **
36938 ** Unless pPgnoNext is NULL, the page number of the next overflow 
36939 ** page in the linked list is written to *pPgnoNext. If page ovfl
36940 ** is the last page in its linked list, *pPgnoNext is set to zero. 
36941 **
36942 ** If ppPage is not NULL, *ppPage is set to the MemPage* handle
36943 ** for page ovfl. The underlying pager page may have been requested
36944 ** with the noContent flag set, so the page data accessable via
36945 ** this handle may not be trusted.
36946 */
36947 static int getOverflowPage(
36948   BtShared *pBt, 
36949   Pgno ovfl,                   /* Overflow page */
36950   MemPage **ppPage,            /* OUT: MemPage handle */
36951   Pgno *pPgnoNext              /* OUT: Next overflow page number */
36952 ){
36953   Pgno next = 0;
36954   int rc;
36955
36956   assert( sqlite3_mutex_held(pBt->mutex) );
36957   /* One of these must not be NULL. Otherwise, why call this function? */
36958   assert(ppPage || pPgnoNext);
36959
36960   /* If pPgnoNext is NULL, then this function is being called to obtain
36961   ** a MemPage* reference only. No page-data is required in this case.
36962   */
36963   if( !pPgnoNext ){
36964     return sqlite3BtreeGetPage(pBt, ovfl, ppPage, 1);
36965   }
36966
36967 #ifndef SQLITE_OMIT_AUTOVACUUM
36968   /* Try to find the next page in the overflow list using the
36969   ** autovacuum pointer-map pages. Guess that the next page in 
36970   ** the overflow list is page number (ovfl+1). If that guess turns 
36971   ** out to be wrong, fall back to loading the data of page 
36972   ** number ovfl to determine the next page number.
36973   */
36974   if( pBt->autoVacuum ){
36975     Pgno pgno;
36976     Pgno iGuess = ovfl+1;
36977     u8 eType;
36978
36979     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
36980       iGuess++;
36981     }
36982
36983     if( iGuess<=pagerPagecount(pBt) ){
36984       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
36985       if( rc!=SQLITE_OK ){
36986         return rc;
36987       }
36988       if( eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
36989         next = iGuess;
36990       }
36991     }
36992   }
36993 #endif
36994
36995   if( next==0 || ppPage ){
36996     MemPage *pPage = 0;
36997
36998     rc = sqlite3BtreeGetPage(pBt, ovfl, &pPage, next!=0);
36999     assert(rc==SQLITE_OK || pPage==0);
37000     if( next==0 && rc==SQLITE_OK ){
37001       next = get4byte(pPage->aData);
37002     }
37003
37004     if( ppPage ){
37005       *ppPage = pPage;
37006     }else{
37007       releasePage(pPage);
37008     }
37009   }
37010   *pPgnoNext = next;
37011
37012   return rc;
37013 }
37014
37015 /*
37016 ** Copy data from a buffer to a page, or from a page to a buffer.
37017 **
37018 ** pPayload is a pointer to data stored on database page pDbPage.
37019 ** If argument eOp is false, then nByte bytes of data are copied
37020 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
37021 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
37022 ** of data are copied from the buffer pBuf to pPayload.
37023 **
37024 ** SQLITE_OK is returned on success, otherwise an error code.
37025 */
37026 static int copyPayload(
37027   void *pPayload,           /* Pointer to page data */
37028   void *pBuf,               /* Pointer to buffer */
37029   int nByte,                /* Number of bytes to copy */
37030   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
37031   DbPage *pDbPage           /* Page containing pPayload */
37032 ){
37033   if( eOp ){
37034     /* Copy data from buffer to page (a write operation) */
37035     int rc = sqlite3PagerWrite(pDbPage);
37036     if( rc!=SQLITE_OK ){
37037       return rc;
37038     }
37039     memcpy(pPayload, pBuf, nByte);
37040   }else{
37041     /* Copy data from page to buffer (a read operation) */
37042     memcpy(pBuf, pPayload, nByte);
37043   }
37044   return SQLITE_OK;
37045 }
37046
37047 /*
37048 ** This function is used to read or overwrite payload information
37049 ** for the entry that the pCur cursor is pointing to. If the eOp
37050 ** parameter is 0, this is a read operation (data copied into
37051 ** buffer pBuf). If it is non-zero, a write (data copied from
37052 ** buffer pBuf).
37053 **
37054 ** A total of "amt" bytes are read or written beginning at "offset".
37055 ** Data is read to or from the buffer pBuf.
37056 **
37057 ** This routine does not make a distinction between key and data.
37058 ** It just reads or writes bytes from the payload area.  Data might 
37059 ** appear on the main page or be scattered out on multiple overflow 
37060 ** pages.
37061 **
37062 ** If the BtCursor.isIncrblobHandle flag is set, and the current
37063 ** cursor entry uses one or more overflow pages, this function
37064 ** allocates space for and lazily popluates the overflow page-list 
37065 ** cache array (BtCursor.aOverflow). Subsequent calls use this
37066 ** cache to make seeking to the supplied offset more efficient.
37067 **
37068 ** Once an overflow page-list cache has been allocated, it may be
37069 ** invalidated if some other cursor writes to the same table, or if
37070 ** the cursor is moved to a different row. Additionally, in auto-vacuum
37071 ** mode, the following events may invalidate an overflow page-list cache.
37072 **
37073 **   * An incremental vacuum,
37074 **   * A commit in auto_vacuum="full" mode,
37075 **   * Creating a table (may require moving an overflow page).
37076 */
37077 static int accessPayload(
37078   BtCursor *pCur,      /* Cursor pointing to entry to read from */
37079   u32 offset,          /* Begin reading this far into payload */
37080   u32 amt,             /* Read this many bytes */
37081   unsigned char *pBuf, /* Write the bytes into this buffer */ 
37082   int skipKey,         /* offset begins at data if this is true */
37083   int eOp              /* zero to read. non-zero to write. */
37084 ){
37085   unsigned char *aPayload;
37086   int rc = SQLITE_OK;
37087   u32 nKey;
37088   int iIdx = 0;
37089   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
37090   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
37091
37092   assert( pPage );
37093   assert( pCur->eState==CURSOR_VALID );
37094   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
37095   assert( cursorHoldsMutex(pCur) );
37096
37097   getCellInfo(pCur);
37098   aPayload = pCur->info.pCell + pCur->info.nHeader;
37099   nKey = (pPage->intKey ? 0 : pCur->info.nKey);
37100
37101   if( skipKey ){
37102     offset += nKey;
37103   }
37104   if( offset+amt > nKey+pCur->info.nData 
37105    || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
37106   ){
37107     /* Trying to read or write past the end of the data is an error */
37108     return SQLITE_CORRUPT_BKPT;
37109   }
37110
37111   /* Check if data must be read/written to/from the btree page itself. */
37112   if( offset<pCur->info.nLocal ){
37113     int a = amt;
37114     if( a+offset>pCur->info.nLocal ){
37115       a = pCur->info.nLocal - offset;
37116     }
37117     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
37118     offset = 0;
37119     pBuf += a;
37120     amt -= a;
37121   }else{
37122     offset -= pCur->info.nLocal;
37123   }
37124
37125   if( rc==SQLITE_OK && amt>0 ){
37126     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
37127     Pgno nextPage;
37128
37129     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
37130
37131 #ifndef SQLITE_OMIT_INCRBLOB
37132     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
37133     ** has not been allocated, allocate it now. The array is sized at
37134     ** one entry for each overflow page in the overflow chain. The
37135     ** page number of the first overflow page is stored in aOverflow[0],
37136     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
37137     ** (the cache is lazily populated).
37138     */
37139     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
37140       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
37141       pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
37142       if( nOvfl && !pCur->aOverflow ){
37143         rc = SQLITE_NOMEM;
37144       }
37145     }
37146
37147     /* If the overflow page-list cache has been allocated and the
37148     ** entry for the first required overflow page is valid, skip
37149     ** directly to it.
37150     */
37151     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
37152       iIdx = (offset/ovflSize);
37153       nextPage = pCur->aOverflow[iIdx];
37154       offset = (offset%ovflSize);
37155     }
37156 #endif
37157
37158     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
37159
37160 #ifndef SQLITE_OMIT_INCRBLOB
37161       /* If required, populate the overflow page-list cache. */
37162       if( pCur->aOverflow ){
37163         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
37164         pCur->aOverflow[iIdx] = nextPage;
37165       }
37166 #endif
37167
37168       if( offset>=ovflSize ){
37169         /* The only reason to read this page is to obtain the page
37170         ** number for the next page in the overflow chain. The page
37171         ** data is not required. So first try to lookup the overflow
37172         ** page-list cache, if any, then fall back to the getOverflowPage()
37173         ** function.
37174         */
37175 #ifndef SQLITE_OMIT_INCRBLOB
37176         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
37177           nextPage = pCur->aOverflow[iIdx+1];
37178         } else 
37179 #endif
37180           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
37181         offset -= ovflSize;
37182       }else{
37183         /* Need to read this page properly. It contains some of the
37184         ** range of data that is being read (eOp==0) or written (eOp!=0).
37185         */
37186         DbPage *pDbPage;
37187         int a = amt;
37188         rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
37189         if( rc==SQLITE_OK ){
37190           aPayload = sqlite3PagerGetData(pDbPage);
37191           nextPage = get4byte(aPayload);
37192           if( a + offset > ovflSize ){
37193             a = ovflSize - offset;
37194           }
37195           rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
37196           sqlite3PagerUnref(pDbPage);
37197           offset = 0;
37198           amt -= a;
37199           pBuf += a;
37200         }
37201       }
37202     }
37203   }
37204
37205   if( rc==SQLITE_OK && amt>0 ){
37206     return SQLITE_CORRUPT_BKPT;
37207   }
37208   return rc;
37209 }
37210
37211 /*
37212 ** Read part of the key associated with cursor pCur.  Exactly
37213 ** "amt" bytes will be transfered into pBuf[].  The transfer
37214 ** begins at "offset".
37215 **
37216 ** Return SQLITE_OK on success or an error code if anything goes
37217 ** wrong.  An error is returned if "offset+amt" is larger than
37218 ** the available payload.
37219 */
37220 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
37221   int rc;
37222
37223   assert( cursorHoldsMutex(pCur) );
37224   rc = restoreCursorPosition(pCur);
37225   if( rc==SQLITE_OK ){
37226     assert( pCur->eState==CURSOR_VALID );
37227     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
37228     if( pCur->apPage[0]->intKey ){
37229       return SQLITE_CORRUPT_BKPT;
37230     }
37231     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
37232     rc = accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0, 0);
37233   }
37234   return rc;
37235 }
37236
37237 /*
37238 ** Read part of the data associated with cursor pCur.  Exactly
37239 ** "amt" bytes will be transfered into pBuf[].  The transfer
37240 ** begins at "offset".
37241 **
37242 ** Return SQLITE_OK on success or an error code if anything goes
37243 ** wrong.  An error is returned if "offset+amt" is larger than
37244 ** the available payload.
37245 */
37246 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
37247   int rc;
37248
37249 #ifndef SQLITE_OMIT_INCRBLOB
37250   if ( pCur->eState==CURSOR_INVALID ){
37251     return SQLITE_ABORT;
37252   }
37253 #endif
37254
37255   assert( cursorHoldsMutex(pCur) );
37256   rc = restoreCursorPosition(pCur);
37257   if( rc==SQLITE_OK ){
37258     assert( pCur->eState==CURSOR_VALID );
37259     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
37260     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
37261     rc = accessPayload(pCur, offset, amt, pBuf, 1, 0);
37262   }
37263   return rc;
37264 }
37265
37266 /*
37267 ** Return a pointer to payload information from the entry that the 
37268 ** pCur cursor is pointing to.  The pointer is to the beginning of
37269 ** the key if skipKey==0 and it points to the beginning of data if
37270 ** skipKey==1.  The number of bytes of available key/data is written
37271 ** into *pAmt.  If *pAmt==0, then the value returned will not be
37272 ** a valid pointer.
37273 **
37274 ** This routine is an optimization.  It is common for the entire key
37275 ** and data to fit on the local page and for there to be no overflow
37276 ** pages.  When that is so, this routine can be used to access the
37277 ** key and data without making a copy.  If the key and/or data spills
37278 ** onto overflow pages, then accessPayload() must be used to reassembly
37279 ** the key/data and copy it into a preallocated buffer.
37280 **
37281 ** The pointer returned by this routine looks directly into the cached
37282 ** page of the database.  The data might change or move the next time
37283 ** any btree routine is called.
37284 */
37285 static const unsigned char *fetchPayload(
37286   BtCursor *pCur,      /* Cursor pointing to entry to read from */
37287   int *pAmt,           /* Write the number of available bytes here */
37288   int skipKey          /* read beginning at data if this is true */
37289 ){
37290   unsigned char *aPayload;
37291   MemPage *pPage;
37292   u32 nKey;
37293   u32 nLocal;
37294
37295   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
37296   assert( pCur->eState==CURSOR_VALID );
37297   assert( cursorHoldsMutex(pCur) );
37298   pPage = pCur->apPage[pCur->iPage];
37299   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
37300   getCellInfo(pCur);
37301   aPayload = pCur->info.pCell;
37302   aPayload += pCur->info.nHeader;
37303   if( pPage->intKey ){
37304     nKey = 0;
37305   }else{
37306     nKey = pCur->info.nKey;
37307   }
37308   if( skipKey ){
37309     aPayload += nKey;
37310     nLocal = pCur->info.nLocal - nKey;
37311   }else{
37312     nLocal = pCur->info.nLocal;
37313     if( nLocal>nKey ){
37314       nLocal = nKey;
37315     }
37316   }
37317   *pAmt = nLocal;
37318   return aPayload;
37319 }
37320
37321
37322 /*
37323 ** For the entry that cursor pCur is point to, return as
37324 ** many bytes of the key or data as are available on the local
37325 ** b-tree page.  Write the number of available bytes into *pAmt.
37326 **
37327 ** The pointer returned is ephemeral.  The key/data may move
37328 ** or be destroyed on the next call to any Btree routine,
37329 ** including calls from other threads against the same cache.
37330 ** Hence, a mutex on the BtShared should be held prior to calling
37331 ** this routine.
37332 **
37333 ** These routines is used to get quick access to key and data
37334 ** in the common case where no overflow pages are used.
37335 */
37336 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
37337   assert( cursorHoldsMutex(pCur) );
37338   if( pCur->eState==CURSOR_VALID ){
37339     return (const void*)fetchPayload(pCur, pAmt, 0);
37340   }
37341   return 0;
37342 }
37343 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
37344   assert( cursorHoldsMutex(pCur) );
37345   if( pCur->eState==CURSOR_VALID ){
37346     return (const void*)fetchPayload(pCur, pAmt, 1);
37347   }
37348   return 0;
37349 }
37350
37351
37352 /*
37353 ** Move the cursor down to a new child page.  The newPgno argument is the
37354 ** page number of the child page to move to.
37355 */
37356 static int moveToChild(BtCursor *pCur, u32 newPgno){
37357   int rc;
37358   int i = pCur->iPage;
37359   MemPage *pNewPage;
37360   BtShared *pBt = pCur->pBt;
37361
37362   assert( cursorHoldsMutex(pCur) );
37363   assert( pCur->eState==CURSOR_VALID );
37364   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
37365   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
37366     return SQLITE_CORRUPT_BKPT;
37367   }
37368   rc = getAndInitPage(pBt, newPgno, &pNewPage);
37369   if( rc ) return rc;
37370   pCur->apPage[i+1] = pNewPage;
37371   pCur->aiIdx[i+1] = 0;
37372   pCur->iPage++;
37373
37374   pCur->info.nSize = 0;
37375   pCur->validNKey = 0;
37376   if( pNewPage->nCell<1 ){
37377     return SQLITE_CORRUPT_BKPT;
37378   }
37379   return SQLITE_OK;
37380 }
37381
37382 #ifndef NDEBUG
37383 /*
37384 ** Page pParent is an internal (non-leaf) tree page. This function 
37385 ** asserts that page number iChild is the left-child if the iIdx'th
37386 ** cell in page pParent. Or, if iIdx is equal to the total number of
37387 ** cells in pParent, that page number iChild is the right-child of
37388 ** the page.
37389 */
37390 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
37391   assert( iIdx<=pParent->nCell );
37392   if( iIdx==pParent->nCell ){
37393     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
37394   }else{
37395     assert( get4byte(findCell(pParent, iIdx))==iChild );
37396   }
37397 }
37398 #else
37399 #  define assertParentIndex(x,y,z) 
37400 #endif
37401
37402 /*
37403 ** Move the cursor up to the parent page.
37404 **
37405 ** pCur->idx is set to the cell index that contains the pointer
37406 ** to the page we are coming from.  If we are coming from the
37407 ** right-most child page then pCur->idx is set to one more than
37408 ** the largest cell index.
37409 */
37410 SQLITE_PRIVATE void sqlite3BtreeMoveToParent(BtCursor *pCur){
37411   assert( cursorHoldsMutex(pCur) );
37412   assert( pCur->eState==CURSOR_VALID );
37413   assert( pCur->iPage>0 );
37414   assert( pCur->apPage[pCur->iPage] );
37415   assertParentIndex(
37416     pCur->apPage[pCur->iPage-1], 
37417     pCur->aiIdx[pCur->iPage-1], 
37418     pCur->apPage[pCur->iPage]->pgno
37419   );
37420   releasePage(pCur->apPage[pCur->iPage]);
37421   pCur->iPage--;
37422   pCur->info.nSize = 0;
37423   pCur->validNKey = 0;
37424 }
37425
37426 /*
37427 ** Move the cursor to the root page
37428 */
37429 static int moveToRoot(BtCursor *pCur){
37430   MemPage *pRoot;
37431   int rc = SQLITE_OK;
37432   Btree *p = pCur->pBtree;
37433   BtShared *pBt = p->pBt;
37434
37435   assert( cursorHoldsMutex(pCur) );
37436   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
37437   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
37438   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
37439   if( pCur->eState>=CURSOR_REQUIRESEEK ){
37440     if( pCur->eState==CURSOR_FAULT ){
37441       return pCur->skip;
37442     }
37443     sqlite3BtreeClearCursor(pCur);
37444   }
37445
37446   if( pCur->iPage>=0 ){
37447     int i;
37448     for(i=1; i<=pCur->iPage; i++){
37449       releasePage(pCur->apPage[i]);
37450     }
37451   }else{
37452     if( 
37453       SQLITE_OK!=(rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]))
37454     ){
37455       pCur->eState = CURSOR_INVALID;
37456       return rc;
37457     }
37458   }
37459
37460   pRoot = pCur->apPage[0];
37461   assert( pRoot->pgno==pCur->pgnoRoot );
37462   pCur->iPage = 0;
37463   pCur->aiIdx[0] = 0;
37464   pCur->info.nSize = 0;
37465   pCur->atLast = 0;
37466   pCur->validNKey = 0;
37467
37468   if( pRoot->nCell==0 && !pRoot->leaf ){
37469     Pgno subpage;
37470     assert( pRoot->pgno==1 );
37471     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
37472     assert( subpage>0 );
37473     pCur->eState = CURSOR_VALID;
37474     rc = moveToChild(pCur, subpage);
37475   }else{
37476     pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
37477   }
37478   return rc;
37479 }
37480
37481 /*
37482 ** Move the cursor down to the left-most leaf entry beneath the
37483 ** entry to which it is currently pointing.
37484 **
37485 ** The left-most leaf is the one with the smallest key - the first
37486 ** in ascending order.
37487 */
37488 static int moveToLeftmost(BtCursor *pCur){
37489   Pgno pgno;
37490   int rc = SQLITE_OK;
37491   MemPage *pPage;
37492
37493   assert( cursorHoldsMutex(pCur) );
37494   assert( pCur->eState==CURSOR_VALID );
37495   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
37496     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
37497     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
37498     rc = moveToChild(pCur, pgno);
37499   }
37500   return rc;
37501 }
37502
37503 /*
37504 ** Move the cursor down to the right-most leaf entry beneath the
37505 ** page to which it is currently pointing.  Notice the difference
37506 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
37507 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
37508 ** finds the right-most entry beneath the *page*.
37509 **
37510 ** The right-most entry is the one with the largest key - the last
37511 ** key in ascending order.
37512 */
37513 static int moveToRightmost(BtCursor *pCur){
37514   Pgno pgno;
37515   int rc = SQLITE_OK;
37516   MemPage *pPage;
37517
37518   assert( cursorHoldsMutex(pCur) );
37519   assert( pCur->eState==CURSOR_VALID );
37520   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
37521     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
37522     pCur->aiIdx[pCur->iPage] = pPage->nCell;
37523     rc = moveToChild(pCur, pgno);
37524   }
37525   if( rc==SQLITE_OK ){
37526     pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
37527     pCur->info.nSize = 0;
37528     pCur->validNKey = 0;
37529   }
37530   return rc;
37531 }
37532
37533 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
37534 ** on success.  Set *pRes to 0 if the cursor actually points to something
37535 ** or set *pRes to 1 if the table is empty.
37536 */
37537 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
37538   int rc;
37539
37540   assert( cursorHoldsMutex(pCur) );
37541   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
37542   rc = moveToRoot(pCur);
37543   if( rc==SQLITE_OK ){
37544     if( pCur->eState==CURSOR_INVALID ){
37545       assert( pCur->apPage[pCur->iPage]->nCell==0 );
37546       *pRes = 1;
37547       rc = SQLITE_OK;
37548     }else{
37549       assert( pCur->apPage[pCur->iPage]->nCell>0 );
37550       *pRes = 0;
37551       rc = moveToLeftmost(pCur);
37552     }
37553   }
37554   return rc;
37555 }
37556
37557 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
37558 ** on success.  Set *pRes to 0 if the cursor actually points to something
37559 ** or set *pRes to 1 if the table is empty.
37560 */
37561 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
37562   int rc;
37563  
37564   assert( cursorHoldsMutex(pCur) );
37565   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
37566   rc = moveToRoot(pCur);
37567   if( rc==SQLITE_OK ){
37568     if( CURSOR_INVALID==pCur->eState ){
37569       assert( pCur->apPage[pCur->iPage]->nCell==0 );
37570       *pRes = 1;
37571     }else{
37572       assert( pCur->eState==CURSOR_VALID );
37573       *pRes = 0;
37574       rc = moveToRightmost(pCur);
37575       getCellInfo(pCur);
37576       pCur->atLast = rc==SQLITE_OK;
37577     }
37578   }
37579   return rc;
37580 }
37581
37582 /* Move the cursor so that it points to an entry near the key 
37583 ** specified by pIdxKey or intKey.   Return a success code.
37584 **
37585 ** For INTKEY tables, the intKey parameter is used.  pIdxKey 
37586 ** must be NULL.  For index tables, pIdxKey is used and intKey
37587 ** is ignored.
37588 **
37589 ** If an exact match is not found, then the cursor is always
37590 ** left pointing at a leaf page which would hold the entry if it
37591 ** were present.  The cursor might point to an entry that comes
37592 ** before or after the key.
37593 **
37594 ** The result of comparing the key with the entry to which the
37595 ** cursor is written to *pRes if pRes!=NULL.  The meaning of
37596 ** this value is as follows:
37597 **
37598 **     *pRes<0      The cursor is left pointing at an entry that
37599 **                  is smaller than pKey or if the table is empty
37600 **                  and the cursor is therefore left point to nothing.
37601 **
37602 **     *pRes==0     The cursor is left pointing at an entry that
37603 **                  exactly matches pKey.
37604 **
37605 **     *pRes>0      The cursor is left pointing at an entry that
37606 **                  is larger than pKey.
37607 **
37608 */
37609 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
37610   BtCursor *pCur,          /* The cursor to be moved */
37611   UnpackedRecord *pIdxKey, /* Unpacked index key */
37612   i64 intKey,              /* The table key */
37613   int biasRight,           /* If true, bias the search to the high end */
37614   int *pRes                /* Write search results here */
37615 ){
37616   int rc;
37617
37618   assert( cursorHoldsMutex(pCur) );
37619   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
37620
37621   /* If the cursor is already positioned at the point we are trying
37622   ** to move to, then just return without doing any work */
37623   if( pCur->eState==CURSOR_VALID && pCur->validNKey 
37624    && pCur->apPage[0]->intKey 
37625   ){
37626     if( pCur->info.nKey==intKey ){
37627       *pRes = 0;
37628       return SQLITE_OK;
37629     }
37630     if( pCur->atLast && pCur->info.nKey<intKey ){
37631       *pRes = -1;
37632       return SQLITE_OK;
37633     }
37634   }
37635
37636   rc = moveToRoot(pCur);
37637   if( rc ){
37638     return rc;
37639   }
37640   assert( pCur->apPage[pCur->iPage] );
37641   assert( pCur->apPage[pCur->iPage]->isInit );
37642   if( pCur->eState==CURSOR_INVALID ){
37643     *pRes = -1;
37644     assert( pCur->apPage[pCur->iPage]->nCell==0 );
37645     return SQLITE_OK;
37646   }
37647   assert( pCur->apPage[0]->intKey || pIdxKey );
37648   for(;;){
37649     int lwr, upr;
37650     Pgno chldPg;
37651     MemPage *pPage = pCur->apPage[pCur->iPage];
37652     int c = -1;  /* pRes return if table is empty must be -1 */
37653     lwr = 0;
37654     upr = pPage->nCell-1;
37655     if( !pPage->intKey && pIdxKey==0 ){
37656       rc = SQLITE_CORRUPT_BKPT;
37657       goto moveto_finish;
37658     }
37659     if( biasRight ){
37660       pCur->aiIdx[pCur->iPage] = upr;
37661     }else{
37662       pCur->aiIdx[pCur->iPage] = (upr+lwr)/2;
37663     }
37664     if( lwr<=upr ) for(;;){
37665       void *pCellKey;
37666       i64 nCellKey;
37667       int idx = pCur->aiIdx[pCur->iPage];
37668       pCur->info.nSize = 0;
37669       pCur->validNKey = 1;
37670       if( pPage->intKey ){
37671         u8 *pCell;
37672         pCell = findCell(pPage, idx) + pPage->childPtrSize;
37673         if( pPage->hasData ){
37674           u32 dummy;
37675           pCell += getVarint32(pCell, dummy);
37676         }
37677         getVarint(pCell, (u64*)&nCellKey);
37678         if( nCellKey==intKey ){
37679           c = 0;
37680         }else if( nCellKey<intKey ){
37681           c = -1;
37682         }else{
37683           assert( nCellKey>intKey );
37684           c = +1;
37685         }
37686       }else{
37687         int available;
37688         pCellKey = (void *)fetchPayload(pCur, &available, 0);
37689         nCellKey = pCur->info.nKey;
37690         if( available>=nCellKey ){
37691           c = sqlite3VdbeRecordCompare(nCellKey, pCellKey, pIdxKey);
37692         }else{
37693           pCellKey = sqlite3Malloc( nCellKey );
37694           if( pCellKey==0 ){
37695             rc = SQLITE_NOMEM;
37696             goto moveto_finish;
37697           }
37698           rc = sqlite3BtreeKey(pCur, 0, nCellKey, (void *)pCellKey);
37699           c = sqlite3VdbeRecordCompare(nCellKey, pCellKey, pIdxKey);
37700           sqlite3_free(pCellKey);
37701           if( rc ) goto moveto_finish;
37702         }
37703       }
37704       if( c==0 ){
37705         pCur->info.nKey = nCellKey;
37706         if( pPage->intKey && !pPage->leaf ){
37707           lwr = idx;
37708           upr = lwr - 1;
37709           break;
37710         }else{
37711           if( pRes ) *pRes = 0;
37712           rc = SQLITE_OK;
37713           goto moveto_finish;
37714         }
37715       }
37716       if( c<0 ){
37717         lwr = idx+1;
37718       }else{
37719         upr = idx-1;
37720       }
37721       if( lwr>upr ){
37722         pCur->info.nKey = nCellKey;
37723         break;
37724       }
37725       pCur->aiIdx[pCur->iPage] = (lwr+upr)/2;
37726     }
37727     assert( lwr==upr+1 );
37728     assert( pPage->isInit );
37729     if( pPage->leaf ){
37730       chldPg = 0;
37731     }else if( lwr>=pPage->nCell ){
37732       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
37733     }else{
37734       chldPg = get4byte(findCell(pPage, lwr));
37735     }
37736     if( chldPg==0 ){
37737       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
37738       if( pRes ) *pRes = c;
37739       rc = SQLITE_OK;
37740       goto moveto_finish;
37741     }
37742     pCur->aiIdx[pCur->iPage] = lwr;
37743     pCur->info.nSize = 0;
37744     pCur->validNKey = 0;
37745     rc = moveToChild(pCur, chldPg);
37746     if( rc ) goto moveto_finish;
37747   }
37748 moveto_finish:
37749   return rc;
37750 }
37751
37752 /*
37753 ** In this version of BtreeMoveto, pKey is a packed index record
37754 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
37755 ** record and then call BtreeMovetoUnpacked() to do the work.
37756 */
37757 SQLITE_PRIVATE int sqlite3BtreeMoveto(
37758   BtCursor *pCur,     /* Cursor open on the btree to be searched */
37759   const void *pKey,   /* Packed key if the btree is an index */
37760   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
37761   int bias,           /* Bias search to the high end */
37762   int *pRes           /* Write search results here */
37763 ){
37764   int rc;                    /* Status code */
37765   UnpackedRecord *pIdxKey;   /* Unpacked index key */
37766   UnpackedRecord aSpace[16]; /* Temp space for pIdxKey - to avoid a malloc */
37767
37768   if( pKey ){
37769     pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, nKey, pKey,
37770                                       aSpace, sizeof(aSpace));
37771     if( pIdxKey==0 ) return SQLITE_NOMEM;
37772   }else{
37773     pIdxKey = 0;
37774   }
37775   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
37776   if( pKey ){
37777     sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
37778   }
37779   return rc;
37780 }
37781
37782
37783 /*
37784 ** Return TRUE if the cursor is not pointing at an entry of the table.
37785 **
37786 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
37787 ** past the last entry in the table or sqlite3BtreePrev() moves past
37788 ** the first entry.  TRUE is also returned if the table is empty.
37789 */
37790 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
37791   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
37792   ** have been deleted? This API will need to change to return an error code
37793   ** as well as the boolean result value.
37794   */
37795   return (CURSOR_VALID!=pCur->eState);
37796 }
37797
37798 /*
37799 ** Return the database connection handle for a cursor.
37800 */
37801 SQLITE_PRIVATE sqlite3 *sqlite3BtreeCursorDb(const BtCursor *pCur){
37802   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
37803   return pCur->pBtree->db;
37804 }
37805
37806 /*
37807 ** Advance the cursor to the next entry in the database.  If
37808 ** successful then set *pRes=0.  If the cursor
37809 ** was already pointing to the last entry in the database before
37810 ** this routine was called, then set *pRes=1.
37811 */
37812 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
37813   int rc;
37814   int idx;
37815   MemPage *pPage;
37816
37817   assert( cursorHoldsMutex(pCur) );
37818   rc = restoreCursorPosition(pCur);
37819   if( rc!=SQLITE_OK ){
37820     return rc;
37821   }
37822   assert( pRes!=0 );
37823   if( CURSOR_INVALID==pCur->eState ){
37824     *pRes = 1;
37825     return SQLITE_OK;
37826   }
37827   if( pCur->skip>0 ){
37828     pCur->skip = 0;
37829     *pRes = 0;
37830     return SQLITE_OK;
37831   }
37832   pCur->skip = 0;
37833
37834   pPage = pCur->apPage[pCur->iPage];
37835   idx = ++pCur->aiIdx[pCur->iPage];
37836   assert( pPage->isInit );
37837   assert( idx<=pPage->nCell );
37838
37839   pCur->info.nSize = 0;
37840   pCur->validNKey = 0;
37841   if( idx>=pPage->nCell ){
37842     if( !pPage->leaf ){
37843       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
37844       if( rc ) return rc;
37845       rc = moveToLeftmost(pCur);
37846       *pRes = 0;
37847       return rc;
37848     }
37849     do{
37850       if( pCur->iPage==0 ){
37851         *pRes = 1;
37852         pCur->eState = CURSOR_INVALID;
37853         return SQLITE_OK;
37854       }
37855       sqlite3BtreeMoveToParent(pCur);
37856       pPage = pCur->apPage[pCur->iPage];
37857     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
37858     *pRes = 0;
37859     if( pPage->intKey ){
37860       rc = sqlite3BtreeNext(pCur, pRes);
37861     }else{
37862       rc = SQLITE_OK;
37863     }
37864     return rc;
37865   }
37866   *pRes = 0;
37867   if( pPage->leaf ){
37868     return SQLITE_OK;
37869   }
37870   rc = moveToLeftmost(pCur);
37871   return rc;
37872 }
37873
37874
37875 /*
37876 ** Step the cursor to the back to the previous entry in the database.  If
37877 ** successful then set *pRes=0.  If the cursor
37878 ** was already pointing to the first entry in the database before
37879 ** this routine was called, then set *pRes=1.
37880 */
37881 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
37882   int rc;
37883   MemPage *pPage;
37884
37885   assert( cursorHoldsMutex(pCur) );
37886   rc = restoreCursorPosition(pCur);
37887   if( rc!=SQLITE_OK ){
37888     return rc;
37889   }
37890   pCur->atLast = 0;
37891   if( CURSOR_INVALID==pCur->eState ){
37892     *pRes = 1;
37893     return SQLITE_OK;
37894   }
37895   if( pCur->skip<0 ){
37896     pCur->skip = 0;
37897     *pRes = 0;
37898     return SQLITE_OK;
37899   }
37900   pCur->skip = 0;
37901
37902   pPage = pCur->apPage[pCur->iPage];
37903   assert( pPage->isInit );
37904   if( !pPage->leaf ){
37905     int idx = pCur->aiIdx[pCur->iPage];
37906     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
37907     if( rc ){
37908       return rc;
37909     }
37910     rc = moveToRightmost(pCur);
37911   }else{
37912     while( pCur->aiIdx[pCur->iPage]==0 ){
37913       if( pCur->iPage==0 ){
37914         pCur->eState = CURSOR_INVALID;
37915         *pRes = 1;
37916         return SQLITE_OK;
37917       }
37918       sqlite3BtreeMoveToParent(pCur);
37919     }
37920     pCur->info.nSize = 0;
37921     pCur->validNKey = 0;
37922
37923     pCur->aiIdx[pCur->iPage]--;
37924     pPage = pCur->apPage[pCur->iPage];
37925     if( pPage->intKey && !pPage->leaf ){
37926       rc = sqlite3BtreePrevious(pCur, pRes);
37927     }else{
37928       rc = SQLITE_OK;
37929     }
37930   }
37931   *pRes = 0;
37932   return rc;
37933 }
37934
37935 /*
37936 ** Allocate a new page from the database file.
37937 **
37938 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
37939 ** has already been called on the new page.)  The new page has also
37940 ** been referenced and the calling routine is responsible for calling
37941 ** sqlite3PagerUnref() on the new page when it is done.
37942 **
37943 ** SQLITE_OK is returned on success.  Any other return value indicates
37944 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
37945 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
37946 **
37947 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to 
37948 ** locate a page close to the page number "nearby".  This can be used in an
37949 ** attempt to keep related pages close to each other in the database file,
37950 ** which in turn can make database access faster.
37951 **
37952 ** If the "exact" parameter is not 0, and the page-number nearby exists 
37953 ** anywhere on the free-list, then it is guarenteed to be returned. This
37954 ** is only used by auto-vacuum databases when allocating a new table.
37955 */
37956 static int allocateBtreePage(
37957   BtShared *pBt, 
37958   MemPage **ppPage, 
37959   Pgno *pPgno, 
37960   Pgno nearby,
37961   u8 exact
37962 ){
37963   MemPage *pPage1;
37964   int rc;
37965   int n;     /* Number of pages on the freelist */
37966   int k;     /* Number of leaves on the trunk of the freelist */
37967   MemPage *pTrunk = 0;
37968   MemPage *pPrevTrunk = 0;
37969
37970   assert( sqlite3_mutex_held(pBt->mutex) );
37971   pPage1 = pBt->pPage1;
37972   n = get4byte(&pPage1->aData[36]);
37973   if( n>0 ){
37974     /* There are pages on the freelist.  Reuse one of those pages. */
37975     Pgno iTrunk;
37976     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
37977     
37978     /* If the 'exact' parameter was true and a query of the pointer-map
37979     ** shows that the page 'nearby' is somewhere on the free-list, then
37980     ** the entire-list will be searched for that page.
37981     */
37982 #ifndef SQLITE_OMIT_AUTOVACUUM
37983     if( exact && nearby<=pagerPagecount(pBt) ){
37984       u8 eType;
37985       assert( nearby>0 );
37986       assert( pBt->autoVacuum );
37987       rc = ptrmapGet(pBt, nearby, &eType, 0);
37988       if( rc ) return rc;
37989       if( eType==PTRMAP_FREEPAGE ){
37990         searchList = 1;
37991       }
37992       *pPgno = nearby;
37993     }
37994 #endif
37995
37996     /* Decrement the free-list count by 1. Set iTrunk to the index of the
37997     ** first free-list trunk page. iPrevTrunk is initially 1.
37998     */
37999     rc = sqlite3PagerWrite(pPage1->pDbPage);
38000     if( rc ) return rc;
38001     put4byte(&pPage1->aData[36], n-1);
38002
38003     /* The code within this loop is run only once if the 'searchList' variable
38004     ** is not true. Otherwise, it runs once for each trunk-page on the
38005     ** free-list until the page 'nearby' is located.
38006     */
38007     do {
38008       pPrevTrunk = pTrunk;
38009       if( pPrevTrunk ){
38010         iTrunk = get4byte(&pPrevTrunk->aData[0]);
38011       }else{
38012         iTrunk = get4byte(&pPage1->aData[32]);
38013       }
38014       rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
38015       if( rc ){
38016         pTrunk = 0;
38017         goto end_allocate_page;
38018       }
38019
38020       k = get4byte(&pTrunk->aData[4]);
38021       if( k==0 && !searchList ){
38022         /* The trunk has no leaves and the list is not being searched. 
38023         ** So extract the trunk page itself and use it as the newly 
38024         ** allocated page */
38025         assert( pPrevTrunk==0 );
38026         rc = sqlite3PagerWrite(pTrunk->pDbPage);
38027         if( rc ){
38028           goto end_allocate_page;
38029         }
38030         *pPgno = iTrunk;
38031         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
38032         *ppPage = pTrunk;
38033         pTrunk = 0;
38034         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
38035       }else if( k>pBt->usableSize/4 - 2 ){
38036         /* Value of k is out of range.  Database corruption */
38037         rc = SQLITE_CORRUPT_BKPT;
38038         goto end_allocate_page;
38039 #ifndef SQLITE_OMIT_AUTOVACUUM
38040       }else if( searchList && nearby==iTrunk ){
38041         /* The list is being searched and this trunk page is the page
38042         ** to allocate, regardless of whether it has leaves.
38043         */
38044         assert( *pPgno==iTrunk );
38045         *ppPage = pTrunk;
38046         searchList = 0;
38047         rc = sqlite3PagerWrite(pTrunk->pDbPage);
38048         if( rc ){
38049           goto end_allocate_page;
38050         }
38051         if( k==0 ){
38052           if( !pPrevTrunk ){
38053             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
38054           }else{
38055             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
38056           }
38057         }else{
38058           /* The trunk page is required by the caller but it contains 
38059           ** pointers to free-list leaves. The first leaf becomes a trunk
38060           ** page in this case.
38061           */
38062           MemPage *pNewTrunk;
38063           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
38064           rc = sqlite3BtreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
38065           if( rc!=SQLITE_OK ){
38066             goto end_allocate_page;
38067           }
38068           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
38069           if( rc!=SQLITE_OK ){
38070             releasePage(pNewTrunk);
38071             goto end_allocate_page;
38072           }
38073           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
38074           put4byte(&pNewTrunk->aData[4], k-1);
38075           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
38076           releasePage(pNewTrunk);
38077           if( !pPrevTrunk ){
38078             put4byte(&pPage1->aData[32], iNewTrunk);
38079           }else{
38080             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
38081             if( rc ){
38082               goto end_allocate_page;
38083             }
38084             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
38085           }
38086         }
38087         pTrunk = 0;
38088         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
38089 #endif
38090       }else{
38091         /* Extract a leaf from the trunk */
38092         int closest;
38093         Pgno iPage;
38094         unsigned char *aData = pTrunk->aData;
38095         rc = sqlite3PagerWrite(pTrunk->pDbPage);
38096         if( rc ){
38097           goto end_allocate_page;
38098         }
38099         if( nearby>0 ){
38100           int i, dist;
38101           closest = 0;
38102           dist = get4byte(&aData[8]) - nearby;
38103           if( dist<0 ) dist = -dist;
38104           for(i=1; i<k; i++){
38105             int d2 = get4byte(&aData[8+i*4]) - nearby;
38106             if( d2<0 ) d2 = -d2;
38107             if( d2<dist ){
38108               closest = i;
38109               dist = d2;
38110             }
38111           }
38112         }else{
38113           closest = 0;
38114         }
38115
38116         iPage = get4byte(&aData[8+closest*4]);
38117         if( !searchList || iPage==nearby ){
38118           Pgno nPage;
38119           *pPgno = iPage;
38120           nPage = pagerPagecount(pBt);
38121           if( *pPgno>nPage ){
38122             /* Free page off the end of the file */
38123             rc = SQLITE_CORRUPT_BKPT;
38124             goto end_allocate_page;
38125           }
38126           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
38127                  ": %d more free pages\n",
38128                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
38129           if( closest<k-1 ){
38130             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
38131           }
38132           put4byte(&aData[4], k-1);
38133           rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 1);
38134           if( rc==SQLITE_OK ){
38135             sqlite3PagerDontRollback((*ppPage)->pDbPage);
38136             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
38137             if( rc!=SQLITE_OK ){
38138               releasePage(*ppPage);
38139             }
38140           }
38141           searchList = 0;
38142         }
38143       }
38144       releasePage(pPrevTrunk);
38145       pPrevTrunk = 0;
38146     }while( searchList );
38147   }else{
38148     /* There are no pages on the freelist, so create a new page at the
38149     ** end of the file */
38150     int nPage = pagerPagecount(pBt);
38151     *pPgno = nPage + 1;
38152
38153 #ifndef SQLITE_OMIT_AUTOVACUUM
38154     if( pBt->nTrunc ){
38155       /* An incr-vacuum has already run within this transaction. So the
38156       ** page to allocate is not from the physical end of the file, but
38157       ** at pBt->nTrunc. 
38158       */
38159       *pPgno = pBt->nTrunc+1;
38160       if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
38161         (*pPgno)++;
38162       }
38163     }
38164     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
38165       /* If *pPgno refers to a pointer-map page, allocate two new pages
38166       ** at the end of the file instead of one. The first allocated page
38167       ** becomes a new pointer-map page, the second is used by the caller.
38168       */
38169       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
38170       assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
38171       (*pPgno)++;
38172       if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ (*pPgno)++; }
38173     }
38174     if( pBt->nTrunc ){
38175       pBt->nTrunc = *pPgno;
38176     }
38177 #endif
38178
38179     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
38180     rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 0);
38181     if( rc ) return rc;
38182     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
38183     if( rc!=SQLITE_OK ){
38184       releasePage(*ppPage);
38185     }
38186     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
38187   }
38188
38189   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
38190
38191 end_allocate_page:
38192   releasePage(pTrunk);
38193   releasePage(pPrevTrunk);
38194   if( rc==SQLITE_OK ){
38195     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
38196       releasePage(*ppPage);
38197       return SQLITE_CORRUPT_BKPT;
38198     }
38199     (*ppPage)->isInit = 0;
38200   }
38201   return rc;
38202 }
38203
38204 /*
38205 ** Add a page of the database file to the freelist.
38206 **
38207 ** sqlite3PagerUnref() is NOT called for pPage.
38208 */
38209 static int freePage(MemPage *pPage){
38210   BtShared *pBt = pPage->pBt;
38211   MemPage *pPage1 = pBt->pPage1;
38212   int rc, n, k;
38213
38214   /* Prepare the page for freeing */
38215   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38216   assert( pPage->pgno>1 );
38217   pPage->isInit = 0;
38218
38219   /* Increment the free page count on pPage1 */
38220   rc = sqlite3PagerWrite(pPage1->pDbPage);
38221   if( rc ) return rc;
38222   n = get4byte(&pPage1->aData[36]);
38223   put4byte(&pPage1->aData[36], n+1);
38224
38225 #ifdef SQLITE_SECURE_DELETE
38226   /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
38227   ** always fully overwrite deleted information with zeros.
38228   */
38229   rc = sqlite3PagerWrite(pPage->pDbPage);
38230   if( rc ) return rc;
38231   memset(pPage->aData, 0, pPage->pBt->pageSize);
38232 #endif
38233
38234   /* If the database supports auto-vacuum, write an entry in the pointer-map
38235   ** to indicate that the page is free.
38236   */
38237   if( ISAUTOVACUUM ){
38238     rc = ptrmapPut(pBt, pPage->pgno, PTRMAP_FREEPAGE, 0);
38239     if( rc ) return rc;
38240   }
38241
38242   if( n==0 ){
38243     /* This is the first free page */
38244     rc = sqlite3PagerWrite(pPage->pDbPage);
38245     if( rc ) return rc;
38246     memset(pPage->aData, 0, 8);
38247     put4byte(&pPage1->aData[32], pPage->pgno);
38248     TRACE(("FREE-PAGE: %d first\n", pPage->pgno));
38249   }else{
38250     /* Other free pages already exist.  Retrive the first trunk page
38251     ** of the freelist and find out how many leaves it has. */
38252     MemPage *pTrunk;
38253     rc = sqlite3BtreeGetPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk, 0);
38254     if( rc ) return rc;
38255     k = get4byte(&pTrunk->aData[4]);
38256     if( k>=pBt->usableSize/4 - 8 ){
38257       /* The trunk is full.  Turn the page being freed into a new
38258       ** trunk page with no leaves.
38259       **
38260       ** Note that the trunk page is not really full until it contains
38261       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
38262       ** coded.  But due to a coding error in versions of SQLite prior to
38263       ** 3.6.0, databases with freelist trunk pages holding more than
38264       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
38265       ** to maintain backwards compatibility with older versions of SQLite,
38266       ** we will contain to restrict the number of entries to usableSize/4 - 8
38267       ** for now.  At some point in the future (once everyone has upgraded
38268       ** to 3.6.0 or later) we should consider fixing the conditional above
38269       ** to read "usableSize/4-2" instead of "usableSize/4-8".
38270       */
38271       rc = sqlite3PagerWrite(pPage->pDbPage);
38272       if( rc==SQLITE_OK ){
38273         put4byte(pPage->aData, pTrunk->pgno);
38274         put4byte(&pPage->aData[4], 0);
38275         put4byte(&pPage1->aData[32], pPage->pgno);
38276         TRACE(("FREE-PAGE: %d new trunk page replacing %d\n",
38277                 pPage->pgno, pTrunk->pgno));
38278       }
38279     }else if( k<0 ){
38280       rc = SQLITE_CORRUPT;
38281     }else{
38282       /* Add the newly freed page as a leaf on the current trunk */
38283       rc = sqlite3PagerWrite(pTrunk->pDbPage);
38284       if( rc==SQLITE_OK ){
38285         put4byte(&pTrunk->aData[4], k+1);
38286         put4byte(&pTrunk->aData[8+k*4], pPage->pgno);
38287 #ifndef SQLITE_SECURE_DELETE
38288         rc = sqlite3PagerDontWrite(pPage->pDbPage);
38289 #endif
38290       }
38291       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
38292     }
38293     releasePage(pTrunk);
38294   }
38295   return rc;
38296 }
38297
38298 /*
38299 ** Free any overflow pages associated with the given Cell.
38300 */
38301 static int clearCell(MemPage *pPage, unsigned char *pCell){
38302   BtShared *pBt = pPage->pBt;
38303   CellInfo info;
38304   Pgno ovflPgno;
38305   int rc;
38306   int nOvfl;
38307   int ovflPageSize;
38308
38309   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38310   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
38311   if( info.iOverflow==0 ){
38312     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
38313   }
38314   ovflPgno = get4byte(&pCell[info.iOverflow]);
38315   ovflPageSize = pBt->usableSize - 4;
38316   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
38317   assert( ovflPgno==0 || nOvfl>0 );
38318   while( nOvfl-- ){
38319     MemPage *pOvfl;
38320     if( ovflPgno==0 || ovflPgno>pagerPagecount(pBt) ){
38321       return SQLITE_CORRUPT_BKPT;
38322     }
38323
38324     rc = getOverflowPage(pBt, ovflPgno, &pOvfl, (nOvfl==0)?0:&ovflPgno);
38325     if( rc ) return rc;
38326     rc = freePage(pOvfl);
38327     sqlite3PagerUnref(pOvfl->pDbPage);
38328     if( rc ) return rc;
38329   }
38330   return SQLITE_OK;
38331 }
38332
38333 /*
38334 ** Create the byte sequence used to represent a cell on page pPage
38335 ** and write that byte sequence into pCell[].  Overflow pages are
38336 ** allocated and filled in as necessary.  The calling procedure
38337 ** is responsible for making sure sufficient space has been allocated
38338 ** for pCell[].
38339 **
38340 ** Note that pCell does not necessary need to point to the pPage->aData
38341 ** area.  pCell might point to some temporary storage.  The cell will
38342 ** be constructed in this temporary area then copied into pPage->aData
38343 ** later.
38344 */
38345 static int fillInCell(
38346   MemPage *pPage,                /* The page that contains the cell */
38347   unsigned char *pCell,          /* Complete text of the cell */
38348   const void *pKey, i64 nKey,    /* The key */
38349   const void *pData,int nData,   /* The data */
38350   int nZero,                     /* Extra zero bytes to append to pData */
38351   int *pnSize                    /* Write cell size here */
38352 ){
38353   int nPayload;
38354   const u8 *pSrc;
38355   int nSrc, n, rc;
38356   int spaceLeft;
38357   MemPage *pOvfl = 0;
38358   MemPage *pToRelease = 0;
38359   unsigned char *pPrior;
38360   unsigned char *pPayload;
38361   BtShared *pBt = pPage->pBt;
38362   Pgno pgnoOvfl = 0;
38363   int nHeader;
38364   CellInfo info;
38365
38366   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38367
38368   /* Fill in the header. */
38369   nHeader = 0;
38370   if( !pPage->leaf ){
38371     nHeader += 4;
38372   }
38373   if( pPage->hasData ){
38374     nHeader += putVarint(&pCell[nHeader], nData+nZero);
38375   }else{
38376     nData = nZero = 0;
38377   }
38378   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
38379   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
38380   assert( info.nHeader==nHeader );
38381   assert( info.nKey==nKey );
38382   assert( info.nData==(u32)(nData+nZero) );
38383   
38384   /* Fill in the payload */
38385   nPayload = nData + nZero;
38386   if( pPage->intKey ){
38387     pSrc = pData;
38388     nSrc = nData;
38389     nData = 0;
38390   }else{
38391     nPayload += nKey;
38392     pSrc = pKey;
38393     nSrc = nKey;
38394   }
38395   *pnSize = info.nSize;
38396   spaceLeft = info.nLocal;
38397   pPayload = &pCell[nHeader];
38398   pPrior = &pCell[info.iOverflow];
38399
38400   while( nPayload>0 ){
38401     if( spaceLeft==0 ){
38402       int isExact = 0;
38403 #ifndef SQLITE_OMIT_AUTOVACUUM
38404       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
38405       if( pBt->autoVacuum ){
38406         do{
38407           pgnoOvfl++;
38408         } while( 
38409           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
38410         );
38411         if( pgnoOvfl>1 ){
38412           /* isExact = 1; */
38413         }
38414       }
38415 #endif
38416       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, isExact);
38417 #ifndef SQLITE_OMIT_AUTOVACUUM
38418       /* If the database supports auto-vacuum, and the second or subsequent
38419       ** overflow page is being allocated, add an entry to the pointer-map
38420       ** for that page now. 
38421       **
38422       ** If this is the first overflow page, then write a partial entry 
38423       ** to the pointer-map. If we write nothing to this pointer-map slot,
38424       ** then the optimistic overflow chain processing in clearCell()
38425       ** may misinterpret the uninitialised values and delete the
38426       ** wrong pages from the database.
38427       */
38428       if( pBt->autoVacuum && rc==SQLITE_OK ){
38429         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
38430         rc = ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap);
38431         if( rc ){
38432           releasePage(pOvfl);
38433         }
38434       }
38435 #endif
38436       if( rc ){
38437         releasePage(pToRelease);
38438         return rc;
38439       }
38440       put4byte(pPrior, pgnoOvfl);
38441       releasePage(pToRelease);
38442       pToRelease = pOvfl;
38443       pPrior = pOvfl->aData;
38444       put4byte(pPrior, 0);
38445       pPayload = &pOvfl->aData[4];
38446       spaceLeft = pBt->usableSize - 4;
38447     }
38448     n = nPayload;
38449     if( n>spaceLeft ) n = spaceLeft;
38450     if( nSrc>0 ){
38451       if( n>nSrc ) n = nSrc;
38452       assert( pSrc );
38453       memcpy(pPayload, pSrc, n);
38454     }else{
38455       memset(pPayload, 0, n);
38456     }
38457     nPayload -= n;
38458     pPayload += n;
38459     pSrc += n;
38460     nSrc -= n;
38461     spaceLeft -= n;
38462     if( nSrc==0 ){
38463       nSrc = nData;
38464       pSrc = pData;
38465     }
38466   }
38467   releasePage(pToRelease);
38468   return SQLITE_OK;
38469 }
38470
38471 /*
38472 ** Remove the i-th cell from pPage.  This routine effects pPage only.
38473 ** The cell content is not freed or deallocated.  It is assumed that
38474 ** the cell content has been copied someplace else.  This routine just
38475 ** removes the reference to the cell from pPage.
38476 **
38477 ** "sz" must be the number of bytes in the cell.
38478 */
38479 static int dropCell(MemPage *pPage, int idx, int sz){
38480   int i;          /* Loop counter */
38481   int pc;         /* Offset to cell content of cell being deleted */
38482   u8 *data;       /* pPage->aData */
38483   u8 *ptr;        /* Used to move bytes around within data[] */
38484   int rc;         /* The return code */
38485
38486   assert( idx>=0 && idx<pPage->nCell );
38487   assert( sz==cellSize(pPage, idx) );
38488   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38489   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38490   data = pPage->aData;
38491   ptr = &data[pPage->cellOffset + 2*idx];
38492   pc = get2byte(ptr);
38493   if ( (pc<pPage->hdrOffset+6+(pPage->leaf?0:4)) || (pc+sz>pPage->pBt->usableSize) ) {
38494     return SQLITE_CORRUPT_BKPT;
38495   }
38496   rc = freeSpace(pPage, pc, sz);
38497   if( rc!=SQLITE_OK ){
38498     return rc;
38499   }
38500   for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
38501     ptr[0] = ptr[2];
38502     ptr[1] = ptr[3];
38503   }
38504   pPage->nCell--;
38505   put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
38506   pPage->nFree += 2;
38507   return SQLITE_OK;
38508 }
38509
38510 /*
38511 ** Insert a new cell on pPage at cell index "i".  pCell points to the
38512 ** content of the cell.
38513 **
38514 ** If the cell content will fit on the page, then put it there.  If it
38515 ** will not fit, then make a copy of the cell content into pTemp if
38516 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
38517 ** in pPage->aOvfl[] and make it point to the cell content (either
38518 ** in pTemp or the original pCell) and also record its index. 
38519 ** Allocating a new entry in pPage->aCell[] implies that 
38520 ** pPage->nOverflow is incremented.
38521 **
38522 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
38523 ** cell. The caller will overwrite them after this function returns. If
38524 ** nSkip is non-zero, then pCell may not point to an invalid memory location 
38525 ** (but pCell+nSkip is always valid).
38526 */
38527 static int insertCell(
38528   MemPage *pPage,   /* Page into which we are copying */
38529   int i,            /* New cell becomes the i-th cell of the page */
38530   u8 *pCell,        /* Content of the new cell */
38531   int sz,           /* Bytes of content in pCell */
38532   u8 *pTemp,        /* Temp storage space for pCell, if needed */
38533   u8 nSkip          /* Do not write the first nSkip bytes of the cell */
38534 ){
38535   int idx;          /* Where to write new cell content in data[] */
38536   int j;            /* Loop counter */
38537   int top;          /* First byte of content for any cell in data[] */
38538   int end;          /* First byte past the last cell pointer in data[] */
38539   int ins;          /* Index in data[] where new cell pointer is inserted */
38540   int hdr;          /* Offset into data[] of the page header */
38541   int cellOffset;   /* Address of first cell pointer in data[] */
38542   u8 *data;         /* The content of the whole page */
38543   u8 *ptr;          /* Used for moving information around in data[] */
38544
38545   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
38546   assert( sz==cellSizePtr(pPage, pCell) );
38547   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38548   if( pPage->nOverflow || sz+2>pPage->nFree ){
38549     if( pTemp ){
38550       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
38551       pCell = pTemp;
38552     }
38553     j = pPage->nOverflow++;
38554     assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
38555     pPage->aOvfl[j].pCell = pCell;
38556     pPage->aOvfl[j].idx = i;
38557     pPage->nFree = 0;
38558   }else{
38559     int rc = sqlite3PagerWrite(pPage->pDbPage);
38560     if( rc!=SQLITE_OK ){
38561       return rc;
38562     }
38563     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38564     data = pPage->aData;
38565     hdr = pPage->hdrOffset;
38566     top = get2byte(&data[hdr+5]);
38567     cellOffset = pPage->cellOffset;
38568     end = cellOffset + 2*pPage->nCell + 2;
38569     ins = cellOffset + 2*i;
38570     if( end > top - sz ){
38571       rc = defragmentPage(pPage);
38572       if( rc!=SQLITE_OK ){
38573         return rc;
38574       }
38575       top = get2byte(&data[hdr+5]);
38576       assert( end + sz <= top );
38577     }
38578     idx = allocateSpace(pPage, sz);
38579     assert( idx>0 );
38580     assert( end <= get2byte(&data[hdr+5]) );
38581     if (idx+sz > pPage->pBt->usableSize) {
38582       return SQLITE_CORRUPT_BKPT;
38583     }
38584     pPage->nCell++;
38585     pPage->nFree -= 2;
38586     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
38587     for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
38588       ptr[0] = ptr[-2];
38589       ptr[1] = ptr[-1];
38590     }
38591     put2byte(&data[ins], idx);
38592     put2byte(&data[hdr+3], pPage->nCell);
38593 #ifndef SQLITE_OMIT_AUTOVACUUM
38594     if( pPage->pBt->autoVacuum ){
38595       /* The cell may contain a pointer to an overflow page. If so, write
38596       ** the entry for the overflow page into the pointer map.
38597       */
38598       CellInfo info;
38599       sqlite3BtreeParseCellPtr(pPage, pCell, &info);
38600       assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
38601       if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
38602         Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
38603         rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
38604         if( rc!=SQLITE_OK ) return rc;
38605       }
38606     }
38607 #endif
38608   }
38609
38610   return SQLITE_OK;
38611 }
38612
38613 /*
38614 ** Add a list of cells to a page.  The page should be initially empty.
38615 ** The cells are guaranteed to fit on the page.
38616 */
38617 static void assemblePage(
38618   MemPage *pPage,   /* The page to be assemblied */
38619   int nCell,        /* The number of cells to add to this page */
38620   u8 **apCell,      /* Pointers to cell bodies */
38621   u16 *aSize        /* Sizes of the cells */
38622 ){
38623   int i;            /* Loop counter */
38624   int totalSize;    /* Total size of all cells */
38625   int hdr;          /* Index of page header */
38626   int cellptr;      /* Address of next cell pointer */
38627   int cellbody;     /* Address of next cell body */
38628   u8 *data;         /* Data for the page */
38629
38630   assert( pPage->nOverflow==0 );
38631   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38632   totalSize = 0;
38633   for(i=0; i<nCell; i++){
38634     totalSize += aSize[i];
38635   }
38636   assert( totalSize+2*nCell<=pPage->nFree );
38637   assert( pPage->nCell==0 );
38638   cellptr = pPage->cellOffset;
38639   data = pPage->aData;
38640   hdr = pPage->hdrOffset;
38641   put2byte(&data[hdr+3], nCell);
38642   if( nCell ){
38643     cellbody = allocateSpace(pPage, totalSize);
38644     assert( cellbody>0 );
38645     assert( pPage->nFree >= 2*nCell );
38646     pPage->nFree -= 2*nCell;
38647     for(i=0; i<nCell; i++){
38648       put2byte(&data[cellptr], cellbody);
38649       memcpy(&data[cellbody], apCell[i], aSize[i]);
38650       cellptr += 2;
38651       cellbody += aSize[i];
38652     }
38653     assert( cellbody==pPage->pBt->usableSize );
38654   }
38655   pPage->nCell = nCell;
38656 }
38657
38658 /*
38659 ** The following parameters determine how many adjacent pages get involved
38660 ** in a balancing operation.  NN is the number of neighbors on either side
38661 ** of the page that participate in the balancing operation.  NB is the
38662 ** total number of pages that participate, including the target page and
38663 ** NN neighbors on either side.
38664 **
38665 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
38666 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
38667 ** in exchange for a larger degradation in INSERT and UPDATE performance.
38668 ** The value of NN appears to give the best results overall.
38669 */
38670 #define NN 1             /* Number of neighbors on either side of pPage */
38671 #define NB (NN*2+1)      /* Total pages involved in the balance */
38672
38673 /* Forward reference */
38674 static int balance(BtCursor*, int);
38675
38676 #ifndef SQLITE_OMIT_QUICKBALANCE
38677 /*
38678 ** This version of balance() handles the common special case where
38679 ** a new entry is being inserted on the extreme right-end of the
38680 ** tree, in other words, when the new entry will become the largest
38681 ** entry in the tree.
38682 **
38683 ** Instead of trying balance the 3 right-most leaf pages, just add
38684 ** a new page to the right-hand side and put the one new entry in
38685 ** that page.  This leaves the right side of the tree somewhat
38686 ** unbalanced.  But odds are that we will be inserting new entries
38687 ** at the end soon afterwards so the nearly empty page will quickly
38688 ** fill up.  On average.
38689 **
38690 ** pPage is the leaf page which is the right-most page in the tree.
38691 ** pParent is its parent.  pPage must have a single overflow entry
38692 ** which is also the right-most entry on the page.
38693 */
38694 static int balance_quick(BtCursor *pCur){
38695   int rc;
38696   MemPage *pNew = 0;
38697   Pgno pgnoNew;
38698   u8 *pCell;
38699   u16 szCell;
38700   CellInfo info;
38701   MemPage *pPage = pCur->apPage[pCur->iPage];
38702   MemPage *pParent = pCur->apPage[pCur->iPage-1];
38703   BtShared *pBt = pPage->pBt;
38704   int parentIdx = pParent->nCell;   /* pParent new divider cell index */
38705   int parentSize;                   /* Size of new divider cell */
38706   u8 parentCell[64];                /* Space for the new divider cell */
38707
38708   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38709
38710   /* Allocate a new page. Insert the overflow cell from pPage
38711   ** into it. Then remove the overflow cell from pPage.
38712   */
38713   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
38714   if( rc==SQLITE_OK ){
38715     pCell = pPage->aOvfl[0].pCell;
38716     szCell = cellSizePtr(pPage, pCell);
38717     zeroPage(pNew, pPage->aData[0]);
38718     assemblePage(pNew, 1, &pCell, &szCell);
38719     pPage->nOverflow = 0;
38720   
38721     /* pPage is currently the right-child of pParent. Change this
38722     ** so that the right-child is the new page allocated above and
38723     ** pPage is the next-to-right child. 
38724     **
38725     ** Ignore the return value of the call to fillInCell(). fillInCell()
38726     ** may only return other than SQLITE_OK if it is required to allocate
38727     ** one or more overflow pages. Since an internal table B-Tree cell 
38728     ** may never spill over onto an overflow page (it is a maximum of 
38729     ** 13 bytes in size), it is not neccessary to check the return code.
38730     **
38731     ** Similarly, the insertCell() function cannot fail if the page
38732     ** being inserted into is already writable and the cell does not 
38733     ** contain an overflow pointer. So ignore this return code too.
38734     */
38735     assert( pPage->nCell>0 );
38736     pCell = findCell(pPage, pPage->nCell-1);
38737     sqlite3BtreeParseCellPtr(pPage, pCell, &info);
38738     fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, 0, &parentSize);
38739     assert( parentSize<64 );
38740     assert( sqlite3PagerIswriteable(pParent->pDbPage) );
38741     insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4);
38742     put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno);
38743     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
38744   
38745     /* If this is an auto-vacuum database, update the pointer map
38746     ** with entries for the new page, and any pointer from the 
38747     ** cell on the page to an overflow page.
38748     */
38749     if( ISAUTOVACUUM ){
38750       rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
38751       if( rc==SQLITE_OK ){
38752         rc = ptrmapPutOvfl(pNew, 0);
38753       }
38754     }
38755
38756     /* Release the reference to the new page. */
38757     releasePage(pNew);
38758   }
38759
38760   /* At this point the pPage->nFree variable is not set correctly with
38761   ** respect to the content of the page (because it was set to 0 by 
38762   ** insertCell). So call sqlite3BtreeInitPage() to make sure it is
38763   ** correct.
38764   **
38765   ** This has to be done even if an error will be returned. Normally, if
38766   ** an error occurs during tree balancing, the contents of MemPage are
38767   ** not important, as they will be recalculated when the page is rolled
38768   ** back. But here, in balance_quick(), it is possible that pPage has 
38769   ** not yet been marked dirty or written into the journal file. Therefore
38770   ** it will not be rolled back and so it is important to make sure that
38771   ** the page data and contents of MemPage are consistent.
38772   */
38773   pPage->isInit = 0;
38774   sqlite3BtreeInitPage(pPage);
38775
38776   /* If everything else succeeded, balance the parent page, in 
38777   ** case the divider cell inserted caused it to become overfull.
38778   */
38779   if( rc==SQLITE_OK ){
38780     releasePage(pPage);
38781     pCur->iPage--;
38782     rc = balance(pCur, 0);
38783   }
38784   return rc;
38785 }
38786 #endif /* SQLITE_OMIT_QUICKBALANCE */
38787
38788 /*
38789 ** This routine redistributes Cells on pPage and up to NN*2 siblings
38790 ** of pPage so that all pages have about the same amount of free space.
38791 ** Usually NN siblings on either side of pPage is used in the balancing,
38792 ** though more siblings might come from one side if pPage is the first
38793 ** or last child of its parent.  If pPage has fewer than 2*NN siblings
38794 ** (something which can only happen if pPage is the root page or a 
38795 ** child of root) then all available siblings participate in the balancing.
38796 **
38797 ** The number of siblings of pPage might be increased or decreased by one or
38798 ** two in an effort to keep pages nearly full but not over full. The root page
38799 ** is special and is allowed to be nearly empty. If pPage is 
38800 ** the root page, then the depth of the tree might be increased
38801 ** or decreased by one, as necessary, to keep the root page from being
38802 ** overfull or completely empty.
38803 **
38804 ** Note that when this routine is called, some of the Cells on pPage
38805 ** might not actually be stored in pPage->aData[].  This can happen
38806 ** if the page is overfull.  Part of the job of this routine is to
38807 ** make sure all Cells for pPage once again fit in pPage->aData[].
38808 **
38809 ** In the course of balancing the siblings of pPage, the parent of pPage
38810 ** might become overfull or underfull.  If that happens, then this routine
38811 ** is called recursively on the parent.
38812 **
38813 ** If this routine fails for any reason, it might leave the database
38814 ** in a corrupted state.  So if this routine fails, the database should
38815 ** be rolled back.
38816 */
38817 static int balance_nonroot(BtCursor *pCur){
38818   MemPage *pPage;              /* The over or underfull page to balance */
38819   MemPage *pParent;            /* The parent of pPage */
38820   BtShared *pBt;               /* The whole database */
38821   int nCell = 0;               /* Number of cells in apCell[] */
38822   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
38823   int nOld;                    /* Number of pages in apOld[] */
38824   int nNew;                    /* Number of pages in apNew[] */
38825   int nDiv;                    /* Number of cells in apDiv[] */
38826   int i, j, k;                 /* Loop counters */
38827   int idx;                     /* Index of pPage in pParent->aCell[] */
38828   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
38829   int rc;                      /* The return code */
38830   int leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
38831   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
38832   int usableSpace;             /* Bytes in pPage beyond the header */
38833   int pageFlags;               /* Value of pPage->aData[0] */
38834   int subtotal;                /* Subtotal of bytes in cells on one page */
38835   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
38836   int iSpace2 = 0;             /* First unused byte of aSpace2[] */
38837   int szScratch;               /* Size of scratch memory requested */
38838   MemPage *apOld[NB];          /* pPage and up to two siblings */
38839   Pgno pgnoOld[NB];            /* Page numbers for each page in apOld[] */
38840   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
38841   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
38842   Pgno pgnoNew[NB+2];          /* Page numbers for each page in apNew[] */
38843   u8 *apDiv[NB];               /* Divider cells in pParent */
38844   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
38845   int szNew[NB+2];             /* Combined size of cells place on i-th page */
38846   u8 **apCell = 0;             /* All cells begin balanced */
38847   u16 *szCell;                 /* Local size of all cells in apCell[] */
38848   u8 *aCopy[NB];         /* Space for holding data of apCopy[] */
38849   u8 *aSpace1;           /* Space for copies of dividers cells before balance */
38850   u8 *aSpace2 = 0;       /* Space for overflow dividers cells after balance */
38851   u8 *aFrom = 0;
38852
38853   pPage = pCur->apPage[pCur->iPage];
38854   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38855   VVA_ONLY( pCur->pagesShuffled = 1 );
38856
38857   /* 
38858   ** Find the parent page.
38859   */
38860   assert( pCur->iPage>0 );
38861   assert( pPage->isInit );
38862   assert( sqlite3PagerIswriteable(pPage->pDbPage) || pPage->nOverflow==1 );
38863   pBt = pPage->pBt;
38864   pParent = pCur->apPage[pCur->iPage-1];
38865   assert( pParent );
38866   if( SQLITE_OK!=(rc = sqlite3PagerWrite(pParent->pDbPage)) ){
38867     return rc;
38868   }
38869
38870   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
38871
38872 #ifndef SQLITE_OMIT_QUICKBALANCE
38873   /*
38874   ** A special case:  If a new entry has just been inserted into a
38875   ** table (that is, a btree with integer keys and all data at the leaves)
38876   ** and the new entry is the right-most entry in the tree (it has the
38877   ** largest key) then use the special balance_quick() routine for
38878   ** balancing.  balance_quick() is much faster and results in a tighter
38879   ** packing of data in the common case.
38880   */
38881   if( pPage->leaf &&
38882       pPage->intKey &&
38883       pPage->nOverflow==1 &&
38884       pPage->aOvfl[0].idx==pPage->nCell &&
38885       pParent->pgno!=1 &&
38886       get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno
38887   ){
38888     assert( pPage->intKey );
38889     /*
38890     ** TODO: Check the siblings to the left of pPage. It may be that
38891     ** they are not full and no new page is required.
38892     */
38893     return balance_quick(pCur);
38894   }
38895 #endif
38896
38897   if( SQLITE_OK!=(rc = sqlite3PagerWrite(pPage->pDbPage)) ){
38898     return rc;
38899   }
38900
38901   /*
38902   ** Find the cell in the parent page whose left child points back
38903   ** to pPage.  The "idx" variable is the index of that cell.  If pPage
38904   ** is the rightmost child of pParent then set idx to pParent->nCell 
38905   */
38906   idx = pCur->aiIdx[pCur->iPage-1];
38907   assertParentIndex(pParent, idx, pPage->pgno);
38908
38909   /*
38910   ** Initialize variables so that it will be safe to jump
38911   ** directly to balance_cleanup at any moment.
38912   */
38913   nOld = nNew = 0;
38914
38915   /*
38916   ** Find sibling pages to pPage and the cells in pParent that divide
38917   ** the siblings.  An attempt is made to find NN siblings on either
38918   ** side of pPage.  More siblings are taken from one side, however, if
38919   ** pPage there are fewer than NN siblings on the other side.  If pParent
38920   ** has NB or fewer children then all children of pParent are taken.
38921   */
38922   nxDiv = idx - NN;
38923   if( nxDiv + NB > pParent->nCell ){
38924     nxDiv = pParent->nCell - NB + 1;
38925   }
38926   if( nxDiv<0 ){
38927     nxDiv = 0;
38928   }
38929   nDiv = 0;
38930   for(i=0, k=nxDiv; i<NB; i++, k++){
38931     if( k<pParent->nCell ){
38932       apDiv[i] = findCell(pParent, k);
38933       nDiv++;
38934       assert( !pParent->leaf );
38935       pgnoOld[i] = get4byte(apDiv[i]);
38936     }else if( k==pParent->nCell ){
38937       pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
38938     }else{
38939       break;
38940     }
38941     rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i]);
38942     if( rc ) goto balance_cleanup;
38943     /* apOld[i]->idxParent = k; */
38944     apCopy[i] = 0;
38945     assert( i==nOld );
38946     nOld++;
38947     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
38948   }
38949
38950   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
38951   ** alignment */
38952   nMaxCells = (nMaxCells + 3)&~3;
38953
38954   /*
38955   ** Allocate space for memory structures
38956   */
38957   szScratch =
38958        nMaxCells*sizeof(u8*)                       /* apCell */
38959      + nMaxCells*sizeof(u16)                       /* szCell */
38960      + (ROUND8(sizeof(MemPage))+pBt->pageSize)*NB  /* aCopy */
38961      + pBt->pageSize                               /* aSpace1 */
38962      + (ISAUTOVACUUM ? nMaxCells : 0);             /* aFrom */
38963   apCell = sqlite3ScratchMalloc( szScratch ); 
38964   if( apCell==0 ){
38965     rc = SQLITE_NOMEM;
38966     goto balance_cleanup;
38967   }
38968   szCell = (u16*)&apCell[nMaxCells];
38969   aCopy[0] = (u8*)&szCell[nMaxCells];
38970   assert( ((aCopy[0] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
38971   for(i=1; i<NB; i++){
38972     aCopy[i] = &aCopy[i-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
38973     assert( ((aCopy[i] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
38974   }
38975   aSpace1 = &aCopy[NB-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
38976   assert( ((aSpace1 - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
38977   if( ISAUTOVACUUM ){
38978     aFrom = &aSpace1[pBt->pageSize];
38979   }
38980   aSpace2 = sqlite3PageMalloc(pBt->pageSize);
38981   if( aSpace2==0 ){
38982     rc = SQLITE_NOMEM;
38983     goto balance_cleanup;
38984   }
38985   
38986   /*
38987   ** Make copies of the content of pPage and its siblings into aOld[].
38988   ** The rest of this function will use data from the copies rather
38989   ** that the original pages since the original pages will be in the
38990   ** process of being overwritten.
38991   */
38992   for(i=0; i<nOld; i++){
38993     MemPage *p = apCopy[i] = (MemPage*)aCopy[i];
38994     memcpy(p, apOld[i], sizeof(MemPage));
38995     p->aData = (void*)&p[1];
38996     memcpy(p->aData, apOld[i]->aData, pBt->pageSize);
38997   }
38998
38999   /*
39000   ** Load pointers to all cells on sibling pages and the divider cells
39001   ** into the local apCell[] array.  Make copies of the divider cells
39002   ** into space obtained form aSpace1[] and remove the the divider Cells
39003   ** from pParent.
39004   **
39005   ** If the siblings are on leaf pages, then the child pointers of the
39006   ** divider cells are stripped from the cells before they are copied
39007   ** into aSpace1[].  In this way, all cells in apCell[] are without
39008   ** child pointers.  If siblings are not leaves, then all cell in
39009   ** apCell[] include child pointers.  Either way, all cells in apCell[]
39010   ** are alike.
39011   **
39012   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
39013   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
39014   */
39015   nCell = 0;
39016   leafCorrection = pPage->leaf*4;
39017   leafData = pPage->hasData;
39018   for(i=0; i<nOld; i++){
39019     MemPage *pOld = apCopy[i];
39020     int limit = pOld->nCell+pOld->nOverflow;
39021     for(j=0; j<limit; j++){
39022       assert( nCell<nMaxCells );
39023       apCell[nCell] = findOverflowCell(pOld, j);
39024       szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
39025       if( ISAUTOVACUUM ){
39026         int a;
39027         aFrom[nCell] = i;
39028         for(a=0; a<pOld->nOverflow; a++){
39029           if( pOld->aOvfl[a].pCell==apCell[nCell] ){
39030             aFrom[nCell] = 0xFF;
39031             break;
39032           }
39033         }
39034       }
39035       nCell++;
39036     }
39037     if( i<nOld-1 ){
39038       u16 sz = cellSizePtr(pParent, apDiv[i]);
39039       if( leafData ){
39040         /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
39041         ** are duplicates of keys on the child pages.  We need to remove
39042         ** the divider cells from pParent, but the dividers cells are not
39043         ** added to apCell[] because they are duplicates of child cells.
39044         */
39045         dropCell(pParent, nxDiv, sz);
39046       }else{
39047         u8 *pTemp;
39048         assert( nCell<nMaxCells );
39049         szCell[nCell] = sz;
39050         pTemp = &aSpace1[iSpace1];
39051         iSpace1 += sz;
39052         assert( sz<=pBt->pageSize/4 );
39053         assert( iSpace1<=pBt->pageSize );
39054         memcpy(pTemp, apDiv[i], sz);
39055         apCell[nCell] = pTemp+leafCorrection;
39056         if( ISAUTOVACUUM ){
39057           aFrom[nCell] = 0xFF;
39058         }
39059         dropCell(pParent, nxDiv, sz);
39060         szCell[nCell] -= leafCorrection;
39061         assert( get4byte(pTemp)==pgnoOld[i] );
39062         if( !pOld->leaf ){
39063           assert( leafCorrection==0 );
39064           /* The right pointer of the child page pOld becomes the left
39065           ** pointer of the divider cell */
39066           memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
39067         }else{
39068           assert( leafCorrection==4 );
39069           if( szCell[nCell]<4 ){
39070             /* Do not allow any cells smaller than 4 bytes. */
39071             szCell[nCell] = 4;
39072           }
39073         }
39074         nCell++;
39075       }
39076     }
39077   }
39078
39079   /*
39080   ** Figure out the number of pages needed to hold all nCell cells.
39081   ** Store this number in "k".  Also compute szNew[] which is the total
39082   ** size of all cells on the i-th page and cntNew[] which is the index
39083   ** in apCell[] of the cell that divides page i from page i+1.  
39084   ** cntNew[k] should equal nCell.
39085   **
39086   ** Values computed by this block:
39087   **
39088   **           k: The total number of sibling pages
39089   **    szNew[i]: Spaced used on the i-th sibling page.
39090   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
39091   **              the right of the i-th sibling page.
39092   ** usableSpace: Number of bytes of space available on each sibling.
39093   ** 
39094   */
39095   usableSpace = pBt->usableSize - 12 + leafCorrection;
39096   for(subtotal=k=i=0; i<nCell; i++){
39097     assert( i<nMaxCells );
39098     subtotal += szCell[i] + 2;
39099     if( subtotal > usableSpace ){
39100       szNew[k] = subtotal - szCell[i];
39101       cntNew[k] = i;
39102       if( leafData ){ i--; }
39103       subtotal = 0;
39104       k++;
39105     }
39106   }
39107   szNew[k] = subtotal;
39108   cntNew[k] = nCell;
39109   k++;
39110
39111   /*
39112   ** The packing computed by the previous block is biased toward the siblings
39113   ** on the left side.  The left siblings are always nearly full, while the
39114   ** right-most sibling might be nearly empty.  This block of code attempts
39115   ** to adjust the packing of siblings to get a better balance.
39116   **
39117   ** This adjustment is more than an optimization.  The packing above might
39118   ** be so out of balance as to be illegal.  For example, the right-most
39119   ** sibling might be completely empty.  This adjustment is not optional.
39120   */
39121   for(i=k-1; i>0; i--){
39122     int szRight = szNew[i];  /* Size of sibling on the right */
39123     int szLeft = szNew[i-1]; /* Size of sibling on the left */
39124     int r;              /* Index of right-most cell in left sibling */
39125     int d;              /* Index of first cell to the left of right sibling */
39126
39127     r = cntNew[i-1] - 1;
39128     d = r + 1 - leafData;
39129     assert( d<nMaxCells );
39130     assert( r<nMaxCells );
39131     while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
39132       szRight += szCell[d] + 2;
39133       szLeft -= szCell[r] + 2;
39134       cntNew[i-1]--;
39135       r = cntNew[i-1] - 1;
39136       d = r + 1 - leafData;
39137     }
39138     szNew[i] = szRight;
39139     szNew[i-1] = szLeft;
39140   }
39141
39142   /* Either we found one or more cells (cntnew[0])>0) or we are the
39143   ** a virtual root page.  A virtual root page is when the real root
39144   ** page is page 1 and we are the only child of that page.
39145   */
39146   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
39147
39148   /*
39149   ** Allocate k new pages.  Reuse old pages where possible.
39150   */
39151   assert( pPage->pgno>1 );
39152   pageFlags = pPage->aData[0];
39153   for(i=0; i<k; i++){
39154     MemPage *pNew;
39155     if( i<nOld ){
39156       pNew = apNew[i] = apOld[i];
39157       pgnoNew[i] = pgnoOld[i];
39158       apOld[i] = 0;
39159       rc = sqlite3PagerWrite(pNew->pDbPage);
39160       nNew++;
39161       if( rc ) goto balance_cleanup;
39162     }else{
39163       assert( i>0 );
39164       rc = allocateBtreePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0);
39165       if( rc ) goto balance_cleanup;
39166       apNew[i] = pNew;
39167       nNew++;
39168     }
39169   }
39170
39171   /* Free any old pages that were not reused as new pages.
39172   */
39173   while( i<nOld ){
39174     rc = freePage(apOld[i]);
39175     if( rc ) goto balance_cleanup;
39176     releasePage(apOld[i]);
39177     apOld[i] = 0;
39178     i++;
39179   }
39180
39181   /*
39182   ** Put the new pages in accending order.  This helps to
39183   ** keep entries in the disk file in order so that a scan
39184   ** of the table is a linear scan through the file.  That
39185   ** in turn helps the operating system to deliver pages
39186   ** from the disk more rapidly.
39187   **
39188   ** An O(n^2) insertion sort algorithm is used, but since
39189   ** n is never more than NB (a small constant), that should
39190   ** not be a problem.
39191   **
39192   ** When NB==3, this one optimization makes the database
39193   ** about 25% faster for large insertions and deletions.
39194   */
39195   for(i=0; i<k-1; i++){
39196     int minV = pgnoNew[i];
39197     int minI = i;
39198     for(j=i+1; j<k; j++){
39199       if( pgnoNew[j]<(unsigned)minV ){
39200         minI = j;
39201         minV = pgnoNew[j];
39202       }
39203     }
39204     if( minI>i ){
39205       int t;
39206       MemPage *pT;
39207       t = pgnoNew[i];
39208       pT = apNew[i];
39209       pgnoNew[i] = pgnoNew[minI];
39210       apNew[i] = apNew[minI];
39211       pgnoNew[minI] = t;
39212       apNew[minI] = pT;
39213     }
39214   }
39215   TRACE(("BALANCE: old: %d %d %d  new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
39216     pgnoOld[0], 
39217     nOld>=2 ? pgnoOld[1] : 0,
39218     nOld>=3 ? pgnoOld[2] : 0,
39219     pgnoNew[0], szNew[0],
39220     nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
39221     nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
39222     nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
39223     nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
39224
39225   /*
39226   ** Evenly distribute the data in apCell[] across the new pages.
39227   ** Insert divider cells into pParent as necessary.
39228   */
39229   j = 0;
39230   for(i=0; i<nNew; i++){
39231     /* Assemble the new sibling page. */
39232     MemPage *pNew = apNew[i];
39233     assert( j<nMaxCells );
39234     assert( pNew->pgno==pgnoNew[i] );
39235     zeroPage(pNew, pageFlags);
39236     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
39237     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
39238     assert( pNew->nOverflow==0 );
39239
39240     /* If this is an auto-vacuum database, update the pointer map entries
39241     ** that point to the siblings that were rearranged. These can be: left
39242     ** children of cells, the right-child of the page, or overflow pages
39243     ** pointed to by cells.
39244     */
39245     if( ISAUTOVACUUM ){
39246       for(k=j; k<cntNew[i]; k++){
39247         assert( k<nMaxCells );
39248         if( aFrom[k]==0xFF || apCopy[aFrom[k]]->pgno!=pNew->pgno ){
39249           rc = ptrmapPutOvfl(pNew, k-j);
39250           if( rc==SQLITE_OK && leafCorrection==0 ){
39251             rc = ptrmapPut(pBt, get4byte(apCell[k]), PTRMAP_BTREE, pNew->pgno);
39252           }
39253           if( rc!=SQLITE_OK ){
39254             goto balance_cleanup;
39255           }
39256         }
39257       }
39258     }
39259
39260     j = cntNew[i];
39261
39262     /* If the sibling page assembled above was not the right-most sibling,
39263     ** insert a divider cell into the parent page.
39264     */
39265     if( i<nNew-1 && j<nCell ){
39266       u8 *pCell;
39267       u8 *pTemp;
39268       int sz;
39269
39270       assert( j<nMaxCells );
39271       pCell = apCell[j];
39272       sz = szCell[j] + leafCorrection;
39273       pTemp = &aSpace2[iSpace2];
39274       if( !pNew->leaf ){
39275         memcpy(&pNew->aData[8], pCell, 4);
39276         if( ISAUTOVACUUM 
39277          && (aFrom[j]==0xFF || apCopy[aFrom[j]]->pgno!=pNew->pgno)
39278         ){
39279           rc = ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno);
39280           if( rc!=SQLITE_OK ){
39281             goto balance_cleanup;
39282           }
39283         }
39284       }else if( leafData ){
39285         /* If the tree is a leaf-data tree, and the siblings are leaves, 
39286         ** then there is no divider cell in apCell[]. Instead, the divider 
39287         ** cell consists of the integer key for the right-most cell of 
39288         ** the sibling-page assembled above only.
39289         */
39290         CellInfo info;
39291         j--;
39292         sqlite3BtreeParseCellPtr(pNew, apCell[j], &info);
39293         pCell = pTemp;
39294         fillInCell(pParent, pCell, 0, info.nKey, 0, 0, 0, &sz);
39295         pTemp = 0;
39296       }else{
39297         pCell -= 4;
39298         /* Obscure case for non-leaf-data trees: If the cell at pCell was
39299         ** previously stored on a leaf node, and its reported size was 4
39300         ** bytes, then it may actually be smaller than this 
39301         ** (see sqlite3BtreeParseCellPtr(), 4 bytes is the minimum size of
39302         ** any cell). But it is important to pass the correct size to 
39303         ** insertCell(), so reparse the cell now.
39304         **
39305         ** Note that this can never happen in an SQLite data file, as all
39306         ** cells are at least 4 bytes. It only happens in b-trees used
39307         ** to evaluate "IN (SELECT ...)" and similar clauses.
39308         */
39309         if( szCell[j]==4 ){
39310           assert(leafCorrection==4);
39311           sz = cellSizePtr(pParent, pCell);
39312         }
39313       }
39314       iSpace2 += sz;
39315       assert( sz<=pBt->pageSize/4 );
39316       assert( iSpace2<=pBt->pageSize );
39317       rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4);
39318       if( rc!=SQLITE_OK ) goto balance_cleanup;
39319       put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
39320
39321       /* If this is an auto-vacuum database, and not a leaf-data tree,
39322       ** then update the pointer map with an entry for the overflow page
39323       ** that the cell just inserted points to (if any).
39324       */
39325       if( ISAUTOVACUUM && !leafData ){
39326         rc = ptrmapPutOvfl(pParent, nxDiv);
39327         if( rc!=SQLITE_OK ){
39328           goto balance_cleanup;
39329         }
39330       }
39331       j++;
39332       nxDiv++;
39333     }
39334
39335     /* Set the pointer-map entry for the new sibling page. */
39336     if( ISAUTOVACUUM ){
39337       rc = ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno);
39338       if( rc!=SQLITE_OK ){
39339         goto balance_cleanup;
39340       }
39341     }
39342   }
39343   assert( j==nCell );
39344   assert( nOld>0 );
39345   assert( nNew>0 );
39346   if( (pageFlags & PTF_LEAF)==0 ){
39347     u8 *zChild = &apCopy[nOld-1]->aData[8];
39348     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
39349     if( ISAUTOVACUUM ){
39350       rc = ptrmapPut(pBt, get4byte(zChild), PTRMAP_BTREE, apNew[nNew-1]->pgno);
39351       if( rc!=SQLITE_OK ){
39352         goto balance_cleanup;
39353       }
39354     }
39355   }
39356   if( nxDiv==pParent->nCell+pParent->nOverflow ){
39357     /* Right-most sibling is the right-most child of pParent */
39358     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
39359   }else{
39360     /* Right-most sibling is the left child of the first entry in pParent
39361     ** past the right-most divider entry */
39362     put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
39363   }
39364
39365   /*
39366   ** Balance the parent page.  Note that the current page (pPage) might
39367   ** have been added to the freelist so it might no longer be initialized.
39368   ** But the parent page will always be initialized.
39369   */
39370   assert( pParent->isInit );
39371   sqlite3ScratchFree(apCell);
39372   apCell = 0;
39373   releasePage(pPage);
39374   pCur->iPage--;
39375   rc = balance(pCur, 0);
39376   
39377   /*
39378   ** Cleanup before returning.
39379   */
39380 balance_cleanup:
39381   sqlite3PageFree(aSpace2);
39382   sqlite3ScratchFree(apCell);
39383   for(i=0; i<nOld; i++){
39384     releasePage(apOld[i]);
39385   }
39386   for(i=0; i<nNew; i++){
39387     releasePage(apNew[i]);
39388   }
39389
39390   /* releasePage(pParent); */
39391   TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
39392           pPage->pgno, nOld, nNew, nCell));
39393
39394   return rc;
39395 }
39396
39397 /*
39398 ** This routine is called for the root page of a btree when the root
39399 ** page contains no cells.  This is an opportunity to make the tree
39400 ** shallower by one level.
39401 */
39402 static int balance_shallower(BtCursor *pCur){
39403   MemPage *pPage;              /* Root page of B-Tree */
39404   MemPage *pChild;             /* The only child page of pPage */
39405   Pgno pgnoChild;              /* Page number for pChild */
39406   int rc = SQLITE_OK;          /* Return code from subprocedures */
39407   BtShared *pBt;                  /* The main BTree structure */
39408   int mxCellPerPage;           /* Maximum number of cells per page */
39409   u8 **apCell;                 /* All cells from pages being balanced */
39410   u16 *szCell;                 /* Local size of all cells */
39411
39412   assert( pCur->iPage==0 );
39413   pPage = pCur->apPage[0];
39414
39415   assert( pPage->nCell==0 );
39416   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
39417   pBt = pPage->pBt;
39418   mxCellPerPage = MX_CELL(pBt);
39419   apCell = sqlite3Malloc( mxCellPerPage*(sizeof(u8*)+sizeof(u16)) );
39420   if( apCell==0 ) return SQLITE_NOMEM;
39421   szCell = (u16*)&apCell[mxCellPerPage];
39422   if( pPage->leaf ){
39423     /* The table is completely empty */
39424     TRACE(("BALANCE: empty table %d\n", pPage->pgno));
39425   }else{
39426     /* The root page is empty but has one child.  Transfer the
39427     ** information from that one child into the root page if it 
39428     ** will fit.  This reduces the depth of the tree by one.
39429     **
39430     ** If the root page is page 1, it has less space available than
39431     ** its child (due to the 100 byte header that occurs at the beginning
39432     ** of the database fle), so it might not be able to hold all of the 
39433     ** information currently contained in the child.  If this is the 
39434     ** case, then do not do the transfer.  Leave page 1 empty except
39435     ** for the right-pointer to the child page.  The child page becomes
39436     ** the virtual root of the tree.
39437     */
39438     VVA_ONLY( pCur->pagesShuffled = 1 );
39439     pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
39440     assert( pgnoChild>0 );
39441     assert( pgnoChild<=pagerPagecount(pPage->pBt) );
39442     rc = sqlite3BtreeGetPage(pPage->pBt, pgnoChild, &pChild, 0);
39443     if( rc ) goto end_shallow_balance;
39444     if( pPage->pgno==1 ){
39445       rc = sqlite3BtreeInitPage(pChild);
39446       if( rc ) goto end_shallow_balance;
39447       assert( pChild->nOverflow==0 );
39448       if( pChild->nFree>=100 ){
39449         /* The child information will fit on the root page, so do the
39450         ** copy */
39451         int i;
39452         zeroPage(pPage, pChild->aData[0]);
39453         for(i=0; i<pChild->nCell; i++){
39454           apCell[i] = findCell(pChild,i);
39455           szCell[i] = cellSizePtr(pChild, apCell[i]);
39456         }
39457         assemblePage(pPage, pChild->nCell, apCell, szCell);
39458         /* Copy the right-pointer of the child to the parent. */
39459         put4byte(&pPage->aData[pPage->hdrOffset+8], 
39460             get4byte(&pChild->aData[pChild->hdrOffset+8]));
39461         freePage(pChild);
39462         TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
39463       }else{
39464         /* The child has more information that will fit on the root.
39465         ** The tree is already balanced.  Do nothing. */
39466         TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
39467       }
39468     }else{
39469       memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
39470       pPage->isInit = 0;
39471       rc = sqlite3BtreeInitPage(pPage);
39472       assert( rc==SQLITE_OK );
39473       freePage(pChild);
39474       TRACE(("BALANCE: transfer child %d into root %d\n",
39475               pChild->pgno, pPage->pgno));
39476     }
39477     assert( pPage->nOverflow==0 );
39478 #ifndef SQLITE_OMIT_AUTOVACUUM
39479     if( ISAUTOVACUUM ){
39480       rc = setChildPtrmaps(pPage);
39481     }
39482 #endif
39483     releasePage(pChild);
39484   }
39485 end_shallow_balance:
39486   sqlite3_free(apCell);
39487   return rc;
39488 }
39489
39490
39491 /*
39492 ** The root page is overfull
39493 **
39494 ** When this happens, Create a new child page and copy the
39495 ** contents of the root into the child.  Then make the root
39496 ** page an empty page with rightChild pointing to the new
39497 ** child.   Finally, call balance_internal() on the new child
39498 ** to cause it to split.
39499 */
39500 static int balance_deeper(BtCursor *pCur){
39501   int rc;             /* Return value from subprocedures */
39502   MemPage *pPage;     /* Pointer to the root page */
39503   MemPage *pChild;    /* Pointer to a new child page */
39504   Pgno pgnoChild;     /* Page number of the new child page */
39505   BtShared *pBt;         /* The BTree */
39506   int usableSize;     /* Total usable size of a page */
39507   u8 *data;           /* Content of the parent page */
39508   u8 *cdata;          /* Content of the child page */
39509   int hdr;            /* Offset to page header in parent */
39510   int cbrk;           /* Offset to content of first cell in parent */
39511
39512   assert( pCur->iPage==0 );
39513   assert( pCur->apPage[0]->nOverflow>0 );
39514
39515   VVA_ONLY( pCur->pagesShuffled = 1 );
39516   pPage = pCur->apPage[0];
39517   pBt = pPage->pBt;
39518   assert( sqlite3_mutex_held(pBt->mutex) );
39519   rc = allocateBtreePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0);
39520   if( rc ) return rc;
39521   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
39522   usableSize = pBt->usableSize;
39523   data = pPage->aData;
39524   hdr = pPage->hdrOffset;
39525   cbrk = get2byte(&data[hdr+5]);
39526   cdata = pChild->aData;
39527   memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
39528   memcpy(&cdata[cbrk], &data[cbrk], usableSize-cbrk);
39529
39530   assert( pChild->isInit==0 );
39531   rc = sqlite3BtreeInitPage(pChild);
39532   if( rc==SQLITE_OK ){
39533     int nCopy = pPage->nOverflow*sizeof(pPage->aOvfl[0]);
39534     memcpy(pChild->aOvfl, pPage->aOvfl, nCopy);
39535     pChild->nOverflow = pPage->nOverflow;
39536     if( pChild->nOverflow ){
39537       pChild->nFree = 0;
39538     }
39539     assert( pChild->nCell==pPage->nCell );
39540     zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
39541     put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
39542     TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
39543     if( ISAUTOVACUUM ){
39544       rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno);
39545 #ifndef SQLITE_OMIT_AUTOVACUUM
39546       if( rc==SQLITE_OK ){
39547         rc = setChildPtrmaps(pChild);
39548       }
39549 #endif
39550     }
39551   }
39552
39553   if( rc==SQLITE_OK ){
39554     pCur->iPage++;
39555     pCur->apPage[1] = pChild;
39556     pCur->aiIdx[0] = 0;
39557     rc = balance_nonroot(pCur);
39558   }else{
39559     releasePage(pChild);
39560   }
39561
39562   return rc;
39563 }
39564
39565 /*
39566 ** The page that pCur currently points to has just been modified in
39567 ** some way. This function figures out if this modification means the
39568 ** tree needs to be balanced, and if so calls the appropriate balancing 
39569 ** routine.
39570 ** 
39571 ** Parameter isInsert is true if a new cell was just inserted into the
39572 ** page, or false otherwise.
39573 */
39574 static int balance(BtCursor *pCur, int isInsert){
39575   int rc = SQLITE_OK;
39576   MemPage *pPage = pCur->apPage[pCur->iPage];
39577
39578   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
39579   if( pCur->iPage==0 ){
39580     rc = sqlite3PagerWrite(pPage->pDbPage);
39581     if( rc==SQLITE_OK && pPage->nOverflow>0 ){
39582       rc = balance_deeper(pCur);
39583     }
39584     if( rc==SQLITE_OK && pPage->nCell==0 ){
39585       rc = balance_shallower(pCur);
39586     }
39587   }else{
39588     if( pPage->nOverflow>0 || 
39589         (!isInsert && pPage->nFree>pPage->pBt->usableSize*2/3) ){
39590       rc = balance_nonroot(pCur);
39591     }
39592   }
39593   return rc;
39594 }
39595
39596 /*
39597 ** This routine checks all cursors that point to table pgnoRoot.
39598 ** If any of those cursors were opened with wrFlag==0 in a different
39599 ** database connection (a database connection that shares the pager
39600 ** cache with the current connection) and that other connection 
39601 ** is not in the ReadUncommmitted state, then this routine returns 
39602 ** SQLITE_LOCKED.
39603 **
39604 ** As well as cursors with wrFlag==0, cursors with wrFlag==1 and 
39605 ** isIncrblobHandle==1 are also considered 'read' cursors. Incremental 
39606 ** blob cursors are used for both reading and writing.
39607 **
39608 ** When pgnoRoot is the root page of an intkey table, this function is also
39609 ** responsible for invalidating incremental blob cursors when the table row
39610 ** on which they are opened is deleted or modified. Cursors are invalidated
39611 ** according to the following rules:
39612 **
39613 **   1) When BtreeClearTable() is called to completely delete the contents
39614 **      of a B-Tree table, pExclude is set to zero and parameter iRow is 
39615 **      set to non-zero. In this case all incremental blob cursors open
39616 **      on the table rooted at pgnoRoot are invalidated.
39617 **
39618 **   2) When BtreeInsert(), BtreeDelete() or BtreePutData() is called to 
39619 **      modify a table row via an SQL statement, pExclude is set to the 
39620 **      write cursor used to do the modification and parameter iRow is set
39621 **      to the integer row id of the B-Tree entry being modified. Unless
39622 **      pExclude is itself an incremental blob cursor, then all incremental
39623 **      blob cursors open on row iRow of the B-Tree are invalidated.
39624 **
39625 **   3) If both pExclude and iRow are set to zero, no incremental blob 
39626 **      cursors are invalidated.
39627 */
39628 static int checkReadLocks(
39629   Btree *pBtree, 
39630   Pgno pgnoRoot, 
39631   BtCursor *pExclude,
39632   i64 iRow
39633 ){
39634   BtCursor *p;
39635   BtShared *pBt = pBtree->pBt;
39636   sqlite3 *db = pBtree->db;
39637   assert( sqlite3BtreeHoldsMutex(pBtree) );
39638   for(p=pBt->pCursor; p; p=p->pNext){
39639     if( p==pExclude ) continue;
39640     if( p->pgnoRoot!=pgnoRoot ) continue;
39641 #ifndef SQLITE_OMIT_INCRBLOB
39642     if( p->isIncrblobHandle && ( 
39643          (!pExclude && iRow)
39644       || (pExclude && !pExclude->isIncrblobHandle && p->info.nKey==iRow)
39645     )){
39646       p->eState = CURSOR_INVALID;
39647     }
39648 #endif
39649     if( p->eState!=CURSOR_VALID ) continue;
39650     if( p->wrFlag==0 
39651 #ifndef SQLITE_OMIT_INCRBLOB
39652      || p->isIncrblobHandle
39653 #endif
39654     ){
39655       sqlite3 *dbOther = p->pBtree->db;
39656       if( dbOther==0 ||
39657          (dbOther!=db && (dbOther->flags & SQLITE_ReadUncommitted)==0) ){
39658         return SQLITE_LOCKED;
39659       }
39660     }
39661   }
39662   return SQLITE_OK;
39663 }
39664
39665 /*
39666 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
39667 ** and the data is given by (pData,nData).  The cursor is used only to
39668 ** define what table the record should be inserted into.  The cursor
39669 ** is left pointing at a random location.
39670 **
39671 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
39672 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
39673 */
39674 SQLITE_PRIVATE int sqlite3BtreeInsert(
39675   BtCursor *pCur,                /* Insert data into the table of this cursor */
39676   const void *pKey, i64 nKey,    /* The key of the new record */
39677   const void *pData, int nData,  /* The data of the new record */
39678   int nZero,                     /* Number of extra 0 bytes to append to data */
39679   int appendBias                 /* True if this is likely an append */
39680 ){
39681   int rc;
39682   int loc;
39683   int szNew;
39684   int idx;
39685   MemPage *pPage;
39686   Btree *p = pCur->pBtree;
39687   BtShared *pBt = p->pBt;
39688   unsigned char *oldCell;
39689   unsigned char *newCell = 0;
39690
39691   assert( cursorHoldsMutex(pCur) );
39692   if( pBt->inTransaction!=TRANS_WRITE ){
39693     /* Must start a transaction before doing an insert */
39694     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
39695     return rc;
39696   }
39697   assert( !pBt->readOnly );
39698   if( !pCur->wrFlag ){
39699     return SQLITE_PERM;   /* Cursor not open for writing */
39700   }
39701   if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur, nKey) ){
39702     return SQLITE_LOCKED; /* The table pCur points to has a read lock */
39703   }
39704   if( pCur->eState==CURSOR_FAULT ){
39705     return pCur->skip;
39706   }
39707
39708   /* Save the positions of any other cursors open on this table */
39709   sqlite3BtreeClearCursor(pCur);
39710   if( 
39711     SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
39712     SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, nKey, appendBias, &loc))
39713   ){
39714     return rc;
39715   }
39716
39717   pPage = pCur->apPage[pCur->iPage];
39718   assert( pPage->intKey || nKey>=0 );
39719   assert( pPage->leaf || !pPage->intKey );
39720   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
39721           pCur->pgnoRoot, nKey, nData, pPage->pgno,
39722           loc==0 ? "overwrite" : "new entry"));
39723   assert( pPage->isInit );
39724   allocateTempSpace(pBt);
39725   newCell = pBt->pTmpSpace;
39726   if( newCell==0 ) return SQLITE_NOMEM;
39727   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
39728   if( rc ) goto end_insert;
39729   assert( szNew==cellSizePtr(pPage, newCell) );
39730   assert( szNew<=MX_CELL_SIZE(pBt) );
39731   idx = pCur->aiIdx[pCur->iPage];
39732   if( loc==0 && CURSOR_VALID==pCur->eState ){
39733     u16 szOld;
39734     assert( idx<pPage->nCell );
39735     rc = sqlite3PagerWrite(pPage->pDbPage);
39736     if( rc ){
39737       goto end_insert;
39738     }
39739     oldCell = findCell(pPage, idx);
39740     if( !pPage->leaf ){
39741       memcpy(newCell, oldCell, 4);
39742     }
39743     szOld = cellSizePtr(pPage, oldCell);
39744     rc = clearCell(pPage, oldCell);
39745     if( rc ) goto end_insert;
39746     rc = dropCell(pPage, idx, szOld);
39747     if( rc!=SQLITE_OK ) {
39748       goto end_insert;
39749     }
39750   }else if( loc<0 && pPage->nCell>0 ){
39751     assert( pPage->leaf );
39752     idx = ++pCur->aiIdx[pCur->iPage];
39753     pCur->info.nSize = 0;
39754     pCur->validNKey = 0;
39755   }else{
39756     assert( pPage->leaf );
39757   }
39758   rc = insertCell(pPage, idx, newCell, szNew, 0, 0);
39759   if( rc!=SQLITE_OK ) goto end_insert;
39760   rc = balance(pCur, 1);
39761   if( rc==SQLITE_OK ){
39762     moveToRoot(pCur);
39763   }
39764 end_insert:
39765   return rc;
39766 }
39767
39768 /*
39769 ** Delete the entry that the cursor is pointing to.  The cursor
39770 ** is left pointing at a arbitrary location.
39771 */
39772 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
39773   MemPage *pPage = pCur->apPage[pCur->iPage];
39774   int idx;
39775   unsigned char *pCell;
39776   int rc;
39777   Pgno pgnoChild = 0;
39778   Btree *p = pCur->pBtree;
39779   BtShared *pBt = p->pBt;
39780
39781   assert( cursorHoldsMutex(pCur) );
39782   assert( pPage->isInit );
39783   if( pBt->inTransaction!=TRANS_WRITE ){
39784     /* Must start a transaction before doing a delete */
39785     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
39786     return rc;
39787   }
39788   assert( !pBt->readOnly );
39789   if( pCur->eState==CURSOR_FAULT ){
39790     return pCur->skip;
39791   }
39792   if( pCur->aiIdx[pCur->iPage]>=pPage->nCell ){
39793     return SQLITE_ERROR;  /* The cursor is not pointing to anything */
39794   }
39795   if( !pCur->wrFlag ){
39796     return SQLITE_PERM;   /* Did not open this cursor for writing */
39797   }
39798   if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur, pCur->info.nKey) ){
39799     return SQLITE_LOCKED; /* The table pCur points to has a read lock */
39800   }
39801
39802   /* Restore the current cursor position (a no-op if the cursor is not in 
39803   ** CURSOR_REQUIRESEEK state) and save the positions of any other cursors 
39804   ** open on the same table. Then call sqlite3PagerWrite() on the page
39805   ** that the entry will be deleted from.
39806   */
39807   if( 
39808     (rc = restoreCursorPosition(pCur))!=0 ||
39809     (rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur))!=0 ||
39810     (rc = sqlite3PagerWrite(pPage->pDbPage))!=0
39811   ){
39812     return rc;
39813   }
39814
39815   /* Locate the cell within its page and leave pCell pointing to the
39816   ** data. The clearCell() call frees any overflow pages associated with the
39817   ** cell. The cell itself is still intact.
39818   */
39819   idx = pCur->aiIdx[pCur->iPage];
39820   pCell = findCell(pPage, idx);
39821   if( !pPage->leaf ){
39822     pgnoChild = get4byte(pCell);
39823   }
39824   rc = clearCell(pPage, pCell);
39825   if( rc ){
39826     return rc;
39827   }
39828
39829   if( !pPage->leaf ){
39830     /*
39831     ** The entry we are about to delete is not a leaf so if we do not
39832     ** do something we will leave a hole on an internal page.
39833     ** We have to fill the hole by moving in a cell from a leaf.  The
39834     ** next Cell after the one to be deleted is guaranteed to exist and
39835     ** to be a leaf so we can use it.
39836     */
39837     BtCursor leafCur;
39838     MemPage *pLeafPage;
39839
39840     unsigned char *pNext;
39841     int notUsed;
39842     unsigned char *tempCell = 0;
39843     assert( !pPage->intKey );
39844     sqlite3BtreeGetTempCursor(pCur, &leafCur);
39845     rc = sqlite3BtreeNext(&leafCur, &notUsed);
39846     if( rc==SQLITE_OK ){
39847       assert( leafCur.aiIdx[leafCur.iPage]==0 );
39848       pLeafPage = leafCur.apPage[leafCur.iPage];
39849       rc = sqlite3PagerWrite(pLeafPage->pDbPage);
39850     }
39851     if( rc==SQLITE_OK ){
39852       int leafCursorInvalid = 0;
39853       u16 szNext;
39854       TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
39855          pCur->pgnoRoot, pPage->pgno, pLeafPage->pgno));
39856       dropCell(pPage, idx, cellSizePtr(pPage, pCell));
39857       pNext = findCell(pLeafPage, 0);
39858       szNext = cellSizePtr(pLeafPage, pNext);
39859       assert( MX_CELL_SIZE(pBt)>=szNext+4 );
39860       allocateTempSpace(pBt);
39861       tempCell = pBt->pTmpSpace;
39862       if( tempCell==0 ){
39863         rc = SQLITE_NOMEM;
39864       }
39865       if( rc==SQLITE_OK ){
39866         rc = insertCell(pPage, idx, pNext-4, szNext+4, tempCell, 0);
39867       }
39868
39869
39870       /* The "if" statement in the next code block is critical.  The
39871       ** slightest error in that statement would allow SQLite to operate
39872       ** correctly most of the time but produce very rare failures.  To
39873       ** guard against this, the following macros help to verify that
39874       ** the "if" statement is well tested.
39875       */
39876       testcase( pPage->nOverflow==0 && pPage->nFree<pBt->usableSize*2/3 
39877                  && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
39878       testcase( pPage->nOverflow==0 && pPage->nFree==pBt->usableSize*2/3 
39879                  && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
39880       testcase( pPage->nOverflow==0 && pPage->nFree==pBt->usableSize*2/3+1 
39881                  && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
39882       testcase( pPage->nOverflow>0 && pPage->nFree<=pBt->usableSize*2/3
39883                  && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
39884       testcase( (pPage->nOverflow>0 || (pPage->nFree > pBt->usableSize*2/3))
39885                  && pLeafPage->nFree+2+szNext == pBt->usableSize*2/3 );
39886
39887
39888       if( (pPage->nOverflow>0 || (pPage->nFree > pBt->usableSize*2/3)) &&
39889           (pLeafPage->nFree+2+szNext > pBt->usableSize*2/3)
39890       ){
39891         /* This branch is taken if the internal node is now either overflowing
39892         ** or underfull and the leaf node will be underfull after the just cell 
39893         ** copied to the internal node is deleted from it. This is a special
39894         ** case because the call to balance() to correct the internal node
39895         ** may change the tree structure and invalidate the contents of
39896         ** the leafCur.apPage[] and leafCur.aiIdx[] arrays, which will be
39897         ** used by the balance() required to correct the underfull leaf
39898         ** node.
39899         **
39900         ** The formula used in the expression above are based on facets of
39901         ** the SQLite file-format that do not change over time.
39902         */
39903         testcase( pPage->nFree==pBt->usableSize*2/3+1 );
39904         testcase( pLeafPage->nFree+2+szNext==pBt->usableSize*2/3+1 );
39905         leafCursorInvalid = 1;
39906       }        
39907
39908       if( rc==SQLITE_OK ){
39909         put4byte(findOverflowCell(pPage, idx), pgnoChild);
39910         VVA_ONLY( pCur->pagesShuffled = 0 );
39911         rc = balance(pCur, 0);
39912       }
39913
39914       if( rc==SQLITE_OK && leafCursorInvalid ){
39915         /* The leaf-node is now underfull and so the tree needs to be 
39916         ** rebalanced. However, the balance() operation on the internal
39917         ** node above may have modified the structure of the B-Tree and
39918         ** so the current contents of leafCur.apPage[] and leafCur.aiIdx[]
39919         ** may not be trusted.
39920         **
39921         ** It is not possible to copy the ancestry from pCur, as the same
39922         ** balance() call has invalidated the pCur->apPage[] and aiIdx[]
39923         ** arrays. 
39924         **
39925         ** The call to saveCursorPosition() below internally saves the 
39926         ** key that leafCur is currently pointing to. Currently, there
39927         ** are two copies of that key in the tree - one here on the leaf
39928         ** page and one on some internal node in the tree. The copy on
39929         ** the leaf node is always the next key in tree-order after the 
39930         ** copy on the internal node. So, the call to sqlite3BtreeNext()
39931         ** calls restoreCursorPosition() to point the cursor to the copy
39932         ** stored on the internal node, then advances to the next entry,
39933         ** which happens to be the copy of the key on the internal node.
39934         ** Net effect: leafCur is pointing back to the duplicate cell
39935         ** that needs to be removed, and the leafCur.apPage[] and
39936         ** leafCur.aiIdx[] arrays are correct.
39937         */
39938         VVA_ONLY( Pgno leafPgno = pLeafPage->pgno );
39939         rc = saveCursorPosition(&leafCur);
39940         if( rc==SQLITE_OK ){
39941           rc = sqlite3BtreeNext(&leafCur, &notUsed);
39942         }
39943         pLeafPage = leafCur.apPage[leafCur.iPage];
39944         assert( pLeafPage->pgno==leafPgno );
39945         assert( leafCur.aiIdx[leafCur.iPage]==0 );
39946       }
39947
39948       if( rc==SQLITE_OK ){
39949         rc = sqlite3PagerWrite(pLeafPage->pDbPage);
39950       }
39951       if( rc==SQLITE_OK ){
39952         dropCell(pLeafPage, 0, szNext);
39953         VVA_ONLY( leafCur.pagesShuffled = 0 );
39954         rc = balance(&leafCur, 0);
39955         assert( leafCursorInvalid || !leafCur.pagesShuffled
39956                                    || !pCur->pagesShuffled );
39957       }
39958     }
39959     sqlite3BtreeReleaseTempCursor(&leafCur);
39960   }else{
39961     TRACE(("DELETE: table=%d delete from leaf %d\n",
39962        pCur->pgnoRoot, pPage->pgno));
39963     rc = dropCell(pPage, idx, cellSizePtr(pPage, pCell));
39964     if( rc==SQLITE_OK ){
39965       rc = balance(pCur, 0);
39966     }
39967   }
39968   if( rc==SQLITE_OK ){
39969     moveToRoot(pCur);
39970   }
39971   return rc;
39972 }
39973
39974 /*
39975 ** Create a new BTree table.  Write into *piTable the page
39976 ** number for the root page of the new table.
39977 **
39978 ** The type of type is determined by the flags parameter.  Only the
39979 ** following values of flags are currently in use.  Other values for
39980 ** flags might not work:
39981 **
39982 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
39983 **     BTREE_ZERODATA                  Used for SQL indices
39984 */
39985 static int btreeCreateTable(Btree *p, int *piTable, int flags){
39986   BtShared *pBt = p->pBt;
39987   MemPage *pRoot;
39988   Pgno pgnoRoot;
39989   int rc;
39990
39991   assert( sqlite3BtreeHoldsMutex(p) );
39992   if( pBt->inTransaction!=TRANS_WRITE ){
39993     /* Must start a transaction first */
39994     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
39995     return rc;
39996   }
39997   assert( !pBt->readOnly );
39998
39999 #ifdef SQLITE_OMIT_AUTOVACUUM
40000   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
40001   if( rc ){
40002     return rc;
40003   }
40004 #else
40005   if( pBt->autoVacuum ){
40006     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
40007     MemPage *pPageMove; /* The page to move to. */
40008
40009     /* Creating a new table may probably require moving an existing database
40010     ** to make room for the new tables root page. In case this page turns
40011     ** out to be an overflow page, delete all overflow page-map caches
40012     ** held by open cursors.
40013     */
40014     invalidateAllOverflowCache(pBt);
40015
40016     /* Read the value of meta[3] from the database to determine where the
40017     ** root page of the new table should go. meta[3] is the largest root-page
40018     ** created so far, so the new root-page is (meta[3]+1).
40019     */
40020     rc = sqlite3BtreeGetMeta(p, 4, &pgnoRoot);
40021     if( rc!=SQLITE_OK ){
40022       return rc;
40023     }
40024     pgnoRoot++;
40025
40026     /* The new root-page may not be allocated on a pointer-map page, or the
40027     ** PENDING_BYTE page.
40028     */
40029     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
40030         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
40031       pgnoRoot++;
40032     }
40033     assert( pgnoRoot>=3 );
40034
40035     /* Allocate a page. The page that currently resides at pgnoRoot will
40036     ** be moved to the allocated page (unless the allocated page happens
40037     ** to reside at pgnoRoot).
40038     */
40039     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
40040     if( rc!=SQLITE_OK ){
40041       return rc;
40042     }
40043
40044     if( pgnoMove!=pgnoRoot ){
40045       /* pgnoRoot is the page that will be used for the root-page of
40046       ** the new table (assuming an error did not occur). But we were
40047       ** allocated pgnoMove. If required (i.e. if it was not allocated
40048       ** by extending the file), the current page at position pgnoMove
40049       ** is already journaled.
40050       */
40051       u8 eType;
40052       Pgno iPtrPage;
40053
40054       releasePage(pPageMove);
40055
40056       /* Move the page currently at pgnoRoot to pgnoMove. */
40057       rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
40058       if( rc!=SQLITE_OK ){
40059         return rc;
40060       }
40061       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
40062       if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
40063         releasePage(pRoot);
40064         return rc;
40065       }
40066       assert( eType!=PTRMAP_ROOTPAGE );
40067       assert( eType!=PTRMAP_FREEPAGE );
40068       rc = sqlite3PagerWrite(pRoot->pDbPage);
40069       if( rc!=SQLITE_OK ){
40070         releasePage(pRoot);
40071         return rc;
40072       }
40073       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
40074       releasePage(pRoot);
40075
40076       /* Obtain the page at pgnoRoot */
40077       if( rc!=SQLITE_OK ){
40078         return rc;
40079       }
40080       rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
40081       if( rc!=SQLITE_OK ){
40082         return rc;
40083       }
40084       rc = sqlite3PagerWrite(pRoot->pDbPage);
40085       if( rc!=SQLITE_OK ){
40086         releasePage(pRoot);
40087         return rc;
40088       }
40089     }else{
40090       pRoot = pPageMove;
40091     } 
40092
40093     /* Update the pointer-map and meta-data with the new root-page number. */
40094     rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
40095     if( rc ){
40096       releasePage(pRoot);
40097       return rc;
40098     }
40099     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
40100     if( rc ){
40101       releasePage(pRoot);
40102       return rc;
40103     }
40104
40105   }else{
40106     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
40107     if( rc ) return rc;
40108   }
40109 #endif
40110   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
40111   zeroPage(pRoot, flags | PTF_LEAF);
40112   sqlite3PagerUnref(pRoot->pDbPage);
40113   *piTable = (int)pgnoRoot;
40114   return SQLITE_OK;
40115 }
40116 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
40117   int rc;
40118   sqlite3BtreeEnter(p);
40119   p->pBt->db = p->db;
40120   rc = btreeCreateTable(p, piTable, flags);
40121   sqlite3BtreeLeave(p);
40122   return rc;
40123 }
40124
40125 /*
40126 ** Erase the given database page and all its children.  Return
40127 ** the page to the freelist.
40128 */
40129 static int clearDatabasePage(
40130   BtShared *pBt,           /* The BTree that contains the table */
40131   Pgno pgno,            /* Page number to clear */
40132   int freePageFlag,     /* Deallocate page if true */
40133   int *pnChange
40134 ){
40135   MemPage *pPage = 0;
40136   int rc;
40137   unsigned char *pCell;
40138   int i;
40139
40140   assert( sqlite3_mutex_held(pBt->mutex) );
40141   if( pgno>pagerPagecount(pBt) ){
40142     return SQLITE_CORRUPT_BKPT;
40143   }
40144
40145   rc = getAndInitPage(pBt, pgno, &pPage);
40146   if( rc ) goto cleardatabasepage_out;
40147   for(i=0; i<pPage->nCell; i++){
40148     pCell = findCell(pPage, i);
40149     if( !pPage->leaf ){
40150       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
40151       if( rc ) goto cleardatabasepage_out;
40152     }
40153     rc = clearCell(pPage, pCell);
40154     if( rc ) goto cleardatabasepage_out;
40155   }
40156   if( !pPage->leaf ){
40157     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
40158     if( rc ) goto cleardatabasepage_out;
40159   }else if( pnChange ){
40160     assert( pPage->intKey );
40161     *pnChange += pPage->nCell;
40162   }
40163   if( freePageFlag ){
40164     rc = freePage(pPage);
40165   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
40166     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
40167   }
40168
40169 cleardatabasepage_out:
40170   releasePage(pPage);
40171   return rc;
40172 }
40173
40174 /*
40175 ** Delete all information from a single table in the database.  iTable is
40176 ** the page number of the root of the table.  After this routine returns,
40177 ** the root page is empty, but still exists.
40178 **
40179 ** This routine will fail with SQLITE_LOCKED if there are any open
40180 ** read cursors on the table.  Open write cursors are moved to the
40181 ** root of the table.
40182 **
40183 ** If pnChange is not NULL, then table iTable must be an intkey table. The
40184 ** integer value pointed to by pnChange is incremented by the number of
40185 ** entries in the table.
40186 */
40187 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
40188   int rc;
40189   BtShared *pBt = p->pBt;
40190   sqlite3BtreeEnter(p);
40191   pBt->db = p->db;
40192   if( p->inTrans!=TRANS_WRITE ){
40193     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
40194   }else if( (rc = checkReadLocks(p, iTable, 0, 1))!=SQLITE_OK ){
40195     /* nothing to do */
40196   }else if( SQLITE_OK!=(rc = saveAllCursors(pBt, iTable, 0)) ){
40197     /* nothing to do */
40198   }else{
40199     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
40200   }
40201   sqlite3BtreeLeave(p);
40202   return rc;
40203 }
40204
40205 /*
40206 ** Erase all information in a table and add the root of the table to
40207 ** the freelist.  Except, the root of the principle table (the one on
40208 ** page 1) is never added to the freelist.
40209 **
40210 ** This routine will fail with SQLITE_LOCKED if there are any open
40211 ** cursors on the table.
40212 **
40213 ** If AUTOVACUUM is enabled and the page at iTable is not the last
40214 ** root page in the database file, then the last root page 
40215 ** in the database file is moved into the slot formerly occupied by
40216 ** iTable and that last slot formerly occupied by the last root page
40217 ** is added to the freelist instead of iTable.  In this say, all
40218 ** root pages are kept at the beginning of the database file, which
40219 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
40220 ** page number that used to be the last root page in the file before
40221 ** the move.  If no page gets moved, *piMoved is set to 0.
40222 ** The last root page is recorded in meta[3] and the value of
40223 ** meta[3] is updated by this procedure.
40224 */
40225 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
40226   int rc;
40227   MemPage *pPage = 0;
40228   BtShared *pBt = p->pBt;
40229
40230   assert( sqlite3BtreeHoldsMutex(p) );
40231   if( p->inTrans!=TRANS_WRITE ){
40232     return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
40233   }
40234
40235   /* It is illegal to drop a table if any cursors are open on the
40236   ** database. This is because in auto-vacuum mode the backend may
40237   ** need to move another root-page to fill a gap left by the deleted
40238   ** root page. If an open cursor was using this page a problem would 
40239   ** occur.
40240   */
40241   if( pBt->pCursor ){
40242     return SQLITE_LOCKED;
40243   }
40244
40245   rc = sqlite3BtreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
40246   if( rc ) return rc;
40247   rc = sqlite3BtreeClearTable(p, iTable, 0);
40248   if( rc ){
40249     releasePage(pPage);
40250     return rc;
40251   }
40252
40253   *piMoved = 0;
40254
40255   if( iTable>1 ){
40256 #ifdef SQLITE_OMIT_AUTOVACUUM
40257     rc = freePage(pPage);
40258     releasePage(pPage);
40259 #else
40260     if( pBt->autoVacuum ){
40261       Pgno maxRootPgno;
40262       rc = sqlite3BtreeGetMeta(p, 4, &maxRootPgno);
40263       if( rc!=SQLITE_OK ){
40264         releasePage(pPage);
40265         return rc;
40266       }
40267
40268       if( iTable==maxRootPgno ){
40269         /* If the table being dropped is the table with the largest root-page
40270         ** number in the database, put the root page on the free list. 
40271         */
40272         rc = freePage(pPage);
40273         releasePage(pPage);
40274         if( rc!=SQLITE_OK ){
40275           return rc;
40276         }
40277       }else{
40278         /* The table being dropped does not have the largest root-page
40279         ** number in the database. So move the page that does into the 
40280         ** gap left by the deleted root-page.
40281         */
40282         MemPage *pMove;
40283         releasePage(pPage);
40284         rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
40285         if( rc!=SQLITE_OK ){
40286           return rc;
40287         }
40288         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
40289         releasePage(pMove);
40290         if( rc!=SQLITE_OK ){
40291           return rc;
40292         }
40293         rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
40294         if( rc!=SQLITE_OK ){
40295           return rc;
40296         }
40297         rc = freePage(pMove);
40298         releasePage(pMove);
40299         if( rc!=SQLITE_OK ){
40300           return rc;
40301         }
40302         *piMoved = maxRootPgno;
40303       }
40304
40305       /* Set the new 'max-root-page' value in the database header. This
40306       ** is the old value less one, less one more if that happens to
40307       ** be a root-page number, less one again if that is the
40308       ** PENDING_BYTE_PAGE.
40309       */
40310       maxRootPgno--;
40311       if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
40312         maxRootPgno--;
40313       }
40314       if( maxRootPgno==PTRMAP_PAGENO(pBt, maxRootPgno) ){
40315         maxRootPgno--;
40316       }
40317       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
40318
40319       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
40320     }else{
40321       rc = freePage(pPage);
40322       releasePage(pPage);
40323     }
40324 #endif
40325   }else{
40326     /* If sqlite3BtreeDropTable was called on page 1. */
40327     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
40328     releasePage(pPage);
40329   }
40330   return rc;  
40331 }
40332 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
40333   int rc;
40334   sqlite3BtreeEnter(p);
40335   p->pBt->db = p->db;
40336   rc = btreeDropTable(p, iTable, piMoved);
40337   sqlite3BtreeLeave(p);
40338   return rc;
40339 }
40340
40341
40342 /*
40343 ** Read the meta-information out of a database file.  Meta[0]
40344 ** is the number of free pages currently in the database.  Meta[1]
40345 ** through meta[15] are available for use by higher layers.  Meta[0]
40346 ** is read-only, the others are read/write.
40347 ** 
40348 ** The schema layer numbers meta values differently.  At the schema
40349 ** layer (and the SetCookie and ReadCookie opcodes) the number of
40350 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
40351 */
40352 SQLITE_PRIVATE int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
40353   DbPage *pDbPage;
40354   int rc;
40355   unsigned char *pP1;
40356   BtShared *pBt = p->pBt;
40357
40358   sqlite3BtreeEnter(p);
40359   pBt->db = p->db;
40360
40361   /* Reading a meta-data value requires a read-lock on page 1 (and hence
40362   ** the sqlite_master table. We grab this lock regardless of whether or
40363   ** not the SQLITE_ReadUncommitted flag is set (the table rooted at page
40364   ** 1 is treated as a special case by queryTableLock() and lockTable()).
40365   */
40366   rc = queryTableLock(p, 1, READ_LOCK);
40367   if( rc!=SQLITE_OK ){
40368     sqlite3BtreeLeave(p);
40369     return rc;
40370   }
40371
40372   assert( idx>=0 && idx<=15 );
40373   if( pBt->pPage1 ){
40374     /* The b-tree is already holding a reference to page 1 of the database
40375     ** file. In this case the required meta-data value can be read directly
40376     ** from the page data of this reference. This is slightly faster than
40377     ** requesting a new reference from the pager layer.
40378     */
40379     pP1 = (unsigned char *)pBt->pPage1->aData;
40380   }else{
40381     /* The b-tree does not have a reference to page 1 of the database file.
40382     ** Obtain one from the pager layer.
40383     */
40384     rc = sqlite3PagerGet(pBt->pPager, 1, &pDbPage);
40385     if( rc ){
40386       sqlite3BtreeLeave(p);
40387       return rc;
40388     }
40389     pP1 = (unsigned char *)sqlite3PagerGetData(pDbPage);
40390   }
40391   *pMeta = get4byte(&pP1[36 + idx*4]);
40392
40393   /* If the b-tree is not holding a reference to page 1, then one was 
40394   ** requested from the pager layer in the above block. Release it now.
40395   */
40396   if( !pBt->pPage1 ){
40397     sqlite3PagerUnref(pDbPage);
40398   }
40399
40400   /* If autovacuumed is disabled in this build but we are trying to 
40401   ** access an autovacuumed database, then make the database readonly. 
40402   */
40403 #ifdef SQLITE_OMIT_AUTOVACUUM
40404   if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
40405 #endif
40406
40407   /* Grab the read-lock on page 1. */
40408   rc = lockTable(p, 1, READ_LOCK);
40409   sqlite3BtreeLeave(p);
40410   return rc;
40411 }
40412
40413 /*
40414 ** Write meta-information back into the database.  Meta[0] is
40415 ** read-only and may not be written.
40416 */
40417 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
40418   BtShared *pBt = p->pBt;
40419   unsigned char *pP1;
40420   int rc;
40421   assert( idx>=1 && idx<=15 );
40422   sqlite3BtreeEnter(p);
40423   pBt->db = p->db;
40424   if( p->inTrans!=TRANS_WRITE ){
40425     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
40426   }else{
40427     assert( pBt->pPage1!=0 );
40428     pP1 = pBt->pPage1->aData;
40429     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
40430     if( rc==SQLITE_OK ){
40431       put4byte(&pP1[36 + idx*4], iMeta);
40432 #ifndef SQLITE_OMIT_AUTOVACUUM
40433       if( idx==7 ){
40434         assert( pBt->autoVacuum || iMeta==0 );
40435         assert( iMeta==0 || iMeta==1 );
40436         pBt->incrVacuum = iMeta;
40437       }
40438 #endif
40439     }
40440   }
40441   sqlite3BtreeLeave(p);
40442   return rc;
40443 }
40444
40445 /*
40446 ** Return the flag byte at the beginning of the page that the cursor
40447 ** is currently pointing to.
40448 */
40449 SQLITE_PRIVATE int sqlite3BtreeFlags(BtCursor *pCur){
40450   /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call
40451   ** restoreCursorPosition() here.
40452   */
40453   MemPage *pPage;
40454   restoreCursorPosition(pCur);
40455   pPage = pCur->apPage[pCur->iPage];
40456   assert( cursorHoldsMutex(pCur) );
40457   assert( pPage->pBt==pCur->pBt );
40458   return pPage ? pPage->aData[pPage->hdrOffset] : 0;
40459 }
40460
40461
40462 /*
40463 ** Return the pager associated with a BTree.  This routine is used for
40464 ** testing and debugging only.
40465 */
40466 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
40467   return p->pBt->pPager;
40468 }
40469
40470 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
40471 /*
40472 ** Append a message to the error message string.
40473 */
40474 static void checkAppendMsg(
40475   IntegrityCk *pCheck,
40476   char *zMsg1,
40477   const char *zFormat,
40478   ...
40479 ){
40480   va_list ap;
40481   if( !pCheck->mxErr ) return;
40482   pCheck->mxErr--;
40483   pCheck->nErr++;
40484   va_start(ap, zFormat);
40485   if( pCheck->errMsg.nChar ){
40486     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
40487   }
40488   if( zMsg1 ){
40489     sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
40490   }
40491   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
40492   va_end(ap);
40493   if( pCheck->errMsg.mallocFailed ){
40494     pCheck->mallocFailed = 1;
40495   }
40496 }
40497 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
40498
40499 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
40500 /*
40501 ** Add 1 to the reference count for page iPage.  If this is the second
40502 ** reference to the page, add an error message to pCheck->zErrMsg.
40503 ** Return 1 if there are 2 ore more references to the page and 0 if
40504 ** if this is the first reference to the page.
40505 **
40506 ** Also check that the page number is in bounds.
40507 */
40508 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
40509   if( iPage==0 ) return 1;
40510   if( iPage>pCheck->nPage ){
40511     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
40512     return 1;
40513   }
40514   if( pCheck->anRef[iPage]==1 ){
40515     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
40516     return 1;
40517   }
40518   return  (pCheck->anRef[iPage]++)>1;
40519 }
40520
40521 #ifndef SQLITE_OMIT_AUTOVACUUM
40522 /*
40523 ** Check that the entry in the pointer-map for page iChild maps to 
40524 ** page iParent, pointer type ptrType. If not, append an error message
40525 ** to pCheck.
40526 */
40527 static void checkPtrmap(
40528   IntegrityCk *pCheck,   /* Integrity check context */
40529   Pgno iChild,           /* Child page number */
40530   u8 eType,              /* Expected pointer map type */
40531   Pgno iParent,          /* Expected pointer map parent page number */
40532   char *zContext         /* Context description (used for error msg) */
40533 ){
40534   int rc;
40535   u8 ePtrmapType;
40536   Pgno iPtrmapParent;
40537
40538   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
40539   if( rc!=SQLITE_OK ){
40540     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
40541     return;
40542   }
40543
40544   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
40545     checkAppendMsg(pCheck, zContext, 
40546       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
40547       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
40548   }
40549 }
40550 #endif
40551
40552 /*
40553 ** Check the integrity of the freelist or of an overflow page list.
40554 ** Verify that the number of pages on the list is N.
40555 */
40556 static void checkList(
40557   IntegrityCk *pCheck,  /* Integrity checking context */
40558   int isFreeList,       /* True for a freelist.  False for overflow page list */
40559   int iPage,            /* Page number for first page in the list */
40560   int N,                /* Expected number of pages in the list */
40561   char *zContext        /* Context for error messages */
40562 ){
40563   int i;
40564   int expected = N;
40565   int iFirst = iPage;
40566   while( N-- > 0 && pCheck->mxErr ){
40567     DbPage *pOvflPage;
40568     unsigned char *pOvflData;
40569     if( iPage<1 ){
40570       checkAppendMsg(pCheck, zContext,
40571          "%d of %d pages missing from overflow list starting at %d",
40572           N+1, expected, iFirst);
40573       break;
40574     }
40575     if( checkRef(pCheck, iPage, zContext) ) break;
40576     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
40577       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
40578       break;
40579     }
40580     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
40581     if( isFreeList ){
40582       int n = get4byte(&pOvflData[4]);
40583 #ifndef SQLITE_OMIT_AUTOVACUUM
40584       if( pCheck->pBt->autoVacuum ){
40585         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
40586       }
40587 #endif
40588       if( n>pCheck->pBt->usableSize/4-2 ){
40589         checkAppendMsg(pCheck, zContext,
40590            "freelist leaf count too big on page %d", iPage);
40591         N--;
40592       }else{
40593         for(i=0; i<n; i++){
40594           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
40595 #ifndef SQLITE_OMIT_AUTOVACUUM
40596           if( pCheck->pBt->autoVacuum ){
40597             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
40598           }
40599 #endif
40600           checkRef(pCheck, iFreePage, zContext);
40601         }
40602         N -= n;
40603       }
40604     }
40605 #ifndef SQLITE_OMIT_AUTOVACUUM
40606     else{
40607       /* If this database supports auto-vacuum and iPage is not the last
40608       ** page in this overflow list, check that the pointer-map entry for
40609       ** the following page matches iPage.
40610       */
40611       if( pCheck->pBt->autoVacuum && N>0 ){
40612         i = get4byte(pOvflData);
40613         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
40614       }
40615     }
40616 #endif
40617     iPage = get4byte(pOvflData);
40618     sqlite3PagerUnref(pOvflPage);
40619   }
40620 }
40621 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
40622
40623 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
40624 /*
40625 ** Do various sanity checks on a single page of a tree.  Return
40626 ** the tree depth.  Root pages return 0.  Parents of root pages
40627 ** return 1, and so forth.
40628 ** 
40629 ** These checks are done:
40630 **
40631 **      1.  Make sure that cells and freeblocks do not overlap
40632 **          but combine to completely cover the page.
40633 **  NO  2.  Make sure cell keys are in order.
40634 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
40635 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
40636 **      5.  Check the integrity of overflow pages.
40637 **      6.  Recursively call checkTreePage on all children.
40638 **      7.  Verify that the depth of all children is the same.
40639 **      8.  Make sure this page is at least 33% full or else it is
40640 **          the root of the tree.
40641 */
40642 static int checkTreePage(
40643   IntegrityCk *pCheck,  /* Context for the sanity check */
40644   int iPage,            /* Page number of the page to check */
40645   char *zParentContext  /* Parent context */
40646 ){
40647   MemPage *pPage;
40648   int i, rc, depth, d2, pgno, cnt;
40649   int hdr, cellStart;
40650   int nCell;
40651   u8 *data;
40652   BtShared *pBt;
40653   int usableSize;
40654   char zContext[100];
40655   char *hit = 0;
40656
40657   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
40658
40659   /* Check that the page exists
40660   */
40661   pBt = pCheck->pBt;
40662   usableSize = pBt->usableSize;
40663   if( iPage==0 ) return 0;
40664   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
40665   if( (rc = sqlite3BtreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
40666     checkAppendMsg(pCheck, zContext,
40667        "unable to get the page. error code=%d", rc);
40668     return 0;
40669   }
40670   if( (rc = sqlite3BtreeInitPage(pPage))!=0 ){
40671     checkAppendMsg(pCheck, zContext, 
40672                    "sqlite3BtreeInitPage() returns error code %d", rc);
40673     releasePage(pPage);
40674     return 0;
40675   }
40676
40677   /* Check out all the cells.
40678   */
40679   depth = 0;
40680   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
40681     u8 *pCell;
40682     u32 sz;
40683     CellInfo info;
40684
40685     /* Check payload overflow pages
40686     */
40687     sqlite3_snprintf(sizeof(zContext), zContext,
40688              "On tree page %d cell %d: ", iPage, i);
40689     pCell = findCell(pPage,i);
40690     sqlite3BtreeParseCellPtr(pPage, pCell, &info);
40691     sz = info.nData;
40692     if( !pPage->intKey ) sz += info.nKey;
40693     assert( sz==info.nPayload );
40694     if( sz>info.nLocal ){
40695       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
40696       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
40697 #ifndef SQLITE_OMIT_AUTOVACUUM
40698       if( pBt->autoVacuum ){
40699         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
40700       }
40701 #endif
40702       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
40703     }
40704
40705     /* Check sanity of left child page.
40706     */
40707     if( !pPage->leaf ){
40708       pgno = get4byte(pCell);
40709 #ifndef SQLITE_OMIT_AUTOVACUUM
40710       if( pBt->autoVacuum ){
40711         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
40712       }
40713 #endif
40714       d2 = checkTreePage(pCheck, pgno, zContext);
40715       if( i>0 && d2!=depth ){
40716         checkAppendMsg(pCheck, zContext, "Child page depth differs");
40717       }
40718       depth = d2;
40719     }
40720   }
40721   if( !pPage->leaf ){
40722     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
40723     sqlite3_snprintf(sizeof(zContext), zContext, 
40724                      "On page %d at right child: ", iPage);
40725 #ifndef SQLITE_OMIT_AUTOVACUUM
40726     if( pBt->autoVacuum ){
40727       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
40728     }
40729 #endif
40730     checkTreePage(pCheck, pgno, zContext);
40731   }
40732  
40733   /* Check for complete coverage of the page
40734   */
40735   data = pPage->aData;
40736   hdr = pPage->hdrOffset;
40737   hit = sqlite3PageMalloc( pBt->pageSize );
40738   if( hit==0 ){
40739     pCheck->mallocFailed = 1;
40740   }else{
40741     u16 contentOffset = get2byte(&data[hdr+5]);
40742     if (contentOffset > usableSize) {
40743       checkAppendMsg(pCheck, 0, 
40744                      "Corruption detected in header on page %d",iPage,0);
40745       goto check_page_abort;
40746     }
40747     memset(hit+contentOffset, 0, usableSize-contentOffset);
40748     memset(hit, 1, contentOffset);
40749     nCell = get2byte(&data[hdr+3]);
40750     cellStart = hdr + 12 - 4*pPage->leaf;
40751     for(i=0; i<nCell; i++){
40752       int pc = get2byte(&data[cellStart+i*2]);
40753       u16 size = 1024;
40754       int j;
40755       if( pc<=usableSize ){
40756         size = cellSizePtr(pPage, &data[pc]);
40757       }
40758       if( (pc+size-1)>=usableSize || pc<0 ){
40759         checkAppendMsg(pCheck, 0, 
40760             "Corruption detected in cell %d on page %d",i,iPage,0);
40761       }else{
40762         for(j=pc+size-1; j>=pc; j--) hit[j]++;
40763       }
40764     }
40765     for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000; 
40766            cnt++){
40767       int size = get2byte(&data[i+2]);
40768       int j;
40769       if( (i+size-1)>=usableSize || i<0 ){
40770         checkAppendMsg(pCheck, 0,  
40771             "Corruption detected in cell %d on page %d",i,iPage,0);
40772       }else{
40773         for(j=i+size-1; j>=i; j--) hit[j]++;
40774       }
40775       i = get2byte(&data[i]);
40776     }
40777     for(i=cnt=0; i<usableSize; i++){
40778       if( hit[i]==0 ){
40779         cnt++;
40780       }else if( hit[i]>1 ){
40781         checkAppendMsg(pCheck, 0,
40782           "Multiple uses for byte %d of page %d", i, iPage);
40783         break;
40784       }
40785     }
40786     if( cnt!=data[hdr+7] ){
40787       checkAppendMsg(pCheck, 0, 
40788           "Fragmented space is %d byte reported as %d on page %d",
40789           cnt, data[hdr+7], iPage);
40790     }
40791   }
40792 check_page_abort:
40793   if (hit) sqlite3PageFree(hit);
40794
40795   releasePage(pPage);
40796   return depth+1;
40797 }
40798 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
40799
40800 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
40801 /*
40802 ** This routine does a complete check of the given BTree file.  aRoot[] is
40803 ** an array of pages numbers were each page number is the root page of
40804 ** a table.  nRoot is the number of entries in aRoot.
40805 **
40806 ** Write the number of error seen in *pnErr.  Except for some memory
40807 ** allocation errors,  nn error message is held in memory obtained from
40808 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
40809 ** returned.
40810 */
40811 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
40812   Btree *p,     /* The btree to be checked */
40813   int *aRoot,   /* An array of root pages numbers for individual trees */
40814   int nRoot,    /* Number of entries in aRoot[] */
40815   int mxErr,    /* Stop reporting errors after this many */
40816   int *pnErr    /* Write number of errors seen to this variable */
40817 ){
40818   Pgno i;
40819   int nRef;
40820   IntegrityCk sCheck;
40821   BtShared *pBt = p->pBt;
40822   char zErr[100];
40823
40824   sqlite3BtreeEnter(p);
40825   pBt->db = p->db;
40826   nRef = sqlite3PagerRefcount(pBt->pPager);
40827   if( lockBtreeWithRetry(p)!=SQLITE_OK ){
40828     *pnErr = 1;
40829     sqlite3BtreeLeave(p);
40830     return sqlite3DbStrDup(0, "cannot acquire a read lock on the database");
40831   }
40832   sCheck.pBt = pBt;
40833   sCheck.pPager = pBt->pPager;
40834   sCheck.nPage = pagerPagecount(sCheck.pBt);
40835   sCheck.mxErr = mxErr;
40836   sCheck.nErr = 0;
40837   sCheck.mallocFailed = 0;
40838   *pnErr = 0;
40839 #ifndef SQLITE_OMIT_AUTOVACUUM
40840   if( pBt->nTrunc!=0 ){
40841     sCheck.nPage = pBt->nTrunc;
40842   }
40843 #endif
40844   if( sCheck.nPage==0 ){
40845     unlockBtreeIfUnused(pBt);
40846     sqlite3BtreeLeave(p);
40847     return 0;
40848   }
40849   sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
40850   if( !sCheck.anRef ){
40851     unlockBtreeIfUnused(pBt);
40852     *pnErr = 1;
40853     sqlite3BtreeLeave(p);
40854     return 0;
40855   }
40856   for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
40857   i = PENDING_BYTE_PAGE(pBt);
40858   if( i<=sCheck.nPage ){
40859     sCheck.anRef[i] = 1;
40860   }
40861   sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
40862
40863   /* Check the integrity of the freelist
40864   */
40865   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
40866             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
40867
40868   /* Check all the tables.
40869   */
40870   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
40871     if( aRoot[i]==0 ) continue;
40872 #ifndef SQLITE_OMIT_AUTOVACUUM
40873     if( pBt->autoVacuum && aRoot[i]>1 ){
40874       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
40875     }
40876 #endif
40877     checkTreePage(&sCheck, aRoot[i], "List of tree roots: ");
40878   }
40879
40880   /* Make sure every page in the file is referenced
40881   */
40882   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
40883 #ifdef SQLITE_OMIT_AUTOVACUUM
40884     if( sCheck.anRef[i]==0 ){
40885       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
40886     }
40887 #else
40888     /* If the database supports auto-vacuum, make sure no tables contain
40889     ** references to pointer-map pages.
40890     */
40891     if( sCheck.anRef[i]==0 && 
40892        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
40893       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
40894     }
40895     if( sCheck.anRef[i]!=0 && 
40896        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
40897       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
40898     }
40899 #endif
40900   }
40901
40902   /* Make sure this analysis did not leave any unref() pages
40903   */
40904   unlockBtreeIfUnused(pBt);
40905   if( nRef != sqlite3PagerRefcount(pBt->pPager) ){
40906     checkAppendMsg(&sCheck, 0, 
40907       "Outstanding page count goes from %d to %d during this analysis",
40908       nRef, sqlite3PagerRefcount(pBt->pPager)
40909     );
40910   }
40911
40912   /* Clean  up and report errors.
40913   */
40914   sqlite3BtreeLeave(p);
40915   sqlite3_free(sCheck.anRef);
40916   if( sCheck.mallocFailed ){
40917     sqlite3StrAccumReset(&sCheck.errMsg);
40918     *pnErr = sCheck.nErr+1;
40919     return 0;
40920   }
40921   *pnErr = sCheck.nErr;
40922   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
40923   return sqlite3StrAccumFinish(&sCheck.errMsg);
40924 }
40925 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
40926
40927 /*
40928 ** Return the full pathname of the underlying database file.
40929 **
40930 ** The pager filename is invariant as long as the pager is
40931 ** open so it is safe to access without the BtShared mutex.
40932 */
40933 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
40934   assert( p->pBt->pPager!=0 );
40935   return sqlite3PagerFilename(p->pBt->pPager);
40936 }
40937
40938 /*
40939 ** Return the pathname of the directory that contains the database file.
40940 **
40941 ** The pager directory name is invariant as long as the pager is
40942 ** open so it is safe to access without the BtShared mutex.
40943 */
40944 SQLITE_PRIVATE const char *sqlite3BtreeGetDirname(Btree *p){
40945   assert( p->pBt->pPager!=0 );
40946   return sqlite3PagerDirname(p->pBt->pPager);
40947 }
40948
40949 /*
40950 ** Return the pathname of the journal file for this database. The return
40951 ** value of this routine is the same regardless of whether the journal file
40952 ** has been created or not.
40953 **
40954 ** The pager journal filename is invariant as long as the pager is
40955 ** open so it is safe to access without the BtShared mutex.
40956 */
40957 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
40958   assert( p->pBt->pPager!=0 );
40959   return sqlite3PagerJournalname(p->pBt->pPager);
40960 }
40961
40962 #ifndef SQLITE_OMIT_VACUUM
40963 /*
40964 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
40965 ** must be active for both files.
40966 **
40967 ** The size of file pTo may be reduced by this operation.
40968 ** If anything goes wrong, the transaction on pTo is rolled back. 
40969 **
40970 ** If successful, CommitPhaseOne() may be called on pTo before returning. 
40971 ** The caller should finish committing the transaction on pTo by calling
40972 ** sqlite3BtreeCommit().
40973 */
40974 static int btreeCopyFile(Btree *pTo, Btree *pFrom){
40975   int rc = SQLITE_OK;
40976   Pgno i;
40977
40978   Pgno nFromPage;     /* Number of pages in pFrom */
40979   Pgno nToPage;       /* Number of pages in pTo */
40980   Pgno nNewPage;      /* Number of pages in pTo after the copy */
40981
40982   Pgno iSkip;         /* Pending byte page in pTo */
40983   int nToPageSize;    /* Page size of pTo in bytes */
40984   int nFromPageSize;  /* Page size of pFrom in bytes */
40985
40986   BtShared *pBtTo = pTo->pBt;
40987   BtShared *pBtFrom = pFrom->pBt;
40988   pBtTo->db = pTo->db;
40989   pBtFrom->db = pFrom->db;
40990
40991   nToPageSize = pBtTo->pageSize;
40992   nFromPageSize = pBtFrom->pageSize;
40993
40994   if( pTo->inTrans!=TRANS_WRITE || pFrom->inTrans!=TRANS_WRITE ){
40995     return SQLITE_ERROR;
40996   }
40997   if( pBtTo->pCursor ){
40998     return SQLITE_BUSY;
40999   }
41000
41001   nToPage = pagerPagecount(pBtTo);
41002   nFromPage = pagerPagecount(pBtFrom);
41003   iSkip = PENDING_BYTE_PAGE(pBtTo);
41004
41005   /* Variable nNewPage is the number of pages required to store the
41006   ** contents of pFrom using the current page-size of pTo.
41007   */
41008   nNewPage = ((i64)nFromPage * (i64)nFromPageSize + (i64)nToPageSize - 1) / 
41009       (i64)nToPageSize;
41010
41011   for(i=1; rc==SQLITE_OK && (i<=nToPage || i<=nNewPage); i++){
41012
41013     /* Journal the original page.
41014     **
41015     ** iSkip is the page number of the locking page (PENDING_BYTE_PAGE)
41016     ** in database *pTo (before the copy). This page is never written 
41017     ** into the journal file. Unless i==iSkip or the page was not
41018     ** present in pTo before the copy operation, journal page i from pTo.
41019     */
41020     if( i!=iSkip && i<=nToPage ){
41021       DbPage *pDbPage = 0;
41022       rc = sqlite3PagerGet(pBtTo->pPager, i, &pDbPage);
41023       if( rc==SQLITE_OK ){
41024         rc = sqlite3PagerWrite(pDbPage);
41025         if( rc==SQLITE_OK && i>nFromPage ){
41026           /* Yeah.  It seems wierd to call DontWrite() right after Write(). But
41027           ** that is because the names of those procedures do not exactly 
41028           ** represent what they do.  Write() really means "put this page in the
41029           ** rollback journal and mark it as dirty so that it will be written
41030           ** to the database file later."  DontWrite() undoes the second part of
41031           ** that and prevents the page from being written to the database. The
41032           ** page is still on the rollback journal, though.  And that is the 
41033           ** whole point of this block: to put pages on the rollback journal. 
41034           */
41035           rc = sqlite3PagerDontWrite(pDbPage);
41036         }
41037         sqlite3PagerUnref(pDbPage);
41038       }
41039     }
41040
41041     /* Overwrite the data in page i of the target database */
41042     if( rc==SQLITE_OK && i!=iSkip && i<=nNewPage ){
41043
41044       DbPage *pToPage = 0;
41045       sqlite3_int64 iOff;
41046
41047       rc = sqlite3PagerGet(pBtTo->pPager, i, &pToPage);
41048       if( rc==SQLITE_OK ){
41049         rc = sqlite3PagerWrite(pToPage);
41050       }
41051
41052       for(
41053         iOff=(i-1)*nToPageSize; 
41054         rc==SQLITE_OK && iOff<i*nToPageSize; 
41055         iOff += nFromPageSize
41056       ){
41057         DbPage *pFromPage = 0;
41058         Pgno iFrom = (iOff/nFromPageSize)+1;
41059
41060         if( iFrom==PENDING_BYTE_PAGE(pBtFrom) ){
41061           continue;
41062         }
41063
41064         rc = sqlite3PagerGet(pBtFrom->pPager, iFrom, &pFromPage);
41065         if( rc==SQLITE_OK ){
41066           char *zTo = sqlite3PagerGetData(pToPage);
41067           char *zFrom = sqlite3PagerGetData(pFromPage);
41068           int nCopy;
41069
41070           if( nFromPageSize>=nToPageSize ){
41071             zFrom += ((i-1)*nToPageSize - ((iFrom-1)*nFromPageSize));
41072             nCopy = nToPageSize;
41073           }else{
41074             zTo += (((iFrom-1)*nFromPageSize) - (i-1)*nToPageSize);
41075             nCopy = nFromPageSize;
41076           }
41077
41078           memcpy(zTo, zFrom, nCopy);
41079           sqlite3PagerUnref(pFromPage);
41080         }
41081       }
41082
41083       if( pToPage ){
41084         MemPage *p = (MemPage *)sqlite3PagerGetExtra(pToPage);
41085         p->isInit = 0;
41086         sqlite3PagerUnref(pToPage);
41087       }
41088     }
41089   }
41090
41091   /* If things have worked so far, the database file may need to be 
41092   ** truncated. The complex part is that it may need to be truncated to
41093   ** a size that is not an integer multiple of nToPageSize - the current
41094   ** page size used by the pager associated with B-Tree pTo.
41095   **
41096   ** For example, say the page-size of pTo is 2048 bytes and the original 
41097   ** number of pages is 5 (10 KB file). If pFrom has a page size of 1024 
41098   ** bytes and 9 pages, then the file needs to be truncated to 9KB.
41099   */
41100   if( rc==SQLITE_OK ){
41101     if( nFromPageSize!=nToPageSize ){
41102       sqlite3_file *pFile = sqlite3PagerFile(pBtTo->pPager);
41103       i64 iSize = (i64)nFromPageSize * (i64)nFromPage;
41104       i64 iNow = (i64)((nToPage>nNewPage)?nToPage:nNewPage) * (i64)nToPageSize; 
41105       i64 iPending = ((i64)PENDING_BYTE_PAGE(pBtTo)-1) *(i64)nToPageSize;
41106   
41107       assert( iSize<=iNow );
41108   
41109       /* Commit phase one syncs the journal file associated with pTo 
41110       ** containing the original data. It does not sync the database file
41111       ** itself. After doing this it is safe to use OsTruncate() and other
41112       ** file APIs on the database file directly.
41113       */
41114       pBtTo->db = pTo->db;
41115       rc = sqlite3PagerCommitPhaseOne(pBtTo->pPager, 0, 0, 1);
41116       if( iSize<iNow && rc==SQLITE_OK ){
41117         rc = sqlite3OsTruncate(pFile, iSize);
41118       }
41119   
41120       /* The loop that copied data from database pFrom to pTo did not
41121       ** populate the locking page of database pTo. If the page-size of
41122       ** pFrom is smaller than that of pTo, this means some data will
41123       ** not have been copied. 
41124       **
41125       ** This block copies the missing data from database pFrom to pTo 
41126       ** using file APIs. This is safe because at this point we know that
41127       ** all of the original data from pTo has been synced into the 
41128       ** journal file. At this point it would be safe to do anything at
41129       ** all to the database file except truncate it to zero bytes.
41130       */
41131       if( rc==SQLITE_OK && nFromPageSize<nToPageSize && iSize>iPending){
41132         i64 iOff;
41133         for(
41134           iOff=iPending; 
41135           rc==SQLITE_OK && iOff<(iPending+nToPageSize); 
41136           iOff += nFromPageSize
41137         ){
41138           DbPage *pFromPage = 0;
41139           Pgno iFrom = (iOff/nFromPageSize)+1;
41140   
41141           if( iFrom==PENDING_BYTE_PAGE(pBtFrom) || iFrom>nFromPage ){
41142             continue;
41143           }
41144   
41145           rc = sqlite3PagerGet(pBtFrom->pPager, iFrom, &pFromPage);
41146           if( rc==SQLITE_OK ){
41147             char *zFrom = sqlite3PagerGetData(pFromPage);
41148             rc = sqlite3OsWrite(pFile, zFrom, nFromPageSize, iOff);
41149             sqlite3PagerUnref(pFromPage);
41150           }
41151         }
41152       }
41153   
41154       /* Sync the database file */
41155       if( rc==SQLITE_OK ){
41156         rc = sqlite3PagerSync(pBtTo->pPager);
41157       }
41158     }else{
41159       rc = sqlite3PagerTruncate(pBtTo->pPager, nNewPage);
41160     }
41161     if( rc==SQLITE_OK ){
41162       pBtTo->pageSizeFixed = 0;
41163     }
41164   }
41165
41166   if( rc ){
41167     sqlite3BtreeRollback(pTo);
41168   }
41169
41170   return rc;  
41171 }
41172 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
41173   int rc;
41174   sqlite3BtreeEnter(pTo);
41175   sqlite3BtreeEnter(pFrom);
41176   rc = btreeCopyFile(pTo, pFrom);
41177   sqlite3BtreeLeave(pFrom);
41178   sqlite3BtreeLeave(pTo);
41179   return rc;
41180 }
41181
41182 #endif /* SQLITE_OMIT_VACUUM */
41183
41184 /*
41185 ** Return non-zero if a transaction is active.
41186 */
41187 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
41188   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
41189   return (p && (p->inTrans==TRANS_WRITE));
41190 }
41191
41192 /*
41193 ** Return non-zero if a statement transaction is active.
41194 */
41195 SQLITE_PRIVATE int sqlite3BtreeIsInStmt(Btree *p){
41196   assert( sqlite3BtreeHoldsMutex(p) );
41197   return (p->pBt && p->pBt->inStmt);
41198 }
41199
41200 /*
41201 ** Return non-zero if a read (or write) transaction is active.
41202 */
41203 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
41204   assert( sqlite3_mutex_held(p->db->mutex) );
41205   return (p && (p->inTrans!=TRANS_NONE));
41206 }
41207
41208 /*
41209 ** This function returns a pointer to a blob of memory associated with
41210 ** a single shared-btree. The memory is used by client code for its own
41211 ** purposes (for example, to store a high-level schema associated with 
41212 ** the shared-btree). The btree layer manages reference counting issues.
41213 **
41214 ** The first time this is called on a shared-btree, nBytes bytes of memory
41215 ** are allocated, zeroed, and returned to the caller. For each subsequent 
41216 ** call the nBytes parameter is ignored and a pointer to the same blob
41217 ** of memory returned. 
41218 **
41219 ** If the nBytes parameter is 0 and the blob of memory has not yet been
41220 ** allocated, a null pointer is returned. If the blob has already been
41221 ** allocated, it is returned as normal.
41222 **
41223 ** Just before the shared-btree is closed, the function passed as the 
41224 ** xFree argument when the memory allocation was made is invoked on the 
41225 ** blob of allocated memory. This function should not call sqlite3_free()
41226 ** on the memory, the btree layer does that.
41227 */
41228 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
41229   BtShared *pBt = p->pBt;
41230   sqlite3BtreeEnter(p);
41231   if( !pBt->pSchema && nBytes ){
41232     pBt->pSchema = sqlite3MallocZero(nBytes);
41233     pBt->xFreeSchema = xFree;
41234   }
41235   sqlite3BtreeLeave(p);
41236   return pBt->pSchema;
41237 }
41238
41239 /*
41240 ** Return true if another user of the same shared btree as the argument
41241 ** handle holds an exclusive lock on the sqlite_master table.
41242 */
41243 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
41244   int rc;
41245   assert( sqlite3_mutex_held(p->db->mutex) );
41246   sqlite3BtreeEnter(p);
41247   rc = (queryTableLock(p, MASTER_ROOT, READ_LOCK)!=SQLITE_OK);
41248   sqlite3BtreeLeave(p);
41249   return rc;
41250 }
41251
41252
41253 #ifndef SQLITE_OMIT_SHARED_CACHE
41254 /*
41255 ** Obtain a lock on the table whose root page is iTab.  The
41256 ** lock is a write lock if isWritelock is true or a read lock
41257 ** if it is false.
41258 */
41259 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
41260   int rc = SQLITE_OK;
41261   if( p->sharable ){
41262     u8 lockType = READ_LOCK + isWriteLock;
41263     assert( READ_LOCK+1==WRITE_LOCK );
41264     assert( isWriteLock==0 || isWriteLock==1 );
41265     sqlite3BtreeEnter(p);
41266     rc = queryTableLock(p, iTab, lockType);
41267     if( rc==SQLITE_OK ){
41268       rc = lockTable(p, iTab, lockType);
41269     }
41270     sqlite3BtreeLeave(p);
41271   }
41272   return rc;
41273 }
41274 #endif
41275
41276 #ifndef SQLITE_OMIT_INCRBLOB
41277 /*
41278 ** Argument pCsr must be a cursor opened for writing on an 
41279 ** INTKEY table currently pointing at a valid table entry. 
41280 ** This function modifies the data stored as part of that entry.
41281 ** Only the data content may only be modified, it is not possible
41282 ** to change the length of the data stored.
41283 */
41284 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
41285   assert( cursorHoldsMutex(pCsr) );
41286   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
41287   assert(pCsr->isIncrblobHandle);
41288
41289   restoreCursorPosition(pCsr);
41290   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
41291   if( pCsr->eState!=CURSOR_VALID ){
41292     return SQLITE_ABORT;
41293   }
41294
41295   /* Check some preconditions: 
41296   **   (a) the cursor is open for writing,
41297   **   (b) there is no read-lock on the table being modified and
41298   **   (c) the cursor points at a valid row of an intKey table.
41299   */
41300   if( !pCsr->wrFlag ){
41301     return SQLITE_READONLY;
41302   }
41303   assert( !pCsr->pBt->readOnly 
41304           && pCsr->pBt->inTransaction==TRANS_WRITE );
41305   if( checkReadLocks(pCsr->pBtree, pCsr->pgnoRoot, pCsr, 0) ){
41306     return SQLITE_LOCKED; /* The table pCur points to has a read lock */
41307   }
41308   if( pCsr->eState==CURSOR_INVALID || !pCsr->apPage[pCsr->iPage]->intKey ){
41309     return SQLITE_ERROR;
41310   }
41311
41312   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 0, 1);
41313 }
41314
41315 /* 
41316 ** Set a flag on this cursor to cache the locations of pages from the 
41317 ** overflow list for the current row. This is used by cursors opened
41318 ** for incremental blob IO only.
41319 **
41320 ** This function sets a flag only. The actual page location cache
41321 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
41322 ** accessPayload() (the worker function for sqlite3BtreeData() and
41323 ** sqlite3BtreePutData()).
41324 */
41325 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
41326   assert( cursorHoldsMutex(pCur) );
41327   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
41328   assert(!pCur->isIncrblobHandle);
41329   assert(!pCur->aOverflow);
41330   pCur->isIncrblobHandle = 1;
41331 }
41332 #endif
41333
41334 /************** End of btree.c ***********************************************/
41335 /************** Begin file vdbefifo.c ****************************************/
41336 /*
41337 ** 2005 June 16
41338 **
41339 ** The author disclaims copyright to this source code.  In place of
41340 ** a legal notice, here is a blessing:
41341 **
41342 **    May you do good and not evil.
41343 **    May you find forgiveness for yourself and forgive others.
41344 **    May you share freely, never taking more than you give.
41345 **
41346 *************************************************************************
41347 ** This file implements a FIFO queue of rowids used for processing
41348 ** UPDATE and DELETE statements.
41349 **
41350 ** $Id: vdbefifo.c,v 1.9 2008/11/17 19:18:55 danielk1977 Exp $
41351 */
41352
41353 /*
41354 ** Constants FIFOSIZE_FIRST and FIFOSIZE_MAX are the initial
41355 ** number of entries in a fifo page and the maximum number of
41356 ** entries in a fifo page.
41357 */
41358 #define FIFOSIZE_FIRST (((128-sizeof(FifoPage))/8)+1)
41359 #ifdef SQLITE_MALLOC_SOFT_LIMIT
41360 # define FIFOSIZE_MAX   (int)(((SQLITE_MALLOC_SOFT_LIMIT-sizeof(FifoPage))/8)+1)
41361 #else
41362 # define FIFOSIZE_MAX   (int)(((262144-sizeof(FifoPage))/8)+1)
41363 #endif
41364
41365 /*
41366 ** Allocate a new FifoPage and return a pointer to it.  Return NULL if
41367 ** we run out of memory.  Leave space on the page for nEntry entries.
41368 */
41369 static FifoPage *allocateFifoPage(sqlite3 *db, int nEntry){
41370   FifoPage *pPage;
41371   if( nEntry>FIFOSIZE_MAX ){
41372     nEntry = FIFOSIZE_MAX;
41373   }
41374   pPage = sqlite3DbMallocRaw(db, sizeof(FifoPage) + sizeof(i64)*(nEntry-1) );
41375   if( pPage ){
41376     pPage->nSlot = nEntry;
41377     pPage->iWrite = 0;
41378     pPage->iRead = 0;
41379     pPage->pNext = 0;
41380   }
41381   return pPage;
41382 }
41383
41384 /*
41385 ** Initialize a Fifo structure.
41386 */
41387 SQLITE_PRIVATE void sqlite3VdbeFifoInit(Fifo *pFifo, sqlite3 *db){
41388   memset(pFifo, 0, sizeof(*pFifo));
41389   pFifo->db = db;
41390 }
41391
41392 /*
41393 ** Push a single 64-bit integer value into the Fifo.  Return SQLITE_OK
41394 ** normally.   SQLITE_NOMEM is returned if we are unable to allocate
41395 ** memory.
41396 */
41397 SQLITE_PRIVATE int sqlite3VdbeFifoPush(Fifo *pFifo, i64 val){
41398   FifoPage *pPage;
41399   pPage = pFifo->pLast;
41400   if( pPage==0 ){
41401     pPage = pFifo->pLast = pFifo->pFirst =
41402          allocateFifoPage(pFifo->db, FIFOSIZE_FIRST);
41403     if( pPage==0 ){
41404       return SQLITE_NOMEM;
41405     }
41406   }else if( pPage->iWrite>=pPage->nSlot ){
41407     pPage->pNext = allocateFifoPage(pFifo->db, pFifo->nEntry);
41408     if( pPage->pNext==0 ){
41409       return SQLITE_NOMEM;
41410     }
41411     pPage = pFifo->pLast = pPage->pNext;
41412   }
41413   pPage->aSlot[pPage->iWrite++] = val;
41414   pFifo->nEntry++;
41415   return SQLITE_OK;
41416 }
41417
41418 /*
41419 ** Extract a single 64-bit integer value from the Fifo.  The integer
41420 ** extracted is the one least recently inserted.  If the Fifo is empty
41421 ** return SQLITE_DONE.
41422 */
41423 SQLITE_PRIVATE int sqlite3VdbeFifoPop(Fifo *pFifo, i64 *pVal){
41424   FifoPage *pPage;
41425   if( pFifo->nEntry==0 ){
41426     return SQLITE_DONE;
41427   }
41428   assert( pFifo->nEntry>0 );
41429   pPage = pFifo->pFirst;
41430   assert( pPage!=0 );
41431   assert( pPage->iWrite>pPage->iRead );
41432   assert( pPage->iWrite<=pPage->nSlot );
41433   assert( pPage->iRead<pPage->nSlot );
41434   assert( pPage->iRead>=0 );
41435   *pVal = pPage->aSlot[pPage->iRead++];
41436   pFifo->nEntry--;
41437   if( pPage->iRead>=pPage->iWrite ){
41438     pFifo->pFirst = pPage->pNext;
41439     sqlite3DbFree(pFifo->db, pPage);
41440     if( pFifo->nEntry==0 ){
41441       assert( pFifo->pLast==pPage );
41442       pFifo->pLast = 0;
41443     }else{
41444       assert( pFifo->pFirst!=0 );
41445     }
41446   }else{
41447     assert( pFifo->nEntry>0 );
41448   }
41449   return SQLITE_OK;
41450 }
41451
41452 /*
41453 ** Delete all information from a Fifo object.   Free all memory held
41454 ** by the Fifo.
41455 */
41456 SQLITE_PRIVATE void sqlite3VdbeFifoClear(Fifo *pFifo){
41457   FifoPage *pPage, *pNextPage;
41458   for(pPage=pFifo->pFirst; pPage; pPage=pNextPage){
41459     pNextPage = pPage->pNext;
41460     sqlite3DbFree(pFifo->db, pPage);
41461   }
41462   sqlite3VdbeFifoInit(pFifo, pFifo->db);
41463 }
41464
41465 /************** End of vdbefifo.c ********************************************/
41466 /************** Begin file vdbemem.c *****************************************/
41467 /*
41468 ** 2004 May 26
41469 **
41470 ** The author disclaims copyright to this source code.  In place of
41471 ** a legal notice, here is a blessing:
41472 **
41473 **    May you do good and not evil.
41474 **    May you find forgiveness for yourself and forgive others.
41475 **    May you share freely, never taking more than you give.
41476 **
41477 *************************************************************************
41478 **
41479 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
41480 ** stores a single value in the VDBE.  Mem is an opaque structure visible
41481 ** only within the VDBE.  Interface routines refer to a Mem using the
41482 ** name sqlite_value
41483 **
41484 ** $Id: vdbemem.c,v 1.126 2008/11/11 00:21:30 drh Exp $
41485 */
41486
41487 /*
41488 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
41489 ** P if required.
41490 */
41491 #define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
41492
41493 /*
41494 ** If pMem is an object with a valid string representation, this routine
41495 ** ensures the internal encoding for the string representation is
41496 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
41497 **
41498 ** If pMem is not a string object, or the encoding of the string
41499 ** representation is already stored using the requested encoding, then this
41500 ** routine is a no-op.
41501 **
41502 ** SQLITE_OK is returned if the conversion is successful (or not required).
41503 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
41504 ** between formats.
41505 */
41506 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
41507   int rc;
41508   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
41509     return SQLITE_OK;
41510   }
41511   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41512 #ifdef SQLITE_OMIT_UTF16
41513   return SQLITE_ERROR;
41514 #else
41515
41516   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
41517   ** then the encoding of the value may not have changed.
41518   */
41519   rc = sqlite3VdbeMemTranslate(pMem, desiredEnc);
41520   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
41521   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
41522   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
41523   return rc;
41524 #endif
41525 }
41526
41527 /*
41528 ** Make sure pMem->z points to a writable allocation of at least 
41529 ** n bytes.
41530 **
41531 ** If the memory cell currently contains string or blob data
41532 ** and the third argument passed to this function is true, the 
41533 ** current content of the cell is preserved. Otherwise, it may
41534 ** be discarded.  
41535 **
41536 ** This function sets the MEM_Dyn flag and clears any xDel callback.
41537 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is 
41538 ** not set, Mem.n is zeroed.
41539 */
41540 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
41541   assert( 1 >=
41542     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
41543     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) + 
41544     ((pMem->flags&MEM_Ephem) ? 1 : 0) + 
41545     ((pMem->flags&MEM_Static) ? 1 : 0)
41546   );
41547
41548   if( n<32 ) n = 32;
41549   if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
41550     if( preserve && pMem->z==pMem->zMalloc ){
41551       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
41552       preserve = 0;
41553     }else{
41554       sqlite3DbFree(pMem->db, pMem->zMalloc);
41555       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
41556     }
41557   }
41558
41559   if( preserve && pMem->z && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
41560     memcpy(pMem->zMalloc, pMem->z, pMem->n);
41561   }
41562   if( pMem->flags&MEM_Dyn && pMem->xDel ){
41563     pMem->xDel((void *)(pMem->z));
41564   }
41565
41566   pMem->z = pMem->zMalloc;
41567   if( pMem->z==0 ){
41568     pMem->flags = MEM_Null;
41569   }else{
41570     pMem->flags &= ~(MEM_Ephem|MEM_Static);
41571   }
41572   pMem->xDel = 0;
41573   return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
41574 }
41575
41576 /*
41577 ** Make the given Mem object MEM_Dyn.  In other words, make it so
41578 ** that any TEXT or BLOB content is stored in memory obtained from
41579 ** malloc().  In this way, we know that the memory is safe to be
41580 ** overwritten or altered.
41581 **
41582 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
41583 */
41584 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
41585   int f;
41586   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41587   expandBlob(pMem);
41588   f = pMem->flags;
41589   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
41590     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
41591       return SQLITE_NOMEM;
41592     }
41593     pMem->z[pMem->n] = 0;
41594     pMem->z[pMem->n+1] = 0;
41595     pMem->flags |= MEM_Term;
41596   }
41597
41598   return SQLITE_OK;
41599 }
41600
41601 /*
41602 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
41603 ** blob stored in dynamically allocated space.
41604 */
41605 #ifndef SQLITE_OMIT_INCRBLOB
41606 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
41607   if( pMem->flags & MEM_Zero ){
41608     int nByte;
41609     assert( pMem->flags&MEM_Blob );
41610     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41611
41612     /* Set nByte to the number of bytes required to store the expanded blob. */
41613     nByte = pMem->n + pMem->u.i;
41614     if( nByte<=0 ){
41615       nByte = 1;
41616     }
41617     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
41618       return SQLITE_NOMEM;
41619     }
41620
41621     memset(&pMem->z[pMem->n], 0, pMem->u.i);
41622     pMem->n += pMem->u.i;
41623     pMem->flags &= ~(MEM_Zero|MEM_Term);
41624   }
41625   return SQLITE_OK;
41626 }
41627 #endif
41628
41629
41630 /*
41631 ** Make sure the given Mem is \u0000 terminated.
41632 */
41633 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
41634   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41635   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
41636     return SQLITE_OK;   /* Nothing to do */
41637   }
41638   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
41639     return SQLITE_NOMEM;
41640   }
41641   pMem->z[pMem->n] = 0;
41642   pMem->z[pMem->n+1] = 0;
41643   pMem->flags |= MEM_Term;
41644   return SQLITE_OK;
41645 }
41646
41647 /*
41648 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
41649 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
41650 ** is a no-op.
41651 **
41652 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
41653 **
41654 ** A MEM_Null value will never be passed to this function. This function is
41655 ** used for converting values to text for returning to the user (i.e. via
41656 ** sqlite3_value_text()), or for ensuring that values to be used as btree
41657 ** keys are strings. In the former case a NULL pointer is returned the
41658 ** user and the later is an internal programming error.
41659 */
41660 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
41661   int rc = SQLITE_OK;
41662   int fg = pMem->flags;
41663   const int nByte = 32;
41664
41665   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41666   assert( !(fg&MEM_Zero) );
41667   assert( !(fg&(MEM_Str|MEM_Blob)) );
41668   assert( fg&(MEM_Int|MEM_Real) );
41669
41670   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
41671     return SQLITE_NOMEM;
41672   }
41673
41674   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
41675   ** string representation of the value. Then, if the required encoding
41676   ** is UTF-16le or UTF-16be do a translation.
41677   ** 
41678   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
41679   */
41680   if( fg & MEM_Int ){
41681     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
41682   }else{
41683     assert( fg & MEM_Real );
41684     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
41685   }
41686   pMem->n = strlen(pMem->z);
41687   pMem->enc = SQLITE_UTF8;
41688   pMem->flags |= MEM_Str|MEM_Term;
41689   sqlite3VdbeChangeEncoding(pMem, enc);
41690   return rc;
41691 }
41692
41693 /*
41694 ** Memory cell pMem contains the context of an aggregate function.
41695 ** This routine calls the finalize method for that function.  The
41696 ** result of the aggregate is stored back into pMem.
41697 **
41698 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
41699 ** otherwise.
41700 */
41701 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
41702   int rc = SQLITE_OK;
41703   if( pFunc && pFunc->xFinalize ){
41704     sqlite3_context ctx;
41705     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
41706     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41707     memset(&ctx, 0, sizeof(ctx));
41708     ctx.s.flags = MEM_Null;
41709     ctx.s.db = pMem->db;
41710     ctx.pMem = pMem;
41711     ctx.pFunc = pFunc;
41712     pFunc->xFinalize(&ctx);
41713     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
41714     sqlite3DbFree(pMem->db, pMem->zMalloc);
41715     *pMem = ctx.s;
41716     rc = (ctx.isError?SQLITE_ERROR:SQLITE_OK);
41717   }
41718   return rc;
41719 }
41720
41721 /*
41722 ** If the memory cell contains a string value that must be freed by
41723 ** invoking an external callback, free it now. Calling this function
41724 ** does not free any Mem.zMalloc buffer.
41725 */
41726 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
41727   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
41728   if( p->flags&MEM_Agg ){
41729     sqlite3VdbeMemFinalize(p, p->u.pDef);
41730     assert( (p->flags & MEM_Agg)==0 );
41731     sqlite3VdbeMemRelease(p);
41732   }else if( p->flags&MEM_Dyn && p->xDel ){
41733     p->xDel((void *)p->z);
41734     p->xDel = 0;
41735   }
41736 }
41737
41738 /*
41739 ** Release any memory held by the Mem. This may leave the Mem in an
41740 ** inconsistent state, for example with (Mem.z==0) and
41741 ** (Mem.type==SQLITE_TEXT).
41742 */
41743 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
41744   sqlite3VdbeMemReleaseExternal(p);
41745   sqlite3DbFree(p->db, p->zMalloc);
41746   p->z = 0;
41747   p->zMalloc = 0;
41748   p->xDel = 0;
41749 }
41750
41751 /*
41752 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
41753 ** If the double is too large, return 0x8000000000000000.
41754 **
41755 ** Most systems appear to do this simply by assigning
41756 ** variables and without the extra range tests.  But
41757 ** there are reports that windows throws an expection
41758 ** if the floating point value is out of range. (See ticket #2880.)
41759 ** Because we do not completely understand the problem, we will
41760 ** take the conservative approach and always do range tests
41761 ** before attempting the conversion.
41762 */
41763 static i64 doubleToInt64(double r){
41764   /*
41765   ** Many compilers we encounter do not define constants for the
41766   ** minimum and maximum 64-bit integers, or they define them
41767   ** inconsistently.  And many do not understand the "LL" notation.
41768   ** So we define our own static constants here using nothing
41769   ** larger than a 32-bit integer constant.
41770   */
41771   static const i64 maxInt = LARGEST_INT64;
41772   static const i64 minInt = SMALLEST_INT64;
41773
41774   if( r<(double)minInt ){
41775     return minInt;
41776   }else if( r>(double)maxInt ){
41777     return minInt;
41778   }else{
41779     return (i64)r;
41780   }
41781 }
41782
41783 /*
41784 ** Return some kind of integer value which is the best we can do
41785 ** at representing the value that *pMem describes as an integer.
41786 ** If pMem is an integer, then the value is exact.  If pMem is
41787 ** a floating-point then the value returned is the integer part.
41788 ** If pMem is a string or blob, then we make an attempt to convert
41789 ** it into a integer and return that.  If pMem is NULL, return 0.
41790 **
41791 ** If pMem is a string, its encoding might be changed.
41792 */
41793 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
41794   int flags;
41795   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41796   flags = pMem->flags;
41797   if( flags & MEM_Int ){
41798     return pMem->u.i;
41799   }else if( flags & MEM_Real ){
41800     return doubleToInt64(pMem->r);
41801   }else if( flags & (MEM_Str|MEM_Blob) ){
41802     i64 value;
41803     pMem->flags |= MEM_Str;
41804     if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
41805        || sqlite3VdbeMemNulTerminate(pMem) ){
41806       return 0;
41807     }
41808     assert( pMem->z );
41809     sqlite3Atoi64(pMem->z, &value);
41810     return value;
41811   }else{
41812     return 0;
41813   }
41814 }
41815
41816 /*
41817 ** Return the best representation of pMem that we can get into a
41818 ** double.  If pMem is already a double or an integer, return its
41819 ** value.  If it is a string or blob, try to convert it to a double.
41820 ** If it is a NULL, return 0.0.
41821 */
41822 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
41823   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41824   if( pMem->flags & MEM_Real ){
41825     return pMem->r;
41826   }else if( pMem->flags & MEM_Int ){
41827     return (double)pMem->u.i;
41828   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
41829     double val = 0.0;
41830     pMem->flags |= MEM_Str;
41831     if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
41832        || sqlite3VdbeMemNulTerminate(pMem) ){
41833       return 0.0;
41834     }
41835     assert( pMem->z );
41836     sqlite3AtoF(pMem->z, &val);
41837     return val;
41838   }else{
41839     return 0.0;
41840   }
41841 }
41842
41843 /*
41844 ** The MEM structure is already a MEM_Real.  Try to also make it a
41845 ** MEM_Int if we can.
41846 */
41847 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
41848   assert( pMem->flags & MEM_Real );
41849   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41850
41851   pMem->u.i = doubleToInt64(pMem->r);
41852   if( pMem->r==(double)pMem->u.i ){
41853     pMem->flags |= MEM_Int;
41854   }
41855 }
41856
41857 static void setTypeFlag(Mem *pMem, int f){
41858   MemSetTypeFlag(pMem, f);
41859 }
41860
41861 /*
41862 ** Convert pMem to type integer.  Invalidate any prior representations.
41863 */
41864 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
41865   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41866   pMem->u.i = sqlite3VdbeIntValue(pMem);
41867   setTypeFlag(pMem, MEM_Int);
41868   return SQLITE_OK;
41869 }
41870
41871 /*
41872 ** Convert pMem so that it is of type MEM_Real.
41873 ** Invalidate any prior representations.
41874 */
41875 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
41876   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41877   pMem->r = sqlite3VdbeRealValue(pMem);
41878   setTypeFlag(pMem, MEM_Real);
41879   return SQLITE_OK;
41880 }
41881
41882 /*
41883 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
41884 ** Invalidate any prior representations.
41885 */
41886 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
41887   double r1, r2;
41888   i64 i;
41889   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 );
41890   assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
41891   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41892   r1 = sqlite3VdbeRealValue(pMem);
41893   i = doubleToInt64(r1);
41894   r2 = (double)i;
41895   if( r1==r2 ){
41896     sqlite3VdbeMemIntegerify(pMem);
41897   }else{
41898     pMem->r = r1;
41899     setTypeFlag(pMem, MEM_Real);
41900   }
41901   return SQLITE_OK;
41902 }
41903
41904 /*
41905 ** Delete any previous value and set the value stored in *pMem to NULL.
41906 */
41907 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
41908   setTypeFlag(pMem, MEM_Null);
41909   pMem->type = SQLITE_NULL;
41910 }
41911
41912 /*
41913 ** Delete any previous value and set the value to be a BLOB of length
41914 ** n containing all zeros.
41915 */
41916 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
41917   sqlite3VdbeMemRelease(pMem);
41918   setTypeFlag(pMem, MEM_Blob);
41919   pMem->flags = MEM_Blob|MEM_Zero;
41920   pMem->type = SQLITE_BLOB;
41921   pMem->n = 0;
41922   if( n<0 ) n = 0;
41923   pMem->u.i = n;
41924   pMem->enc = SQLITE_UTF8;
41925 }
41926
41927 /*
41928 ** Delete any previous value and set the value stored in *pMem to val,
41929 ** manifest type INTEGER.
41930 */
41931 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
41932   sqlite3VdbeMemRelease(pMem);
41933   pMem->u.i = val;
41934   pMem->flags = MEM_Int;
41935   pMem->type = SQLITE_INTEGER;
41936 }
41937
41938 /*
41939 ** Delete any previous value and set the value stored in *pMem to val,
41940 ** manifest type REAL.
41941 */
41942 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
41943   if( sqlite3IsNaN(val) ){
41944     sqlite3VdbeMemSetNull(pMem);
41945   }else{
41946     sqlite3VdbeMemRelease(pMem);
41947     pMem->r = val;
41948     pMem->flags = MEM_Real;
41949     pMem->type = SQLITE_FLOAT;
41950   }
41951 }
41952
41953 /*
41954 ** Return true if the Mem object contains a TEXT or BLOB that is
41955 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
41956 */
41957 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
41958   assert( p->db!=0 );
41959   if( p->flags & (MEM_Str|MEM_Blob) ){
41960     int n = p->n;
41961     if( p->flags & MEM_Zero ){
41962       n += p->u.i;
41963     }
41964     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
41965   }
41966   return 0; 
41967 }
41968
41969 /*
41970 ** Size of struct Mem not including the Mem.zMalloc member.
41971 */
41972 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
41973
41974 /*
41975 ** Make an shallow copy of pFrom into pTo.  Prior contents of
41976 ** pTo are freed.  The pFrom->z field is not duplicated.  If
41977 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
41978 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
41979 */
41980 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
41981   sqlite3VdbeMemReleaseExternal(pTo);
41982   memcpy(pTo, pFrom, MEMCELLSIZE);
41983   pTo->xDel = 0;
41984   if( (pFrom->flags&MEM_Dyn)!=0 || pFrom->z==pFrom->zMalloc ){
41985     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
41986     assert( srcType==MEM_Ephem || srcType==MEM_Static );
41987     pTo->flags |= srcType;
41988   }
41989 }
41990
41991 /*
41992 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
41993 ** freed before the copy is made.
41994 */
41995 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
41996   int rc = SQLITE_OK;
41997
41998   sqlite3VdbeMemReleaseExternal(pTo);
41999   memcpy(pTo, pFrom, MEMCELLSIZE);
42000   pTo->flags &= ~MEM_Dyn;
42001
42002   if( pTo->flags&(MEM_Str|MEM_Blob) ){
42003     if( 0==(pFrom->flags&MEM_Static) ){
42004       pTo->flags |= MEM_Ephem;
42005       rc = sqlite3VdbeMemMakeWriteable(pTo);
42006     }
42007   }
42008
42009   return rc;
42010 }
42011
42012 /*
42013 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
42014 ** freed. If pFrom contains ephemeral data, a copy is made.
42015 **
42016 ** pFrom contains an SQL NULL when this routine returns.
42017 */
42018 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
42019   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
42020   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
42021   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
42022
42023   sqlite3VdbeMemRelease(pTo);
42024   memcpy(pTo, pFrom, sizeof(Mem));
42025   pFrom->flags = MEM_Null;
42026   pFrom->xDel = 0;
42027   pFrom->zMalloc = 0;
42028 }
42029
42030 /*
42031 ** Change the value of a Mem to be a string or a BLOB.
42032 **
42033 ** The memory management strategy depends on the value of the xDel
42034 ** parameter. If the value passed is SQLITE_TRANSIENT, then the 
42035 ** string is copied into a (possibly existing) buffer managed by the 
42036 ** Mem structure. Otherwise, any existing buffer is freed and the
42037 ** pointer copied.
42038 */
42039 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
42040   Mem *pMem,          /* Memory cell to set to string value */
42041   const char *z,      /* String pointer */
42042   int n,              /* Bytes in string, or negative */
42043   u8 enc,             /* Encoding of z.  0 for BLOBs */
42044   void (*xDel)(void*) /* Destructor function */
42045 ){
42046   int nByte = n;      /* New value for pMem->n */
42047   int iLimit;         /* Maximum allowed string or blob size */
42048   int flags = 0;      /* New value for pMem->flags */
42049
42050   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
42051
42052   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
42053   if( !z ){
42054     sqlite3VdbeMemSetNull(pMem);
42055     return SQLITE_OK;
42056   }
42057
42058   if( pMem->db ){
42059     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
42060   }else{
42061     iLimit = SQLITE_MAX_LENGTH;
42062   }
42063   flags = (enc==0?MEM_Blob:MEM_Str);
42064   if( nByte<0 ){
42065     assert( enc!=0 );
42066     if( enc==SQLITE_UTF8 ){
42067       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
42068     }else{
42069       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
42070     }
42071     flags |= MEM_Term;
42072   }
42073
42074   /* The following block sets the new values of Mem.z and Mem.xDel. It
42075   ** also sets a flag in local variable "flags" to indicate the memory
42076   ** management (one of MEM_Dyn or MEM_Static).
42077   */
42078   if( xDel==SQLITE_TRANSIENT ){
42079     int nAlloc = nByte;
42080     if( flags&MEM_Term ){
42081       nAlloc += (enc==SQLITE_UTF8?1:2);
42082     }
42083     if( nByte>iLimit ){
42084       return SQLITE_TOOBIG;
42085     }
42086     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
42087       return SQLITE_NOMEM;
42088     }
42089     memcpy(pMem->z, z, nAlloc);
42090   }else if( xDel==SQLITE_DYNAMIC ){
42091     sqlite3VdbeMemRelease(pMem);
42092     pMem->zMalloc = pMem->z = (char *)z;
42093     pMem->xDel = 0;
42094   }else{
42095     sqlite3VdbeMemRelease(pMem);
42096     pMem->z = (char *)z;
42097     pMem->xDel = xDel;
42098     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
42099   }
42100   if( nByte>iLimit ){
42101     return SQLITE_TOOBIG;
42102   }
42103
42104   pMem->n = nByte;
42105   pMem->flags = flags;
42106   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
42107   pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
42108
42109 #ifndef SQLITE_OMIT_UTF16
42110   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
42111     return SQLITE_NOMEM;
42112   }
42113 #endif
42114
42115   return SQLITE_OK;
42116 }
42117
42118 /*
42119 ** Compare the values contained by the two memory cells, returning
42120 ** negative, zero or positive if pMem1 is less than, equal to, or greater
42121 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
42122 ** and reals) sorted numerically, followed by text ordered by the collating
42123 ** sequence pColl and finally blob's ordered by memcmp().
42124 **
42125 ** Two NULL values are considered equal by this function.
42126 */
42127 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
42128   int rc;
42129   int f1, f2;
42130   int combined_flags;
42131
42132   /* Interchange pMem1 and pMem2 if the collating sequence specifies
42133   ** DESC order.
42134   */
42135   f1 = pMem1->flags;
42136   f2 = pMem2->flags;
42137   combined_flags = f1|f2;
42138  
42139   /* If one value is NULL, it is less than the other. If both values
42140   ** are NULL, return 0.
42141   */
42142   if( combined_flags&MEM_Null ){
42143     return (f2&MEM_Null) - (f1&MEM_Null);
42144   }
42145
42146   /* If one value is a number and the other is not, the number is less.
42147   ** If both are numbers, compare as reals if one is a real, or as integers
42148   ** if both values are integers.
42149   */
42150   if( combined_flags&(MEM_Int|MEM_Real) ){
42151     if( !(f1&(MEM_Int|MEM_Real)) ){
42152       return 1;
42153     }
42154     if( !(f2&(MEM_Int|MEM_Real)) ){
42155       return -1;
42156     }
42157     if( (f1 & f2 & MEM_Int)==0 ){
42158       double r1, r2;
42159       if( (f1&MEM_Real)==0 ){
42160         r1 = pMem1->u.i;
42161       }else{
42162         r1 = pMem1->r;
42163       }
42164       if( (f2&MEM_Real)==0 ){
42165         r2 = pMem2->u.i;
42166       }else{
42167         r2 = pMem2->r;
42168       }
42169       if( r1<r2 ) return -1;
42170       if( r1>r2 ) return 1;
42171       return 0;
42172     }else{
42173       assert( f1&MEM_Int );
42174       assert( f2&MEM_Int );
42175       if( pMem1->u.i < pMem2->u.i ) return -1;
42176       if( pMem1->u.i > pMem2->u.i ) return 1;
42177       return 0;
42178     }
42179   }
42180
42181   /* If one value is a string and the other is a blob, the string is less.
42182   ** If both are strings, compare using the collating functions.
42183   */
42184   if( combined_flags&MEM_Str ){
42185     if( (f1 & MEM_Str)==0 ){
42186       return 1;
42187     }
42188     if( (f2 & MEM_Str)==0 ){
42189       return -1;
42190     }
42191
42192     assert( pMem1->enc==pMem2->enc );
42193     assert( pMem1->enc==SQLITE_UTF8 || 
42194             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
42195
42196     /* The collation sequence must be defined at this point, even if
42197     ** the user deletes the collation sequence after the vdbe program is
42198     ** compiled (this was not always the case).
42199     */
42200     assert( !pColl || pColl->xCmp );
42201
42202     if( pColl ){
42203       if( pMem1->enc==pColl->enc ){
42204         /* The strings are already in the correct encoding.  Call the
42205         ** comparison function directly */
42206         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
42207       }else{
42208         const void *v1, *v2;
42209         int n1, n2;
42210         Mem c1;
42211         Mem c2;
42212         memset(&c1, 0, sizeof(c1));
42213         memset(&c2, 0, sizeof(c2));
42214         sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
42215         sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
42216         v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
42217         n1 = v1==0 ? 0 : c1.n;
42218         v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
42219         n2 = v2==0 ? 0 : c2.n;
42220         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
42221         sqlite3VdbeMemRelease(&c1);
42222         sqlite3VdbeMemRelease(&c2);
42223         return rc;
42224       }
42225     }
42226     /* If a NULL pointer was passed as the collate function, fall through
42227     ** to the blob case and use memcmp().  */
42228   }
42229  
42230   /* Both values must be blobs.  Compare using memcmp().  */
42231   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
42232   if( rc==0 ){
42233     rc = pMem1->n - pMem2->n;
42234   }
42235   return rc;
42236 }
42237
42238 /*
42239 ** Move data out of a btree key or data field and into a Mem structure.
42240 ** The data or key is taken from the entry that pCur is currently pointing
42241 ** to.  offset and amt determine what portion of the data or key to retrieve.
42242 ** key is true to get the key or false to get data.  The result is written
42243 ** into the pMem element.
42244 **
42245 ** The pMem structure is assumed to be uninitialized.  Any prior content
42246 ** is overwritten without being freed.
42247 **
42248 ** If this routine fails for any reason (malloc returns NULL or unable
42249 ** to read from the disk) then the pMem is left in an inconsistent state.
42250 */
42251 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
42252   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
42253   int offset,       /* Offset from the start of data to return bytes from. */
42254   int amt,          /* Number of bytes to return. */
42255   int key,          /* If true, retrieve from the btree key, not data. */
42256   Mem *pMem         /* OUT: Return data in this Mem structure. */
42257 ){
42258   char *zData;       /* Data from the btree layer */
42259   int available = 0; /* Number of bytes available on the local btree page */
42260   sqlite3 *db;       /* Database connection */
42261   int rc = SQLITE_OK;
42262
42263   db = sqlite3BtreeCursorDb(pCur);
42264   assert( sqlite3_mutex_held(db->mutex) );
42265   if( key ){
42266     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
42267   }else{
42268     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
42269   }
42270   assert( zData!=0 );
42271
42272   if( offset+amt<=available && ((pMem->flags&MEM_Dyn)==0 || pMem->xDel) ){
42273     sqlite3VdbeMemRelease(pMem);
42274     pMem->z = &zData[offset];
42275     pMem->flags = MEM_Blob|MEM_Ephem;
42276   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
42277     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
42278     pMem->enc = 0;
42279     pMem->type = SQLITE_BLOB;
42280     if( key ){
42281       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
42282     }else{
42283       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
42284     }
42285     pMem->z[amt] = 0;
42286     pMem->z[amt+1] = 0;
42287     if( rc!=SQLITE_OK ){
42288       sqlite3VdbeMemRelease(pMem);
42289     }
42290   }
42291   pMem->n = amt;
42292
42293   return rc;
42294 }
42295
42296 #if 0
42297 /*
42298 ** Perform various checks on the memory cell pMem. An assert() will
42299 ** fail if pMem is internally inconsistent.
42300 */
42301 SQLITE_PRIVATE void sqlite3VdbeMemSanity(Mem *pMem){
42302   int flags = pMem->flags;
42303   assert( flags!=0 );  /* Must define some type */
42304   if( flags & (MEM_Str|MEM_Blob) ){
42305     int x = flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short);
42306     assert( x!=0 );            /* Strings must define a string subtype */
42307     assert( (x & (x-1))==0 );  /* Only one string subtype can be defined */
42308     assert( pMem->z!=0 );      /* Strings must have a value */
42309     /* Mem.z points to Mem.zShort iff the subtype is MEM_Short */
42310     assert( (x & MEM_Short)==0 || pMem->z==pMem->zShort );
42311     assert( (x & MEM_Short)!=0 || pMem->z!=pMem->zShort );
42312     /* No destructor unless there is MEM_Dyn */
42313     assert( pMem->xDel==0 || (pMem->flags & MEM_Dyn)!=0 );
42314
42315     if( (flags & MEM_Str) ){
42316       assert( pMem->enc==SQLITE_UTF8 || 
42317               pMem->enc==SQLITE_UTF16BE ||
42318               pMem->enc==SQLITE_UTF16LE 
42319       );
42320       /* If the string is UTF-8 encoded and nul terminated, then pMem->n
42321       ** must be the length of the string.  (Later:)  If the database file
42322       ** has been corrupted, '\000' characters might have been inserted
42323       ** into the middle of the string.  In that case, the strlen() might
42324       ** be less.
42325       */
42326       if( pMem->enc==SQLITE_UTF8 && (flags & MEM_Term) ){ 
42327         assert( strlen(pMem->z)<=pMem->n );
42328         assert( pMem->z[pMem->n]==0 );
42329       }
42330     }
42331   }else{
42332     /* Cannot define a string subtype for non-string objects */
42333     assert( (pMem->flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short))==0 );
42334     assert( pMem->xDel==0 );
42335   }
42336   /* MEM_Null excludes all other types */
42337   assert( (pMem->flags&(MEM_Str|MEM_Int|MEM_Real|MEM_Blob))==0
42338           || (pMem->flags&MEM_Null)==0 );
42339   /* If the MEM is both real and integer, the values are equal */
42340   assert( (pMem->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) 
42341           || pMem->r==pMem->u.i );
42342 }
42343 #endif
42344
42345 /* This function is only available internally, it is not part of the
42346 ** external API. It works in a similar way to sqlite3_value_text(),
42347 ** except the data returned is in the encoding specified by the second
42348 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
42349 ** SQLITE_UTF8.
42350 **
42351 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
42352 ** If that is the case, then the result must be aligned on an even byte
42353 ** boundary.
42354 */
42355 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
42356   if( !pVal ) return 0;
42357
42358   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
42359   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
42360
42361   if( pVal->flags&MEM_Null ){
42362     return 0;
42363   }
42364   assert( (MEM_Blob>>3) == MEM_Str );
42365   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
42366   expandBlob(pVal);
42367   if( pVal->flags&MEM_Str ){
42368     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
42369     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
42370       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
42371       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
42372         return 0;
42373       }
42374     }
42375     sqlite3VdbeMemNulTerminate(pVal);
42376   }else{
42377     assert( (pVal->flags&MEM_Blob)==0 );
42378     sqlite3VdbeMemStringify(pVal, enc);
42379     assert( 0==(1&(int)pVal->z) );
42380   }
42381   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
42382               || pVal->db->mallocFailed );
42383   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
42384     return pVal->z;
42385   }else{
42386     return 0;
42387   }
42388 }
42389
42390 /*
42391 ** Create a new sqlite3_value object.
42392 */
42393 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
42394   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
42395   if( p ){
42396     p->flags = MEM_Null;
42397     p->type = SQLITE_NULL;
42398     p->db = db;
42399   }
42400   return p;
42401 }
42402
42403 /*
42404 ** Create a new sqlite3_value object, containing the value of pExpr.
42405 **
42406 ** This only works for very simple expressions that consist of one constant
42407 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
42408 ** be converted directly into a value, then the value is allocated and
42409 ** a pointer written to *ppVal. The caller is responsible for deallocating
42410 ** the value by passing it to sqlite3ValueFree() later on. If the expression
42411 ** cannot be converted to a value, then *ppVal is set to NULL.
42412 */
42413 SQLITE_PRIVATE int sqlite3ValueFromExpr(
42414   sqlite3 *db,              /* The database connection */
42415   Expr *pExpr,              /* The expression to evaluate */
42416   u8 enc,                   /* Encoding to use */
42417   u8 affinity,              /* Affinity to use */
42418   sqlite3_value **ppVal     /* Write the new value here */
42419 ){
42420   int op;
42421   char *zVal = 0;
42422   sqlite3_value *pVal = 0;
42423
42424   if( !pExpr ){
42425     *ppVal = 0;
42426     return SQLITE_OK;
42427   }
42428   op = pExpr->op;
42429
42430   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
42431     zVal = sqlite3DbStrNDup(db, (char*)pExpr->token.z, pExpr->token.n);
42432     pVal = sqlite3ValueNew(db);
42433     if( !zVal || !pVal ) goto no_mem;
42434     sqlite3Dequote(zVal);
42435     sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
42436     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
42437       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, enc);
42438     }else{
42439       sqlite3ValueApplyAffinity(pVal, affinity, enc);
42440     }
42441   }else if( op==TK_UMINUS ) {
42442     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
42443       pVal->u.i = -1 * pVal->u.i;
42444       pVal->r = -1.0 * pVal->r;
42445     }
42446   }
42447 #ifndef SQLITE_OMIT_BLOB_LITERAL
42448   else if( op==TK_BLOB ){
42449     int nVal;
42450     assert( pExpr->token.n>=3 );
42451     assert( pExpr->token.z[0]=='x' || pExpr->token.z[0]=='X' );
42452     assert( pExpr->token.z[1]=='\'' );
42453     assert( pExpr->token.z[pExpr->token.n-1]=='\'' );
42454     pVal = sqlite3ValueNew(db);
42455     if( !pVal ) goto no_mem;
42456     nVal = pExpr->token.n - 3;
42457     zVal = (char*)pExpr->token.z + 2;
42458     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
42459                          0, SQLITE_DYNAMIC);
42460   }
42461 #endif
42462
42463   *ppVal = pVal;
42464   return SQLITE_OK;
42465
42466 no_mem:
42467   db->mallocFailed = 1;
42468   sqlite3DbFree(db, zVal);
42469   sqlite3ValueFree(pVal);
42470   *ppVal = 0;
42471   return SQLITE_NOMEM;
42472 }
42473
42474 /*
42475 ** Change the string value of an sqlite3_value object
42476 */
42477 SQLITE_PRIVATE void sqlite3ValueSetStr(
42478   sqlite3_value *v,     /* Value to be set */
42479   int n,                /* Length of string z */
42480   const void *z,        /* Text of the new string */
42481   u8 enc,               /* Encoding to use */
42482   void (*xDel)(void*)   /* Destructor for the string */
42483 ){
42484   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
42485 }
42486
42487 /*
42488 ** Free an sqlite3_value object
42489 */
42490 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
42491   if( !v ) return;
42492   sqlite3VdbeMemRelease((Mem *)v);
42493   sqlite3DbFree(((Mem*)v)->db, v);
42494 }
42495
42496 /*
42497 ** Return the number of bytes in the sqlite3_value object assuming
42498 ** that it uses the encoding "enc"
42499 */
42500 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
42501   Mem *p = (Mem*)pVal;
42502   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
42503     if( p->flags & MEM_Zero ){
42504       return p->n+p->u.i;
42505     }else{
42506       return p->n;
42507     }
42508   }
42509   return 0;
42510 }
42511
42512 /************** End of vdbemem.c *********************************************/
42513 /************** Begin file vdbeaux.c *****************************************/
42514 /*
42515 ** 2003 September 6
42516 **
42517 ** The author disclaims copyright to this source code.  In place of
42518 ** a legal notice, here is a blessing:
42519 **
42520 **    May you do good and not evil.
42521 **    May you find forgiveness for yourself and forgive others.
42522 **    May you share freely, never taking more than you give.
42523 **
42524 *************************************************************************
42525 ** This file contains code used for creating, destroying, and populating
42526 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
42527 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
42528 ** But that file was getting too big so this subroutines were split out.
42529 **
42530 ** $Id: vdbeaux.c,v 1.420 2008/11/17 19:18:55 danielk1977 Exp $
42531 */
42532
42533
42534
42535 /*
42536 ** When debugging the code generator in a symbolic debugger, one can
42537 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
42538 ** as they are added to the instruction stream.
42539 */
42540 #ifdef SQLITE_DEBUG
42541 SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
42542 #endif
42543
42544
42545 /*
42546 ** Create a new virtual database engine.
42547 */
42548 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
42549   Vdbe *p;
42550   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
42551   if( p==0 ) return 0;
42552   p->db = db;
42553   if( db->pVdbe ){
42554     db->pVdbe->pPrev = p;
42555   }
42556   p->pNext = db->pVdbe;
42557   p->pPrev = 0;
42558   db->pVdbe = p;
42559   p->magic = VDBE_MAGIC_INIT;
42560   return p;
42561 }
42562
42563 /*
42564 ** Remember the SQL string for a prepared statement.
42565 */
42566 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n){
42567   if( p==0 ) return;
42568   assert( p->zSql==0 );
42569   p->zSql = sqlite3DbStrNDup(p->db, z, n);
42570 }
42571
42572 /*
42573 ** Return the SQL associated with a prepared statement
42574 */
42575 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
42576   return ((Vdbe *)pStmt)->zSql;
42577 }
42578
42579 /*
42580 ** Swap all content between two VDBE structures.
42581 */
42582 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
42583   Vdbe tmp, *pTmp;
42584   char *zTmp;
42585   int nTmp;
42586   tmp = *pA;
42587   *pA = *pB;
42588   *pB = tmp;
42589   pTmp = pA->pNext;
42590   pA->pNext = pB->pNext;
42591   pB->pNext = pTmp;
42592   pTmp = pA->pPrev;
42593   pA->pPrev = pB->pPrev;
42594   pB->pPrev = pTmp;
42595   zTmp = pA->zSql;
42596   pA->zSql = pB->zSql;
42597   pB->zSql = zTmp;
42598   nTmp = pA->nSql;
42599   pA->nSql = pB->nSql;
42600   pB->nSql = nTmp;
42601 }
42602
42603 #ifdef SQLITE_DEBUG
42604 /*
42605 ** Turn tracing on or off
42606 */
42607 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
42608   p->trace = trace;
42609 }
42610 #endif
42611
42612 /*
42613 ** Resize the Vdbe.aOp array so that it is at least one op larger than 
42614 ** it was.
42615 **
42616 ** If an out-of-memory error occurs while resizing the array, return
42617 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain 
42618 ** unchanged (this is so that any opcodes already allocated can be 
42619 ** correctly deallocated along with the rest of the Vdbe).
42620 */
42621 static int growOpArray(Vdbe *p){
42622   VdbeOp *pNew;
42623   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
42624   pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
42625   if( pNew ){
42626     p->nOpAlloc = nNew;
42627     p->aOp = pNew;
42628   }
42629   return (pNew ? SQLITE_OK : SQLITE_NOMEM);
42630 }
42631
42632 /*
42633 ** Add a new instruction to the list of instructions current in the
42634 ** VDBE.  Return the address of the new instruction.
42635 **
42636 ** Parameters:
42637 **
42638 **    p               Pointer to the VDBE
42639 **
42640 **    op              The opcode for this instruction
42641 **
42642 **    p1, p2, p3      Operands
42643 **
42644 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
42645 ** the sqlite3VdbeChangeP4() function to change the value of the P4
42646 ** operand.
42647 */
42648 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
42649   int i;
42650   VdbeOp *pOp;
42651
42652   i = p->nOp;
42653   assert( p->magic==VDBE_MAGIC_INIT );
42654   if( p->nOpAlloc<=i ){
42655     if( growOpArray(p) ){
42656       return 0;
42657     }
42658   }
42659   p->nOp++;
42660   pOp = &p->aOp[i];
42661   pOp->opcode = op;
42662   pOp->p5 = 0;
42663   pOp->p1 = p1;
42664   pOp->p2 = p2;
42665   pOp->p3 = p3;
42666   pOp->p4.p = 0;
42667   pOp->p4type = P4_NOTUSED;
42668   p->expired = 0;
42669 #ifdef SQLITE_DEBUG
42670   pOp->zComment = 0;
42671   if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
42672 #endif
42673 #ifdef VDBE_PROFILE
42674   pOp->cycles = 0;
42675   pOp->cnt = 0;
42676 #endif
42677   return i;
42678 }
42679 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
42680   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
42681 }
42682 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
42683   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
42684 }
42685 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
42686   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
42687 }
42688
42689
42690 /*
42691 ** Add an opcode that includes the p4 value as a pointer.
42692 */
42693 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
42694   Vdbe *p,            /* Add the opcode to this VM */
42695   int op,             /* The new opcode */
42696   int p1,             /* The P1 operand */
42697   int p2,             /* The P2 operand */
42698   int p3,             /* The P3 operand */
42699   const char *zP4,    /* The P4 operand */
42700   int p4type          /* P4 operand type */
42701 ){
42702   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
42703   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
42704   return addr;
42705 }
42706
42707 /*
42708 ** Create a new symbolic label for an instruction that has yet to be
42709 ** coded.  The symbolic label is really just a negative number.  The
42710 ** label can be used as the P2 value of an operation.  Later, when
42711 ** the label is resolved to a specific address, the VDBE will scan
42712 ** through its operation list and change all values of P2 which match
42713 ** the label into the resolved address.
42714 **
42715 ** The VDBE knows that a P2 value is a label because labels are
42716 ** always negative and P2 values are suppose to be non-negative.
42717 ** Hence, a negative P2 value is a label that has yet to be resolved.
42718 **
42719 ** Zero is returned if a malloc() fails.
42720 */
42721 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
42722   int i;
42723   i = p->nLabel++;
42724   assert( p->magic==VDBE_MAGIC_INIT );
42725   if( i>=p->nLabelAlloc ){
42726     p->nLabelAlloc = p->nLabelAlloc*2 + 10;
42727     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
42728                                     p->nLabelAlloc*sizeof(p->aLabel[0]));
42729   }
42730   if( p->aLabel ){
42731     p->aLabel[i] = -1;
42732   }
42733   return -1-i;
42734 }
42735
42736 /*
42737 ** Resolve label "x" to be the address of the next instruction to
42738 ** be inserted.  The parameter "x" must have been obtained from
42739 ** a prior call to sqlite3VdbeMakeLabel().
42740 */
42741 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
42742   int j = -1-x;
42743   assert( p->magic==VDBE_MAGIC_INIT );
42744   assert( j>=0 && j<p->nLabel );
42745   if( p->aLabel ){
42746     p->aLabel[j] = p->nOp;
42747   }
42748 }
42749
42750 /*
42751 ** Loop through the program looking for P2 values that are negative
42752 ** on jump instructions.  Each such value is a label.  Resolve the
42753 ** label by setting the P2 value to its correct non-zero value.
42754 **
42755 ** This routine is called once after all opcodes have been inserted.
42756 **
42757 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
42758 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by 
42759 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
42760 **
42761 ** This routine also does the following optimization:  It scans for
42762 ** instructions that might cause a statement rollback.  Such instructions
42763 ** are:
42764 **
42765 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
42766 **   *  OP_Destroy
42767 **   *  OP_VUpdate
42768 **   *  OP_VRename
42769 **
42770 ** If no such instruction is found, then every Statement instruction 
42771 ** is changed to a Noop.  In this way, we avoid creating the statement 
42772 ** journal file unnecessarily.
42773 */
42774 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
42775   int i;
42776   int nMaxArgs = 0;
42777   Op *pOp;
42778   int *aLabel = p->aLabel;
42779   int doesStatementRollback = 0;
42780   int hasStatementBegin = 0;
42781   p->readOnly = 1;
42782   p->usesStmtJournal = 0;
42783   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
42784     u8 opcode = pOp->opcode;
42785
42786     if( opcode==OP_Function || opcode==OP_AggStep ){
42787       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
42788 #ifndef SQLITE_OMIT_VIRTUALTABLE
42789     }else if( opcode==OP_VUpdate ){
42790       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
42791 #endif
42792     }
42793     if( opcode==OP_Halt ){
42794       if( pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort ){
42795         doesStatementRollback = 1;
42796       }
42797     }else if( opcode==OP_Statement ){
42798       hasStatementBegin = 1;
42799       p->usesStmtJournal = 1;
42800     }else if( opcode==OP_Destroy ){
42801       doesStatementRollback = 1;
42802     }else if( opcode==OP_Transaction && pOp->p2!=0 ){
42803       p->readOnly = 0;
42804 #ifndef SQLITE_OMIT_VIRTUALTABLE
42805     }else if( opcode==OP_VUpdate || opcode==OP_VRename ){
42806       doesStatementRollback = 1;
42807     }else if( opcode==OP_VFilter ){
42808       int n;
42809       assert( p->nOp - i >= 3 );
42810       assert( pOp[-1].opcode==OP_Integer );
42811       n = pOp[-1].p1;
42812       if( n>nMaxArgs ) nMaxArgs = n;
42813 #endif
42814     }
42815
42816     if( sqlite3VdbeOpcodeHasProperty(opcode, OPFLG_JUMP) && pOp->p2<0 ){
42817       assert( -1-pOp->p2<p->nLabel );
42818       pOp->p2 = aLabel[-1-pOp->p2];
42819     }
42820   }
42821   sqlite3DbFree(p->db, p->aLabel);
42822   p->aLabel = 0;
42823
42824   *pMaxFuncArgs = nMaxArgs;
42825
42826   /* If we never rollback a statement transaction, then statement
42827   ** transactions are not needed.  So change every OP_Statement
42828   ** opcode into an OP_Noop.  This avoid a call to sqlite3OsOpenExclusive()
42829   ** which can be expensive on some platforms.
42830   */
42831   if( hasStatementBegin && !doesStatementRollback ){
42832     p->usesStmtJournal = 0;
42833     for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
42834       if( pOp->opcode==OP_Statement ){
42835         pOp->opcode = OP_Noop;
42836       }
42837     }
42838   }
42839 }
42840
42841 /*
42842 ** Return the address of the next instruction to be inserted.
42843 */
42844 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
42845   assert( p->magic==VDBE_MAGIC_INIT );
42846   return p->nOp;
42847 }
42848
42849 /*
42850 ** Add a whole list of operations to the operation stack.  Return the
42851 ** address of the first operation added.
42852 */
42853 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
42854   int addr;
42855   assert( p->magic==VDBE_MAGIC_INIT );
42856   if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
42857     return 0;
42858   }
42859   addr = p->nOp;
42860   if( nOp>0 ){
42861     int i;
42862     VdbeOpList const *pIn = aOp;
42863     for(i=0; i<nOp; i++, pIn++){
42864       int p2 = pIn->p2;
42865       VdbeOp *pOut = &p->aOp[i+addr];
42866       pOut->opcode = pIn->opcode;
42867       pOut->p1 = pIn->p1;
42868       if( p2<0 && sqlite3VdbeOpcodeHasProperty(pOut->opcode, OPFLG_JUMP) ){
42869         pOut->p2 = addr + ADDR(p2);
42870       }else{
42871         pOut->p2 = p2;
42872       }
42873       pOut->p3 = pIn->p3;
42874       pOut->p4type = P4_NOTUSED;
42875       pOut->p4.p = 0;
42876       pOut->p5 = 0;
42877 #ifdef SQLITE_DEBUG
42878       pOut->zComment = 0;
42879       if( sqlite3VdbeAddopTrace ){
42880         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
42881       }
42882 #endif
42883     }
42884     p->nOp += nOp;
42885   }
42886   return addr;
42887 }
42888
42889 /*
42890 ** Change the value of the P1 operand for a specific instruction.
42891 ** This routine is useful when a large program is loaded from a
42892 ** static array using sqlite3VdbeAddOpList but we want to make a
42893 ** few minor changes to the program.
42894 */
42895 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
42896   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
42897   if( p && addr>=0 && p->nOp>addr && p->aOp ){
42898     p->aOp[addr].p1 = val;
42899   }
42900 }
42901
42902 /*
42903 ** Change the value of the P2 operand for a specific instruction.
42904 ** This routine is useful for setting a jump destination.
42905 */
42906 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
42907   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
42908   if( p && addr>=0 && p->nOp>addr && p->aOp ){
42909     p->aOp[addr].p2 = val;
42910   }
42911 }
42912
42913 /*
42914 ** Change the value of the P3 operand for a specific instruction.
42915 */
42916 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
42917   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
42918   if( p && addr>=0 && p->nOp>addr && p->aOp ){
42919     p->aOp[addr].p3 = val;
42920   }
42921 }
42922
42923 /*
42924 ** Change the value of the P5 operand for the most recently
42925 ** added operation.
42926 */
42927 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
42928   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
42929   if( p && p->aOp ){
42930     assert( p->nOp>0 );
42931     p->aOp[p->nOp-1].p5 = val;
42932   }
42933 }
42934
42935 /*
42936 ** Change the P2 operand of instruction addr so that it points to
42937 ** the address of the next instruction to be coded.
42938 */
42939 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
42940   sqlite3VdbeChangeP2(p, addr, p->nOp);
42941 }
42942
42943
42944 /*
42945 ** If the input FuncDef structure is ephemeral, then free it.  If
42946 ** the FuncDef is not ephermal, then do nothing.
42947 */
42948 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
42949   if( pDef && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
42950     sqlite3DbFree(db, pDef);
42951   }
42952 }
42953
42954 /*
42955 ** Delete a P4 value if necessary.
42956 */
42957 static void freeP4(sqlite3 *db, int p4type, void *p4){
42958   if( p4 ){
42959     switch( p4type ){
42960       case P4_REAL:
42961       case P4_INT64:
42962       case P4_MPRINTF:
42963       case P4_DYNAMIC:
42964       case P4_KEYINFO:
42965       case P4_INTARRAY:
42966       case P4_KEYINFO_HANDOFF: {
42967         sqlite3DbFree(db, p4);
42968         break;
42969       }
42970       case P4_VDBEFUNC: {
42971         VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
42972         freeEphemeralFunction(db, pVdbeFunc->pFunc);
42973         sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
42974         sqlite3DbFree(db, pVdbeFunc);
42975         break;
42976       }
42977       case P4_FUNCDEF: {
42978         freeEphemeralFunction(db, (FuncDef*)p4);
42979         break;
42980       }
42981       case P4_MEM: {
42982         sqlite3ValueFree((sqlite3_value*)p4);
42983         break;
42984       }
42985     }
42986   }
42987 }
42988
42989
42990 /*
42991 ** Change N opcodes starting at addr to No-ops.
42992 */
42993 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
42994   if( p && p->aOp ){
42995     VdbeOp *pOp = &p->aOp[addr];
42996     sqlite3 *db = p->db;
42997     while( N-- ){
42998       freeP4(db, pOp->p4type, pOp->p4.p);
42999       memset(pOp, 0, sizeof(pOp[0]));
43000       pOp->opcode = OP_Noop;
43001       pOp++;
43002     }
43003   }
43004 }
43005
43006 /*
43007 ** Change the value of the P4 operand for a specific instruction.
43008 ** This routine is useful when a large program is loaded from a
43009 ** static array using sqlite3VdbeAddOpList but we want to make a
43010 ** few minor changes to the program.
43011 **
43012 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
43013 ** the string is made into memory obtained from sqlite3_malloc().
43014 ** A value of n==0 means copy bytes of zP4 up to and including the
43015 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
43016 **
43017 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
43018 ** A copy is made of the KeyInfo structure into memory obtained from
43019 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
43020 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
43021 ** stored in memory that the caller has obtained from sqlite3_malloc. The 
43022 ** caller should not free the allocation, it will be freed when the Vdbe is
43023 ** finalized.
43024 ** 
43025 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
43026 ** to a string or structure that is guaranteed to exist for the lifetime of
43027 ** the Vdbe. In these cases we can just copy the pointer.
43028 **
43029 ** If addr<0 then change P4 on the most recently inserted instruction.
43030 */
43031 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
43032   Op *pOp;
43033   sqlite3 *db;
43034   assert( p!=0 );
43035   db = p->db;
43036   assert( p->magic==VDBE_MAGIC_INIT );
43037   if( p->aOp==0 || db->mallocFailed ){
43038     if (n != P4_KEYINFO) {
43039       freeP4(db, n, (void*)*(char**)&zP4);
43040     }
43041     return;
43042   }
43043   assert( addr<p->nOp );
43044   if( addr<0 ){
43045     addr = p->nOp - 1;
43046     if( addr<0 ) return;
43047   }
43048   pOp = &p->aOp[addr];
43049   freeP4(db, pOp->p4type, pOp->p4.p);
43050   pOp->p4.p = 0;
43051   if( n==P4_INT32 ){
43052     /* Note: this cast is safe, because the origin data point was an int
43053     ** that was cast to a (const char *). */
43054     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
43055     pOp->p4type = n;
43056   }else if( zP4==0 ){
43057     pOp->p4.p = 0;
43058     pOp->p4type = P4_NOTUSED;
43059   }else if( n==P4_KEYINFO ){
43060     KeyInfo *pKeyInfo;
43061     int nField, nByte;
43062
43063     nField = ((KeyInfo*)zP4)->nField;
43064     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
43065     pKeyInfo = sqlite3Malloc( nByte );
43066     pOp->p4.pKeyInfo = pKeyInfo;
43067     if( pKeyInfo ){
43068       u8 *aSortOrder;
43069       memcpy(pKeyInfo, zP4, nByte);
43070       aSortOrder = pKeyInfo->aSortOrder;
43071       if( aSortOrder ){
43072         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
43073         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
43074       }
43075       pOp->p4type = P4_KEYINFO;
43076     }else{
43077       p->db->mallocFailed = 1;
43078       pOp->p4type = P4_NOTUSED;
43079     }
43080   }else if( n==P4_KEYINFO_HANDOFF ){
43081     pOp->p4.p = (void*)zP4;
43082     pOp->p4type = P4_KEYINFO;
43083   }else if( n<0 ){
43084     pOp->p4.p = (void*)zP4;
43085     pOp->p4type = n;
43086   }else{
43087     if( n==0 ) n = strlen(zP4);
43088     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
43089     pOp->p4type = P4_DYNAMIC;
43090   }
43091 }
43092
43093 #ifndef NDEBUG
43094 /*
43095 ** Change the comment on the the most recently coded instruction.  Or
43096 ** insert a No-op and add the comment to that new instruction.  This
43097 ** makes the code easier to read during debugging.  None of this happens
43098 ** in a production build.
43099 */
43100 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
43101   va_list ap;
43102   assert( p->nOp>0 || p->aOp==0 );
43103   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
43104   if( p->nOp ){
43105     char **pz = &p->aOp[p->nOp-1].zComment;
43106     va_start(ap, zFormat);
43107     sqlite3DbFree(p->db, *pz);
43108     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
43109     va_end(ap);
43110   }
43111 }
43112 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
43113   va_list ap;
43114   sqlite3VdbeAddOp0(p, OP_Noop);
43115   assert( p->nOp>0 || p->aOp==0 );
43116   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
43117   if( p->nOp ){
43118     char **pz = &p->aOp[p->nOp-1].zComment;
43119     va_start(ap, zFormat);
43120     sqlite3DbFree(p->db, *pz);
43121     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
43122     va_end(ap);
43123   }
43124 }
43125 #endif  /* NDEBUG */
43126
43127 /*
43128 ** Return the opcode for a given address.
43129 */
43130 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
43131   assert( p->magic==VDBE_MAGIC_INIT );
43132   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
43133   return ((addr>=0 && addr<p->nOp)?(&p->aOp[addr]):0);
43134 }
43135
43136 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
43137      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
43138 /*
43139 ** Compute a string that describes the P4 parameter for an opcode.
43140 ** Use zTemp for any required temporary buffer space.
43141 */
43142 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
43143   char *zP4 = zTemp;
43144   assert( nTemp>=20 );
43145   switch( pOp->p4type ){
43146     case P4_KEYINFO_STATIC:
43147     case P4_KEYINFO: {
43148       int i, j;
43149       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
43150       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
43151       i = strlen(zTemp);
43152       for(j=0; j<pKeyInfo->nField; j++){
43153         CollSeq *pColl = pKeyInfo->aColl[j];
43154         if( pColl ){
43155           int n = strlen(pColl->zName);
43156           if( i+n>nTemp-6 ){
43157             memcpy(&zTemp[i],",...",4);
43158             break;
43159           }
43160           zTemp[i++] = ',';
43161           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
43162             zTemp[i++] = '-';
43163           }
43164           memcpy(&zTemp[i], pColl->zName,n+1);
43165           i += n;
43166         }else if( i+4<nTemp-6 ){
43167           memcpy(&zTemp[i],",nil",4);
43168           i += 4;
43169         }
43170       }
43171       zTemp[i++] = ')';
43172       zTemp[i] = 0;
43173       assert( i<nTemp );
43174       break;
43175     }
43176     case P4_COLLSEQ: {
43177       CollSeq *pColl = pOp->p4.pColl;
43178       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
43179       break;
43180     }
43181     case P4_FUNCDEF: {
43182       FuncDef *pDef = pOp->p4.pFunc;
43183       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
43184       break;
43185     }
43186     case P4_INT64: {
43187       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
43188       break;
43189     }
43190     case P4_INT32: {
43191       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
43192       break;
43193     }
43194     case P4_REAL: {
43195       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
43196       break;
43197     }
43198     case P4_MEM: {
43199       Mem *pMem = pOp->p4.pMem;
43200       assert( (pMem->flags & MEM_Null)==0 );
43201       if( pMem->flags & MEM_Str ){
43202         zP4 = pMem->z;
43203       }else if( pMem->flags & MEM_Int ){
43204         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
43205       }else if( pMem->flags & MEM_Real ){
43206         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
43207       }
43208       break;
43209     }
43210 #ifndef SQLITE_OMIT_VIRTUALTABLE
43211     case P4_VTAB: {
43212       sqlite3_vtab *pVtab = pOp->p4.pVtab;
43213       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
43214       break;
43215     }
43216 #endif
43217     case P4_INTARRAY: {
43218       sqlite3_snprintf(nTemp, zTemp, "intarray");
43219       break;
43220     }
43221     default: {
43222       zP4 = pOp->p4.z;
43223       if( zP4==0 ){
43224         zP4 = zTemp;
43225         zTemp[0] = 0;
43226       }
43227     }
43228   }
43229   assert( zP4!=0 );
43230   return zP4;
43231 }
43232 #endif
43233
43234 /*
43235 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
43236 **
43237 */
43238 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
43239   int mask;
43240   assert( i>=0 && i<p->db->nDb );
43241   assert( i<(int)sizeof(p->btreeMask)*8 );
43242   mask = 1<<i;
43243   if( (p->btreeMask & mask)==0 ){
43244     p->btreeMask |= mask;
43245     sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
43246   }
43247 }
43248
43249
43250 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
43251 /*
43252 ** Print a single opcode.  This routine is used for debugging only.
43253 */
43254 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
43255   char *zP4;
43256   char zPtr[50];
43257   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
43258   if( pOut==0 ) pOut = stdout;
43259   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
43260   fprintf(pOut, zFormat1, pc, 
43261       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
43262 #ifdef SQLITE_DEBUG
43263       pOp->zComment ? pOp->zComment : ""
43264 #else
43265       ""
43266 #endif
43267   );
43268   fflush(pOut);
43269 }
43270 #endif
43271
43272 /*
43273 ** Release an array of N Mem elements
43274 */
43275 static void releaseMemArray(Mem *p, int N){
43276   if( p && N ){
43277     Mem *pEnd;
43278     sqlite3 *db = p->db;
43279     int malloc_failed = db->mallocFailed;
43280     for(pEnd=&p[N]; p<pEnd; p++){
43281       assert( (&p[1])==pEnd || p[0].db==p[1].db );
43282
43283       /* This block is really an inlined version of sqlite3VdbeMemRelease()
43284       ** that takes advantage of the fact that the memory cell value is 
43285       ** being set to NULL after releasing any dynamic resources.
43286       **
43287       ** The justification for duplicating code is that according to 
43288       ** callgrind, this causes a certain test case to hit the CPU 4.7 
43289       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if 
43290       ** sqlite3MemRelease() were called from here. With -O2, this jumps
43291       ** to 6.6 percent. The test case is inserting 1000 rows into a table 
43292       ** with no indexes using a single prepared INSERT statement, bind() 
43293       ** and reset(). Inserts are grouped into a transaction.
43294       */
43295       if( p->flags&(MEM_Agg|MEM_Dyn) ){
43296         sqlite3VdbeMemRelease(p);
43297       }else if( p->zMalloc ){
43298         sqlite3DbFree(db, p->zMalloc);
43299         p->zMalloc = 0;
43300       }
43301
43302       p->flags = MEM_Null;
43303     }
43304     db->mallocFailed = malloc_failed;
43305   }
43306 }
43307
43308 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
43309 SQLITE_PRIVATE int sqlite3VdbeReleaseBuffers(Vdbe *p){
43310   int ii;
43311   int nFree = 0;
43312   assert( sqlite3_mutex_held(p->db->mutex) );
43313   for(ii=1; ii<=p->nMem; ii++){
43314     Mem *pMem = &p->aMem[ii];
43315     if( pMem->z && pMem->flags&MEM_Dyn ){
43316       assert( !pMem->xDel );
43317       nFree += sqlite3DbMallocSize(pMem->db, pMem->z);
43318       sqlite3VdbeMemRelease(pMem);
43319     }
43320   }
43321   return nFree;
43322 }
43323 #endif
43324
43325 #ifndef SQLITE_OMIT_EXPLAIN
43326 /*
43327 ** Give a listing of the program in the virtual machine.
43328 **
43329 ** The interface is the same as sqlite3VdbeExec().  But instead of
43330 ** running the code, it invokes the callback once for each instruction.
43331 ** This feature is used to implement "EXPLAIN".
43332 **
43333 ** When p->explain==1, each instruction is listed.  When
43334 ** p->explain==2, only OP_Explain instructions are listed and these
43335 ** are shown in a different format.  p->explain==2 is used to implement
43336 ** EXPLAIN QUERY PLAN.
43337 */
43338 SQLITE_PRIVATE int sqlite3VdbeList(
43339   Vdbe *p                   /* The VDBE */
43340 ){
43341   sqlite3 *db = p->db;
43342   int i;
43343   int rc = SQLITE_OK;
43344   Mem *pMem = p->pResultSet = &p->aMem[1];
43345
43346   assert( p->explain );
43347   if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
43348   assert( db->magic==SQLITE_MAGIC_BUSY );
43349   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
43350
43351   /* Even though this opcode does not use dynamic strings for
43352   ** the result, result columns may become dynamic if the user calls
43353   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
43354   */
43355   releaseMemArray(pMem, p->nMem);
43356
43357   do{
43358     i = p->pc++;
43359   }while( i<p->nOp && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
43360   if( i>=p->nOp ){
43361     p->rc = SQLITE_OK;
43362     rc = SQLITE_DONE;
43363   }else if( db->u1.isInterrupted ){
43364     p->rc = SQLITE_INTERRUPT;
43365     rc = SQLITE_ERROR;
43366     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
43367   }else{
43368     char *z;
43369     Op *pOp = &p->aOp[i];
43370     if( p->explain==1 ){
43371       pMem->flags = MEM_Int;
43372       pMem->type = SQLITE_INTEGER;
43373       pMem->u.i = i;                                /* Program counter */
43374       pMem++;
43375   
43376       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
43377       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
43378       assert( pMem->z!=0 );
43379       pMem->n = strlen(pMem->z);
43380       pMem->type = SQLITE_TEXT;
43381       pMem->enc = SQLITE_UTF8;
43382       pMem++;
43383     }
43384
43385     pMem->flags = MEM_Int;
43386     pMem->u.i = pOp->p1;                          /* P1 */
43387     pMem->type = SQLITE_INTEGER;
43388     pMem++;
43389
43390     pMem->flags = MEM_Int;
43391     pMem->u.i = pOp->p2;                          /* P2 */
43392     pMem->type = SQLITE_INTEGER;
43393     pMem++;
43394
43395     if( p->explain==1 ){
43396       pMem->flags = MEM_Int;
43397       pMem->u.i = pOp->p3;                          /* P3 */
43398       pMem->type = SQLITE_INTEGER;
43399       pMem++;
43400     }
43401
43402     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
43403       p->db->mallocFailed = 1;
43404       return SQLITE_NOMEM;
43405     }
43406     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
43407     z = displayP4(pOp, pMem->z, 32);
43408     if( z!=pMem->z ){
43409       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
43410     }else{
43411       assert( pMem->z!=0 );
43412       pMem->n = strlen(pMem->z);
43413       pMem->enc = SQLITE_UTF8;
43414     }
43415     pMem->type = SQLITE_TEXT;
43416     pMem++;
43417
43418     if( p->explain==1 ){
43419       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
43420         p->db->mallocFailed = 1;
43421         return SQLITE_NOMEM;
43422       }
43423       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
43424       pMem->n = 2;
43425       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
43426       pMem->type = SQLITE_TEXT;
43427       pMem->enc = SQLITE_UTF8;
43428       pMem++;
43429   
43430 #ifdef SQLITE_DEBUG
43431       if( pOp->zComment ){
43432         pMem->flags = MEM_Str|MEM_Term;
43433         pMem->z = pOp->zComment;
43434         pMem->n = strlen(pMem->z);
43435         pMem->enc = SQLITE_UTF8;
43436         pMem->type = SQLITE_TEXT;
43437       }else
43438 #endif
43439       {
43440         pMem->flags = MEM_Null;                       /* Comment */
43441         pMem->type = SQLITE_NULL;
43442       }
43443     }
43444
43445     p->nResColumn = 8 - 5*(p->explain-1);
43446     p->rc = SQLITE_OK;
43447     rc = SQLITE_ROW;
43448   }
43449   return rc;
43450 }
43451 #endif /* SQLITE_OMIT_EXPLAIN */
43452
43453 #ifdef SQLITE_DEBUG
43454 /*
43455 ** Print the SQL that was used to generate a VDBE program.
43456 */
43457 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
43458   int nOp = p->nOp;
43459   VdbeOp *pOp;
43460   if( nOp<1 ) return;
43461   pOp = &p->aOp[0];
43462   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
43463     const char *z = pOp->p4.z;
43464     while( isspace(*(u8*)z) ) z++;
43465     printf("SQL: [%s]\n", z);
43466   }
43467 }
43468 #endif
43469
43470 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
43471 /*
43472 ** Print an IOTRACE message showing SQL content.
43473 */
43474 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
43475   int nOp = p->nOp;
43476   VdbeOp *pOp;
43477   if( sqlite3IoTrace==0 ) return;
43478   if( nOp<1 ) return;
43479   pOp = &p->aOp[0];
43480   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
43481     int i, j;
43482     char z[1000];
43483     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
43484     for(i=0; isspace((unsigned char)z[i]); i++){}
43485     for(j=0; z[i]; i++){
43486       if( isspace((unsigned char)z[i]) ){
43487         if( z[i-1]!=' ' ){
43488           z[j++] = ' ';
43489         }
43490       }else{
43491         z[j++] = z[i];
43492       }
43493     }
43494     z[j] = 0;
43495     sqlite3IoTrace("SQL %s\n", z);
43496   }
43497 }
43498 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
43499
43500
43501 /*
43502 ** Prepare a virtual machine for execution.  This involves things such
43503 ** as allocating stack space and initializing the program counter.
43504 ** After the VDBE has be prepped, it can be executed by one or more
43505 ** calls to sqlite3VdbeExec().  
43506 **
43507 ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
43508 ** VDBE_MAGIC_RUN.
43509 */
43510 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
43511   Vdbe *p,                       /* The VDBE */
43512   int nVar,                      /* Number of '?' see in the SQL statement */
43513   int nMem,                      /* Number of memory cells to allocate */
43514   int nCursor,                   /* Number of cursors to allocate */
43515   int isExplain                  /* True if the EXPLAIN keywords is present */
43516 ){
43517   int n;
43518   sqlite3 *db = p->db;
43519
43520   assert( p!=0 );
43521   assert( p->magic==VDBE_MAGIC_INIT );
43522
43523   /* There should be at least one opcode.
43524   */
43525   assert( p->nOp>0 );
43526
43527   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
43528   p->magic = VDBE_MAGIC_RUN;
43529
43530   /* For each cursor required, also allocate a memory cell. Memory
43531   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
43532   ** the vdbe program. Instead they are used to allocate space for
43533   ** VdbeCursor/BtCursor structures. The blob of memory associated with 
43534   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
43535   ** stores the blob of memory associated with cursor 1, etc.
43536   **
43537   ** See also: allocateCursor().
43538   */
43539   nMem += nCursor;
43540
43541   /*
43542   ** Allocation space for registers.
43543   */
43544   if( p->aMem==0 ){
43545     int nArg;       /* Maximum number of args passed to a user function. */
43546     resolveP2Values(p, &nArg);
43547     assert( nVar>=0 );
43548     if( isExplain && nMem<10 ){
43549       nMem = 10;
43550     }
43551     p->aMem = sqlite3DbMallocZero(db,
43552         nMem*sizeof(Mem)               /* aMem */
43553       + nVar*sizeof(Mem)               /* aVar */
43554       + nArg*sizeof(Mem*)              /* apArg */
43555       + nVar*sizeof(char*)             /* azVar */
43556       + nCursor*sizeof(VdbeCursor*)+1  /* apCsr */
43557     );
43558     if( !db->mallocFailed ){
43559       p->aMem--;             /* aMem[] goes from 1..nMem */
43560       p->nMem = nMem;        /*       not from 0..nMem-1 */
43561       p->aVar = &p->aMem[nMem+1];
43562       p->nVar = nVar;
43563       p->okVar = 0;
43564       p->apArg = (Mem**)&p->aVar[nVar];
43565       p->azVar = (char**)&p->apArg[nArg];
43566       p->apCsr = (VdbeCursor**)&p->azVar[nVar];
43567       p->nCursor = nCursor;
43568       for(n=0; n<nVar; n++){
43569         p->aVar[n].flags = MEM_Null;
43570         p->aVar[n].db = db;
43571       }
43572       for(n=1; n<=nMem; n++){
43573         p->aMem[n].flags = MEM_Null;
43574         p->aMem[n].db = db;
43575       }
43576     }
43577   }
43578 #ifdef SQLITE_DEBUG
43579   for(n=1; n<p->nMem; n++){
43580     assert( p->aMem[n].db==db );
43581   }
43582 #endif
43583
43584   p->pc = -1;
43585   p->rc = SQLITE_OK;
43586   p->uniqueCnt = 0;
43587   p->errorAction = OE_Abort;
43588   p->explain |= isExplain;
43589   p->magic = VDBE_MAGIC_RUN;
43590   p->nChange = 0;
43591   p->cacheCtr = 1;
43592   p->minWriteFileFormat = 255;
43593   p->openedStatement = 0;
43594 #ifdef VDBE_PROFILE
43595   {
43596     int i;
43597     for(i=0; i<p->nOp; i++){
43598       p->aOp[i].cnt = 0;
43599       p->aOp[i].cycles = 0;
43600     }
43601   }
43602 #endif
43603 }
43604
43605 /*
43606 ** Close a VDBE cursor and release all the resources that cursor 
43607 ** happens to hold.
43608 */
43609 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
43610   if( pCx==0 ){
43611     return;
43612   }
43613   if( pCx->pBt ){
43614     sqlite3BtreeClose(pCx->pBt);
43615     /* The pCx->pCursor will be close automatically, if it exists, by
43616     ** the call above. */
43617   }else if( pCx->pCursor ){
43618     sqlite3BtreeCloseCursor(pCx->pCursor);
43619   }
43620 #ifndef SQLITE_OMIT_VIRTUALTABLE
43621   if( pCx->pVtabCursor ){
43622     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
43623     const sqlite3_module *pModule = pCx->pModule;
43624     p->inVtabMethod = 1;
43625     (void)sqlite3SafetyOff(p->db);
43626     pModule->xClose(pVtabCursor);
43627     (void)sqlite3SafetyOn(p->db);
43628     p->inVtabMethod = 0;
43629   }
43630 #endif
43631   if( !pCx->ephemPseudoTable ){
43632     sqlite3DbFree(p->db, pCx->pData);
43633   }
43634 }
43635
43636 /*
43637 ** Close all cursors except for VTab cursors that are currently
43638 ** in use.
43639 */
43640 static void closeAllCursorsExceptActiveVtabs(Vdbe *p){
43641   int i;
43642   if( p->apCsr==0 ) return;
43643   for(i=0; i<p->nCursor; i++){
43644     VdbeCursor *pC = p->apCsr[i];
43645     if( pC && (!p->inVtabMethod || !pC->pVtabCursor) ){
43646       sqlite3VdbeFreeCursor(p, pC);
43647       p->apCsr[i] = 0;
43648     }
43649   }
43650 }
43651
43652 /*
43653 ** Clean up the VM after execution.
43654 **
43655 ** This routine will automatically close any cursors, lists, and/or
43656 ** sorters that were left open.  It also deletes the values of
43657 ** variables in the aVar[] array.
43658 */
43659 static void Cleanup(Vdbe *p){
43660   int i;
43661   sqlite3 *db = p->db;
43662   closeAllCursorsExceptActiveVtabs(p);
43663   for(i=1; i<=p->nMem; i++){
43664     MemSetTypeFlag(&p->aMem[i], MEM_Null);
43665   }
43666   releaseMemArray(&p->aMem[1], p->nMem);
43667   sqlite3VdbeFifoClear(&p->sFifo);
43668   if( p->contextStack ){
43669     for(i=0; i<p->contextStackTop; i++){
43670       sqlite3VdbeFifoClear(&p->contextStack[i].sFifo);
43671     }
43672     sqlite3DbFree(db, p->contextStack);
43673   }
43674   p->contextStack = 0;
43675   p->contextStackDepth = 0;
43676   p->contextStackTop = 0;
43677   sqlite3DbFree(db, p->zErrMsg);
43678   p->zErrMsg = 0;
43679   p->pResultSet = 0;
43680 }
43681
43682 /*
43683 ** Set the number of result columns that will be returned by this SQL
43684 ** statement. This is now set at compile time, rather than during
43685 ** execution of the vdbe program so that sqlite3_column_count() can
43686 ** be called on an SQL statement before sqlite3_step().
43687 */
43688 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
43689   Mem *pColName;
43690   int n;
43691   sqlite3 *db = p->db;
43692
43693   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
43694   sqlite3DbFree(db, p->aColName);
43695   n = nResColumn*COLNAME_N;
43696   p->nResColumn = nResColumn;
43697   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
43698   if( p->aColName==0 ) return;
43699   while( n-- > 0 ){
43700     pColName->flags = MEM_Null;
43701     pColName->db = p->db;
43702     pColName++;
43703   }
43704 }
43705
43706 /*
43707 ** Set the name of the idx'th column to be returned by the SQL statement.
43708 ** zName must be a pointer to a nul terminated string.
43709 **
43710 ** This call must be made after a call to sqlite3VdbeSetNumCols().
43711 **
43712 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
43713 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
43714 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
43715 */
43716 SQLITE_PRIVATE int sqlite3VdbeSetColName(
43717   Vdbe *p,                         /* Vdbe being configured */
43718   int idx,                         /* Index of column zName applies to */
43719   int var,                         /* One of the COLNAME_* constants */
43720   const char *zName,               /* Pointer to buffer containing name */
43721   void (*xDel)(void*)              /* Memory management strategy for zName */
43722 ){
43723   int rc;
43724   Mem *pColName;
43725   assert( idx<p->nResColumn );
43726   assert( var<COLNAME_N );
43727   if( p->db->mallocFailed ){
43728     assert( !zName || xDel!=SQLITE_DYNAMIC );
43729     return SQLITE_NOMEM;
43730   }
43731   assert( p->aColName!=0 );
43732   pColName = &(p->aColName[idx+var*p->nResColumn]);
43733   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
43734   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
43735   return rc;
43736 }
43737
43738 /*
43739 ** A read or write transaction may or may not be active on database handle
43740 ** db. If a transaction is active, commit it. If there is a
43741 ** write-transaction spanning more than one database file, this routine
43742 ** takes care of the master journal trickery.
43743 */
43744 static int vdbeCommit(sqlite3 *db, Vdbe *p){
43745   int i;
43746   int nTrans = 0;  /* Number of databases with an active write-transaction */
43747   int rc = SQLITE_OK;
43748   int needXcommit = 0;
43749
43750   /* Before doing anything else, call the xSync() callback for any
43751   ** virtual module tables written in this transaction. This has to
43752   ** be done before determining whether a master journal file is 
43753   ** required, as an xSync() callback may add an attached database
43754   ** to the transaction.
43755   */
43756   rc = sqlite3VtabSync(db, &p->zErrMsg);
43757   if( rc!=SQLITE_OK ){
43758     return rc;
43759   }
43760
43761   /* This loop determines (a) if the commit hook should be invoked and
43762   ** (b) how many database files have open write transactions, not 
43763   ** including the temp database. (b) is important because if more than 
43764   ** one database file has an open write transaction, a master journal
43765   ** file is required for an atomic commit.
43766   */ 
43767   for(i=0; i<db->nDb; i++){ 
43768     Btree *pBt = db->aDb[i].pBt;
43769     if( sqlite3BtreeIsInTrans(pBt) ){
43770       needXcommit = 1;
43771       if( i!=1 ) nTrans++;
43772     }
43773   }
43774
43775   /* If there are any write-transactions at all, invoke the commit hook */
43776   if( needXcommit && db->xCommitCallback ){
43777     (void)sqlite3SafetyOff(db);
43778     rc = db->xCommitCallback(db->pCommitArg);
43779     (void)sqlite3SafetyOn(db);
43780     if( rc ){
43781       return SQLITE_CONSTRAINT;
43782     }
43783   }
43784
43785   /* The simple case - no more than one database file (not counting the
43786   ** TEMP database) has a transaction active.   There is no need for the
43787   ** master-journal.
43788   **
43789   ** If the return value of sqlite3BtreeGetFilename() is a zero length
43790   ** string, it means the main database is :memory: or a temp file.  In 
43791   ** that case we do not support atomic multi-file commits, so use the 
43792   ** simple case then too.
43793   */
43794   if( 0==strlen(sqlite3BtreeGetFilename(db->aDb[0].pBt)) || nTrans<=1 ){
43795     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
43796       Btree *pBt = db->aDb[i].pBt;
43797       if( pBt ){
43798         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
43799       }
43800     }
43801
43802     /* Do the commit only if all databases successfully complete phase 1. 
43803     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
43804     ** IO error while deleting or truncating a journal file. It is unlikely,
43805     ** but could happen. In this case abandon processing and return the error.
43806     */
43807     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
43808       Btree *pBt = db->aDb[i].pBt;
43809       if( pBt ){
43810         rc = sqlite3BtreeCommitPhaseTwo(pBt);
43811       }
43812     }
43813     if( rc==SQLITE_OK ){
43814       sqlite3VtabCommit(db);
43815     }
43816   }
43817
43818   /* The complex case - There is a multi-file write-transaction active.
43819   ** This requires a master journal file to ensure the transaction is
43820   ** committed atomicly.
43821   */
43822 #ifndef SQLITE_OMIT_DISKIO
43823   else{
43824     sqlite3_vfs *pVfs = db->pVfs;
43825     int needSync = 0;
43826     char *zMaster = 0;   /* File-name for the master journal */
43827     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
43828     sqlite3_file *pMaster = 0;
43829     i64 offset = 0;
43830     int res;
43831
43832     /* Select a master journal file name */
43833     do {
43834       u32 random;
43835       sqlite3DbFree(db, zMaster);
43836       sqlite3_randomness(sizeof(random), &random);
43837       zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, random&0x7fffffff);
43838       if( !zMaster ){
43839         return SQLITE_NOMEM;
43840       }
43841       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
43842     }while( rc==SQLITE_OK && res );
43843     if( rc==SQLITE_OK ){
43844       /* Open the master journal. */
43845       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
43846           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
43847           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
43848       );
43849     }
43850     if( rc!=SQLITE_OK ){
43851       sqlite3DbFree(db, zMaster);
43852       return rc;
43853     }
43854  
43855     /* Write the name of each database file in the transaction into the new
43856     ** master journal file. If an error occurs at this point close
43857     ** and delete the master journal file. All the individual journal files
43858     ** still have 'null' as the master journal pointer, so they will roll
43859     ** back independently if a failure occurs.
43860     */
43861     for(i=0; i<db->nDb; i++){
43862       Btree *pBt = db->aDb[i].pBt;
43863       if( i==1 ) continue;   /* Ignore the TEMP database */
43864       if( sqlite3BtreeIsInTrans(pBt) ){
43865         char const *zFile = sqlite3BtreeGetJournalname(pBt);
43866         if( zFile[0]==0 ) continue;  /* Ignore :memory: databases */
43867         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
43868           needSync = 1;
43869         }
43870         rc = sqlite3OsWrite(pMaster, zFile, strlen(zFile)+1, offset);
43871         offset += strlen(zFile)+1;
43872         if( rc!=SQLITE_OK ){
43873           sqlite3OsCloseFree(pMaster);
43874           sqlite3OsDelete(pVfs, zMaster, 0);
43875           sqlite3DbFree(db, zMaster);
43876           return rc;
43877         }
43878       }
43879     }
43880
43881     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
43882     ** flag is set this is not required.
43883     */
43884     zMainFile = sqlite3BtreeGetDirname(db->aDb[0].pBt);
43885     if( (needSync 
43886      && (0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL))
43887      && (rc=sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))!=SQLITE_OK) ){
43888       sqlite3OsCloseFree(pMaster);
43889       sqlite3OsDelete(pVfs, zMaster, 0);
43890       sqlite3DbFree(db, zMaster);
43891       return rc;
43892     }
43893
43894     /* Sync all the db files involved in the transaction. The same call
43895     ** sets the master journal pointer in each individual journal. If
43896     ** an error occurs here, do not delete the master journal file.
43897     **
43898     ** If the error occurs during the first call to
43899     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
43900     ** master journal file will be orphaned. But we cannot delete it,
43901     ** in case the master journal file name was written into the journal
43902     ** file before the failure occured.
43903     */
43904     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
43905       Btree *pBt = db->aDb[i].pBt;
43906       if( pBt ){
43907         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
43908       }
43909     }
43910     sqlite3OsCloseFree(pMaster);
43911     if( rc!=SQLITE_OK ){
43912       sqlite3DbFree(db, zMaster);
43913       return rc;
43914     }
43915
43916     /* Delete the master journal file. This commits the transaction. After
43917     ** doing this the directory is synced again before any individual
43918     ** transaction files are deleted.
43919     */
43920     rc = sqlite3OsDelete(pVfs, zMaster, 1);
43921     sqlite3DbFree(db, zMaster);
43922     zMaster = 0;
43923     if( rc ){
43924       return rc;
43925     }
43926
43927     /* All files and directories have already been synced, so the following
43928     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
43929     ** deleting or truncating journals. If something goes wrong while
43930     ** this is happening we don't really care. The integrity of the
43931     ** transaction is already guaranteed, but some stray 'cold' journals
43932     ** may be lying around. Returning an error code won't help matters.
43933     */
43934     disable_simulated_io_errors();
43935     sqlite3BeginBenignMalloc();
43936     for(i=0; i<db->nDb; i++){ 
43937       Btree *pBt = db->aDb[i].pBt;
43938       if( pBt ){
43939         sqlite3BtreeCommitPhaseTwo(pBt);
43940       }
43941     }
43942     sqlite3EndBenignMalloc();
43943     enable_simulated_io_errors();
43944
43945     sqlite3VtabCommit(db);
43946   }
43947 #endif
43948
43949   return rc;
43950 }
43951
43952 /* 
43953 ** This routine checks that the sqlite3.activeVdbeCnt count variable
43954 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
43955 ** currently active. An assertion fails if the two counts do not match.
43956 ** This is an internal self-check only - it is not an essential processing
43957 ** step.
43958 **
43959 ** This is a no-op if NDEBUG is defined.
43960 */
43961 #ifndef NDEBUG
43962 static void checkActiveVdbeCnt(sqlite3 *db){
43963   Vdbe *p;
43964   int cnt = 0;
43965   int nWrite = 0;
43966   p = db->pVdbe;
43967   while( p ){
43968     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
43969       cnt++;
43970       if( p->readOnly==0 ) nWrite++;
43971     }
43972     p = p->pNext;
43973   }
43974   assert( cnt==db->activeVdbeCnt );
43975   assert( nWrite==db->writeVdbeCnt );
43976 }
43977 #else
43978 #define checkActiveVdbeCnt(x)
43979 #endif
43980
43981 /*
43982 ** For every Btree that in database connection db which 
43983 ** has been modified, "trip" or invalidate each cursor in
43984 ** that Btree might have been modified so that the cursor
43985 ** can never be used again.  This happens when a rollback
43986 *** occurs.  We have to trip all the other cursors, even
43987 ** cursor from other VMs in different database connections,
43988 ** so that none of them try to use the data at which they
43989 ** were pointing and which now may have been changed due
43990 ** to the rollback.
43991 **
43992 ** Remember that a rollback can delete tables complete and
43993 ** reorder rootpages.  So it is not sufficient just to save
43994 ** the state of the cursor.  We have to invalidate the cursor
43995 ** so that it is never used again.
43996 */
43997 static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
43998   int i;
43999   for(i=0; i<db->nDb; i++){
44000     Btree *p = db->aDb[i].pBt;
44001     if( p && sqlite3BtreeIsInTrans(p) ){
44002       sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
44003     }
44004   }
44005 }
44006
44007 /*
44008 ** This routine is called the when a VDBE tries to halt.  If the VDBE
44009 ** has made changes and is in autocommit mode, then commit those
44010 ** changes.  If a rollback is needed, then do the rollback.
44011 **
44012 ** This routine is the only way to move the state of a VM from
44013 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
44014 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
44015 **
44016 ** Return an error code.  If the commit could not complete because of
44017 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
44018 ** means the close did not happen and needs to be repeated.
44019 */
44020 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
44021   sqlite3 *db = p->db;
44022   int i;
44023   int (*xFunc)(Btree *pBt) = 0;  /* Function to call on each btree backend */
44024   int isSpecialError;            /* Set to true if SQLITE_NOMEM or IOERR */
44025
44026   /* This function contains the logic that determines if a statement or
44027   ** transaction will be committed or rolled back as a result of the
44028   ** execution of this virtual machine. 
44029   **
44030   ** If any of the following errors occur:
44031   **
44032   **     SQLITE_NOMEM
44033   **     SQLITE_IOERR
44034   **     SQLITE_FULL
44035   **     SQLITE_INTERRUPT
44036   **
44037   ** Then the internal cache might have been left in an inconsistent
44038   ** state.  We need to rollback the statement transaction, if there is
44039   ** one, or the complete transaction if there is no statement transaction.
44040   */
44041
44042   if( p->db->mallocFailed ){
44043     p->rc = SQLITE_NOMEM;
44044   }
44045   closeAllCursorsExceptActiveVtabs(p);
44046   if( p->magic!=VDBE_MAGIC_RUN ){
44047     return SQLITE_OK;
44048   }
44049   checkActiveVdbeCnt(db);
44050
44051   /* No commit or rollback needed if the program never started */
44052   if( p->pc>=0 ){
44053     int mrc;   /* Primary error code from p->rc */
44054
44055     /* Lock all btrees used by the statement */
44056     sqlite3BtreeMutexArrayEnter(&p->aMutex);
44057
44058     /* Check for one of the special errors */
44059     mrc = p->rc & 0xff;
44060     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
44061                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
44062     if( isSpecialError ){
44063       /* If the query was read-only, we need do no rollback at all. Otherwise,
44064       ** proceed with the special handling.
44065       */
44066       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
44067         if( p->rc==SQLITE_IOERR_BLOCKED && p->usesStmtJournal ){
44068           xFunc = sqlite3BtreeRollbackStmt;
44069           p->rc = SQLITE_BUSY;
44070         }else if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL)
44071                    && p->usesStmtJournal ){
44072           xFunc = sqlite3BtreeRollbackStmt;
44073         }else{
44074           /* We are forced to roll back the active transaction. Before doing
44075           ** so, abort any other statements this handle currently has active.
44076           */
44077           invalidateCursorsOnModifiedBtrees(db);
44078           sqlite3RollbackAll(db);
44079           db->autoCommit = 1;
44080         }
44081       }
44082     }
44083   
44084     /* If the auto-commit flag is set and this is the only active vdbe, then
44085     ** we do either a commit or rollback of the current transaction. 
44086     **
44087     ** Note: This block also runs if one of the special errors handled 
44088     ** above has occurred. 
44089     */
44090     if( !sqlite3VtabInSync(db) 
44091      && db->autoCommit 
44092      && db->writeVdbeCnt==(p->readOnly==0) 
44093     ){
44094       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
44095         /* The auto-commit flag is true, and the vdbe program was 
44096         ** successful or hit an 'OR FAIL' constraint. This means a commit 
44097         ** is required.
44098         */
44099         int rc = vdbeCommit(db, p);
44100         if( rc==SQLITE_BUSY ){
44101           sqlite3BtreeMutexArrayLeave(&p->aMutex);
44102           return SQLITE_BUSY;
44103         }else if( rc!=SQLITE_OK ){
44104           p->rc = rc;
44105           sqlite3RollbackAll(db);
44106         }else{
44107           sqlite3CommitInternalChanges(db);
44108         }
44109       }else{
44110         sqlite3RollbackAll(db);
44111       }
44112     }else if( !xFunc ){
44113       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
44114         if( p->openedStatement ){
44115           xFunc = sqlite3BtreeCommitStmt;
44116         } 
44117       }else if( p->errorAction==OE_Abort ){
44118         xFunc = sqlite3BtreeRollbackStmt;
44119       }else{
44120         invalidateCursorsOnModifiedBtrees(db);
44121         sqlite3RollbackAll(db);
44122         db->autoCommit = 1;
44123       }
44124     }
44125   
44126     /* If xFunc is not NULL, then it is one of sqlite3BtreeRollbackStmt or
44127     ** sqlite3BtreeCommitStmt. Call it once on each backend. If an error occurs
44128     ** and the return code is still SQLITE_OK, set the return code to the new
44129     ** error value.
44130     */
44131     assert(!xFunc ||
44132       xFunc==sqlite3BtreeCommitStmt ||
44133       xFunc==sqlite3BtreeRollbackStmt
44134     );
44135     for(i=0; xFunc && i<db->nDb; i++){ 
44136       int rc;
44137       Btree *pBt = db->aDb[i].pBt;
44138       if( pBt ){
44139         rc = xFunc(pBt);
44140         if( rc && (p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT) ){
44141           p->rc = rc;
44142           sqlite3DbFree(db, p->zErrMsg);
44143           p->zErrMsg = 0;
44144         }
44145       }
44146     }
44147   
44148     /* If this was an INSERT, UPDATE or DELETE and the statement was committed, 
44149     ** set the change counter. 
44150     */
44151     if( p->changeCntOn && p->pc>=0 ){
44152       if( !xFunc || xFunc==sqlite3BtreeCommitStmt ){
44153         sqlite3VdbeSetChanges(db, p->nChange);
44154       }else{
44155         sqlite3VdbeSetChanges(db, 0);
44156       }
44157       p->nChange = 0;
44158     }
44159   
44160     /* Rollback or commit any schema changes that occurred. */
44161     if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
44162       sqlite3ResetInternalSchema(db, 0);
44163       db->flags = (db->flags | SQLITE_InternChanges);
44164     }
44165
44166     /* Release the locks */
44167     sqlite3BtreeMutexArrayLeave(&p->aMutex);
44168   }
44169
44170   /* We have successfully halted and closed the VM.  Record this fact. */
44171   if( p->pc>=0 ){
44172     db->activeVdbeCnt--;
44173     if( !p->readOnly ){
44174       db->writeVdbeCnt--;
44175     }
44176     assert( db->activeVdbeCnt>=db->writeVdbeCnt );
44177   }
44178   p->magic = VDBE_MAGIC_HALT;
44179   checkActiveVdbeCnt(db);
44180   if( p->db->mallocFailed ){
44181     p->rc = SQLITE_NOMEM;
44182   }
44183
44184   return SQLITE_OK;
44185 }
44186
44187
44188 /*
44189 ** Each VDBE holds the result of the most recent sqlite3_step() call
44190 ** in p->rc.  This routine sets that result back to SQLITE_OK.
44191 */
44192 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
44193   p->rc = SQLITE_OK;
44194 }
44195
44196 /*
44197 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
44198 ** Write any error messages into *pzErrMsg.  Return the result code.
44199 **
44200 ** After this routine is run, the VDBE should be ready to be executed
44201 ** again.
44202 **
44203 ** To look at it another way, this routine resets the state of the
44204 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
44205 ** VDBE_MAGIC_INIT.
44206 */
44207 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
44208   sqlite3 *db;
44209   db = p->db;
44210
44211   /* If the VM did not run to completion or if it encountered an
44212   ** error, then it might not have been halted properly.  So halt
44213   ** it now.
44214   */
44215   (void)sqlite3SafetyOn(db);
44216   sqlite3VdbeHalt(p);
44217   (void)sqlite3SafetyOff(db);
44218
44219   /* If the VDBE has be run even partially, then transfer the error code
44220   ** and error message from the VDBE into the main database structure.  But
44221   ** if the VDBE has just been set to run but has not actually executed any
44222   ** instructions yet, leave the main database error information unchanged.
44223   */
44224   if( p->pc>=0 ){
44225     if( p->zErrMsg ){
44226       sqlite3BeginBenignMalloc();
44227       sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
44228       sqlite3EndBenignMalloc();
44229       db->errCode = p->rc;
44230       sqlite3DbFree(db, p->zErrMsg);
44231       p->zErrMsg = 0;
44232     }else if( p->rc ){
44233       sqlite3Error(db, p->rc, 0);
44234     }else{
44235       sqlite3Error(db, SQLITE_OK, 0);
44236     }
44237   }else if( p->rc && p->expired ){
44238     /* The expired flag was set on the VDBE before the first call
44239     ** to sqlite3_step(). For consistency (since sqlite3_step() was
44240     ** called), set the database error in this case as well.
44241     */
44242     sqlite3Error(db, p->rc, 0);
44243     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
44244     sqlite3DbFree(db, p->zErrMsg);
44245     p->zErrMsg = 0;
44246   }
44247
44248   /* Reclaim all memory used by the VDBE
44249   */
44250   Cleanup(p);
44251
44252   /* Save profiling information from this VDBE run.
44253   */
44254 #ifdef VDBE_PROFILE
44255   {
44256     FILE *out = fopen("vdbe_profile.out", "a");
44257     if( out ){
44258       int i;
44259       fprintf(out, "---- ");
44260       for(i=0; i<p->nOp; i++){
44261         fprintf(out, "%02x", p->aOp[i].opcode);
44262       }
44263       fprintf(out, "\n");
44264       for(i=0; i<p->nOp; i++){
44265         fprintf(out, "%6d %10lld %8lld ",
44266            p->aOp[i].cnt,
44267            p->aOp[i].cycles,
44268            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
44269         );
44270         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
44271       }
44272       fclose(out);
44273     }
44274   }
44275 #endif
44276   p->magic = VDBE_MAGIC_INIT;
44277   return p->rc & db->errMask;
44278 }
44279  
44280 /*
44281 ** Clean up and delete a VDBE after execution.  Return an integer which is
44282 ** the result code.  Write any error message text into *pzErrMsg.
44283 */
44284 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
44285   int rc = SQLITE_OK;
44286   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
44287     rc = sqlite3VdbeReset(p);
44288     assert( (rc & p->db->errMask)==rc );
44289   }else if( p->magic!=VDBE_MAGIC_INIT ){
44290     return SQLITE_MISUSE;
44291   }
44292   sqlite3VdbeDelete(p);
44293   return rc;
44294 }
44295
44296 /*
44297 ** Call the destructor for each auxdata entry in pVdbeFunc for which
44298 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
44299 ** are always destroyed.  To destroy all auxdata entries, call this
44300 ** routine with mask==0.
44301 */
44302 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
44303   int i;
44304   for(i=0; i<pVdbeFunc->nAux; i++){
44305     struct AuxData *pAux = &pVdbeFunc->apAux[i];
44306     if( (i>31 || !(mask&(1<<i))) && pAux->pAux ){
44307       if( pAux->xDelete ){
44308         pAux->xDelete(pAux->pAux);
44309       }
44310       pAux->pAux = 0;
44311     }
44312   }
44313 }
44314
44315 /*
44316 ** Delete an entire VDBE.
44317 */
44318 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
44319   int i;
44320   sqlite3 *db;
44321
44322   if( p==0 ) return;
44323   db = p->db;
44324   if( p->pPrev ){
44325     p->pPrev->pNext = p->pNext;
44326   }else{
44327     assert( db->pVdbe==p );
44328     db->pVdbe = p->pNext;
44329   }
44330   if( p->pNext ){
44331     p->pNext->pPrev = p->pPrev;
44332   }
44333   if( p->aOp ){
44334     Op *pOp = p->aOp;
44335     for(i=0; i<p->nOp; i++, pOp++){
44336       freeP4(db, pOp->p4type, pOp->p4.p);
44337 #ifdef SQLITE_DEBUG
44338       sqlite3DbFree(db, pOp->zComment);
44339 #endif     
44340     }
44341     sqlite3DbFree(db, p->aOp);
44342   }
44343   releaseMemArray(p->aVar, p->nVar);
44344   sqlite3DbFree(db, p->aLabel);
44345   if( p->aMem ){
44346     sqlite3DbFree(db, &p->aMem[1]);
44347   }
44348   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
44349   sqlite3DbFree(db, p->aColName);
44350   sqlite3DbFree(db, p->zSql);
44351   p->magic = VDBE_MAGIC_DEAD;
44352   sqlite3DbFree(db, p);
44353 }
44354
44355 /*
44356 ** If a MoveTo operation is pending on the given cursor, then do that
44357 ** MoveTo now.  Return an error code.  If no MoveTo is pending, this
44358 ** routine does nothing and returns SQLITE_OK.
44359 */
44360 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
44361   if( p->deferredMoveto ){
44362     int res, rc;
44363 #ifdef SQLITE_TEST
44364     extern int sqlite3_search_count;
44365 #endif
44366     assert( p->isTable );
44367     rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
44368     if( rc ) return rc;
44369     p->lastRowid = keyToInt(p->movetoTarget);
44370     p->rowidIsValid = res==0;
44371     if( res<0 ){
44372       rc = sqlite3BtreeNext(p->pCursor, &res);
44373       if( rc ) return rc;
44374     }
44375 #ifdef SQLITE_TEST
44376     sqlite3_search_count++;
44377 #endif
44378     p->deferredMoveto = 0;
44379     p->cacheStatus = CACHE_STALE;
44380   }else if( p->pCursor ){
44381     int hasMoved;
44382     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
44383     if( rc ) return rc;
44384     if( hasMoved ){
44385       p->cacheStatus = CACHE_STALE;
44386       p->nullRow = 1;
44387     }
44388   }
44389   return SQLITE_OK;
44390 }
44391
44392 /*
44393 ** The following functions:
44394 **
44395 ** sqlite3VdbeSerialType()
44396 ** sqlite3VdbeSerialTypeLen()
44397 ** sqlite3VdbeSerialLen()
44398 ** sqlite3VdbeSerialPut()
44399 ** sqlite3VdbeSerialGet()
44400 **
44401 ** encapsulate the code that serializes values for storage in SQLite
44402 ** data and index records. Each serialized value consists of a
44403 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
44404 ** integer, stored as a varint.
44405 **
44406 ** In an SQLite index record, the serial type is stored directly before
44407 ** the blob of data that it corresponds to. In a table record, all serial
44408 ** types are stored at the start of the record, and the blobs of data at
44409 ** the end. Hence these functions allow the caller to handle the
44410 ** serial-type and data blob seperately.
44411 **
44412 ** The following table describes the various storage classes for data:
44413 **
44414 **   serial type        bytes of data      type
44415 **   --------------     ---------------    ---------------
44416 **      0                     0            NULL
44417 **      1                     1            signed integer
44418 **      2                     2            signed integer
44419 **      3                     3            signed integer
44420 **      4                     4            signed integer
44421 **      5                     6            signed integer
44422 **      6                     8            signed integer
44423 **      7                     8            IEEE float
44424 **      8                     0            Integer constant 0
44425 **      9                     0            Integer constant 1
44426 **     10,11                               reserved for expansion
44427 **    N>=12 and even       (N-12)/2        BLOB
44428 **    N>=13 and odd        (N-13)/2        text
44429 **
44430 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
44431 ** of SQLite will not understand those serial types.
44432 */
44433
44434 /*
44435 ** Return the serial-type for the value stored in pMem.
44436 */
44437 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
44438   int flags = pMem->flags;
44439   int n;
44440
44441   if( flags&MEM_Null ){
44442     return 0;
44443   }
44444   if( flags&MEM_Int ){
44445     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
44446 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
44447     i64 i = pMem->u.i;
44448     u64 u;
44449     if( file_format>=4 && (i&1)==i ){
44450       return 8+i;
44451     }
44452     u = i<0 ? -i : i;
44453     if( u<=127 ) return 1;
44454     if( u<=32767 ) return 2;
44455     if( u<=8388607 ) return 3;
44456     if( u<=2147483647 ) return 4;
44457     if( u<=MAX_6BYTE ) return 5;
44458     return 6;
44459   }
44460   if( flags&MEM_Real ){
44461     return 7;
44462   }
44463   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
44464   n = pMem->n;
44465   if( flags & MEM_Zero ){
44466     n += pMem->u.i;
44467   }
44468   assert( n>=0 );
44469   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
44470 }
44471
44472 /*
44473 ** Return the length of the data corresponding to the supplied serial-type.
44474 */
44475 SQLITE_PRIVATE int sqlite3VdbeSerialTypeLen(u32 serial_type){
44476   if( serial_type>=12 ){
44477     return (serial_type-12)/2;
44478   }else{
44479     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
44480     return aSize[serial_type];
44481   }
44482 }
44483
44484 /*
44485 ** If we are on an architecture with mixed-endian floating 
44486 ** points (ex: ARM7) then swap the lower 4 bytes with the 
44487 ** upper 4 bytes.  Return the result.
44488 **
44489 ** For most architectures, this is a no-op.
44490 **
44491 ** (later):  It is reported to me that the mixed-endian problem
44492 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
44493 ** that early versions of GCC stored the two words of a 64-bit
44494 ** float in the wrong order.  And that error has been propagated
44495 ** ever since.  The blame is not necessarily with GCC, though.
44496 ** GCC might have just copying the problem from a prior compiler.
44497 ** I am also told that newer versions of GCC that follow a different
44498 ** ABI get the byte order right.
44499 **
44500 ** Developers using SQLite on an ARM7 should compile and run their
44501 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
44502 ** enabled, some asserts below will ensure that the byte order of
44503 ** floating point values is correct.
44504 **
44505 ** (2007-08-30)  Frank van Vugt has studied this problem closely
44506 ** and has send his findings to the SQLite developers.  Frank
44507 ** writes that some Linux kernels offer floating point hardware
44508 ** emulation that uses only 32-bit mantissas instead of a full 
44509 ** 48-bits as required by the IEEE standard.  (This is the
44510 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
44511 ** byte swapping becomes very complicated.  To avoid problems,
44512 ** the necessary byte swapping is carried out using a 64-bit integer
44513 ** rather than a 64-bit float.  Frank assures us that the code here
44514 ** works for him.  We, the developers, have no way to independently
44515 ** verify this, but Frank seems to know what he is talking about
44516 ** so we trust him.
44517 */
44518 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
44519 static u64 floatSwap(u64 in){
44520   union {
44521     u64 r;
44522     u32 i[2];
44523   } u;
44524   u32 t;
44525
44526   u.r = in;
44527   t = u.i[0];
44528   u.i[0] = u.i[1];
44529   u.i[1] = t;
44530   return u.r;
44531 }
44532 # define swapMixedEndianFloat(X)  X = floatSwap(X)
44533 #else
44534 # define swapMixedEndianFloat(X)
44535 #endif
44536
44537 /*
44538 ** Write the serialized data blob for the value stored in pMem into 
44539 ** buf. It is assumed that the caller has allocated sufficient space.
44540 ** Return the number of bytes written.
44541 **
44542 ** nBuf is the amount of space left in buf[].  nBuf must always be
44543 ** large enough to hold the entire field.  Except, if the field is
44544 ** a blob with a zero-filled tail, then buf[] might be just the right
44545 ** size to hold everything except for the zero-filled tail.  If buf[]
44546 ** is only big enough to hold the non-zero prefix, then only write that
44547 ** prefix into buf[].  But if buf[] is large enough to hold both the
44548 ** prefix and the tail then write the prefix and set the tail to all
44549 ** zeros.
44550 **
44551 ** Return the number of bytes actually written into buf[].  The number
44552 ** of bytes in the zero-filled tail is included in the return value only
44553 ** if those bytes were zeroed in buf[].
44554 */ 
44555 SQLITE_PRIVATE int sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
44556   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
44557   int len;
44558
44559   /* Integer and Real */
44560   if( serial_type<=7 && serial_type>0 ){
44561     u64 v;
44562     int i;
44563     if( serial_type==7 ){
44564       assert( sizeof(v)==sizeof(pMem->r) );
44565       memcpy(&v, &pMem->r, sizeof(v));
44566       swapMixedEndianFloat(v);
44567     }else{
44568       v = pMem->u.i;
44569     }
44570     len = i = sqlite3VdbeSerialTypeLen(serial_type);
44571     assert( len<=nBuf );
44572     while( i-- ){
44573       buf[i] = (v&0xFF);
44574       v >>= 8;
44575     }
44576     return len;
44577   }
44578
44579   /* String or blob */
44580   if( serial_type>=12 ){
44581     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.i:0)
44582              == sqlite3VdbeSerialTypeLen(serial_type) );
44583     assert( pMem->n<=nBuf );
44584     len = pMem->n;
44585     memcpy(buf, pMem->z, len);
44586     if( pMem->flags & MEM_Zero ){
44587       len += pMem->u.i;
44588       if( len>nBuf ){
44589         len = nBuf;
44590       }
44591       memset(&buf[pMem->n], 0, len-pMem->n);
44592     }
44593     return len;
44594   }
44595
44596   /* NULL or constants 0 or 1 */
44597   return 0;
44598 }
44599
44600 /*
44601 ** Deserialize the data blob pointed to by buf as serial type serial_type
44602 ** and store the result in pMem.  Return the number of bytes read.
44603 */ 
44604 SQLITE_PRIVATE int sqlite3VdbeSerialGet(
44605   const unsigned char *buf,     /* Buffer to deserialize from */
44606   u32 serial_type,              /* Serial type to deserialize */
44607   Mem *pMem                     /* Memory cell to write value into */
44608 ){
44609   switch( serial_type ){
44610     case 10:   /* Reserved for future use */
44611     case 11:   /* Reserved for future use */
44612     case 0: {  /* NULL */
44613       pMem->flags = MEM_Null;
44614       break;
44615     }
44616     case 1: { /* 1-byte signed integer */
44617       pMem->u.i = (signed char)buf[0];
44618       pMem->flags = MEM_Int;
44619       return 1;
44620     }
44621     case 2: { /* 2-byte signed integer */
44622       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
44623       pMem->flags = MEM_Int;
44624       return 2;
44625     }
44626     case 3: { /* 3-byte signed integer */
44627       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
44628       pMem->flags = MEM_Int;
44629       return 3;
44630     }
44631     case 4: { /* 4-byte signed integer */
44632       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
44633       pMem->flags = MEM_Int;
44634       return 4;
44635     }
44636     case 5: { /* 6-byte signed integer */
44637       u64 x = (((signed char)buf[0])<<8) | buf[1];
44638       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
44639       x = (x<<32) | y;
44640       pMem->u.i = *(i64*)&x;
44641       pMem->flags = MEM_Int;
44642       return 6;
44643     }
44644     case 6:   /* 8-byte signed integer */
44645     case 7: { /* IEEE floating point */
44646       u64 x;
44647       u32 y;
44648 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
44649       /* Verify that integers and floating point values use the same
44650       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
44651       ** defined that 64-bit floating point values really are mixed
44652       ** endian.
44653       */
44654       static const u64 t1 = ((u64)0x3ff00000)<<32;
44655       static const double r1 = 1.0;
44656       u64 t2 = t1;
44657       swapMixedEndianFloat(t2);
44658       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
44659 #endif
44660
44661       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
44662       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
44663       x = (x<<32) | y;
44664       if( serial_type==6 ){
44665         pMem->u.i = *(i64*)&x;
44666         pMem->flags = MEM_Int;
44667       }else{
44668         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
44669         swapMixedEndianFloat(x);
44670         memcpy(&pMem->r, &x, sizeof(x));
44671         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
44672       }
44673       return 8;
44674     }
44675     case 8:    /* Integer 0 */
44676     case 9: {  /* Integer 1 */
44677       pMem->u.i = serial_type-8;
44678       pMem->flags = MEM_Int;
44679       return 0;
44680     }
44681     default: {
44682       int len = (serial_type-12)/2;
44683       pMem->z = (char *)buf;
44684       pMem->n = len;
44685       pMem->xDel = 0;
44686       if( serial_type&0x01 ){
44687         pMem->flags = MEM_Str | MEM_Ephem;
44688       }else{
44689         pMem->flags = MEM_Blob | MEM_Ephem;
44690       }
44691       return len;
44692     }
44693   }
44694   return 0;
44695 }
44696
44697
44698 /*
44699 ** Given the nKey-byte encoding of a record in pKey[], parse the
44700 ** record into a UnpackedRecord structure.  Return a pointer to
44701 ** that structure.
44702 **
44703 ** The calling function might provide szSpace bytes of memory
44704 ** space at pSpace.  This space can be used to hold the returned
44705 ** VDbeParsedRecord structure if it is large enough.  If it is
44706 ** not big enough, space is obtained from sqlite3_malloc().
44707 **
44708 ** The returned structure should be closed by a call to
44709 ** sqlite3VdbeDeleteUnpackedRecord().
44710 */ 
44711 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(
44712   KeyInfo *pKeyInfo,     /* Information about the record format */
44713   int nKey,              /* Size of the binary record */
44714   const void *pKey,      /* The binary record */
44715   UnpackedRecord *pSpace,/* Space available to hold resulting object */
44716   int szSpace            /* Size of pSpace[] in bytes */
44717 ){
44718   const unsigned char *aKey = (const unsigned char *)pKey;
44719   UnpackedRecord *p;
44720   int nByte, d;
44721   u32 idx;
44722   u16 u;                 /* Unsigned loop counter */
44723   u32 szHdr;
44724   Mem *pMem;
44725   
44726   assert( sizeof(Mem)>sizeof(*p) );
44727   nByte = sizeof(Mem)*(pKeyInfo->nField+2);
44728   if( nByte>szSpace ){
44729     p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
44730     if( p==0 ) return 0;
44731     p->flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
44732   }else{
44733     p = pSpace;
44734     p->flags = UNPACKED_NEED_DESTROY;
44735   }
44736   p->pKeyInfo = pKeyInfo;
44737   p->nField = pKeyInfo->nField + 1;
44738   p->aMem = pMem = &((Mem*)p)[1];
44739   idx = getVarint32(aKey, szHdr);
44740   d = szHdr;
44741   u = 0;
44742   while( idx<szHdr && u<p->nField ){
44743     u32 serial_type;
44744
44745     idx += getVarint32(&aKey[idx], serial_type);
44746     if( d>=nKey && sqlite3VdbeSerialTypeLen(serial_type)>0 ) break;
44747     pMem->enc = pKeyInfo->enc;
44748     pMem->db = pKeyInfo->db;
44749     pMem->flags = 0;
44750     pMem->zMalloc = 0;
44751     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
44752     pMem++;
44753     u++;
44754   }
44755   assert( u<=pKeyInfo->nField + 1 );
44756   p->nField = u;
44757   return (void*)p;
44758 }
44759
44760 /*
44761 ** This routine destroys a UnpackedRecord object
44762 */
44763 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
44764   if( p ){
44765     if( p->flags & UNPACKED_NEED_DESTROY ){
44766       int i;
44767       Mem *pMem;
44768       for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
44769         if( pMem->zMalloc ){
44770           sqlite3VdbeMemRelease(pMem);
44771         }
44772       }
44773     }
44774     if( p->flags & UNPACKED_NEED_FREE ){
44775       sqlite3DbFree(p->pKeyInfo->db, p);
44776     }
44777   }
44778 }
44779
44780 /*
44781 ** This function compares the two table rows or index records
44782 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
44783 ** or positive integer if key1 is less than, equal to or 
44784 ** greater than key2.  The {nKey1, pKey1} key must be a blob
44785 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
44786 ** key must be a parsed key such as obtained from
44787 ** sqlite3VdbeParseRecord.
44788 **
44789 ** Key1 and Key2 do not have to contain the same number of fields.
44790 ** The key with fewer fields is usually compares less than the 
44791 ** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
44792 ** and the common prefixes are equal, then key1 is less than key2.
44793 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
44794 ** equal, then the keys are considered to be equal and
44795 ** the parts beyond the common prefix are ignored.
44796 **
44797 ** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
44798 ** the header of pKey1 is ignored.  It is assumed that pKey1 is
44799 ** an index key, and thus ends with a rowid value.  The last byte
44800 ** of the header will therefore be the serial type of the rowid:
44801 ** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
44802 ** The serial type of the final rowid will always be a single byte.
44803 ** By ignoring this last byte of the header, we force the comparison
44804 ** to ignore the rowid at the end of key1.
44805 */
44806 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
44807   int nKey1, const void *pKey1, /* Left key */
44808   UnpackedRecord *pPKey2        /* Right key */
44809 ){
44810   int d1;            /* Offset into aKey[] of next data element */
44811   u32 idx1;          /* Offset into aKey[] of next header element */
44812   u32 szHdr1;        /* Number of bytes in header */
44813   int i = 0;
44814   int nField;
44815   int rc = 0;
44816   const unsigned char *aKey1 = (const unsigned char *)pKey1;
44817   KeyInfo *pKeyInfo;
44818   Mem mem1;
44819
44820   pKeyInfo = pPKey2->pKeyInfo;
44821   mem1.enc = pKeyInfo->enc;
44822   mem1.db = pKeyInfo->db;
44823   mem1.flags = 0;
44824   mem1.zMalloc = 0;
44825   
44826   idx1 = getVarint32(aKey1, szHdr1);
44827   d1 = szHdr1;
44828   if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
44829     szHdr1--;
44830   }
44831   nField = pKeyInfo->nField;
44832   while( idx1<szHdr1 && i<pPKey2->nField ){
44833     u32 serial_type1;
44834
44835     /* Read the serial types for the next element in each key. */
44836     idx1 += getVarint32( aKey1+idx1, serial_type1 );
44837     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
44838
44839     /* Extract the values to be compared.
44840     */
44841     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
44842
44843     /* Do the comparison
44844     */
44845     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
44846                            i<nField ? pKeyInfo->aColl[i] : 0);
44847     if( rc!=0 ){
44848       break;
44849     }
44850     i++;
44851   }
44852   if( mem1.zMalloc ) sqlite3VdbeMemRelease(&mem1);
44853
44854   if( rc==0 ){
44855     /* rc==0 here means that one of the keys ran out of fields and
44856     ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
44857     ** flag is set, then break the tie by treating key2 as larger.
44858     ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
44859     ** are considered to be equal.  Otherwise, the longer key is the 
44860     ** larger.  As it happens, the pPKey2 will always be the longer
44861     ** if there is a difference.
44862     */
44863     if( pPKey2->flags & UNPACKED_INCRKEY ){
44864       rc = -1;
44865     }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
44866       /* Leave rc==0 */
44867     }else if( idx1<szHdr1 ){
44868       rc = 1;
44869     }
44870   }else if( pKeyInfo->aSortOrder && i<pKeyInfo->nField
44871                && pKeyInfo->aSortOrder[i] ){
44872     rc = -rc;
44873   }
44874
44875   return rc;
44876 }
44877  
44878
44879 /*
44880 ** pCur points at an index entry created using the OP_MakeRecord opcode.
44881 ** Read the rowid (the last field in the record) and store it in *rowid.
44882 ** Return SQLITE_OK if everything works, or an error code otherwise.
44883 */
44884 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(BtCursor *pCur, i64 *rowid){
44885   i64 nCellKey = 0;
44886   int rc;
44887   u32 szHdr;        /* Size of the header */
44888   u32 typeRowid;    /* Serial type of the rowid */
44889   u32 lenRowid;     /* Size of the rowid */
44890   Mem m, v;
44891
44892   sqlite3BtreeKeySize(pCur, &nCellKey);
44893   if( nCellKey<=0 ){
44894     return SQLITE_CORRUPT_BKPT;
44895   }
44896   m.flags = 0;
44897   m.db = 0;
44898   m.zMalloc = 0;
44899   rc = sqlite3VdbeMemFromBtree(pCur, 0, nCellKey, 1, &m);
44900   if( rc ){
44901     return rc;
44902   }
44903   (void)getVarint32((u8*)m.z, szHdr);
44904   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
44905   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
44906   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
44907   *rowid = v.u.i;
44908   sqlite3VdbeMemRelease(&m);
44909   return SQLITE_OK;
44910 }
44911
44912 /*
44913 ** Compare the key of the index entry that cursor pC is point to against
44914 ** the key string in pKey (of length nKey).  Write into *pRes a number
44915 ** that is negative, zero, or positive if pC is less than, equal to,
44916 ** or greater than pKey.  Return SQLITE_OK on success.
44917 **
44918 ** pKey is either created without a rowid or is truncated so that it
44919 ** omits the rowid at the end.  The rowid at the end of the index entry
44920 ** is ignored as well.  Hence, this routine only compares the prefixes 
44921 ** of the keys prior to the final rowid, not the entire key.
44922 **
44923 ** pUnpacked may be an unpacked version of pKey,nKey.  If pUnpacked is
44924 ** supplied it is used in place of pKey,nKey.
44925 */
44926 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
44927   VdbeCursor *pC,             /* The cursor to compare against */
44928   UnpackedRecord *pUnpacked,  /* Unpacked version of pKey and nKey */
44929   int *res                    /* Write the comparison result here */
44930 ){
44931   i64 nCellKey = 0;
44932   int rc;
44933   BtCursor *pCur = pC->pCursor;
44934   Mem m;
44935
44936   sqlite3BtreeKeySize(pCur, &nCellKey);
44937   if( nCellKey<=0 ){
44938     *res = 0;
44939     return SQLITE_OK;
44940   }
44941   m.db = 0;
44942   m.flags = 0;
44943   m.zMalloc = 0;
44944   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, nCellKey, 1, &m);
44945   if( rc ){
44946     return rc;
44947   }
44948   assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
44949   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
44950   sqlite3VdbeMemRelease(&m);
44951   return SQLITE_OK;
44952 }
44953
44954 /*
44955 ** This routine sets the value to be returned by subsequent calls to
44956 ** sqlite3_changes() on the database handle 'db'. 
44957 */
44958 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
44959   assert( sqlite3_mutex_held(db->mutex) );
44960   db->nChange = nChange;
44961   db->nTotalChange += nChange;
44962 }
44963
44964 /*
44965 ** Set a flag in the vdbe to update the change counter when it is finalised
44966 ** or reset.
44967 */
44968 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
44969   v->changeCntOn = 1;
44970 }
44971
44972 /*
44973 ** Mark every prepared statement associated with a database connection
44974 ** as expired.
44975 **
44976 ** An expired statement means that recompilation of the statement is
44977 ** recommend.  Statements expire when things happen that make their
44978 ** programs obsolete.  Removing user-defined functions or collating
44979 ** sequences, or changing an authorization function are the types of
44980 ** things that make prepared statements obsolete.
44981 */
44982 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
44983   Vdbe *p;
44984   for(p = db->pVdbe; p; p=p->pNext){
44985     p->expired = 1;
44986   }
44987 }
44988
44989 /*
44990 ** Return the database associated with the Vdbe.
44991 */
44992 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
44993   return v->db;
44994 }
44995
44996 /************** End of vdbeaux.c *********************************************/
44997 /************** Begin file vdbeapi.c *****************************************/
44998 /*
44999 ** 2004 May 26
45000 **
45001 ** The author disclaims copyright to this source code.  In place of
45002 ** a legal notice, here is a blessing:
45003 **
45004 **    May you do good and not evil.
45005 **    May you find forgiveness for yourself and forgive others.
45006 **    May you share freely, never taking more than you give.
45007 **
45008 *************************************************************************
45009 **
45010 ** This file contains code use to implement APIs that are part of the
45011 ** VDBE.
45012 **
45013 ** $Id: vdbeapi.c,v 1.149 2008/11/19 09:05:27 danielk1977 Exp $
45014 */
45015
45016 #if 0 && defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
45017 /*
45018 ** The following structure contains pointers to the end points of a
45019 ** doubly-linked list of all compiled SQL statements that may be holding
45020 ** buffers eligible for release when the sqlite3_release_memory() interface is
45021 ** invoked. Access to this list is protected by the SQLITE_MUTEX_STATIC_LRU2
45022 ** mutex.
45023 **
45024 ** Statements are added to the end of this list when sqlite3_reset() is
45025 ** called. They are removed either when sqlite3_step() or sqlite3_finalize()
45026 ** is called. When statements are added to this list, the associated 
45027 ** register array (p->aMem[1..p->nMem]) may contain dynamic buffers that
45028 ** can be freed using sqlite3VdbeReleaseMemory().
45029 **
45030 ** When statements are added or removed from this list, the mutex
45031 ** associated with the Vdbe being added or removed (Vdbe.db->mutex) is
45032 ** already held. The LRU2 mutex is then obtained, blocking if necessary,
45033 ** the linked-list pointers manipulated and the LRU2 mutex relinquished.
45034 */
45035 struct StatementLruList {
45036   Vdbe *pFirst;
45037   Vdbe *pLast;
45038 };
45039 static struct StatementLruList sqlite3LruStatements;
45040
45041 /*
45042 ** Check that the list looks to be internally consistent. This is used
45043 ** as part of an assert() statement as follows:
45044 **
45045 **   assert( stmtLruCheck() );
45046 */
45047 #ifndef NDEBUG
45048 static int stmtLruCheck(){
45049   Vdbe *p;
45050   for(p=sqlite3LruStatements.pFirst; p; p=p->pLruNext){
45051     assert(p->pLruNext || p==sqlite3LruStatements.pLast);
45052     assert(!p->pLruNext || p->pLruNext->pLruPrev==p);
45053     assert(p->pLruPrev || p==sqlite3LruStatements.pFirst);
45054     assert(!p->pLruPrev || p->pLruPrev->pLruNext==p);
45055   }
45056   return 1;
45057 }
45058 #endif
45059
45060 /*
45061 ** Add vdbe p to the end of the statement lru list. It is assumed that
45062 ** p is not already part of the list when this is called. The lru list
45063 ** is protected by the SQLITE_MUTEX_STATIC_LRU mutex.
45064 */
45065 static void stmtLruAdd(Vdbe *p){
45066   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
45067
45068   if( p->pLruPrev || p->pLruNext || sqlite3LruStatements.pFirst==p ){
45069     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
45070     return;
45071   }
45072
45073   assert( stmtLruCheck() );
45074
45075   if( !sqlite3LruStatements.pFirst ){
45076     assert( !sqlite3LruStatements.pLast );
45077     sqlite3LruStatements.pFirst = p;
45078     sqlite3LruStatements.pLast = p;
45079   }else{
45080     assert( !sqlite3LruStatements.pLast->pLruNext );
45081     p->pLruPrev = sqlite3LruStatements.pLast;
45082     sqlite3LruStatements.pLast->pLruNext = p;
45083     sqlite3LruStatements.pLast = p;
45084   }
45085
45086   assert( stmtLruCheck() );
45087
45088   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
45089 }
45090
45091 /*
45092 ** Assuming the SQLITE_MUTEX_STATIC_LRU2 mutext is already held, remove
45093 ** statement p from the least-recently-used statement list. If the 
45094 ** statement is not currently part of the list, this call is a no-op.
45095 */
45096 static void stmtLruRemoveNomutex(Vdbe *p){
45097   if( p->pLruPrev || p->pLruNext || p==sqlite3LruStatements.pFirst ){
45098     assert( stmtLruCheck() );
45099     if( p->pLruNext ){
45100       p->pLruNext->pLruPrev = p->pLruPrev;
45101     }else{
45102       sqlite3LruStatements.pLast = p->pLruPrev;
45103     }
45104     if( p->pLruPrev ){
45105       p->pLruPrev->pLruNext = p->pLruNext;
45106     }else{
45107       sqlite3LruStatements.pFirst = p->pLruNext;
45108     }
45109     p->pLruNext = 0;
45110     p->pLruPrev = 0;
45111     assert( stmtLruCheck() );
45112   }
45113 }
45114
45115 /*
45116 ** Assuming the SQLITE_MUTEX_STATIC_LRU2 mutext is not held, remove
45117 ** statement p from the least-recently-used statement list. If the 
45118 ** statement is not currently part of the list, this call is a no-op.
45119 */
45120 static void stmtLruRemove(Vdbe *p){
45121   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
45122   stmtLruRemoveNomutex(p);
45123   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
45124 }
45125
45126 /*
45127 ** Try to release n bytes of memory by freeing buffers associated 
45128 ** with the memory registers of currently unused vdbes.
45129 */
45130 SQLITE_PRIVATE int sqlite3VdbeReleaseMemory(int n){
45131   Vdbe *p;
45132   Vdbe *pNext;
45133   int nFree = 0;
45134
45135   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
45136   for(p=sqlite3LruStatements.pFirst; p && nFree<n; p=pNext){
45137     pNext = p->pLruNext;
45138
45139     /* For each statement handle in the lru list, attempt to obtain the
45140     ** associated database mutex. If it cannot be obtained, continue
45141     ** to the next statement handle. It is not possible to block on
45142     ** the database mutex - that could cause deadlock.
45143     */
45144     if( SQLITE_OK==sqlite3_mutex_try(p->db->mutex) ){
45145       nFree += sqlite3VdbeReleaseBuffers(p);
45146       stmtLruRemoveNomutex(p);
45147       sqlite3_mutex_leave(p->db->mutex);
45148     }
45149   }
45150   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
45151
45152   return nFree;
45153 }
45154
45155 /*
45156 ** Call sqlite3Reprepare() on the statement. Remove it from the
45157 ** lru list before doing so, as Reprepare() will free all the
45158 ** memory register buffers anyway.
45159 */
45160 int vdbeReprepare(Vdbe *p){
45161   stmtLruRemove(p);
45162   return sqlite3Reprepare(p);
45163 }
45164
45165 #else       /* !SQLITE_ENABLE_MEMORY_MANAGEMENT */
45166   #define stmtLruRemove(x)
45167   #define stmtLruAdd(x)
45168   #define vdbeReprepare(x) sqlite3Reprepare(x)
45169 #endif
45170
45171
45172 #ifndef SQLITE_OMIT_DEPRECATED
45173 /*
45174 ** Return TRUE (non-zero) of the statement supplied as an argument needs
45175 ** to be recompiled.  A statement needs to be recompiled whenever the
45176 ** execution environment changes in a way that would alter the program
45177 ** that sqlite3_prepare() generates.  For example, if new functions or
45178 ** collating sequences are registered or if an authorizer function is
45179 ** added or changed.
45180 */
45181 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
45182   Vdbe *p = (Vdbe*)pStmt;
45183   return p==0 || p->expired;
45184 }
45185 #endif
45186
45187 /*
45188 ** The following routine destroys a virtual machine that is created by
45189 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
45190 ** success/failure code that describes the result of executing the virtual
45191 ** machine.
45192 **
45193 ** This routine sets the error code and string returned by
45194 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
45195 */
45196 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
45197   int rc;
45198   if( pStmt==0 ){
45199     rc = SQLITE_OK;
45200   }else{
45201     Vdbe *v = (Vdbe*)pStmt;
45202 #if SQLITE_THREADSAFE
45203     sqlite3_mutex *mutex = v->db->mutex;
45204 #endif
45205     sqlite3_mutex_enter(mutex);
45206     stmtLruRemove(v);
45207     rc = sqlite3VdbeFinalize(v);
45208     sqlite3_mutex_leave(mutex);
45209   }
45210   return rc;
45211 }
45212
45213 /*
45214 ** Terminate the current execution of an SQL statement and reset it
45215 ** back to its starting state so that it can be reused. A success code from
45216 ** the prior execution is returned.
45217 **
45218 ** This routine sets the error code and string returned by
45219 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
45220 */
45221 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
45222   int rc;
45223   if( pStmt==0 ){
45224     rc = SQLITE_OK;
45225   }else{
45226     Vdbe *v = (Vdbe*)pStmt;
45227     sqlite3_mutex_enter(v->db->mutex);
45228     rc = sqlite3VdbeReset(v);
45229     stmtLruAdd(v);
45230     sqlite3VdbeMakeReady(v, -1, 0, 0, 0);
45231     assert( (rc & (v->db->errMask))==rc );
45232     sqlite3_mutex_leave(v->db->mutex);
45233   }
45234   return rc;
45235 }
45236
45237 /*
45238 ** Set all the parameters in the compiled SQL statement to NULL.
45239 */
45240 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
45241   int i;
45242   int rc = SQLITE_OK;
45243   Vdbe *p = (Vdbe*)pStmt;
45244 #if SQLITE_THREADSAFE
45245   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
45246 #endif
45247   sqlite3_mutex_enter(mutex);
45248   for(i=0; i<p->nVar; i++){
45249     sqlite3VdbeMemRelease(&p->aVar[i]);
45250     p->aVar[i].flags = MEM_Null;
45251   }
45252   sqlite3_mutex_leave(mutex);
45253   return rc;
45254 }
45255
45256
45257 /**************************** sqlite3_value_  *******************************
45258 ** The following routines extract information from a Mem or sqlite3_value
45259 ** structure.
45260 */
45261 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
45262   Mem *p = (Mem*)pVal;
45263   if( p->flags & (MEM_Blob|MEM_Str) ){
45264     sqlite3VdbeMemExpandBlob(p);
45265     p->flags &= ~MEM_Str;
45266     p->flags |= MEM_Blob;
45267     return p->z;
45268   }else{
45269     return sqlite3_value_text(pVal);
45270   }
45271 }
45272 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
45273   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
45274 }
45275 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
45276   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
45277 }
45278 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
45279   return sqlite3VdbeRealValue((Mem*)pVal);
45280 }
45281 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
45282   return sqlite3VdbeIntValue((Mem*)pVal);
45283 }
45284 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
45285   return sqlite3VdbeIntValue((Mem*)pVal);
45286 }
45287 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
45288   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
45289 }
45290 #ifndef SQLITE_OMIT_UTF16
45291 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
45292   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
45293 }
45294 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
45295   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
45296 }
45297 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
45298   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
45299 }
45300 #endif /* SQLITE_OMIT_UTF16 */
45301 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
45302   return pVal->type;
45303 }
45304
45305 /**************************** sqlite3_result_  *******************************
45306 ** The following routines are used by user-defined functions to specify
45307 ** the function result.
45308 */
45309 SQLITE_API void sqlite3_result_blob(
45310   sqlite3_context *pCtx, 
45311   const void *z, 
45312   int n, 
45313   void (*xDel)(void *)
45314 ){
45315   assert( n>=0 );
45316   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
45317   sqlite3VdbeMemSetStr(&pCtx->s, z, n, 0, xDel);
45318 }
45319 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
45320   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
45321   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
45322 }
45323 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
45324   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
45325   pCtx->isError = SQLITE_ERROR;
45326   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
45327 }
45328 #ifndef SQLITE_OMIT_UTF16
45329 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
45330   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
45331   pCtx->isError = SQLITE_ERROR;
45332   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
45333 }
45334 #endif
45335 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
45336   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
45337   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
45338 }
45339 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
45340   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
45341   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
45342 }
45343 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
45344   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
45345   sqlite3VdbeMemSetNull(&pCtx->s);
45346 }
45347 SQLITE_API void sqlite3_result_text(
45348   sqlite3_context *pCtx, 
45349   const char *z, 
45350   int n,
45351   void (*xDel)(void *)
45352 ){
45353   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
45354   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, xDel);
45355 }
45356 #ifndef SQLITE_OMIT_UTF16
45357 SQLITE_API void sqlite3_result_text16(
45358   sqlite3_context *pCtx, 
45359   const void *z, 
45360   int n, 
45361   void (*xDel)(void *)
45362 ){
45363   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
45364   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, xDel);
45365 }
45366 SQLITE_API void sqlite3_result_text16be(
45367   sqlite3_context *pCtx, 
45368   const void *z, 
45369   int n, 
45370   void (*xDel)(void *)
45371 ){
45372   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
45373   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16BE, xDel);
45374 }
45375 SQLITE_API void sqlite3_result_text16le(
45376   sqlite3_context *pCtx, 
45377   const void *z, 
45378   int n, 
45379   void (*xDel)(void *)
45380 ){
45381   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
45382   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16LE, xDel);
45383 }
45384 #endif /* SQLITE_OMIT_UTF16 */
45385 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
45386   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
45387   sqlite3VdbeMemCopy(&pCtx->s, pValue);
45388 }
45389 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
45390   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
45391   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
45392 }
45393 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
45394   pCtx->isError = errCode;
45395 }
45396
45397 /* Force an SQLITE_TOOBIG error. */
45398 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
45399   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
45400   pCtx->isError = SQLITE_TOOBIG;
45401   sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1, 
45402                        SQLITE_UTF8, SQLITE_STATIC);
45403 }
45404
45405 /* An SQLITE_NOMEM error. */
45406 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
45407   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
45408   sqlite3VdbeMemSetNull(&pCtx->s);
45409   pCtx->isError = SQLITE_NOMEM;
45410   pCtx->s.db->mallocFailed = 1;
45411 }
45412
45413 /*
45414 ** Execute the statement pStmt, either until a row of data is ready, the
45415 ** statement is completely executed or an error occurs.
45416 **
45417 ** This routine implements the bulk of the logic behind the sqlite_step()
45418 ** API.  The only thing omitted is the automatic recompile if a 
45419 ** schema change has occurred.  That detail is handled by the
45420 ** outer sqlite3_step() wrapper procedure.
45421 */
45422 static int sqlite3Step(Vdbe *p){
45423   sqlite3 *db;
45424   int rc;
45425
45426   assert(p);
45427   if( p->magic!=VDBE_MAGIC_RUN ){
45428     return SQLITE_MISUSE;
45429   }
45430
45431   /* Assert that malloc() has not failed */
45432   db = p->db;
45433   if( db->mallocFailed ){
45434     return SQLITE_NOMEM;
45435   }
45436
45437   if( p->pc<=0 && p->expired ){
45438     if( p->rc==SQLITE_OK ){
45439       p->rc = SQLITE_SCHEMA;
45440     }
45441     rc = SQLITE_ERROR;
45442     goto end_of_step;
45443   }
45444   if( sqlite3SafetyOn(db) ){
45445     p->rc = SQLITE_MISUSE;
45446     return SQLITE_MISUSE;
45447   }
45448   if( p->pc<0 ){
45449     /* If there are no other statements currently running, then
45450     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
45451     ** from interrupting a statement that has not yet started.
45452     */
45453     if( db->activeVdbeCnt==0 ){
45454       db->u1.isInterrupted = 0;
45455     }
45456
45457 #ifndef SQLITE_OMIT_TRACE
45458     if( db->xProfile && !db->init.busy ){
45459       double rNow;
45460       sqlite3OsCurrentTime(db->pVfs, &rNow);
45461       p->startTime = (rNow - (int)rNow)*3600.0*24.0*1000000000.0;
45462     }
45463 #endif
45464
45465     db->activeVdbeCnt++;
45466     if( p->readOnly==0 ) db->writeVdbeCnt++;
45467     p->pc = 0;
45468     stmtLruRemove(p);
45469   }
45470 #ifndef SQLITE_OMIT_EXPLAIN
45471   if( p->explain ){
45472     rc = sqlite3VdbeList(p);
45473   }else
45474 #endif /* SQLITE_OMIT_EXPLAIN */
45475   {
45476     rc = sqlite3VdbeExec(p);
45477   }
45478
45479   if( sqlite3SafetyOff(db) ){
45480     rc = SQLITE_MISUSE;
45481   }
45482
45483 #ifndef SQLITE_OMIT_TRACE
45484   /* Invoke the profile callback if there is one
45485   */
45486   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->nOp>0
45487            && p->aOp[0].opcode==OP_Trace && p->aOp[0].p4.z!=0 ){
45488     double rNow;
45489     u64 elapseTime;
45490
45491     sqlite3OsCurrentTime(db->pVfs, &rNow);
45492     elapseTime = (rNow - (int)rNow)*3600.0*24.0*1000000000.0 - p->startTime;
45493     db->xProfile(db->pProfileArg, p->aOp[0].p4.z, elapseTime);
45494   }
45495 #endif
45496
45497   db->errCode = rc;
45498   /*sqlite3Error(p->db, rc, 0);*/
45499   p->rc = sqlite3ApiExit(p->db, p->rc);
45500 end_of_step:
45501   assert( (rc&0xff)==rc );
45502   if( p->zSql && (rc&0xff)<SQLITE_ROW ){
45503     /* This behavior occurs if sqlite3_prepare_v2() was used to build
45504     ** the prepared statement.  Return error codes directly */
45505     p->db->errCode = p->rc;
45506     /* sqlite3Error(p->db, p->rc, 0); */
45507     return p->rc;
45508   }else{
45509     /* This is for legacy sqlite3_prepare() builds and when the code
45510     ** is SQLITE_ROW or SQLITE_DONE */
45511     return rc;
45512   }
45513 }
45514
45515 /*
45516 ** This is the top-level implementation of sqlite3_step().  Call
45517 ** sqlite3Step() to do most of the work.  If a schema error occurs,
45518 ** call sqlite3Reprepare() and try again.
45519 */
45520 #ifdef SQLITE_OMIT_PARSER
45521 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
45522   int rc = SQLITE_MISUSE;
45523   if( pStmt ){
45524     Vdbe *v;
45525     v = (Vdbe*)pStmt;
45526     sqlite3_mutex_enter(v->db->mutex);
45527     rc = sqlite3Step(v);
45528     sqlite3_mutex_leave(v->db->mutex);
45529   }
45530   return rc;
45531 }
45532 #else
45533 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
45534   int rc = SQLITE_MISUSE;
45535   if( pStmt ){
45536     int cnt = 0;
45537     Vdbe *v = (Vdbe*)pStmt;
45538     sqlite3 *db = v->db;
45539     sqlite3_mutex_enter(db->mutex);
45540     while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
45541            && cnt++ < 5
45542            && vdbeReprepare(v) ){
45543       sqlite3_reset(pStmt);
45544       v->expired = 0;
45545     }
45546     if( rc==SQLITE_SCHEMA && v->zSql && db->pErr ){
45547       /* This case occurs after failing to recompile an sql statement. 
45548       ** The error message from the SQL compiler has already been loaded 
45549       ** into the database handle. This block copies the error message 
45550       ** from the database handle into the statement and sets the statement
45551       ** program counter to 0 to ensure that when the statement is 
45552       ** finalized or reset the parser error message is available via
45553       ** sqlite3_errmsg() and sqlite3_errcode().
45554       */
45555       const char *zErr = (const char *)sqlite3_value_text(db->pErr); 
45556       sqlite3DbFree(db, v->zErrMsg);
45557       if( !db->mallocFailed ){
45558         v->zErrMsg = sqlite3DbStrDup(db, zErr);
45559       } else {
45560         v->zErrMsg = 0;
45561         v->rc = SQLITE_NOMEM;
45562       }
45563     }
45564     rc = sqlite3ApiExit(db, rc);
45565     sqlite3_mutex_leave(db->mutex);
45566   }
45567   return rc;
45568 }
45569 #endif
45570
45571 /*
45572 ** Extract the user data from a sqlite3_context structure and return a
45573 ** pointer to it.
45574 */
45575 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
45576   assert( p && p->pFunc );
45577   return p->pFunc->pUserData;
45578 }
45579
45580 /*
45581 ** Extract the user data from a sqlite3_context structure and return a
45582 ** pointer to it.
45583 */
45584 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
45585   assert( p && p->pFunc );
45586   return p->s.db;
45587 }
45588
45589 /*
45590 ** The following is the implementation of an SQL function that always
45591 ** fails with an error message stating that the function is used in the
45592 ** wrong context.  The sqlite3_overload_function() API might construct
45593 ** SQL function that use this routine so that the functions will exist
45594 ** for name resolution but are actually overloaded by the xFindFunction
45595 ** method of virtual tables.
45596 */
45597 SQLITE_PRIVATE void sqlite3InvalidFunction(
45598   sqlite3_context *context,  /* The function calling context */
45599   int NotUsed,               /* Number of arguments to the function */
45600   sqlite3_value **NotUsed2   /* Value of each argument */
45601 ){
45602   const char *zName = context->pFunc->zName;
45603   char *zErr;
45604   UNUSED_PARAMETER2(NotUsed, NotUsed2);
45605   zErr = sqlite3MPrintf(0,
45606       "unable to use function %s in the requested context", zName);
45607   sqlite3_result_error(context, zErr, -1);
45608   sqlite3_free(zErr);
45609 }
45610
45611 /*
45612 ** Allocate or return the aggregate context for a user function.  A new
45613 ** context is allocated on the first call.  Subsequent calls return the
45614 ** same context that was returned on prior calls.
45615 */
45616 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
45617   Mem *pMem;
45618   assert( p && p->pFunc && p->pFunc->xStep );
45619   assert( sqlite3_mutex_held(p->s.db->mutex) );
45620   pMem = p->pMem;
45621   if( (pMem->flags & MEM_Agg)==0 ){
45622     if( nByte==0 ){
45623       sqlite3VdbeMemReleaseExternal(pMem);
45624       pMem->flags = MEM_Null;
45625       pMem->z = 0;
45626     }else{
45627       sqlite3VdbeMemGrow(pMem, nByte, 0);
45628       pMem->flags = MEM_Agg;
45629       pMem->u.pDef = p->pFunc;
45630       if( pMem->z ){
45631         memset(pMem->z, 0, nByte);
45632       }
45633     }
45634   }
45635   return (void*)pMem->z;
45636 }
45637
45638 /*
45639 ** Return the auxilary data pointer, if any, for the iArg'th argument to
45640 ** the user-function defined by pCtx.
45641 */
45642 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
45643   VdbeFunc *pVdbeFunc;
45644
45645   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
45646   pVdbeFunc = pCtx->pVdbeFunc;
45647   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
45648     return 0;
45649   }
45650   return pVdbeFunc->apAux[iArg].pAux;
45651 }
45652
45653 /*
45654 ** Set the auxilary data pointer and delete function, for the iArg'th
45655 ** argument to the user-function defined by pCtx. Any previous value is
45656 ** deleted by calling the delete function specified when it was set.
45657 */
45658 SQLITE_API void sqlite3_set_auxdata(
45659   sqlite3_context *pCtx, 
45660   int iArg, 
45661   void *pAux, 
45662   void (*xDelete)(void*)
45663 ){
45664   struct AuxData *pAuxData;
45665   VdbeFunc *pVdbeFunc;
45666   if( iArg<0 ) goto failed;
45667
45668   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
45669   pVdbeFunc = pCtx->pVdbeFunc;
45670   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
45671     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
45672     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
45673     pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
45674     if( !pVdbeFunc ){
45675       goto failed;
45676     }
45677     pCtx->pVdbeFunc = pVdbeFunc;
45678     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
45679     pVdbeFunc->nAux = iArg+1;
45680     pVdbeFunc->pFunc = pCtx->pFunc;
45681   }
45682
45683   pAuxData = &pVdbeFunc->apAux[iArg];
45684   if( pAuxData->pAux && pAuxData->xDelete ){
45685     pAuxData->xDelete(pAuxData->pAux);
45686   }
45687   pAuxData->pAux = pAux;
45688   pAuxData->xDelete = xDelete;
45689   return;
45690
45691 failed:
45692   if( xDelete ){
45693     xDelete(pAux);
45694   }
45695 }
45696
45697 #ifndef SQLITE_OMIT_DEPRECATED
45698 /*
45699 ** Return the number of times the Step function of a aggregate has been 
45700 ** called.
45701 **
45702 ** This function is deprecated.  Do not use it for new code.  It is
45703 ** provide only to avoid breaking legacy code.  New aggregate function
45704 ** implementations should keep their own counts within their aggregate
45705 ** context.
45706 */
45707 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
45708   assert( p && p->pFunc && p->pFunc->xStep );
45709   return p->pMem->n;
45710 }
45711 #endif
45712
45713 /*
45714 ** Return the number of columns in the result set for the statement pStmt.
45715 */
45716 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
45717   Vdbe *pVm = (Vdbe *)pStmt;
45718   return pVm ? pVm->nResColumn : 0;
45719 }
45720
45721 /*
45722 ** Return the number of values available from the current row of the
45723 ** currently executing statement pStmt.
45724 */
45725 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
45726   Vdbe *pVm = (Vdbe *)pStmt;
45727   if( pVm==0 || pVm->pResultSet==0 ) return 0;
45728   return pVm->nResColumn;
45729 }
45730
45731
45732 /*
45733 ** Check to see if column iCol of the given statement is valid.  If
45734 ** it is, return a pointer to the Mem for the value of that column.
45735 ** If iCol is not valid, return a pointer to a Mem which has a value
45736 ** of NULL.
45737 */
45738 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
45739   Vdbe *pVm;
45740   int vals;
45741   Mem *pOut;
45742
45743   pVm = (Vdbe *)pStmt;
45744   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
45745     sqlite3_mutex_enter(pVm->db->mutex);
45746     vals = sqlite3_data_count(pStmt);
45747     pOut = &pVm->pResultSet[i];
45748   }else{
45749     static const Mem nullMem = {{0}, 0.0, 0, "", 0, MEM_Null, SQLITE_NULL, 0, 0, 0 };
45750     if( pVm->db ){
45751       sqlite3_mutex_enter(pVm->db->mutex);
45752       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
45753     }
45754     pOut = (Mem*)&nullMem;
45755   }
45756   return pOut;
45757 }
45758
45759 /*
45760 ** This function is called after invoking an sqlite3_value_XXX function on a 
45761 ** column value (i.e. a value returned by evaluating an SQL expression in the
45762 ** select list of a SELECT statement) that may cause a malloc() failure. If 
45763 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
45764 ** code of statement pStmt set to SQLITE_NOMEM.
45765 **
45766 ** Specifically, this is called from within:
45767 **
45768 **     sqlite3_column_int()
45769 **     sqlite3_column_int64()
45770 **     sqlite3_column_text()
45771 **     sqlite3_column_text16()
45772 **     sqlite3_column_real()
45773 **     sqlite3_column_bytes()
45774 **     sqlite3_column_bytes16()
45775 **
45776 ** But not for sqlite3_column_blob(), which never calls malloc().
45777 */
45778 static void columnMallocFailure(sqlite3_stmt *pStmt)
45779 {
45780   /* If malloc() failed during an encoding conversion within an
45781   ** sqlite3_column_XXX API, then set the return code of the statement to
45782   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
45783   ** and _finalize() will return NOMEM.
45784   */
45785   Vdbe *p = (Vdbe *)pStmt;
45786   if( p ){
45787     p->rc = sqlite3ApiExit(p->db, p->rc);
45788     sqlite3_mutex_leave(p->db->mutex);
45789   }
45790 }
45791
45792 /**************************** sqlite3_column_  *******************************
45793 ** The following routines are used to access elements of the current row
45794 ** in the result set.
45795 */
45796 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
45797   const void *val;
45798   val = sqlite3_value_blob( columnMem(pStmt,i) );
45799   /* Even though there is no encoding conversion, value_blob() might
45800   ** need to call malloc() to expand the result of a zeroblob() 
45801   ** expression. 
45802   */
45803   columnMallocFailure(pStmt);
45804   return val;
45805 }
45806 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
45807   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
45808   columnMallocFailure(pStmt);
45809   return val;
45810 }
45811 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
45812   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
45813   columnMallocFailure(pStmt);
45814   return val;
45815 }
45816 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
45817   double val = sqlite3_value_double( columnMem(pStmt,i) );
45818   columnMallocFailure(pStmt);
45819   return val;
45820 }
45821 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
45822   int val = sqlite3_value_int( columnMem(pStmt,i) );
45823   columnMallocFailure(pStmt);
45824   return val;
45825 }
45826 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
45827   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
45828   columnMallocFailure(pStmt);
45829   return val;
45830 }
45831 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
45832   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
45833   columnMallocFailure(pStmt);
45834   return val;
45835 }
45836 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
45837   Mem *pOut = columnMem(pStmt, i);
45838   if( pOut->flags&MEM_Static ){
45839     pOut->flags &= ~MEM_Static;
45840     pOut->flags |= MEM_Ephem;
45841   }
45842   columnMallocFailure(pStmt);
45843   return (sqlite3_value *)pOut;
45844 }
45845 #ifndef SQLITE_OMIT_UTF16
45846 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
45847   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
45848   columnMallocFailure(pStmt);
45849   return val;
45850 }
45851 #endif /* SQLITE_OMIT_UTF16 */
45852 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
45853   int iType = sqlite3_value_type( columnMem(pStmt,i) );
45854   columnMallocFailure(pStmt);
45855   return iType;
45856 }
45857
45858 /* The following function is experimental and subject to change or
45859 ** removal */
45860 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
45861 **  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
45862 **}
45863 */
45864
45865 /*
45866 ** Convert the N-th element of pStmt->pColName[] into a string using
45867 ** xFunc() then return that string.  If N is out of range, return 0.
45868 **
45869 ** There are up to 5 names for each column.  useType determines which
45870 ** name is returned.  Here are the names:
45871 **
45872 **    0      The column name as it should be displayed for output
45873 **    1      The datatype name for the column
45874 **    2      The name of the database that the column derives from
45875 **    3      The name of the table that the column derives from
45876 **    4      The name of the table column that the result column derives from
45877 **
45878 ** If the result is not a simple column reference (if it is an expression
45879 ** or a constant) then useTypes 2, 3, and 4 return NULL.
45880 */
45881 static const void *columnName(
45882   sqlite3_stmt *pStmt,
45883   int N,
45884   const void *(*xFunc)(Mem*),
45885   int useType
45886 ){
45887   const void *ret = 0;
45888   Vdbe *p = (Vdbe *)pStmt;
45889   int n;
45890   
45891
45892   if( p!=0 ){
45893     n = sqlite3_column_count(pStmt);
45894     if( N<n && N>=0 ){
45895       N += useType*n;
45896       sqlite3_mutex_enter(p->db->mutex);
45897       ret = xFunc(&p->aColName[N]);
45898
45899       /* A malloc may have failed inside of the xFunc() call. If this
45900       ** is the case, clear the mallocFailed flag and return NULL.
45901       */
45902       if( p->db && p->db->mallocFailed ){
45903         p->db->mallocFailed = 0;
45904         ret = 0;
45905       }
45906       sqlite3_mutex_leave(p->db->mutex);
45907     }
45908   }
45909   return ret;
45910 }
45911
45912 /*
45913 ** Return the name of the Nth column of the result set returned by SQL
45914 ** statement pStmt.
45915 */
45916 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
45917   return columnName(
45918       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
45919 }
45920 #ifndef SQLITE_OMIT_UTF16
45921 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
45922   return columnName(
45923       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
45924 }
45925 #endif
45926
45927 /*
45928 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
45929 ** not define OMIT_DECLTYPE.
45930 */
45931 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
45932 # error "Must not define both SQLITE_OMIT_DECLTYPE \
45933          and SQLITE_ENABLE_COLUMN_METADATA"
45934 #endif
45935
45936 #ifndef SQLITE_OMIT_DECLTYPE
45937 /*
45938 ** Return the column declaration type (if applicable) of the 'i'th column
45939 ** of the result set of SQL statement pStmt.
45940 */
45941 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
45942   return columnName(
45943       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
45944 }
45945 #ifndef SQLITE_OMIT_UTF16
45946 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
45947   return columnName(
45948       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
45949 }
45950 #endif /* SQLITE_OMIT_UTF16 */
45951 #endif /* SQLITE_OMIT_DECLTYPE */
45952
45953 #ifdef SQLITE_ENABLE_COLUMN_METADATA
45954 /*
45955 ** Return the name of the database from which a result column derives.
45956 ** NULL is returned if the result column is an expression or constant or
45957 ** anything else which is not an unabiguous reference to a database column.
45958 */
45959 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
45960   return columnName(
45961       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
45962 }
45963 #ifndef SQLITE_OMIT_UTF16
45964 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
45965   return columnName(
45966       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
45967 }
45968 #endif /* SQLITE_OMIT_UTF16 */
45969
45970 /*
45971 ** Return the name of the table from which a result column derives.
45972 ** NULL is returned if the result column is an expression or constant or
45973 ** anything else which is not an unabiguous reference to a database column.
45974 */
45975 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
45976   return columnName(
45977       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
45978 }
45979 #ifndef SQLITE_OMIT_UTF16
45980 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
45981   return columnName(
45982       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
45983 }
45984 #endif /* SQLITE_OMIT_UTF16 */
45985
45986 /*
45987 ** Return the name of the table column from which a result column derives.
45988 ** NULL is returned if the result column is an expression or constant or
45989 ** anything else which is not an unabiguous reference to a database column.
45990 */
45991 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
45992   return columnName(
45993       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
45994 }
45995 #ifndef SQLITE_OMIT_UTF16
45996 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
45997   return columnName(
45998       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
45999 }
46000 #endif /* SQLITE_OMIT_UTF16 */
46001 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
46002
46003
46004 /******************************* sqlite3_bind_  ***************************
46005 ** 
46006 ** Routines used to attach values to wildcards in a compiled SQL statement.
46007 */
46008 /*
46009 ** Unbind the value bound to variable i in virtual machine p. This is the 
46010 ** the same as binding a NULL value to the column. If the "i" parameter is
46011 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
46012 **
46013 ** A successful evaluation of this routine acquires the mutex on p.
46014 ** the mutex is released if any kind of error occurs.
46015 **
46016 ** The error code stored in database p->db is overwritten with the return
46017 ** value in any case.
46018 */
46019 static int vdbeUnbind(Vdbe *p, int i){
46020   Mem *pVar;
46021   if( p==0 ) return SQLITE_MISUSE;
46022   sqlite3_mutex_enter(p->db->mutex);
46023   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
46024     sqlite3Error(p->db, SQLITE_MISUSE, 0);
46025     sqlite3_mutex_leave(p->db->mutex);
46026     return SQLITE_MISUSE;
46027   }
46028   if( i<1 || i>p->nVar ){
46029     sqlite3Error(p->db, SQLITE_RANGE, 0);
46030     sqlite3_mutex_leave(p->db->mutex);
46031     return SQLITE_RANGE;
46032   }
46033   i--;
46034   pVar = &p->aVar[i];
46035   sqlite3VdbeMemRelease(pVar);
46036   pVar->flags = MEM_Null;
46037   sqlite3Error(p->db, SQLITE_OK, 0);
46038   return SQLITE_OK;
46039 }
46040
46041 /*
46042 ** Bind a text or BLOB value.
46043 */
46044 static int bindText(
46045   sqlite3_stmt *pStmt,   /* The statement to bind against */
46046   int i,                 /* Index of the parameter to bind */
46047   const void *zData,     /* Pointer to the data to be bound */
46048   int nData,             /* Number of bytes of data to be bound */
46049   void (*xDel)(void*),   /* Destructor for the data */
46050   int encoding           /* Encoding for the data */
46051 ){
46052   Vdbe *p = (Vdbe *)pStmt;
46053   Mem *pVar;
46054   int rc;
46055
46056   rc = vdbeUnbind(p, i);
46057   if( rc==SQLITE_OK ){
46058     if( zData!=0 ){
46059       pVar = &p->aVar[i-1];
46060       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
46061       if( rc==SQLITE_OK && encoding!=0 ){
46062         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
46063       }
46064       sqlite3Error(p->db, rc, 0);
46065       rc = sqlite3ApiExit(p->db, rc);
46066     }
46067     sqlite3_mutex_leave(p->db->mutex);
46068   }
46069   return rc;
46070 }
46071
46072
46073 /*
46074 ** Bind a blob value to an SQL statement variable.
46075 */
46076 SQLITE_API int sqlite3_bind_blob(
46077   sqlite3_stmt *pStmt, 
46078   int i, 
46079   const void *zData, 
46080   int nData, 
46081   void (*xDel)(void*)
46082 ){
46083   return bindText(pStmt, i, zData, nData, xDel, 0);
46084 }
46085 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
46086   int rc;
46087   Vdbe *p = (Vdbe *)pStmt;
46088   rc = vdbeUnbind(p, i);
46089   if( rc==SQLITE_OK ){
46090     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
46091     sqlite3_mutex_leave(p->db->mutex);
46092   }
46093   return rc;
46094 }
46095 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
46096   return sqlite3_bind_int64(p, i, (i64)iValue);
46097 }
46098 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
46099   int rc;
46100   Vdbe *p = (Vdbe *)pStmt;
46101   rc = vdbeUnbind(p, i);
46102   if( rc==SQLITE_OK ){
46103     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
46104     sqlite3_mutex_leave(p->db->mutex);
46105   }
46106   return rc;
46107 }
46108 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
46109   int rc;
46110   Vdbe *p = (Vdbe*)pStmt;
46111   rc = vdbeUnbind(p, i);
46112   if( rc==SQLITE_OK ){
46113     sqlite3_mutex_leave(p->db->mutex);
46114   }
46115   return rc;
46116 }
46117 SQLITE_API int sqlite3_bind_text( 
46118   sqlite3_stmt *pStmt, 
46119   int i, 
46120   const char *zData, 
46121   int nData, 
46122   void (*xDel)(void*)
46123 ){
46124   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
46125 }
46126 #ifndef SQLITE_OMIT_UTF16
46127 SQLITE_API int sqlite3_bind_text16(
46128   sqlite3_stmt *pStmt, 
46129   int i, 
46130   const void *zData, 
46131   int nData, 
46132   void (*xDel)(void*)
46133 ){
46134   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
46135 }
46136 #endif /* SQLITE_OMIT_UTF16 */
46137 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
46138   int rc;
46139   Vdbe *p = (Vdbe *)pStmt;
46140   rc = vdbeUnbind(p, i);
46141   if( rc==SQLITE_OK ){
46142     rc = sqlite3VdbeMemCopy(&p->aVar[i-1], pValue);
46143     if( rc==SQLITE_OK ){
46144       rc = sqlite3VdbeChangeEncoding(&p->aVar[i-1], ENC(p->db));
46145     }
46146     sqlite3_mutex_leave(p->db->mutex);
46147   }
46148   rc = sqlite3ApiExit(p->db, rc);
46149   return rc;
46150 }
46151 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
46152   int rc;
46153   Vdbe *p = (Vdbe *)pStmt;
46154   rc = vdbeUnbind(p, i);
46155   if( rc==SQLITE_OK ){
46156     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
46157     sqlite3_mutex_leave(p->db->mutex);
46158   }
46159   return rc;
46160 }
46161
46162 /*
46163 ** Return the number of wildcards that can be potentially bound to.
46164 ** This routine is added to support DBD::SQLite.  
46165 */
46166 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
46167   Vdbe *p = (Vdbe*)pStmt;
46168   return p ? p->nVar : 0;
46169 }
46170
46171 /*
46172 ** Create a mapping from variable numbers to variable names
46173 ** in the Vdbe.azVar[] array, if such a mapping does not already
46174 ** exist.
46175 */
46176 static void createVarMap(Vdbe *p){
46177   if( !p->okVar ){
46178     sqlite3_mutex_enter(p->db->mutex);
46179     if( !p->okVar ){
46180       int j;
46181       Op *pOp;
46182       for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
46183         if( pOp->opcode==OP_Variable ){
46184           assert( pOp->p1>0 && pOp->p1<=p->nVar );
46185           p->azVar[pOp->p1-1] = pOp->p4.z;
46186         }
46187       }
46188       p->okVar = 1;
46189     }
46190     sqlite3_mutex_leave(p->db->mutex);
46191   }
46192 }
46193
46194 /*
46195 ** Return the name of a wildcard parameter.  Return NULL if the index
46196 ** is out of range or if the wildcard is unnamed.
46197 **
46198 ** The result is always UTF-8.
46199 */
46200 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
46201   Vdbe *p = (Vdbe*)pStmt;
46202   if( p==0 || i<1 || i>p->nVar ){
46203     return 0;
46204   }
46205   createVarMap(p);
46206   return p->azVar[i-1];
46207 }
46208
46209 /*
46210 ** Given a wildcard parameter name, return the index of the variable
46211 ** with that name.  If there is no variable with the given name,
46212 ** return 0.
46213 */
46214 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
46215   Vdbe *p = (Vdbe*)pStmt;
46216   int i;
46217   if( p==0 ){
46218     return 0;
46219   }
46220   createVarMap(p); 
46221   if( zName ){
46222     for(i=0; i<p->nVar; i++){
46223       const char *z = p->azVar[i];
46224       if( z && strcmp(z,zName)==0 ){
46225         return i+1;
46226       }
46227     }
46228   }
46229   return 0;
46230 }
46231
46232 /*
46233 ** Transfer all bindings from the first statement over to the second.
46234 ** If the two statements contain a different number of bindings, then
46235 ** an SQLITE_ERROR is returned.
46236 */
46237 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
46238   Vdbe *pFrom = (Vdbe*)pFromStmt;
46239   Vdbe *pTo = (Vdbe*)pToStmt;
46240   int i, rc = SQLITE_OK;
46241   if( (pFrom->magic!=VDBE_MAGIC_RUN && pFrom->magic!=VDBE_MAGIC_HALT)
46242     || (pTo->magic!=VDBE_MAGIC_RUN && pTo->magic!=VDBE_MAGIC_HALT)
46243     || pTo->db!=pFrom->db ){
46244     return SQLITE_MISUSE;
46245   }
46246   if( pFrom->nVar!=pTo->nVar ){
46247     return SQLITE_ERROR;
46248   }
46249   sqlite3_mutex_enter(pTo->db->mutex);
46250   for(i=0; rc==SQLITE_OK && i<pFrom->nVar; i++){
46251     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
46252   }
46253   sqlite3_mutex_leave(pTo->db->mutex);
46254   assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
46255   return rc;
46256 }
46257
46258 #ifndef SQLITE_OMIT_DEPRECATED
46259 /*
46260 ** Deprecated external interface.  Internal/core SQLite code
46261 ** should call sqlite3TransferBindings.
46262 */
46263 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
46264   return sqlite3TransferBindings(pFromStmt, pToStmt);
46265 }
46266 #endif
46267
46268 /*
46269 ** Return the sqlite3* database handle to which the prepared statement given
46270 ** in the argument belongs.  This is the same database handle that was
46271 ** the first argument to the sqlite3_prepare() that was used to create
46272 ** the statement in the first place.
46273 */
46274 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
46275   return pStmt ? ((Vdbe*)pStmt)->db : 0;
46276 }
46277
46278 /*
46279 ** Return a pointer to the next prepared statement after pStmt associated
46280 ** with database connection pDb.  If pStmt is NULL, return the first
46281 ** prepared statement for the database connection.  Return NULL if there
46282 ** are no more.
46283 */
46284 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
46285   sqlite3_stmt *pNext;
46286   sqlite3_mutex_enter(pDb->mutex);
46287   if( pStmt==0 ){
46288     pNext = (sqlite3_stmt*)pDb->pVdbe;
46289   }else{
46290     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
46291   }
46292   sqlite3_mutex_leave(pDb->mutex);
46293   return pNext;
46294 }
46295
46296 /*
46297 ** Return the value of a status counter for a prepared statement
46298 */
46299 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
46300   Vdbe *pVdbe = (Vdbe*)pStmt;
46301   int v = pVdbe->aCounter[op-1];
46302   if( resetFlag ) pVdbe->aCounter[op-1] = 0;
46303   return v;
46304 }
46305
46306 /************** End of vdbeapi.c *********************************************/
46307 /************** Begin file vdbe.c ********************************************/
46308 /*
46309 ** 2001 September 15
46310 **
46311 ** The author disclaims copyright to this source code.  In place of
46312 ** a legal notice, here is a blessing:
46313 **
46314 **    May you do good and not evil.
46315 **    May you find forgiveness for yourself and forgive others.
46316 **    May you share freely, never taking more than you give.
46317 **
46318 *************************************************************************
46319 ** The code in this file implements execution method of the 
46320 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
46321 ** handles housekeeping details such as creating and deleting
46322 ** VDBE instances.  This file is solely interested in executing
46323 ** the VDBE program.
46324 **
46325 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
46326 ** to a VDBE.
46327 **
46328 ** The SQL parser generates a program which is then executed by
46329 ** the VDBE to do the work of the SQL statement.  VDBE programs are 
46330 ** similar in form to assembly language.  The program consists of
46331 ** a linear sequence of operations.  Each operation has an opcode 
46332 ** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4 
46333 ** is a null-terminated string.  Operand P5 is an unsigned character.
46334 ** Few opcodes use all 5 operands.
46335 **
46336 ** Computation results are stored on a set of registers numbered beginning
46337 ** with 1 and going up to Vdbe.nMem.  Each register can store
46338 ** either an integer, a null-terminated string, a floating point
46339 ** number, or the SQL "NULL" value.  An implicit conversion from one
46340 ** type to the other occurs as necessary.
46341 ** 
46342 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
46343 ** function which does the work of interpreting a VDBE program.
46344 ** But other routines are also provided to help in building up
46345 ** a program instruction by instruction.
46346 **
46347 ** Various scripts scan this source file in order to generate HTML
46348 ** documentation, headers files, or other derived files.  The formatting
46349 ** of the code in this file is, therefore, important.  See other comments
46350 ** in this file for details.  If in doubt, do not deviate from existing
46351 ** commenting and indentation practices when changing or adding code.
46352 **
46353 ** $Id: vdbe.c,v 1.788 2008/11/17 15:31:48 danielk1977 Exp $
46354 */
46355
46356 /*
46357 ** The following global variable is incremented every time a cursor
46358 ** moves, either by the OP_MoveXX, OP_Next, or OP_Prev opcodes.  The test
46359 ** procedures use this information to make sure that indices are
46360 ** working correctly.  This variable has no function other than to
46361 ** help verify the correct operation of the library.
46362 */
46363 #ifdef SQLITE_TEST
46364 SQLITE_API int sqlite3_search_count = 0;
46365 #endif
46366
46367 /*
46368 ** When this global variable is positive, it gets decremented once before
46369 ** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
46370 ** field of the sqlite3 structure is set in order to simulate and interrupt.
46371 **
46372 ** This facility is used for testing purposes only.  It does not function
46373 ** in an ordinary build.
46374 */
46375 #ifdef SQLITE_TEST
46376 SQLITE_API int sqlite3_interrupt_count = 0;
46377 #endif
46378
46379 /*
46380 ** The next global variable is incremented each type the OP_Sort opcode
46381 ** is executed.  The test procedures use this information to make sure that
46382 ** sorting is occurring or not occurring at appropriate times.   This variable
46383 ** has no function other than to help verify the correct operation of the
46384 ** library.
46385 */
46386 #ifdef SQLITE_TEST
46387 SQLITE_API int sqlite3_sort_count = 0;
46388 #endif
46389
46390 /*
46391 ** The next global variable records the size of the largest MEM_Blob
46392 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
46393 ** use this information to make sure that the zero-blob functionality
46394 ** is working correctly.   This variable has no function other than to
46395 ** help verify the correct operation of the library.
46396 */
46397 #ifdef SQLITE_TEST
46398 SQLITE_API int sqlite3_max_blobsize = 0;
46399 static void updateMaxBlobsize(Mem *p){
46400   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
46401     sqlite3_max_blobsize = p->n;
46402   }
46403 }
46404 #endif
46405
46406 /*
46407 ** Test a register to see if it exceeds the current maximum blob size.
46408 ** If it does, record the new maximum blob size.
46409 */
46410 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
46411 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
46412 #else
46413 # define UPDATE_MAX_BLOBSIZE(P)
46414 #endif
46415
46416 /*
46417 ** Convert the given register into a string if it isn't one
46418 ** already. Return non-zero if a malloc() fails.
46419 */
46420 #define Stringify(P, enc) \
46421    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
46422      { goto no_mem; }
46423
46424 /*
46425 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
46426 ** a pointer to a dynamically allocated string where some other entity
46427 ** is responsible for deallocating that string.  Because the register
46428 ** does not control the string, it might be deleted without the register
46429 ** knowing it.
46430 **
46431 ** This routine converts an ephemeral string into a dynamically allocated
46432 ** string that the register itself controls.  In other words, it
46433 ** converts an MEM_Ephem string into an MEM_Dyn string.
46434 */
46435 #define Deephemeralize(P) \
46436    if( ((P)->flags&MEM_Ephem)!=0 \
46437        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
46438
46439 /*
46440 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
46441 ** P if required.
46442 */
46443 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
46444
46445 /*
46446 ** Argument pMem points at a register that will be passed to a
46447 ** user-defined function or returned to the user as the result of a query.
46448 ** The second argument, 'db_enc' is the text encoding used by the vdbe for
46449 ** register variables.  This routine sets the pMem->enc and pMem->type
46450 ** variables used by the sqlite3_value_*() routines.
46451 */
46452 #define storeTypeInfo(A,B) _storeTypeInfo(A)
46453 static void _storeTypeInfo(Mem *pMem){
46454   int flags = pMem->flags;
46455   if( flags & MEM_Null ){
46456     pMem->type = SQLITE_NULL;
46457   }
46458   else if( flags & MEM_Int ){
46459     pMem->type = SQLITE_INTEGER;
46460   }
46461   else if( flags & MEM_Real ){
46462     pMem->type = SQLITE_FLOAT;
46463   }
46464   else if( flags & MEM_Str ){
46465     pMem->type = SQLITE_TEXT;
46466   }else{
46467     pMem->type = SQLITE_BLOB;
46468   }
46469 }
46470
46471 /*
46472 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
46473 ** created by mkopcodeh.awk during compilation.  Data is obtained
46474 ** from the comments following the "case OP_xxxx:" statements in
46475 ** this file.  
46476 */
46477 static const unsigned char opcodeProperty[] = OPFLG_INITIALIZER;
46478
46479 /*
46480 ** Return true if an opcode has any of the OPFLG_xxx properties
46481 ** specified by mask.
46482 */
46483 SQLITE_PRIVATE int sqlite3VdbeOpcodeHasProperty(int opcode, int mask){
46484   assert( opcode>0 && opcode<(int)sizeof(opcodeProperty) );
46485   return (opcodeProperty[opcode]&mask)!=0;
46486 }
46487
46488 /*
46489 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
46490 ** if we run out of memory.
46491 */
46492 static VdbeCursor *allocateCursor(
46493   Vdbe *p,              /* The virtual machine */
46494   int iCur,             /* Index of the new VdbeCursor */
46495   Op *pOp,              /* */
46496   int iDb,              /* */
46497   int isBtreeCursor     /* */
46498 ){
46499   /* Find the memory cell that will be used to store the blob of memory
46500   ** required for this VdbeCursor structure. It is convenient to use a 
46501   ** vdbe memory cell to manage the memory allocation required for a
46502   ** VdbeCursor structure for the following reasons:
46503   **
46504   **   * Sometimes cursor numbers are used for a couple of different
46505   **     purposes in a vdbe program. The different uses might require
46506   **     different sized allocations. Memory cells provide growable
46507   **     allocations.
46508   **
46509   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
46510   **     be freed lazily via the sqlite3_release_memory() API. This
46511   **     minimizes the number of malloc calls made by the system.
46512   **
46513   ** Memory cells for cursors are allocated at the top of the address
46514   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
46515   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
46516   */
46517   Mem *pMem = &p->aMem[p->nMem-iCur];
46518
46519   int nByte;
46520   VdbeCursor *pCx = 0;
46521   /* If the opcode of pOp is OP_SetNumColumns, then pOp->p2 contains
46522   ** the number of fields in the records contained in the table or
46523   ** index being opened. Use this to reserve space for the 
46524   ** VdbeCursor.aType[] array.
46525   */
46526   int nField = 0;
46527   if( pOp->opcode==OP_SetNumColumns || pOp->opcode==OP_OpenEphemeral ){
46528     nField = pOp->p2;
46529   }
46530   nByte = 
46531       sizeof(VdbeCursor) + 
46532       (isBtreeCursor?sqlite3BtreeCursorSize():0) + 
46533       2*nField*sizeof(u32);
46534
46535   assert( iCur<p->nCursor );
46536   if( p->apCsr[iCur] ){
46537     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
46538     p->apCsr[iCur] = 0;
46539   }
46540   if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
46541     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
46542     memset(pMem->z, 0, nByte);
46543     pCx->iDb = iDb;
46544     pCx->nField = nField;
46545     if( nField ){
46546       pCx->aType = (u32 *)&pMem->z[sizeof(VdbeCursor)];
46547     }
46548     if( isBtreeCursor ){
46549       pCx->pCursor = (BtCursor*)
46550           &pMem->z[sizeof(VdbeCursor)+2*nField*sizeof(u32)];
46551     }
46552   }
46553   return pCx;
46554 }
46555
46556 /*
46557 ** Try to convert a value into a numeric representation if we can
46558 ** do so without loss of information.  In other words, if the string
46559 ** looks like a number, convert it into a number.  If it does not
46560 ** look like a number, leave it alone.
46561 */
46562 static void applyNumericAffinity(Mem *pRec){
46563   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
46564     int realnum;
46565     sqlite3VdbeMemNulTerminate(pRec);
46566     if( (pRec->flags&MEM_Str)
46567          && sqlite3IsNumber(pRec->z, &realnum, pRec->enc) ){
46568       i64 value;
46569       sqlite3VdbeChangeEncoding(pRec, SQLITE_UTF8);
46570       if( !realnum && sqlite3Atoi64(pRec->z, &value) ){
46571         pRec->u.i = value;
46572         MemSetTypeFlag(pRec, MEM_Int);
46573       }else{
46574         sqlite3VdbeMemRealify(pRec);
46575       }
46576     }
46577   }
46578 }
46579
46580 /*
46581 ** Processing is determine by the affinity parameter:
46582 **
46583 ** SQLITE_AFF_INTEGER:
46584 ** SQLITE_AFF_REAL:
46585 ** SQLITE_AFF_NUMERIC:
46586 **    Try to convert pRec to an integer representation or a 
46587 **    floating-point representation if an integer representation
46588 **    is not possible.  Note that the integer representation is
46589 **    always preferred, even if the affinity is REAL, because
46590 **    an integer representation is more space efficient on disk.
46591 **
46592 ** SQLITE_AFF_TEXT:
46593 **    Convert pRec to a text representation.
46594 **
46595 ** SQLITE_AFF_NONE:
46596 **    No-op.  pRec is unchanged.
46597 */
46598 static void applyAffinity(
46599   Mem *pRec,          /* The value to apply affinity to */
46600   char affinity,      /* The affinity to be applied */
46601   u8 enc              /* Use this text encoding */
46602 ){
46603   if( affinity==SQLITE_AFF_TEXT ){
46604     /* Only attempt the conversion to TEXT if there is an integer or real
46605     ** representation (blob and NULL do not get converted) but no string
46606     ** representation.
46607     */
46608     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
46609       sqlite3VdbeMemStringify(pRec, enc);
46610     }
46611     pRec->flags &= ~(MEM_Real|MEM_Int);
46612   }else if( affinity!=SQLITE_AFF_NONE ){
46613     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
46614              || affinity==SQLITE_AFF_NUMERIC );
46615     applyNumericAffinity(pRec);
46616     if( pRec->flags & MEM_Real ){
46617       sqlite3VdbeIntegerAffinity(pRec);
46618     }
46619   }
46620 }
46621
46622 /*
46623 ** Try to convert the type of a function argument or a result column
46624 ** into a numeric representation.  Use either INTEGER or REAL whichever
46625 ** is appropriate.  But only do the conversion if it is possible without
46626 ** loss of information and return the revised type of the argument.
46627 **
46628 ** This is an EXPERIMENTAL api and is subject to change or removal.
46629 */
46630 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
46631   Mem *pMem = (Mem*)pVal;
46632   applyNumericAffinity(pMem);
46633   storeTypeInfo(pMem, 0);
46634   return pMem->type;
46635 }
46636
46637 /*
46638 ** Exported version of applyAffinity(). This one works on sqlite3_value*, 
46639 ** not the internal Mem* type.
46640 */
46641 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
46642   sqlite3_value *pVal, 
46643   u8 affinity, 
46644   u8 enc
46645 ){
46646   applyAffinity((Mem *)pVal, affinity, enc);
46647 }
46648
46649 #ifdef SQLITE_DEBUG
46650 /*
46651 ** Write a nice string representation of the contents of cell pMem
46652 ** into buffer zBuf, length nBuf.
46653 */
46654 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
46655   char *zCsr = zBuf;
46656   int f = pMem->flags;
46657
46658   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
46659
46660   if( f&MEM_Blob ){
46661     int i;
46662     char c;
46663     if( f & MEM_Dyn ){
46664       c = 'z';
46665       assert( (f & (MEM_Static|MEM_Ephem))==0 );
46666     }else if( f & MEM_Static ){
46667       c = 't';
46668       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
46669     }else if( f & MEM_Ephem ){
46670       c = 'e';
46671       assert( (f & (MEM_Static|MEM_Dyn))==0 );
46672     }else{
46673       c = 's';
46674     }
46675
46676     sqlite3_snprintf(100, zCsr, "%c", c);
46677     zCsr += strlen(zCsr);
46678     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
46679     zCsr += strlen(zCsr);
46680     for(i=0; i<16 && i<pMem->n; i++){
46681       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
46682       zCsr += strlen(zCsr);
46683     }
46684     for(i=0; i<16 && i<pMem->n; i++){
46685       char z = pMem->z[i];
46686       if( z<32 || z>126 ) *zCsr++ = '.';
46687       else *zCsr++ = z;
46688     }
46689
46690     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
46691     zCsr += strlen(zCsr);
46692     if( f & MEM_Zero ){
46693       sqlite3_snprintf(100, zCsr,"+%lldz",pMem->u.i);
46694       zCsr += strlen(zCsr);
46695     }
46696     *zCsr = '\0';
46697   }else if( f & MEM_Str ){
46698     int j, k;
46699     zBuf[0] = ' ';
46700     if( f & MEM_Dyn ){
46701       zBuf[1] = 'z';
46702       assert( (f & (MEM_Static|MEM_Ephem))==0 );
46703     }else if( f & MEM_Static ){
46704       zBuf[1] = 't';
46705       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
46706     }else if( f & MEM_Ephem ){
46707       zBuf[1] = 'e';
46708       assert( (f & (MEM_Static|MEM_Dyn))==0 );
46709     }else{
46710       zBuf[1] = 's';
46711     }
46712     k = 2;
46713     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
46714     k += strlen(&zBuf[k]);
46715     zBuf[k++] = '[';
46716     for(j=0; j<15 && j<pMem->n; j++){
46717       u8 c = pMem->z[j];
46718       if( c>=0x20 && c<0x7f ){
46719         zBuf[k++] = c;
46720       }else{
46721         zBuf[k++] = '.';
46722       }
46723     }
46724     zBuf[k++] = ']';
46725     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
46726     k += strlen(&zBuf[k]);
46727     zBuf[k++] = 0;
46728   }
46729 }
46730 #endif
46731
46732 #ifdef SQLITE_DEBUG
46733 /*
46734 ** Print the value of a register for tracing purposes:
46735 */
46736 static void memTracePrint(FILE *out, Mem *p){
46737   if( p->flags & MEM_Null ){
46738     fprintf(out, " NULL");
46739   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
46740     fprintf(out, " si:%lld", p->u.i);
46741   }else if( p->flags & MEM_Int ){
46742     fprintf(out, " i:%lld", p->u.i);
46743   }else if( p->flags & MEM_Real ){
46744     fprintf(out, " r:%g", p->r);
46745   }else{
46746     char zBuf[200];
46747     sqlite3VdbeMemPrettyPrint(p, zBuf);
46748     fprintf(out, " ");
46749     fprintf(out, "%s", zBuf);
46750   }
46751 }
46752 static void registerTrace(FILE *out, int iReg, Mem *p){
46753   fprintf(out, "REG[%d] = ", iReg);
46754   memTracePrint(out, p);
46755   fprintf(out, "\n");
46756 }
46757 #endif
46758
46759 #ifdef SQLITE_DEBUG
46760 #  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
46761 #else
46762 #  define REGISTER_TRACE(R,M)
46763 #endif
46764
46765
46766 #ifdef VDBE_PROFILE
46767
46768 /* 
46769 ** hwtime.h contains inline assembler code for implementing 
46770 ** high-performance timing routines.
46771 */
46772 /************** Include hwtime.h in the middle of vdbe.c *********************/
46773 /************** Begin file hwtime.h ******************************************/
46774 /*
46775 ** 2008 May 27
46776 **
46777 ** The author disclaims copyright to this source code.  In place of
46778 ** a legal notice, here is a blessing:
46779 **
46780 **    May you do good and not evil.
46781 **    May you find forgiveness for yourself and forgive others.
46782 **    May you share freely, never taking more than you give.
46783 **
46784 ******************************************************************************
46785 **
46786 ** This file contains inline asm code for retrieving "high-performance"
46787 ** counters for x86 class CPUs.
46788 **
46789 ** $Id: hwtime.h,v 1.3 2008/08/01 14:33:15 shane Exp $
46790 */
46791 #ifndef _HWTIME_H_
46792 #define _HWTIME_H_
46793
46794 /*
46795 ** The following routine only works on pentium-class (or newer) processors.
46796 ** It uses the RDTSC opcode to read the cycle count value out of the
46797 ** processor and returns that value.  This can be used for high-res
46798 ** profiling.
46799 */
46800 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
46801       (defined(i386) || defined(__i386__) || defined(_M_IX86))
46802
46803   #if defined(__GNUC__)
46804
46805   __inline__ sqlite_uint64 sqlite3Hwtime(void){
46806      unsigned int lo, hi;
46807      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
46808      return (sqlite_uint64)hi << 32 | lo;
46809   }
46810
46811   #elif defined(_MSC_VER)
46812
46813   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
46814      __asm {
46815         rdtsc
46816         ret       ; return value at EDX:EAX
46817      }
46818   }
46819
46820   #endif
46821
46822 #elif (defined(__GNUC__) && defined(__x86_64__))
46823
46824   __inline__ sqlite_uint64 sqlite3Hwtime(void){
46825       unsigned long val;
46826       __asm__ __volatile__ ("rdtsc" : "=A" (val));
46827       return val;
46828   }
46829  
46830 #elif (defined(__GNUC__) && defined(__ppc__))
46831
46832   __inline__ sqlite_uint64 sqlite3Hwtime(void){
46833       unsigned long long retval;
46834       unsigned long junk;
46835       __asm__ __volatile__ ("\n\
46836           1:      mftbu   %1\n\
46837                   mftb    %L0\n\
46838                   mftbu   %0\n\
46839                   cmpw    %0,%1\n\
46840                   bne     1b"
46841                   : "=r" (retval), "=r" (junk));
46842       return retval;
46843   }
46844
46845 #else
46846
46847   #error Need implementation of sqlite3Hwtime() for your platform.
46848
46849   /*
46850   ** To compile without implementing sqlite3Hwtime() for your platform,
46851   ** you can remove the above #error and use the following
46852   ** stub function.  You will lose timing support for many
46853   ** of the debugging and testing utilities, but it should at
46854   ** least compile and run.
46855   */
46856 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
46857
46858 #endif
46859
46860 #endif /* !defined(_HWTIME_H_) */
46861
46862 /************** End of hwtime.h **********************************************/
46863 /************** Continuing where we left off in vdbe.c ***********************/
46864
46865 #endif
46866
46867 /*
46868 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
46869 ** sqlite3_interrupt() routine has been called.  If it has been, then
46870 ** processing of the VDBE program is interrupted.
46871 **
46872 ** This macro added to every instruction that does a jump in order to
46873 ** implement a loop.  This test used to be on every single instruction,
46874 ** but that meant we more testing that we needed.  By only testing the
46875 ** flag on jump instructions, we get a (small) speed improvement.
46876 */
46877 #define CHECK_FOR_INTERRUPT \
46878    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
46879
46880 #ifdef SQLITE_DEBUG
46881 static int fileExists(sqlite3 *db, const char *zFile){
46882   int res = 0;
46883   int rc = SQLITE_OK;
46884 #ifdef SQLITE_TEST
46885   /* If we are currently testing IO errors, then do not call OsAccess() to
46886   ** test for the presence of zFile. This is because any IO error that
46887   ** occurs here will not be reported, causing the test to fail.
46888   */
46889   extern int sqlite3_io_error_pending;
46890   if( sqlite3_io_error_pending<=0 )
46891 #endif
46892     rc = sqlite3OsAccess(db->pVfs, zFile, SQLITE_ACCESS_EXISTS, &res);
46893   return (res && rc==SQLITE_OK);
46894 }
46895 #endif
46896
46897 /*
46898 ** Execute as much of a VDBE program as we can then return.
46899 **
46900 ** sqlite3VdbeMakeReady() must be called before this routine in order to
46901 ** close the program with a final OP_Halt and to set up the callbacks
46902 ** and the error message pointer.
46903 **
46904 ** Whenever a row or result data is available, this routine will either
46905 ** invoke the result callback (if there is one) or return with
46906 ** SQLITE_ROW.
46907 **
46908 ** If an attempt is made to open a locked database, then this routine
46909 ** will either invoke the busy callback (if there is one) or it will
46910 ** return SQLITE_BUSY.
46911 **
46912 ** If an error occurs, an error message is written to memory obtained
46913 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
46914 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
46915 **
46916 ** If the callback ever returns non-zero, then the program exits
46917 ** immediately.  There will be no error message but the p->rc field is
46918 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
46919 **
46920 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
46921 ** routine to return SQLITE_ERROR.
46922 **
46923 ** Other fatal errors return SQLITE_ERROR.
46924 **
46925 ** After this routine has finished, sqlite3VdbeFinalize() should be
46926 ** used to clean up the mess that was left behind.
46927 */
46928 SQLITE_PRIVATE int sqlite3VdbeExec(
46929   Vdbe *p                    /* The VDBE */
46930 ){
46931   int pc;                    /* The program counter */
46932   Op *pOp;                   /* Current operation */
46933   int rc = SQLITE_OK;        /* Value to return */
46934   sqlite3 *db = p->db;       /* The database */
46935   u8 encoding = ENC(db);     /* The database encoding */
46936   Mem *pIn1, *pIn2, *pIn3;   /* Input operands */
46937   Mem *pOut;                 /* Output operand */
46938   u8 opProperty;
46939   int iCompare = 0;          /* Result of last OP_Compare operation */
46940   int *aPermute = 0;         /* Permuation of columns for OP_Compare */
46941 #ifdef VDBE_PROFILE
46942   u64 start;                 /* CPU clock count at start of opcode */
46943   int origPc;                /* Program counter at start of opcode */
46944 #endif
46945 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
46946   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
46947 #endif
46948   UnpackedRecord aTempRec[16]; /* Space to hold a transient UnpackedRecord */
46949
46950   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
46951   assert( db->magic==SQLITE_MAGIC_BUSY );
46952   sqlite3BtreeMutexArrayEnter(&p->aMutex);
46953   if( p->rc==SQLITE_NOMEM ){
46954     /* This happens if a malloc() inside a call to sqlite3_column_text() or
46955     ** sqlite3_column_text16() failed.  */
46956     goto no_mem;
46957   }
46958   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
46959   p->rc = SQLITE_OK;
46960   assert( p->explain==0 );
46961   p->pResultSet = 0;
46962   db->busyHandler.nBusy = 0;
46963   CHECK_FOR_INTERRUPT;
46964   sqlite3VdbeIOTraceSql(p);
46965 #ifdef SQLITE_DEBUG
46966   sqlite3BeginBenignMalloc();
46967   if( p->pc==0 
46968    && ((p->db->flags & SQLITE_VdbeListing) || fileExists(db, "vdbe_explain"))
46969   ){
46970     int i;
46971     printf("VDBE Program Listing:\n");
46972     sqlite3VdbePrintSql(p);
46973     for(i=0; i<p->nOp; i++){
46974       sqlite3VdbePrintOp(stdout, i, &p->aOp[i]);
46975     }
46976   }
46977   if( fileExists(db, "vdbe_trace") ){
46978     p->trace = stdout;
46979   }
46980   sqlite3EndBenignMalloc();
46981 #endif
46982   for(pc=p->pc; rc==SQLITE_OK; pc++){
46983     assert( pc>=0 && pc<p->nOp );
46984     if( db->mallocFailed ) goto no_mem;
46985 #ifdef VDBE_PROFILE
46986     origPc = pc;
46987     start = sqlite3Hwtime();
46988 #endif
46989     pOp = &p->aOp[pc];
46990
46991     /* Only allow tracing if SQLITE_DEBUG is defined.
46992     */
46993 #ifdef SQLITE_DEBUG
46994     if( p->trace ){
46995       if( pc==0 ){
46996         printf("VDBE Execution Trace:\n");
46997         sqlite3VdbePrintSql(p);
46998       }
46999       sqlite3VdbePrintOp(p->trace, pc, pOp);
47000     }
47001     if( p->trace==0 && pc==0 ){
47002       sqlite3BeginBenignMalloc();
47003       if( fileExists(db, "vdbe_sqltrace") ){
47004         sqlite3VdbePrintSql(p);
47005       }
47006       sqlite3EndBenignMalloc();
47007     }
47008 #endif
47009       
47010
47011     /* Check to see if we need to simulate an interrupt.  This only happens
47012     ** if we have a special test build.
47013     */
47014 #ifdef SQLITE_TEST
47015     if( sqlite3_interrupt_count>0 ){
47016       sqlite3_interrupt_count--;
47017       if( sqlite3_interrupt_count==0 ){
47018         sqlite3_interrupt(db);
47019       }
47020     }
47021 #endif
47022
47023 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
47024     /* Call the progress callback if it is configured and the required number
47025     ** of VDBE ops have been executed (either since this invocation of
47026     ** sqlite3VdbeExec() or since last time the progress callback was called).
47027     ** If the progress callback returns non-zero, exit the virtual machine with
47028     ** a return code SQLITE_ABORT.
47029     */
47030     if( db->xProgress ){
47031       if( db->nProgressOps==nProgressOps ){
47032         int prc;
47033         if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
47034         prc =db->xProgress(db->pProgressArg);
47035         if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
47036         if( prc!=0 ){
47037           rc = SQLITE_INTERRUPT;
47038           goto vdbe_error_halt;
47039         }
47040         nProgressOps = 0;
47041       }
47042       nProgressOps++;
47043     }
47044 #endif
47045
47046     /* Do common setup processing for any opcode that is marked
47047     ** with the "out2-prerelease" tag.  Such opcodes have a single
47048     ** output which is specified by the P2 parameter.  The P2 register
47049     ** is initialized to a NULL.
47050     */
47051     opProperty = opcodeProperty[pOp->opcode];
47052     if( (opProperty & OPFLG_OUT2_PRERELEASE)!=0 ){
47053       assert( pOp->p2>0 );
47054       assert( pOp->p2<=p->nMem );
47055       pOut = &p->aMem[pOp->p2];
47056       sqlite3VdbeMemReleaseExternal(pOut);
47057       pOut->flags = MEM_Null;
47058     }else
47059  
47060     /* Do common setup for opcodes marked with one of the following
47061     ** combinations of properties.
47062     **
47063     **           in1
47064     **           in1 in2
47065     **           in1 in2 out3
47066     **           in1 in3
47067     **
47068     ** Variables pIn1, pIn2, and pIn3 are made to point to appropriate
47069     ** registers for inputs.  Variable pOut points to the output register.
47070     */
47071     if( (opProperty & OPFLG_IN1)!=0 ){
47072       assert( pOp->p1>0 );
47073       assert( pOp->p1<=p->nMem );
47074       pIn1 = &p->aMem[pOp->p1];
47075       REGISTER_TRACE(pOp->p1, pIn1);
47076       if( (opProperty & OPFLG_IN2)!=0 ){
47077         assert( pOp->p2>0 );
47078         assert( pOp->p2<=p->nMem );
47079         pIn2 = &p->aMem[pOp->p2];
47080         REGISTER_TRACE(pOp->p2, pIn2);
47081         if( (opProperty & OPFLG_OUT3)!=0 ){
47082           assert( pOp->p3>0 );
47083           assert( pOp->p3<=p->nMem );
47084           pOut = &p->aMem[pOp->p3];
47085         }
47086       }else if( (opProperty & OPFLG_IN3)!=0 ){
47087         assert( pOp->p3>0 );
47088         assert( pOp->p3<=p->nMem );
47089         pIn3 = &p->aMem[pOp->p3];
47090         REGISTER_TRACE(pOp->p3, pIn3);
47091       }
47092     }else if( (opProperty & OPFLG_IN2)!=0 ){
47093       assert( pOp->p2>0 );
47094       assert( pOp->p2<=p->nMem );
47095       pIn2 = &p->aMem[pOp->p2];
47096       REGISTER_TRACE(pOp->p2, pIn2);
47097     }else if( (opProperty & OPFLG_IN3)!=0 ){
47098       assert( pOp->p3>0 );
47099       assert( pOp->p3<=p->nMem );
47100       pIn3 = &p->aMem[pOp->p3];
47101       REGISTER_TRACE(pOp->p3, pIn3);
47102     }
47103
47104     switch( pOp->opcode ){
47105
47106 /*****************************************************************************
47107 ** What follows is a massive switch statement where each case implements a
47108 ** separate instruction in the virtual machine.  If we follow the usual
47109 ** indentation conventions, each case should be indented by 6 spaces.  But
47110 ** that is a lot of wasted space on the left margin.  So the code within
47111 ** the switch statement will break with convention and be flush-left. Another
47112 ** big comment (similar to this one) will mark the point in the code where
47113 ** we transition back to normal indentation.
47114 **
47115 ** The formatting of each case is important.  The makefile for SQLite
47116 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
47117 ** file looking for lines that begin with "case OP_".  The opcodes.h files
47118 ** will be filled with #defines that give unique integer values to each
47119 ** opcode and the opcodes.c file is filled with an array of strings where
47120 ** each string is the symbolic name for the corresponding opcode.  If the
47121 ** case statement is followed by a comment of the form "/# same as ... #/"
47122 ** that comment is used to determine the particular value of the opcode.
47123 **
47124 ** Other keywords in the comment that follows each case are used to
47125 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
47126 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
47127 ** the mkopcodeh.awk script for additional information.
47128 **
47129 ** Documentation about VDBE opcodes is generated by scanning this file
47130 ** for lines of that contain "Opcode:".  That line and all subsequent
47131 ** comment lines are used in the generation of the opcode.html documentation
47132 ** file.
47133 **
47134 ** SUMMARY:
47135 **
47136 **     Formatting is important to scripts that scan this file.
47137 **     Do not deviate from the formatting style currently in use.
47138 **
47139 *****************************************************************************/
47140
47141 /* Opcode:  Goto * P2 * * *
47142 **
47143 ** An unconditional jump to address P2.
47144 ** The next instruction executed will be 
47145 ** the one at index P2 from the beginning of
47146 ** the program.
47147 */
47148 case OP_Goto: {             /* jump */
47149   CHECK_FOR_INTERRUPT;
47150   pc = pOp->p2 - 1;
47151   break;
47152 }
47153
47154 /* Opcode:  Gosub P1 P2 * * *
47155 **
47156 ** Write the current address onto register P1
47157 ** and then jump to address P2.
47158 */
47159 case OP_Gosub: {            /* jump */
47160   assert( pOp->p1>0 );
47161   assert( pOp->p1<=p->nMem );
47162   pIn1 = &p->aMem[pOp->p1];
47163   assert( (pIn1->flags & MEM_Dyn)==0 );
47164   pIn1->flags = MEM_Int;
47165   pIn1->u.i = pc;
47166   REGISTER_TRACE(pOp->p1, pIn1);
47167   pc = pOp->p2 - 1;
47168   break;
47169 }
47170
47171 /* Opcode:  Return P1 * * * *
47172 **
47173 ** Jump to the next instruction after the address in register P1.
47174 */
47175 case OP_Return: {           /* in1 */
47176   assert( pIn1->flags & MEM_Int );
47177   pc = pIn1->u.i;
47178   break;
47179 }
47180
47181 /* Opcode:  Yield P1 * * * *
47182 **
47183 ** Swap the program counter with the value in register P1.
47184 */
47185 case OP_Yield: {
47186   int pcDest;
47187   assert( pOp->p1>0 );
47188   assert( pOp->p1<=p->nMem );
47189   pIn1 = &p->aMem[pOp->p1];
47190   assert( (pIn1->flags & MEM_Dyn)==0 );
47191   pIn1->flags = MEM_Int;
47192   pcDest = pIn1->u.i;
47193   pIn1->u.i = pc;
47194   REGISTER_TRACE(pOp->p1, pIn1);
47195   pc = pcDest;
47196   break;
47197 }
47198
47199
47200 /* Opcode:  Halt P1 P2 * P4 *
47201 **
47202 ** Exit immediately.  All open cursors, Fifos, etc are closed
47203 ** automatically.
47204 **
47205 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
47206 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
47207 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
47208 ** whether or not to rollback the current transaction.  Do not rollback
47209 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
47210 ** then back out all changes that have occurred during this execution of the
47211 ** VDBE, but do not rollback the transaction. 
47212 **
47213 ** If P4 is not null then it is an error message string.
47214 **
47215 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
47216 ** every program.  So a jump past the last instruction of the program
47217 ** is the same as executing Halt.
47218 */
47219 case OP_Halt: {
47220   p->rc = pOp->p1;
47221   p->pc = pc;
47222   p->errorAction = pOp->p2;
47223   if( pOp->p4.z ){
47224     sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
47225   }
47226   rc = sqlite3VdbeHalt(p);
47227   assert( rc==SQLITE_BUSY || rc==SQLITE_OK );
47228   if( rc==SQLITE_BUSY ){
47229     p->rc = rc = SQLITE_BUSY;
47230   }else{
47231     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
47232   }
47233   goto vdbe_return;
47234 }
47235
47236 /* Opcode: Integer P1 P2 * * *
47237 **
47238 ** The 32-bit integer value P1 is written into register P2.
47239 */
47240 case OP_Integer: {         /* out2-prerelease */
47241   pOut->flags = MEM_Int;
47242   pOut->u.i = pOp->p1;
47243   break;
47244 }
47245
47246 /* Opcode: Int64 * P2 * P4 *
47247 **
47248 ** P4 is a pointer to a 64-bit integer value.
47249 ** Write that value into register P2.
47250 */
47251 case OP_Int64: {           /* out2-prerelease */
47252   assert( pOp->p4.pI64!=0 );
47253   pOut->flags = MEM_Int;
47254   pOut->u.i = *pOp->p4.pI64;
47255   break;
47256 }
47257
47258 /* Opcode: Real * P2 * P4 *
47259 **
47260 ** P4 is a pointer to a 64-bit floating point value.
47261 ** Write that value into register P2.
47262 */
47263 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
47264   pOut->flags = MEM_Real;
47265   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
47266   pOut->r = *pOp->p4.pReal;
47267   break;
47268 }
47269
47270 /* Opcode: String8 * P2 * P4 *
47271 **
47272 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
47273 ** into an OP_String before it is executed for the first time.
47274 */
47275 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
47276   assert( pOp->p4.z!=0 );
47277   pOp->opcode = OP_String;
47278   pOp->p1 = strlen(pOp->p4.z);
47279
47280 #ifndef SQLITE_OMIT_UTF16
47281   if( encoding!=SQLITE_UTF8 ){
47282     sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
47283     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
47284     if( SQLITE_OK!=sqlite3VdbeMemMakeWriteable(pOut) ) goto no_mem;
47285     pOut->zMalloc = 0;
47286     pOut->flags |= MEM_Static;
47287     pOut->flags &= ~MEM_Dyn;
47288     if( pOp->p4type==P4_DYNAMIC ){
47289       sqlite3DbFree(db, pOp->p4.z);
47290     }
47291     pOp->p4type = P4_DYNAMIC;
47292     pOp->p4.z = pOut->z;
47293     pOp->p1 = pOut->n;
47294     if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
47295       goto too_big;
47296     }
47297     UPDATE_MAX_BLOBSIZE(pOut);
47298     break;
47299   }
47300 #endif
47301   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
47302     goto too_big;
47303   }
47304   /* Fall through to the next case, OP_String */
47305 }
47306   
47307 /* Opcode: String P1 P2 * P4 *
47308 **
47309 ** The string value P4 of length P1 (bytes) is stored in register P2.
47310 */
47311 case OP_String: {          /* out2-prerelease */
47312   assert( pOp->p4.z!=0 );
47313   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
47314   pOut->z = pOp->p4.z;
47315   pOut->n = pOp->p1;
47316   pOut->enc = encoding;
47317   UPDATE_MAX_BLOBSIZE(pOut);
47318   break;
47319 }
47320
47321 /* Opcode: Null * P2 * * *
47322 **
47323 ** Write a NULL into register P2.
47324 */
47325 case OP_Null: {           /* out2-prerelease */
47326   break;
47327 }
47328
47329
47330 #ifndef SQLITE_OMIT_BLOB_LITERAL
47331 /* Opcode: Blob P1 P2 * P4
47332 **
47333 ** P4 points to a blob of data P1 bytes long.  Store this
47334 ** blob in register P2. This instruction is not coded directly
47335 ** by the compiler. Instead, the compiler layer specifies
47336 ** an OP_HexBlob opcode, with the hex string representation of
47337 ** the blob as P4. This opcode is transformed to an OP_Blob
47338 ** the first time it is executed.
47339 */
47340 case OP_Blob: {                /* out2-prerelease */
47341   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
47342   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
47343   pOut->enc = encoding;
47344   UPDATE_MAX_BLOBSIZE(pOut);
47345   break;
47346 }
47347 #endif /* SQLITE_OMIT_BLOB_LITERAL */
47348
47349 /* Opcode: Variable P1 P2 * * *
47350 **
47351 ** The value of variable P1 is written into register P2. A variable is
47352 ** an unknown in the original SQL string as handed to sqlite3_compile().
47353 ** Any occurrence of the '?' character in the original SQL is considered
47354 ** a variable.  Variables in the SQL string are number from left to
47355 ** right beginning with 1.  The values of variables are set using the
47356 ** sqlite3_bind() API.
47357 */
47358 case OP_Variable: {           /* out2-prerelease */
47359   int j = pOp->p1 - 1;
47360   Mem *pVar;
47361   assert( j>=0 && j<p->nVar );
47362
47363   pVar = &p->aVar[j];
47364   if( sqlite3VdbeMemTooBig(pVar) ){
47365     goto too_big;
47366   }
47367   sqlite3VdbeMemShallowCopy(pOut, &p->aVar[j], MEM_Static);
47368   UPDATE_MAX_BLOBSIZE(pOut);
47369   break;
47370 }
47371
47372 /* Opcode: Move P1 P2 P3 * *
47373 **
47374 ** Move the values in register P1..P1+P3-1 over into
47375 ** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
47376 ** left holding a NULL.  It is an error for register ranges
47377 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
47378 */
47379 case OP_Move: {
47380   char *zMalloc;
47381   int n = pOp->p3;
47382   int p1 = pOp->p1;
47383   int p2 = pOp->p2;
47384   assert( n>0 );
47385   assert( p1>0 );
47386   assert( p1+n<p->nMem );
47387   pIn1 = &p->aMem[p1];
47388   assert( p2>0 );
47389   assert( p2+n<p->nMem );
47390   pOut = &p->aMem[p2];
47391   assert( p1+n<=p2 || p2+n<=p1 );
47392   while( n-- ){
47393     zMalloc = pOut->zMalloc;
47394     pOut->zMalloc = 0;
47395     sqlite3VdbeMemMove(pOut, pIn1);
47396     pIn1->zMalloc = zMalloc;
47397     REGISTER_TRACE(p2++, pOut);
47398     pIn1++;
47399     pOut++;
47400   }
47401   break;
47402 }
47403
47404 /* Opcode: Copy P1 P2 * * *
47405 **
47406 ** Make a copy of register P1 into register P2.
47407 **
47408 ** This instruction makes a deep copy of the value.  A duplicate
47409 ** is made of any string or blob constant.  See also OP_SCopy.
47410 */
47411 case OP_Copy: {
47412   assert( pOp->p1>0 );
47413   assert( pOp->p1<=p->nMem );
47414   pIn1 = &p->aMem[pOp->p1];
47415   assert( pOp->p2>0 );
47416   assert( pOp->p2<=p->nMem );
47417   pOut = &p->aMem[pOp->p2];
47418   assert( pOut!=pIn1 );
47419   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
47420   Deephemeralize(pOut);
47421   REGISTER_TRACE(pOp->p2, pOut);
47422   break;
47423 }
47424
47425 /* Opcode: SCopy P1 P2 * * *
47426 **
47427 ** Make a shallow copy of register P1 into register P2.
47428 **
47429 ** This instruction makes a shallow copy of the value.  If the value
47430 ** is a string or blob, then the copy is only a pointer to the
47431 ** original and hence if the original changes so will the copy.
47432 ** Worse, if the original is deallocated, the copy becomes invalid.
47433 ** Thus the program must guarantee that the original will not change
47434 ** during the lifetime of the copy.  Use OP_Copy to make a complete
47435 ** copy.
47436 */
47437 case OP_SCopy: {
47438   assert( pOp->p1>0 );
47439   assert( pOp->p1<=p->nMem );
47440   pIn1 = &p->aMem[pOp->p1];
47441   REGISTER_TRACE(pOp->p1, pIn1);
47442   assert( pOp->p2>0 );
47443   assert( pOp->p2<=p->nMem );
47444   pOut = &p->aMem[pOp->p2];
47445   assert( pOut!=pIn1 );
47446   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
47447   REGISTER_TRACE(pOp->p2, pOut);
47448   break;
47449 }
47450
47451 /* Opcode: ResultRow P1 P2 * * *
47452 **
47453 ** The registers P1 through P1+P2-1 contain a single row of
47454 ** results. This opcode causes the sqlite3_step() call to terminate
47455 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
47456 ** structure to provide access to the top P1 values as the result
47457 ** row.
47458 */
47459 case OP_ResultRow: {
47460   Mem *pMem;
47461   int i;
47462   assert( p->nResColumn==pOp->p2 );
47463   assert( pOp->p1>0 );
47464   assert( pOp->p1+pOp->p2<=p->nMem );
47465
47466   /* Invalidate all ephemeral cursor row caches */
47467   p->cacheCtr = (p->cacheCtr + 2)|1;
47468
47469   /* Make sure the results of the current row are \000 terminated
47470   ** and have an assigned type.  The results are de-ephemeralized as
47471   ** as side effect.
47472   */
47473   pMem = p->pResultSet = &p->aMem[pOp->p1];
47474   for(i=0; i<pOp->p2; i++){
47475     sqlite3VdbeMemNulTerminate(&pMem[i]);
47476     storeTypeInfo(&pMem[i], encoding);
47477     REGISTER_TRACE(pOp->p1+i, &pMem[i]);
47478   }
47479   if( db->mallocFailed ) goto no_mem;
47480
47481   /* Return SQLITE_ROW
47482   */
47483   p->nCallback++;
47484   p->pc = pc + 1;
47485   rc = SQLITE_ROW;
47486   goto vdbe_return;
47487 }
47488
47489 /* Opcode: Concat P1 P2 P3 * *
47490 **
47491 ** Add the text in register P1 onto the end of the text in
47492 ** register P2 and store the result in register P3.
47493 ** If either the P1 or P2 text are NULL then store NULL in P3.
47494 **
47495 **   P3 = P2 || P1
47496 **
47497 ** It is illegal for P1 and P3 to be the same register. Sometimes,
47498 ** if P3 is the same register as P2, the implementation is able
47499 ** to avoid a memcpy().
47500 */
47501 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
47502   i64 nByte;
47503
47504   assert( pIn1!=pOut );
47505   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
47506     sqlite3VdbeMemSetNull(pOut);
47507     break;
47508   }
47509   ExpandBlob(pIn1);
47510   Stringify(pIn1, encoding);
47511   ExpandBlob(pIn2);
47512   Stringify(pIn2, encoding);
47513   nByte = pIn1->n + pIn2->n;
47514   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
47515     goto too_big;
47516   }
47517   MemSetTypeFlag(pOut, MEM_Str);
47518   if( sqlite3VdbeMemGrow(pOut, nByte+2, pOut==pIn2) ){
47519     goto no_mem;
47520   }
47521   if( pOut!=pIn2 ){
47522     memcpy(pOut->z, pIn2->z, pIn2->n);
47523   }
47524   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
47525   pOut->z[nByte] = 0;
47526   pOut->z[nByte+1] = 0;
47527   pOut->flags |= MEM_Term;
47528   pOut->n = nByte;
47529   pOut->enc = encoding;
47530   UPDATE_MAX_BLOBSIZE(pOut);
47531   break;
47532 }
47533
47534 /* Opcode: Add P1 P2 P3 * *
47535 **
47536 ** Add the value in register P1 to the value in register P2
47537 ** and store the result in register P3.
47538 ** If either input is NULL, the result is NULL.
47539 */
47540 /* Opcode: Multiply P1 P2 P3 * *
47541 **
47542 **
47543 ** Multiply the value in register P1 by the value in register P2
47544 ** and store the result in register P3.
47545 ** If either input is NULL, the result is NULL.
47546 */
47547 /* Opcode: Subtract P1 P2 P3 * *
47548 **
47549 ** Subtract the value in register P1 from the value in register P2
47550 ** and store the result in register P3.
47551 ** If either input is NULL, the result is NULL.
47552 */
47553 /* Opcode: Divide P1 P2 P3 * *
47554 **
47555 ** Divide the value in register P1 by the value in register P2
47556 ** and store the result in register P3.  If the value in register P2
47557 ** is zero, then the result is NULL.
47558 ** If either input is NULL, the result is NULL.
47559 */
47560 /* Opcode: Remainder P1 P2 P3 * *
47561 **
47562 ** Compute the remainder after integer division of the value in
47563 ** register P1 by the value in register P2 and store the result in P3. 
47564 ** If the value in register P2 is zero the result is NULL.
47565 ** If either operand is NULL, the result is NULL.
47566 */
47567 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
47568 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
47569 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
47570 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
47571 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
47572   int flags;
47573   applyNumericAffinity(pIn1);
47574   applyNumericAffinity(pIn2);
47575   flags = pIn1->flags | pIn2->flags;
47576   if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
47577   if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
47578     i64 a, b;
47579     a = pIn1->u.i;
47580     b = pIn2->u.i;
47581     switch( pOp->opcode ){
47582       case OP_Add:         b += a;       break;
47583       case OP_Subtract:    b -= a;       break;
47584       case OP_Multiply:    b *= a;       break;
47585       case OP_Divide: {
47586         if( a==0 ) goto arithmetic_result_is_null;
47587         /* Dividing the largest possible negative 64-bit integer (1<<63) by 
47588         ** -1 returns an integer too large to store in a 64-bit data-type. On
47589         ** some architectures, the value overflows to (1<<63). On others,
47590         ** a SIGFPE is issued. The following statement normalizes this
47591         ** behavior so that all architectures behave as if integer 
47592         ** overflow occurred.
47593         */
47594         if( a==-1 && b==SMALLEST_INT64 ) a = 1;
47595         b /= a;
47596         break;
47597       }
47598       default: {
47599         if( a==0 ) goto arithmetic_result_is_null;
47600         if( a==-1 ) a = 1;
47601         b %= a;
47602         break;
47603       }
47604     }
47605     pOut->u.i = b;
47606     MemSetTypeFlag(pOut, MEM_Int);
47607   }else{
47608     double a, b;
47609     a = sqlite3VdbeRealValue(pIn1);
47610     b = sqlite3VdbeRealValue(pIn2);
47611     switch( pOp->opcode ){
47612       case OP_Add:         b += a;       break;
47613       case OP_Subtract:    b -= a;       break;
47614       case OP_Multiply:    b *= a;       break;
47615       case OP_Divide: {
47616         if( a==0.0 ) goto arithmetic_result_is_null;
47617         b /= a;
47618         break;
47619       }
47620       default: {
47621         i64 ia = (i64)a;
47622         i64 ib = (i64)b;
47623         if( ia==0 ) goto arithmetic_result_is_null;
47624         if( ia==-1 ) ia = 1;
47625         b = ib % ia;
47626         break;
47627       }
47628     }
47629     if( sqlite3IsNaN(b) ){
47630       goto arithmetic_result_is_null;
47631     }
47632     pOut->r = b;
47633     MemSetTypeFlag(pOut, MEM_Real);
47634     if( (flags & MEM_Real)==0 ){
47635       sqlite3VdbeIntegerAffinity(pOut);
47636     }
47637   }
47638   break;
47639
47640 arithmetic_result_is_null:
47641   sqlite3VdbeMemSetNull(pOut);
47642   break;
47643 }
47644
47645 /* Opcode: CollSeq * * P4
47646 **
47647 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
47648 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
47649 ** be returned. This is used by the built-in min(), max() and nullif()
47650 ** functions.
47651 **
47652 ** The interface used by the implementation of the aforementioned functions
47653 ** to retrieve the collation sequence set by this opcode is not available
47654 ** publicly, only to user functions defined in func.c.
47655 */
47656 case OP_CollSeq: {
47657   assert( pOp->p4type==P4_COLLSEQ );
47658   break;
47659 }
47660
47661 /* Opcode: Function P1 P2 P3 P4 P5
47662 **
47663 ** Invoke a user function (P4 is a pointer to a Function structure that
47664 ** defines the function) with P5 arguments taken from register P2 and
47665 ** successors.  The result of the function is stored in register P3.
47666 ** Register P3 must not be one of the function inputs.
47667 **
47668 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
47669 ** function was determined to be constant at compile time. If the first
47670 ** argument was constant then bit 0 of P1 is set. This is used to determine
47671 ** whether meta data associated with a user function argument using the
47672 ** sqlite3_set_auxdata() API may be safely retained until the next
47673 ** invocation of this opcode.
47674 **
47675 ** See also: AggStep and AggFinal
47676 */
47677 case OP_Function: {
47678   int i;
47679   Mem *pArg;
47680   sqlite3_context ctx;
47681   sqlite3_value **apVal;
47682   int n = pOp->p5;
47683
47684   apVal = p->apArg;
47685   assert( apVal || n==0 );
47686
47687   assert( n==0 || (pOp->p2>0 && pOp->p2+n<=p->nMem) );
47688   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
47689   pArg = &p->aMem[pOp->p2];
47690   for(i=0; i<n; i++, pArg++){
47691     apVal[i] = pArg;
47692     storeTypeInfo(pArg, encoding);
47693     REGISTER_TRACE(pOp->p2, pArg);
47694   }
47695
47696   assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
47697   if( pOp->p4type==P4_FUNCDEF ){
47698     ctx.pFunc = pOp->p4.pFunc;
47699     ctx.pVdbeFunc = 0;
47700   }else{
47701     ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
47702     ctx.pFunc = ctx.pVdbeFunc->pFunc;
47703   }
47704
47705   assert( pOp->p3>0 && pOp->p3<=p->nMem );
47706   pOut = &p->aMem[pOp->p3];
47707   ctx.s.flags = MEM_Null;
47708   ctx.s.db = db;
47709   ctx.s.xDel = 0;
47710   ctx.s.zMalloc = 0;
47711
47712   /* The output cell may already have a buffer allocated. Move
47713   ** the pointer to ctx.s so in case the user-function can use
47714   ** the already allocated buffer instead of allocating a new one.
47715   */
47716   sqlite3VdbeMemMove(&ctx.s, pOut);
47717   MemSetTypeFlag(&ctx.s, MEM_Null);
47718
47719   ctx.isError = 0;
47720   if( ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
47721     assert( pOp>p->aOp );
47722     assert( pOp[-1].p4type==P4_COLLSEQ );
47723     assert( pOp[-1].opcode==OP_CollSeq );
47724     ctx.pColl = pOp[-1].p4.pColl;
47725   }
47726   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
47727   (*ctx.pFunc->xFunc)(&ctx, n, apVal);
47728   if( sqlite3SafetyOn(db) ){
47729     sqlite3VdbeMemRelease(&ctx.s);
47730     goto abort_due_to_misuse;
47731   }
47732   if( db->mallocFailed ){
47733     /* Even though a malloc() has failed, the implementation of the
47734     ** user function may have called an sqlite3_result_XXX() function
47735     ** to return a value. The following call releases any resources
47736     ** associated with such a value.
47737     **
47738     ** Note: Maybe MemRelease() should be called if sqlite3SafetyOn()
47739     ** fails also (the if(...) statement above). But if people are
47740     ** misusing sqlite, they have bigger problems than a leaked value.
47741     */
47742     sqlite3VdbeMemRelease(&ctx.s);
47743     goto no_mem;
47744   }
47745
47746   /* If any auxiliary data functions have been called by this user function,
47747   ** immediately call the destructor for any non-static values.
47748   */
47749   if( ctx.pVdbeFunc ){
47750     sqlite3VdbeDeleteAuxData(ctx.pVdbeFunc, pOp->p1);
47751     pOp->p4.pVdbeFunc = ctx.pVdbeFunc;
47752     pOp->p4type = P4_VDBEFUNC;
47753   }
47754
47755   /* If the function returned an error, throw an exception */
47756   if( ctx.isError ){
47757     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s));
47758     rc = ctx.isError;
47759   }
47760
47761   /* Copy the result of the function into register P3 */
47762   sqlite3VdbeChangeEncoding(&ctx.s, encoding);
47763   sqlite3VdbeMemMove(pOut, &ctx.s);
47764   if( sqlite3VdbeMemTooBig(pOut) ){
47765     goto too_big;
47766   }
47767   REGISTER_TRACE(pOp->p3, pOut);
47768   UPDATE_MAX_BLOBSIZE(pOut);
47769   break;
47770 }
47771
47772 /* Opcode: BitAnd P1 P2 P3 * *
47773 **
47774 ** Take the bit-wise AND of the values in register P1 and P2 and
47775 ** store the result in register P3.
47776 ** If either input is NULL, the result is NULL.
47777 */
47778 /* Opcode: BitOr P1 P2 P3 * *
47779 **
47780 ** Take the bit-wise OR of the values in register P1 and P2 and
47781 ** store the result in register P3.
47782 ** If either input is NULL, the result is NULL.
47783 */
47784 /* Opcode: ShiftLeft P1 P2 P3 * *
47785 **
47786 ** Shift the integer value in register P2 to the left by the
47787 ** number of bits specified by the integer in regiser P1.
47788 ** Store the result in register P3.
47789 ** If either input is NULL, the result is NULL.
47790 */
47791 /* Opcode: ShiftRight P1 P2 P3 * *
47792 **
47793 ** Shift the integer value in register P2 to the right by the
47794 ** number of bits specified by the integer in register P1.
47795 ** Store the result in register P3.
47796 ** If either input is NULL, the result is NULL.
47797 */
47798 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
47799 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
47800 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
47801 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
47802   i64 a, b;
47803
47804   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
47805     sqlite3VdbeMemSetNull(pOut);
47806     break;
47807   }
47808   a = sqlite3VdbeIntValue(pIn2);
47809   b = sqlite3VdbeIntValue(pIn1);
47810   switch( pOp->opcode ){
47811     case OP_BitAnd:      a &= b;     break;
47812     case OP_BitOr:       a |= b;     break;
47813     case OP_ShiftLeft:   a <<= b;    break;
47814     default:  assert( pOp->opcode==OP_ShiftRight );
47815                          a >>= b;    break;
47816   }
47817   pOut->u.i = a;
47818   MemSetTypeFlag(pOut, MEM_Int);
47819   break;
47820 }
47821
47822 /* Opcode: AddImm  P1 P2 * * *
47823 ** 
47824 ** Add the constant P2 to the value in register P1.
47825 ** The result is always an integer.
47826 **
47827 ** To force any register to be an integer, just add 0.
47828 */
47829 case OP_AddImm: {            /* in1 */
47830   sqlite3VdbeMemIntegerify(pIn1);
47831   pIn1->u.i += pOp->p2;
47832   break;
47833 }
47834
47835 /* Opcode: ForceInt P1 P2 P3 * *
47836 **
47837 ** Convert value in register P1 into an integer.  If the value 
47838 ** in P1 is not numeric (meaning that is is a NULL or a string that
47839 ** does not look like an integer or floating point number) then
47840 ** jump to P2.  If the value in P1 is numeric then
47841 ** convert it into the least integer that is greater than or equal to its
47842 ** current value if P3==0, or to the least integer that is strictly
47843 ** greater than its current value if P3==1.
47844 */
47845 case OP_ForceInt: {            /* jump, in1 */
47846   i64 v;
47847   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
47848   if( (pIn1->flags & (MEM_Int|MEM_Real))==0 ){
47849     pc = pOp->p2 - 1;
47850     break;
47851   }
47852   if( pIn1->flags & MEM_Int ){
47853     v = pIn1->u.i + (pOp->p3!=0);
47854   }else{
47855     assert( pIn1->flags & MEM_Real );
47856     v = (sqlite3_int64)pIn1->r;
47857     if( pIn1->r>(double)v ) v++;
47858     if( pOp->p3 && pIn1->r==(double)v ) v++;
47859   }
47860   pIn1->u.i = v;
47861   MemSetTypeFlag(pIn1, MEM_Int);
47862   break;
47863 }
47864
47865 /* Opcode: MustBeInt P1 P2 * * *
47866 ** 
47867 ** Force the value in register P1 to be an integer.  If the value
47868 ** in P1 is not an integer and cannot be converted into an integer
47869 ** without data loss, then jump immediately to P2, or if P2==0
47870 ** raise an SQLITE_MISMATCH exception.
47871 */
47872 case OP_MustBeInt: {            /* jump, in1 */
47873   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
47874   if( (pIn1->flags & MEM_Int)==0 ){
47875     if( pOp->p2==0 ){
47876       rc = SQLITE_MISMATCH;
47877       goto abort_due_to_error;
47878     }else{
47879       pc = pOp->p2 - 1;
47880     }
47881   }else{
47882     MemSetTypeFlag(pIn1, MEM_Int);
47883   }
47884   break;
47885 }
47886
47887 /* Opcode: RealAffinity P1 * * * *
47888 **
47889 ** If register P1 holds an integer convert it to a real value.
47890 **
47891 ** This opcode is used when extracting information from a column that
47892 ** has REAL affinity.  Such column values may still be stored as
47893 ** integers, for space efficiency, but after extraction we want them
47894 ** to have only a real value.
47895 */
47896 case OP_RealAffinity: {                  /* in1 */
47897   if( pIn1->flags & MEM_Int ){
47898     sqlite3VdbeMemRealify(pIn1);
47899   }
47900   break;
47901 }
47902
47903 #ifndef SQLITE_OMIT_CAST
47904 /* Opcode: ToText P1 * * * *
47905 **
47906 ** Force the value in register P1 to be text.
47907 ** If the value is numeric, convert it to a string using the
47908 ** equivalent of printf().  Blob values are unchanged and
47909 ** are afterwards simply interpreted as text.
47910 **
47911 ** A NULL value is not changed by this routine.  It remains NULL.
47912 */
47913 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
47914   if( pIn1->flags & MEM_Null ) break;
47915   assert( MEM_Str==(MEM_Blob>>3) );
47916   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
47917   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
47918   rc = ExpandBlob(pIn1);
47919   assert( pIn1->flags & MEM_Str || db->mallocFailed );
47920   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob);
47921   UPDATE_MAX_BLOBSIZE(pIn1);
47922   break;
47923 }
47924
47925 /* Opcode: ToBlob P1 * * * *
47926 **
47927 ** Force the value in register P1 to be a BLOB.
47928 ** If the value is numeric, convert it to a string first.
47929 ** Strings are simply reinterpreted as blobs with no change
47930 ** to the underlying data.
47931 **
47932 ** A NULL value is not changed by this routine.  It remains NULL.
47933 */
47934 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
47935   if( pIn1->flags & MEM_Null ) break;
47936   if( (pIn1->flags & MEM_Blob)==0 ){
47937     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
47938     assert( pIn1->flags & MEM_Str || db->mallocFailed );
47939   }
47940   MemSetTypeFlag(pIn1, MEM_Blob);
47941   UPDATE_MAX_BLOBSIZE(pIn1);
47942   break;
47943 }
47944
47945 /* Opcode: ToNumeric P1 * * * *
47946 **
47947 ** Force the value in register P1 to be numeric (either an
47948 ** integer or a floating-point number.)
47949 ** If the value is text or blob, try to convert it to an using the
47950 ** equivalent of atoi() or atof() and store 0 if no such conversion 
47951 ** is possible.
47952 **
47953 ** A NULL value is not changed by this routine.  It remains NULL.
47954 */
47955 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
47956   if( (pIn1->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
47957     sqlite3VdbeMemNumerify(pIn1);
47958   }
47959   break;
47960 }
47961 #endif /* SQLITE_OMIT_CAST */
47962
47963 /* Opcode: ToInt P1 * * * *
47964 **
47965 ** Force the value in register P1 be an integer.  If
47966 ** The value is currently a real number, drop its fractional part.
47967 ** If the value is text or blob, try to convert it to an integer using the
47968 ** equivalent of atoi() and store 0 if no such conversion is possible.
47969 **
47970 ** A NULL value is not changed by this routine.  It remains NULL.
47971 */
47972 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
47973   if( (pIn1->flags & MEM_Null)==0 ){
47974     sqlite3VdbeMemIntegerify(pIn1);
47975   }
47976   break;
47977 }
47978
47979 #ifndef SQLITE_OMIT_CAST
47980 /* Opcode: ToReal P1 * * * *
47981 **
47982 ** Force the value in register P1 to be a floating point number.
47983 ** If The value is currently an integer, convert it.
47984 ** If the value is text or blob, try to convert it to an integer using the
47985 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
47986 **
47987 ** A NULL value is not changed by this routine.  It remains NULL.
47988 */
47989 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
47990   if( (pIn1->flags & MEM_Null)==0 ){
47991     sqlite3VdbeMemRealify(pIn1);
47992   }
47993   break;
47994 }
47995 #endif /* SQLITE_OMIT_CAST */
47996
47997 /* Opcode: Lt P1 P2 P3 P4 P5
47998 **
47999 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
48000 ** jump to address P2.  
48001 **
48002 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
48003 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL 
48004 ** bit is clear then fall thru if either operand is NULL.
48005 **
48006 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
48007 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
48008 ** to coerce both inputs according to this affinity before the
48009 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
48010 ** affinity is used. Note that the affinity conversions are stored
48011 ** back into the input registers P1 and P3.  So this opcode can cause
48012 ** persistent changes to registers P1 and P3.
48013 **
48014 ** Once any conversions have taken place, and neither value is NULL, 
48015 ** the values are compared. If both values are blobs then memcmp() is
48016 ** used to determine the results of the comparison.  If both values
48017 ** are text, then the appropriate collating function specified in
48018 ** P4 is  used to do the comparison.  If P4 is not specified then
48019 ** memcmp() is used to compare text string.  If both values are
48020 ** numeric, then a numeric comparison is used. If the two values
48021 ** are of different types, then numbers are considered less than
48022 ** strings and strings are considered less than blobs.
48023 **
48024 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
48025 ** store a boolean result (either 0, or 1, or NULL) in register P2.
48026 */
48027 /* Opcode: Ne P1 P2 P3 P4 P5
48028 **
48029 ** This works just like the Lt opcode except that the jump is taken if
48030 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
48031 ** additional information.
48032 */
48033 /* Opcode: Eq P1 P2 P3 P4 P5
48034 **
48035 ** This works just like the Lt opcode except that the jump is taken if
48036 ** the operands in registers P1 and P3 are equal.
48037 ** See the Lt opcode for additional information.
48038 */
48039 /* Opcode: Le P1 P2 P3 P4 P5
48040 **
48041 ** This works just like the Lt opcode except that the jump is taken if
48042 ** the content of register P3 is less than or equal to the content of
48043 ** register P1.  See the Lt opcode for additional information.
48044 */
48045 /* Opcode: Gt P1 P2 P3 P4 P5
48046 **
48047 ** This works just like the Lt opcode except that the jump is taken if
48048 ** the content of register P3 is greater than the content of
48049 ** register P1.  See the Lt opcode for additional information.
48050 */
48051 /* Opcode: Ge P1 P2 P3 P4 P5
48052 **
48053 ** This works just like the Lt opcode except that the jump is taken if
48054 ** the content of register P3 is greater than or equal to the content of
48055 ** register P1.  See the Lt opcode for additional information.
48056 */
48057 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
48058 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
48059 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
48060 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
48061 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
48062 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
48063   int flags;
48064   int res;
48065   char affinity;
48066
48067   flags = pIn1->flags|pIn3->flags;
48068
48069   if( flags&MEM_Null ){
48070     /* If either operand is NULL then the result is always NULL.
48071     ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
48072     */
48073     if( pOp->p5 & SQLITE_STOREP2 ){
48074       pOut = &p->aMem[pOp->p2];
48075       MemSetTypeFlag(pOut, MEM_Null);
48076       REGISTER_TRACE(pOp->p2, pOut);
48077     }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
48078       pc = pOp->p2-1;
48079     }
48080     break;
48081   }
48082
48083   affinity = pOp->p5 & SQLITE_AFF_MASK;
48084   if( affinity ){
48085     applyAffinity(pIn1, affinity, encoding);
48086     applyAffinity(pIn3, affinity, encoding);
48087   }
48088
48089   assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
48090   ExpandBlob(pIn1);
48091   ExpandBlob(pIn3);
48092   res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
48093   switch( pOp->opcode ){
48094     case OP_Eq:    res = res==0;     break;
48095     case OP_Ne:    res = res!=0;     break;
48096     case OP_Lt:    res = res<0;      break;
48097     case OP_Le:    res = res<=0;     break;
48098     case OP_Gt:    res = res>0;      break;
48099     default:       res = res>=0;     break;
48100   }
48101
48102   if( pOp->p5 & SQLITE_STOREP2 ){
48103     pOut = &p->aMem[pOp->p2];
48104     MemSetTypeFlag(pOut, MEM_Int);
48105     pOut->u.i = res;
48106     REGISTER_TRACE(pOp->p2, pOut);
48107   }else if( res ){
48108     pc = pOp->p2-1;
48109   }
48110   break;
48111 }
48112
48113 /* Opcode: Permutation * * * P4 *
48114 **
48115 ** Set the permuation used by the OP_Compare operator to be the array
48116 ** of integers in P4.
48117 **
48118 ** The permutation is only valid until the next OP_Permutation, OP_Compare,
48119 ** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
48120 ** immediately prior to the OP_Compare.
48121 */
48122 case OP_Permutation: {
48123   assert( pOp->p4type==P4_INTARRAY );
48124   assert( pOp->p4.ai );
48125   aPermute = pOp->p4.ai;
48126   break;
48127 }
48128
48129 /* Opcode: Compare P1 P2 P3 P4 *
48130 **
48131 ** Compare to vectors of registers in reg(P1)..reg(P1+P3-1) (all this
48132 ** one "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
48133 ** the comparison for use by the next OP_Jump instruct.
48134 **
48135 ** P4 is a KeyInfo structure that defines collating sequences and sort
48136 ** orders for the comparison.  The permutation applies to registers
48137 ** only.  The KeyInfo elements are used sequentially.
48138 **
48139 ** The comparison is a sort comparison, so NULLs compare equal,
48140 ** NULLs are less than numbers, numbers are less than strings,
48141 ** and strings are less than blobs.
48142 */
48143 case OP_Compare: {
48144   int n = pOp->p3;
48145   int i, p1, p2;
48146   const KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
48147   assert( n>0 );
48148   assert( pKeyInfo!=0 );
48149   p1 = pOp->p1;
48150   assert( p1>0 && p1+n-1<p->nMem );
48151   p2 = pOp->p2;
48152   assert( p2>0 && p2+n-1<p->nMem );
48153   for(i=0; i<n; i++){
48154     int idx = aPermute ? aPermute[i] : i;
48155     CollSeq *pColl;    /* Collating sequence to use on this term */
48156     int bRev;          /* True for DESCENDING sort order */
48157     REGISTER_TRACE(p1+idx, &p->aMem[p1+idx]);
48158     REGISTER_TRACE(p2+idx, &p->aMem[p2+idx]);
48159     assert( i<pKeyInfo->nField );
48160     pColl = pKeyInfo->aColl[i];
48161     bRev = pKeyInfo->aSortOrder[i];
48162     iCompare = sqlite3MemCompare(&p->aMem[p1+idx], &p->aMem[p2+idx], pColl);
48163     if( iCompare ){
48164       if( bRev ) iCompare = -iCompare;
48165       break;
48166     }
48167   }
48168   aPermute = 0;
48169   break;
48170 }
48171
48172 /* Opcode: Jump P1 P2 P3 * *
48173 **
48174 ** Jump to the instruction at address P1, P2, or P3 depending on whether
48175 ** in the most recent OP_Compare instruction the P1 vector was less than
48176 ** equal to, or greater than the P2 vector, respectively.
48177 */
48178 case OP_Jump: {             /* jump */
48179   if( iCompare<0 ){
48180     pc = pOp->p1 - 1;
48181   }else if( iCompare==0 ){
48182     pc = pOp->p2 - 1;
48183   }else{
48184     pc = pOp->p3 - 1;
48185   }
48186   break;
48187 }
48188
48189 /* Opcode: And P1 P2 P3 * *
48190 **
48191 ** Take the logical AND of the values in registers P1 and P2 and
48192 ** write the result into register P3.
48193 **
48194 ** If either P1 or P2 is 0 (false) then the result is 0 even if
48195 ** the other input is NULL.  A NULL and true or two NULLs give
48196 ** a NULL output.
48197 */
48198 /* Opcode: Or P1 P2 P3 * *
48199 **
48200 ** Take the logical OR of the values in register P1 and P2 and
48201 ** store the answer in register P3.
48202 **
48203 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
48204 ** even if the other input is NULL.  A NULL and false or two NULLs
48205 ** give a NULL output.
48206 */
48207 case OP_And:              /* same as TK_AND, in1, in2, out3 */
48208 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
48209   int v1, v2;    /* 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
48210
48211   if( pIn1->flags & MEM_Null ){
48212     v1 = 2;
48213   }else{
48214     v1 = sqlite3VdbeIntValue(pIn1)!=0;
48215   }
48216   if( pIn2->flags & MEM_Null ){
48217     v2 = 2;
48218   }else{
48219     v2 = sqlite3VdbeIntValue(pIn2)!=0;
48220   }
48221   if( pOp->opcode==OP_And ){
48222     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
48223     v1 = and_logic[v1*3+v2];
48224   }else{
48225     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
48226     v1 = or_logic[v1*3+v2];
48227   }
48228   if( v1==2 ){
48229     MemSetTypeFlag(pOut, MEM_Null);
48230   }else{
48231     pOut->u.i = v1;
48232     MemSetTypeFlag(pOut, MEM_Int);
48233   }
48234   break;
48235 }
48236
48237 /* Opcode: Not P1 * * * *
48238 **
48239 ** Interpret the value in register P1 as a boolean value.  Replace it
48240 ** with its complement.  If the value in register P1 is NULL its value
48241 ** is unchanged.
48242 */
48243 case OP_Not: {                /* same as TK_NOT, in1 */
48244   if( pIn1->flags & MEM_Null ) break;  /* Do nothing to NULLs */
48245   sqlite3VdbeMemIntegerify(pIn1);
48246   pIn1->u.i = !pIn1->u.i;
48247   assert( pIn1->flags&MEM_Int );
48248   break;
48249 }
48250
48251 /* Opcode: BitNot P1 * * * *
48252 **
48253 ** Interpret the content of register P1 as an integer.  Replace it
48254 ** with its ones-complement.  If the value is originally NULL, leave
48255 ** it unchanged.
48256 */
48257 case OP_BitNot: {             /* same as TK_BITNOT, in1 */
48258   if( pIn1->flags & MEM_Null ) break;  /* Do nothing to NULLs */
48259   sqlite3VdbeMemIntegerify(pIn1);
48260   pIn1->u.i = ~pIn1->u.i;
48261   assert( pIn1->flags&MEM_Int );
48262   break;
48263 }
48264
48265 /* Opcode: If P1 P2 P3 * *
48266 **
48267 ** Jump to P2 if the value in register P1 is true.  The value is
48268 ** is considered true if it is numeric and non-zero.  If the value
48269 ** in P1 is NULL then take the jump if P3 is true.
48270 */
48271 /* Opcode: IfNot P1 P2 P3 * *
48272 **
48273 ** Jump to P2 if the value in register P1 is False.  The value is
48274 ** is considered true if it has a numeric value of zero.  If the value
48275 ** in P1 is NULL then take the jump if P3 is true.
48276 */
48277 case OP_If:                 /* jump, in1 */
48278 case OP_IfNot: {            /* jump, in1 */
48279   int c;
48280   if( pIn1->flags & MEM_Null ){
48281     c = pOp->p3;
48282   }else{
48283 #ifdef SQLITE_OMIT_FLOATING_POINT
48284     c = sqlite3VdbeIntValue(pIn1);
48285 #else
48286     c = sqlite3VdbeRealValue(pIn1)!=0.0;
48287 #endif
48288     if( pOp->opcode==OP_IfNot ) c = !c;
48289   }
48290   if( c ){
48291     pc = pOp->p2-1;
48292   }
48293   break;
48294 }
48295
48296 /* Opcode: IsNull P1 P2 P3 * *
48297 **
48298 ** Jump to P2 if the value in register P1 is NULL.  If P3 is greater
48299 ** than zero, then check all values reg(P1), reg(P1+1), 
48300 ** reg(P1+2), ..., reg(P1+P3-1).
48301 */
48302 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
48303   int n = pOp->p3;
48304   assert( pOp->p3==0 || pOp->p1>0 );
48305   do{
48306     if( (pIn1->flags & MEM_Null)!=0 ){
48307       pc = pOp->p2 - 1;
48308       break;
48309     }
48310     pIn1++;
48311   }while( --n > 0 );
48312   break;
48313 }
48314
48315 /* Opcode: NotNull P1 P2 * * *
48316 **
48317 ** Jump to P2 if the value in register P1 is not NULL.  
48318 */
48319 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
48320   if( (pIn1->flags & MEM_Null)==0 ){
48321     pc = pOp->p2 - 1;
48322   }
48323   break;
48324 }
48325
48326 /* Opcode: SetNumColumns * P2 * * *
48327 **
48328 ** This opcode sets the number of columns for the cursor opened by the
48329 ** following instruction to P2.
48330 **
48331 ** An OP_SetNumColumns is only useful if it occurs immediately before 
48332 ** one of the following opcodes:
48333 **
48334 **     OpenRead
48335 **     OpenWrite
48336 **     OpenPseudo
48337 **
48338 ** If the OP_Column opcode is to be executed on a cursor, then
48339 ** this opcode must be present immediately before the opcode that
48340 ** opens the cursor.
48341 */
48342 case OP_SetNumColumns: {
48343   break;
48344 }
48345
48346 /* Opcode: Column P1 P2 P3 P4 *
48347 **
48348 ** Interpret the data that cursor P1 points to as a structure built using
48349 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
48350 ** information about the format of the data.)  Extract the P2-th column
48351 ** from this record.  If there are less that (P2+1) 
48352 ** values in the record, extract a NULL.
48353 **
48354 ** The value extracted is stored in register P3.
48355 **
48356 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
48357 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
48358 ** the result.
48359 */
48360 case OP_Column: {
48361   int payloadSize;   /* Number of bytes in the record */
48362   int p1 = pOp->p1;  /* P1 value of the opcode */
48363   int p2 = pOp->p2;  /* column number to retrieve */
48364   VdbeCursor *pC = 0;/* The VDBE cursor */
48365   char *zRec;        /* Pointer to complete record-data */
48366   BtCursor *pCrsr;   /* The BTree cursor */
48367   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
48368   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
48369   int nField;        /* number of fields in the record */
48370   int len;           /* The length of the serialized data for the column */
48371   int i;             /* Loop counter */
48372   char *zData;       /* Part of the record being decoded */
48373   Mem *pDest;        /* Where to write the extracted value */
48374   Mem sMem;          /* For storing the record being decoded */
48375
48376   sMem.flags = 0;
48377   sMem.db = 0;
48378   sMem.zMalloc = 0;
48379   assert( p1<p->nCursor );
48380   assert( pOp->p3>0 && pOp->p3<=p->nMem );
48381   pDest = &p->aMem[pOp->p3];
48382   MemSetTypeFlag(pDest, MEM_Null);
48383
48384   /* This block sets the variable payloadSize to be the total number of
48385   ** bytes in the record.
48386   **
48387   ** zRec is set to be the complete text of the record if it is available.
48388   ** The complete record text is always available for pseudo-tables
48389   ** If the record is stored in a cursor, the complete record text
48390   ** might be available in the  pC->aRow cache.  Or it might not be.
48391   ** If the data is unavailable,  zRec is set to NULL.
48392   **
48393   ** We also compute the number of columns in the record.  For cursors,
48394   ** the number of columns is stored in the VdbeCursor.nField element.
48395   */
48396   pC = p->apCsr[p1];
48397   assert( pC!=0 );
48398 #ifndef SQLITE_OMIT_VIRTUALTABLE
48399   assert( pC->pVtabCursor==0 );
48400 #endif
48401   if( pC->pCursor!=0 ){
48402     /* The record is stored in a B-Tree */
48403     rc = sqlite3VdbeCursorMoveto(pC);
48404     if( rc ) goto abort_due_to_error;
48405     zRec = 0;
48406     pCrsr = pC->pCursor;
48407     if( pC->nullRow ){
48408       payloadSize = 0;
48409     }else if( pC->cacheStatus==p->cacheCtr ){
48410       payloadSize = pC->payloadSize;
48411       zRec = (char*)pC->aRow;
48412     }else if( pC->isIndex ){
48413       i64 payloadSize64;
48414       sqlite3BtreeKeySize(pCrsr, &payloadSize64);
48415       payloadSize = payloadSize64;
48416     }else{
48417       sqlite3BtreeDataSize(pCrsr, (u32 *)&payloadSize);
48418     }
48419     nField = pC->nField;
48420   }else{
48421     assert( pC->pseudoTable );
48422     /* The record is the sole entry of a pseudo-table */
48423     payloadSize = pC->nData;
48424     zRec = pC->pData;
48425     pC->cacheStatus = CACHE_STALE;
48426     assert( payloadSize==0 || zRec!=0 );
48427     nField = pC->nField;
48428     pCrsr = 0;
48429   }
48430
48431   /* If payloadSize is 0, then just store a NULL */
48432   if( payloadSize==0 ){
48433     assert( pDest->flags&MEM_Null );
48434     goto op_column_out;
48435   }
48436   if( payloadSize>db->aLimit[SQLITE_LIMIT_LENGTH] ){
48437     goto too_big;
48438   }
48439
48440   assert( p2<nField );
48441
48442   /* Read and parse the table header.  Store the results of the parse
48443   ** into the record header cache fields of the cursor.
48444   */
48445   aType = pC->aType;
48446   if( pC->cacheStatus==p->cacheCtr ){
48447     aOffset = pC->aOffset;
48448   }else{
48449     u8 *zIdx;        /* Index into header */
48450     u8 *zEndHdr;     /* Pointer to first byte after the header */
48451     int offset;      /* Offset into the data */
48452     int szHdrSz;     /* Size of the header size field at start of record */
48453     int avail;       /* Number of bytes of available data */
48454
48455     assert(aType);
48456     pC->aOffset = aOffset = &aType[nField];
48457     pC->payloadSize = payloadSize;
48458     pC->cacheStatus = p->cacheCtr;
48459
48460     /* Figure out how many bytes are in the header */
48461     if( zRec ){
48462       zData = zRec;
48463     }else{
48464       if( pC->isIndex ){
48465         zData = (char*)sqlite3BtreeKeyFetch(pCrsr, &avail);
48466       }else{
48467         zData = (char*)sqlite3BtreeDataFetch(pCrsr, &avail);
48468       }
48469       /* If KeyFetch()/DataFetch() managed to get the entire payload,
48470       ** save the payload in the pC->aRow cache.  That will save us from
48471       ** having to make additional calls to fetch the content portion of
48472       ** the record.
48473       */
48474       if( avail>=payloadSize ){
48475         zRec = zData;
48476         pC->aRow = (u8*)zData;
48477       }else{
48478         pC->aRow = 0;
48479       }
48480     }
48481     /* The following assert is true in all cases accept when
48482     ** the database file has been corrupted externally.
48483     **    assert( zRec!=0 || avail>=payloadSize || avail>=9 ); */
48484     szHdrSz = getVarint32((u8*)zData, offset);
48485
48486     /* The KeyFetch() or DataFetch() above are fast and will get the entire
48487     ** record header in most cases.  But they will fail to get the complete
48488     ** record header if the record header does not fit on a single page
48489     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
48490     ** acquire the complete header text.
48491     */
48492     if( !zRec && avail<offset ){
48493       sMem.flags = 0;
48494       sMem.db = 0;
48495       rc = sqlite3VdbeMemFromBtree(pCrsr, 0, offset, pC->isIndex, &sMem);
48496       if( rc!=SQLITE_OK ){
48497         goto op_column_out;
48498       }
48499       zData = sMem.z;
48500     }
48501     zEndHdr = (u8 *)&zData[offset];
48502     zIdx = (u8 *)&zData[szHdrSz];
48503
48504     /* Scan the header and use it to fill in the aType[] and aOffset[]
48505     ** arrays.  aType[i] will contain the type integer for the i-th
48506     ** column and aOffset[i] will contain the offset from the beginning
48507     ** of the record to the start of the data for the i-th column
48508     */
48509     for(i=0; i<nField; i++){
48510       if( zIdx<zEndHdr ){
48511         aOffset[i] = offset;
48512         zIdx += getVarint32(zIdx, aType[i]);
48513         offset += sqlite3VdbeSerialTypeLen(aType[i]);
48514       }else{
48515         /* If i is less that nField, then there are less fields in this
48516         ** record than SetNumColumns indicated there are columns in the
48517         ** table. Set the offset for any extra columns not present in
48518         ** the record to 0. This tells code below to store a NULL
48519         ** instead of deserializing a value from the record.
48520         */
48521         aOffset[i] = 0;
48522       }
48523     }
48524     sqlite3VdbeMemRelease(&sMem);
48525     sMem.flags = MEM_Null;
48526
48527     /* If we have read more header data than was contained in the header,
48528     ** or if the end of the last field appears to be past the end of the
48529     ** record, or if the end of the last field appears to be before the end
48530     ** of the record (when all fields present), then we must be dealing 
48531     ** with a corrupt database.
48532     */
48533     if( zIdx>zEndHdr || offset>payloadSize 
48534      || (zIdx==zEndHdr && offset!=payloadSize) ){
48535       rc = SQLITE_CORRUPT_BKPT;
48536       goto op_column_out;
48537     }
48538   }
48539
48540   /* Get the column information. If aOffset[p2] is non-zero, then 
48541   ** deserialize the value from the record. If aOffset[p2] is zero,
48542   ** then there are not enough fields in the record to satisfy the
48543   ** request.  In this case, set the value NULL or to P4 if P4 is
48544   ** a pointer to a Mem object.
48545   */
48546   if( aOffset[p2] ){
48547     assert( rc==SQLITE_OK );
48548     if( zRec ){
48549       sqlite3VdbeMemReleaseExternal(pDest);
48550       sqlite3VdbeSerialGet((u8 *)&zRec[aOffset[p2]], aType[p2], pDest);
48551     }else{
48552       len = sqlite3VdbeSerialTypeLen(aType[p2]);
48553       sqlite3VdbeMemMove(&sMem, pDest);
48554       rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, pC->isIndex, &sMem);
48555       if( rc!=SQLITE_OK ){
48556         goto op_column_out;
48557       }
48558       zData = sMem.z;
48559       sqlite3VdbeSerialGet((u8*)zData, aType[p2], pDest);
48560     }
48561     pDest->enc = encoding;
48562   }else{
48563     if( pOp->p4type==P4_MEM ){
48564       sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
48565     }else{
48566       assert( pDest->flags&MEM_Null );
48567     }
48568   }
48569
48570   /* If we dynamically allocated space to hold the data (in the
48571   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
48572   ** dynamically allocated space over to the pDest structure.
48573   ** This prevents a memory copy.
48574   */
48575   if( sMem.zMalloc ){
48576     assert( sMem.z==sMem.zMalloc );
48577     assert( !(pDest->flags & MEM_Dyn) );
48578     assert( !(pDest->flags & (MEM_Blob|MEM_Str)) || pDest->z==sMem.z );
48579     pDest->flags &= ~(MEM_Ephem|MEM_Static);
48580     pDest->flags |= MEM_Term;
48581     pDest->z = sMem.z;
48582     pDest->zMalloc = sMem.zMalloc;
48583   }
48584
48585   rc = sqlite3VdbeMemMakeWriteable(pDest);
48586
48587 op_column_out:
48588   UPDATE_MAX_BLOBSIZE(pDest);
48589   REGISTER_TRACE(pOp->p3, pDest);
48590   break;
48591 }
48592
48593 /* Opcode: Affinity P1 P2 * P4 *
48594 **
48595 ** Apply affinities to a range of P2 registers starting with P1.
48596 **
48597 ** P4 is a string that is P2 characters long. The nth character of the
48598 ** string indicates the column affinity that should be used for the nth
48599 ** memory cell in the range.
48600 */
48601 case OP_Affinity: {
48602   char *zAffinity = pOp->p4.z;
48603   Mem *pData0 = &p->aMem[pOp->p1];
48604   Mem *pLast = &pData0[pOp->p2-1];
48605   Mem *pRec;
48606
48607   for(pRec=pData0; pRec<=pLast; pRec++){
48608     ExpandBlob(pRec);
48609     applyAffinity(pRec, zAffinity[pRec-pData0], encoding);
48610   }
48611   break;
48612 }
48613
48614 /* Opcode: MakeRecord P1 P2 P3 P4 *
48615 **
48616 ** Convert P2 registers beginning with P1 into a single entry
48617 ** suitable for use as a data record in a database table or as a key
48618 ** in an index.  The details of the format are irrelevant as long as
48619 ** the OP_Column opcode can decode the record later.
48620 ** Refer to source code comments for the details of the record
48621 ** format.
48622 **
48623 ** P4 may be a string that is P2 characters long.  The nth character of the
48624 ** string indicates the column affinity that should be used for the nth
48625 ** field of the index key.
48626 **
48627 ** The mapping from character to affinity is given by the SQLITE_AFF_
48628 ** macros defined in sqliteInt.h.
48629 **
48630 ** If P4 is NULL then all index fields have the affinity NONE.
48631 */
48632 case OP_MakeRecord: {
48633   /* Assuming the record contains N fields, the record format looks
48634   ** like this:
48635   **
48636   ** ------------------------------------------------------------------------
48637   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 | 
48638   ** ------------------------------------------------------------------------
48639   **
48640   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
48641   ** and so froth.
48642   **
48643   ** Each type field is a varint representing the serial type of the 
48644   ** corresponding data element (see sqlite3VdbeSerialType()). The
48645   ** hdr-size field is also a varint which is the offset from the beginning
48646   ** of the record to data0.
48647   */
48648   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
48649   Mem *pRec;             /* The new record */
48650   u64 nData = 0;         /* Number of bytes of data space */
48651   int nHdr = 0;          /* Number of bytes of header space */
48652   i64 nByte = 0;         /* Data space required for this record */
48653   int nZero = 0;         /* Number of zero bytes at the end of the record */
48654   int nVarint;           /* Number of bytes in a varint */
48655   u32 serial_type;       /* Type field */
48656   Mem *pData0;           /* First field to be combined into the record */
48657   Mem *pLast;            /* Last field of the record */
48658   int nField;            /* Number of fields in the record */
48659   char *zAffinity;       /* The affinity string for the record */
48660   int file_format;       /* File format to use for encoding */
48661   int i;                 /* Space used in zNewRecord[] */
48662
48663   nField = pOp->p1;
48664   zAffinity = pOp->p4.z;
48665   assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=p->nMem );
48666   pData0 = &p->aMem[nField];
48667   nField = pOp->p2;
48668   pLast = &pData0[nField-1];
48669   file_format = p->minWriteFileFormat;
48670
48671   /* Loop through the elements that will make up the record to figure
48672   ** out how much space is required for the new record.
48673   */
48674   for(pRec=pData0; pRec<=pLast; pRec++){
48675     int len;
48676     if( zAffinity ){
48677       applyAffinity(pRec, zAffinity[pRec-pData0], encoding);
48678     }
48679     if( pRec->flags&MEM_Zero && pRec->n>0 ){
48680       sqlite3VdbeMemExpandBlob(pRec);
48681     }
48682     serial_type = sqlite3VdbeSerialType(pRec, file_format);
48683     len = sqlite3VdbeSerialTypeLen(serial_type);
48684     nData += len;
48685     nHdr += sqlite3VarintLen(serial_type);
48686     if( pRec->flags & MEM_Zero ){
48687       /* Only pure zero-filled BLOBs can be input to this Opcode.
48688       ** We do not allow blobs with a prefix and a zero-filled tail. */
48689       nZero += pRec->u.i;
48690     }else if( len ){
48691       nZero = 0;
48692     }
48693   }
48694
48695   /* Add the initial header varint and total the size */
48696   nHdr += nVarint = sqlite3VarintLen(nHdr);
48697   if( nVarint<sqlite3VarintLen(nHdr) ){
48698     nHdr++;
48699   }
48700   nByte = nHdr+nData-nZero;
48701   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
48702     goto too_big;
48703   }
48704
48705   /* Make sure the output register has a buffer large enough to store 
48706   ** the new record. The output register (pOp->p3) is not allowed to
48707   ** be one of the input registers (because the following call to
48708   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
48709   */
48710   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
48711   pOut = &p->aMem[pOp->p3];
48712   if( sqlite3VdbeMemGrow(pOut, nByte, 0) ){
48713     goto no_mem;
48714   }
48715   zNewRecord = (u8 *)pOut->z;
48716
48717   /* Write the record */
48718   i = putVarint32(zNewRecord, nHdr);
48719   for(pRec=pData0; pRec<=pLast; pRec++){
48720     serial_type = sqlite3VdbeSerialType(pRec, file_format);
48721     i += putVarint32(&zNewRecord[i], serial_type);      /* serial type */
48722   }
48723   for(pRec=pData0; pRec<=pLast; pRec++){  /* serial data */
48724     i += sqlite3VdbeSerialPut(&zNewRecord[i], nByte-i, pRec, file_format);
48725   }
48726   assert( i==nByte );
48727
48728   assert( pOp->p3>0 && pOp->p3<=p->nMem );
48729   pOut->n = nByte;
48730   pOut->flags = MEM_Blob | MEM_Dyn;
48731   pOut->xDel = 0;
48732   if( nZero ){
48733     pOut->u.i = nZero;
48734     pOut->flags |= MEM_Zero;
48735   }
48736   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
48737   REGISTER_TRACE(pOp->p3, pOut);
48738   UPDATE_MAX_BLOBSIZE(pOut);
48739   break;
48740 }
48741
48742 /* Opcode: Statement P1 * * * *
48743 **
48744 ** Begin an individual statement transaction which is part of a larger
48745 ** transaction.  This is needed so that the statement
48746 ** can be rolled back after an error without having to roll back the
48747 ** entire transaction.  The statement transaction will automatically
48748 ** commit when the VDBE halts.
48749 **
48750 ** If the database connection is currently in autocommit mode (that 
48751 ** is to say, if it is in between BEGIN and COMMIT)
48752 ** and if there are no other active statements on the same database
48753 ** connection, then this operation is a no-op.  No statement transaction
48754 ** is needed since any error can use the normal ROLLBACK process to
48755 ** undo changes.
48756 **
48757 ** If a statement transaction is started, then a statement journal file
48758 ** will be allocated and initialized.
48759 **
48760 ** The statement is begun on the database file with index P1.  The main
48761 ** database file has an index of 0 and the file used for temporary tables
48762 ** has an index of 1.
48763 */
48764 case OP_Statement: {
48765   if( db->autoCommit==0 || db->activeVdbeCnt>1 ){
48766     int i = pOp->p1;
48767     Btree *pBt;
48768     assert( i>=0 && i<db->nDb );
48769     assert( db->aDb[i].pBt!=0 );
48770     pBt = db->aDb[i].pBt;
48771     assert( sqlite3BtreeIsInTrans(pBt) );
48772     assert( (p->btreeMask & (1<<i))!=0 );
48773     if( !sqlite3BtreeIsInStmt(pBt) ){
48774       rc = sqlite3BtreeBeginStmt(pBt);
48775       p->openedStatement = 1;
48776     }
48777   }
48778   break;
48779 }
48780
48781 /* Opcode: AutoCommit P1 P2 * * *
48782 **
48783 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
48784 ** back any currently active btree transactions. If there are any active
48785 ** VMs (apart from this one), then the COMMIT or ROLLBACK statement fails.
48786 **
48787 ** This instruction causes the VM to halt.
48788 */
48789 case OP_AutoCommit: {
48790   int desiredAutoCommit = pOp->p1;
48791   int rollback = pOp->p2;
48792   int turnOnAC = desiredAutoCommit && !db->autoCommit;
48793
48794   assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
48795   assert( desiredAutoCommit==1 || rollback==0 );
48796
48797   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
48798
48799   if( turnOnAC && rollback && db->activeVdbeCnt>1 ){
48800     /* If this instruction implements a ROLLBACK and other VMs are
48801     ** still running, and a transaction is active, return an error indicating
48802     ** that the other VMs must complete first. 
48803     */
48804     sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
48805         "SQL statements in progress");
48806     rc = SQLITE_BUSY;
48807   }else if( turnOnAC && !rollback && db->writeVdbeCnt>1 ){
48808     /* If this instruction implements a COMMIT and other VMs are writing
48809     ** return an error indicating that the other VMs must complete first. 
48810     */
48811     sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
48812         "SQL statements in progress");
48813     rc = SQLITE_BUSY;
48814   }else if( desiredAutoCommit!=db->autoCommit ){
48815     if( pOp->p2 ){
48816       assert( desiredAutoCommit==1 );
48817       sqlite3RollbackAll(db);
48818       db->autoCommit = 1;
48819     }else{
48820       db->autoCommit = desiredAutoCommit;
48821       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
48822         p->pc = pc;
48823         db->autoCommit = 1-desiredAutoCommit;
48824         p->rc = rc = SQLITE_BUSY;
48825         goto vdbe_return;
48826       }
48827     }
48828     if( p->rc==SQLITE_OK ){
48829       rc = SQLITE_DONE;
48830     }else{
48831       rc = SQLITE_ERROR;
48832     }
48833     goto vdbe_return;
48834   }else{
48835     sqlite3SetString(&p->zErrMsg, db,
48836         (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
48837         (rollback)?"cannot rollback - no transaction is active":
48838                    "cannot commit - no transaction is active"));
48839          
48840     rc = SQLITE_ERROR;
48841   }
48842   break;
48843 }
48844
48845 /* Opcode: Transaction P1 P2 * * *
48846 **
48847 ** Begin a transaction.  The transaction ends when a Commit or Rollback
48848 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
48849 ** transaction might also be rolled back if an error is encountered.
48850 **
48851 ** P1 is the index of the database file on which the transaction is
48852 ** started.  Index 0 is the main database file and index 1 is the
48853 ** file used for temporary tables.  Indices of 2 or more are used for
48854 ** attached databases.
48855 **
48856 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
48857 ** obtained on the database file when a write-transaction is started.  No
48858 ** other process can start another write transaction while this transaction is
48859 ** underway.  Starting a write transaction also creates a rollback journal. A
48860 ** write transaction must be started before any changes can be made to the
48861 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
48862 ** on the file.
48863 **
48864 ** If P2 is zero, then a read-lock is obtained on the database file.
48865 */
48866 case OP_Transaction: {
48867   int i = pOp->p1;
48868   Btree *pBt;
48869
48870   assert( i>=0 && i<db->nDb );
48871   assert( (p->btreeMask & (1<<i))!=0 );
48872   pBt = db->aDb[i].pBt;
48873
48874   if( pBt ){
48875     rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
48876     if( rc==SQLITE_BUSY ){
48877       p->pc = pc;
48878       p->rc = rc = SQLITE_BUSY;
48879       goto vdbe_return;
48880     }
48881     if( rc!=SQLITE_OK && rc!=SQLITE_READONLY /* && rc!=SQLITE_BUSY */ ){
48882       goto abort_due_to_error;
48883     }
48884   }
48885   break;
48886 }
48887
48888 /* Opcode: ReadCookie P1 P2 P3 * *
48889 **
48890 ** Read cookie number P3 from database P1 and write it into register P2.
48891 ** P3==0 is the schema version.  P3==1 is the database format.
48892 ** P3==2 is the recommended pager cache size, and so forth.  P1==0 is
48893 ** the main database file and P1==1 is the database file used to store
48894 ** temporary tables.
48895 **
48896 ** If P1 is negative, then this is a request to read the size of a
48897 ** databases free-list. P3 must be set to 1 in this case. The actual
48898 ** database accessed is ((P1+1)*-1). For example, a P1 parameter of -1
48899 ** corresponds to database 0 ("main"), a P1 of -2 is database 1 ("temp").
48900 **
48901 ** There must be a read-lock on the database (either a transaction
48902 ** must be started or there must be an open cursor) before
48903 ** executing this instruction.
48904 */
48905 case OP_ReadCookie: {               /* out2-prerelease */
48906   int iMeta;
48907   int iDb = pOp->p1;
48908   int iCookie = pOp->p3;
48909
48910   assert( pOp->p3<SQLITE_N_BTREE_META );
48911   if( iDb<0 ){
48912     iDb = (-1*(iDb+1));
48913     iCookie *= -1;
48914   }
48915   assert( iDb>=0 && iDb<db->nDb );
48916   assert( db->aDb[iDb].pBt!=0 );
48917   assert( (p->btreeMask & (1<<iDb))!=0 );
48918   /* The indexing of meta values at the schema layer is off by one from
48919   ** the indexing in the btree layer.  The btree considers meta[0] to
48920   ** be the number of free pages in the database (a read-only value)
48921   ** and meta[1] to be the schema cookie.  The schema layer considers
48922   ** meta[1] to be the schema cookie.  So we have to shift the index
48923   ** by one in the following statement.
48924   */
48925   rc = sqlite3BtreeGetMeta(db->aDb[iDb].pBt, 1 + iCookie, (u32 *)&iMeta);
48926   pOut->u.i = iMeta;
48927   MemSetTypeFlag(pOut, MEM_Int);
48928   break;
48929 }
48930
48931 /* Opcode: SetCookie P1 P2 P3 * *
48932 **
48933 ** Write the content of register P3 (interpreted as an integer)
48934 ** into cookie number P2 of database P1.
48935 ** P2==0 is the schema version.  P2==1 is the database format.
48936 ** P2==2 is the recommended pager cache size, and so forth.  P1==0 is
48937 ** the main database file and P1==1 is the database file used to store
48938 ** temporary tables.
48939 **
48940 ** A transaction must be started before executing this opcode.
48941 */
48942 case OP_SetCookie: {       /* in3 */
48943   Db *pDb;
48944   assert( pOp->p2<SQLITE_N_BTREE_META );
48945   assert( pOp->p1>=0 && pOp->p1<db->nDb );
48946   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
48947   pDb = &db->aDb[pOp->p1];
48948   assert( pDb->pBt!=0 );
48949   sqlite3VdbeMemIntegerify(pIn3);
48950   /* See note about index shifting on OP_ReadCookie */
48951   rc = sqlite3BtreeUpdateMeta(pDb->pBt, 1+pOp->p2, (int)pIn3->u.i);
48952   if( pOp->p2==0 ){
48953     /* When the schema cookie changes, record the new cookie internally */
48954     pDb->pSchema->schema_cookie = pIn3->u.i;
48955     db->flags |= SQLITE_InternChanges;
48956   }else if( pOp->p2==1 ){
48957     /* Record changes in the file format */
48958     pDb->pSchema->file_format = pIn3->u.i;
48959   }
48960   if( pOp->p1==1 ){
48961     /* Invalidate all prepared statements whenever the TEMP database
48962     ** schema is changed.  Ticket #1644 */
48963     sqlite3ExpirePreparedStatements(db);
48964   }
48965   break;
48966 }
48967
48968 /* Opcode: VerifyCookie P1 P2 *
48969 **
48970 ** Check the value of global database parameter number 0 (the
48971 ** schema version) and make sure it is equal to P2.  
48972 ** P1 is the database number which is 0 for the main database file
48973 ** and 1 for the file holding temporary tables and some higher number
48974 ** for auxiliary databases.
48975 **
48976 ** The cookie changes its value whenever the database schema changes.
48977 ** This operation is used to detect when that the cookie has changed
48978 ** and that the current process needs to reread the schema.
48979 **
48980 ** Either a transaction needs to have been started or an OP_Open needs
48981 ** to be executed (to establish a read lock) before this opcode is
48982 ** invoked.
48983 */
48984 case OP_VerifyCookie: {
48985   int iMeta;
48986   Btree *pBt;
48987   assert( pOp->p1>=0 && pOp->p1<db->nDb );
48988   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
48989   pBt = db->aDb[pOp->p1].pBt;
48990   if( pBt ){
48991     rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&iMeta);
48992   }else{
48993     rc = SQLITE_OK;
48994     iMeta = 0;
48995   }
48996   if( rc==SQLITE_OK && iMeta!=pOp->p2 ){
48997     sqlite3DbFree(db, p->zErrMsg);
48998     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
48999     /* If the schema-cookie from the database file matches the cookie 
49000     ** stored with the in-memory representation of the schema, do
49001     ** not reload the schema from the database file.
49002     **
49003     ** If virtual-tables are in use, this is not just an optimization.
49004     ** Often, v-tables store their data in other SQLite tables, which
49005     ** are queried from within xNext() and other v-table methods using
49006     ** prepared queries. If such a query is out-of-date, we do not want to
49007     ** discard the database schema, as the user code implementing the
49008     ** v-table would have to be ready for the sqlite3_vtab structure itself
49009     ** to be invalidated whenever sqlite3_step() is called from within 
49010     ** a v-table method.
49011     */
49012     if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
49013       sqlite3ResetInternalSchema(db, pOp->p1);
49014     }
49015
49016     sqlite3ExpirePreparedStatements(db);
49017     rc = SQLITE_SCHEMA;
49018   }
49019   break;
49020 }
49021
49022 /* Opcode: OpenRead P1 P2 P3 P4 P5
49023 **
49024 ** Open a read-only cursor for the database table whose root page is
49025 ** P2 in a database file.  The database file is determined by P3. 
49026 ** P3==0 means the main database, P3==1 means the database used for 
49027 ** temporary tables, and P3>1 means used the corresponding attached
49028 ** database.  Give the new cursor an identifier of P1.  The P1
49029 ** values need not be contiguous but all P1 values should be small integers.
49030 ** It is an error for P1 to be negative.
49031 **
49032 ** If P5!=0 then use the content of register P2 as the root page, not
49033 ** the value of P2 itself.
49034 **
49035 ** There will be a read lock on the database whenever there is an
49036 ** open cursor.  If the database was unlocked prior to this instruction
49037 ** then a read lock is acquired as part of this instruction.  A read
49038 ** lock allows other processes to read the database but prohibits
49039 ** any other process from modifying the database.  The read lock is
49040 ** released when all cursors are closed.  If this instruction attempts
49041 ** to get a read lock but fails, the script terminates with an
49042 ** SQLITE_BUSY error code.
49043 **
49044 ** The P4 value is a pointer to a KeyInfo structure that defines the
49045 ** content and collating sequence of indices.  P4 is NULL for cursors
49046 ** that are not pointing to indices.
49047 **
49048 ** See also OpenWrite.
49049 */
49050 /* Opcode: OpenWrite P1 P2 P3 P4 P5
49051 **
49052 ** Open a read/write cursor named P1 on the table or index whose root
49053 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
49054 ** root page.
49055 **
49056 ** The P4 value is a pointer to a KeyInfo structure that defines the
49057 ** content and collating sequence of indices.  P4 is NULL for cursors
49058 ** that are not pointing to indices.
49059 **
49060 ** This instruction works just like OpenRead except that it opens the cursor
49061 ** in read/write mode.  For a given table, there can be one or more read-only
49062 ** cursors or a single read/write cursor but not both.
49063 **
49064 ** See also OpenRead.
49065 */
49066 case OP_OpenRead:
49067 case OP_OpenWrite: {
49068   int i = pOp->p1;
49069   int p2 = pOp->p2;
49070   int iDb = pOp->p3;
49071   int wrFlag;
49072   Btree *pX;
49073   VdbeCursor *pCur;
49074   Db *pDb;
49075   
49076   assert( iDb>=0 && iDb<db->nDb );
49077   assert( (p->btreeMask & (1<<iDb))!=0 );
49078   pDb = &db->aDb[iDb];
49079   pX = pDb->pBt;
49080   assert( pX!=0 );
49081   if( pOp->opcode==OP_OpenWrite ){
49082     wrFlag = 1;
49083     if( pDb->pSchema->file_format < p->minWriteFileFormat ){
49084       p->minWriteFileFormat = pDb->pSchema->file_format;
49085     }
49086   }else{
49087     wrFlag = 0;
49088   }
49089   if( pOp->p5 ){
49090     assert( p2>0 );
49091     assert( p2<=p->nMem );
49092     pIn2 = &p->aMem[p2];
49093     sqlite3VdbeMemIntegerify(pIn2);
49094     p2 = pIn2->u.i;
49095     if( p2<2 ) {
49096       rc = SQLITE_CORRUPT_BKPT;
49097       goto abort_due_to_error;
49098     }
49099   }
49100   assert( i>=0 );
49101   pCur = allocateCursor(p, i, &pOp[-1], iDb, 1);
49102   if( pCur==0 ) goto no_mem;
49103   pCur->nullRow = 1;
49104   rc = sqlite3BtreeCursor(pX, p2, wrFlag, pOp->p4.p, pCur->pCursor);
49105   if( pOp->p4type==P4_KEYINFO ){
49106     pCur->pKeyInfo = pOp->p4.pKeyInfo;
49107     pCur->pKeyInfo->enc = ENC(p->db);
49108   }else{
49109     pCur->pKeyInfo = 0;
49110   }
49111   switch( rc ){
49112     case SQLITE_BUSY: {
49113       p->pc = pc;
49114       p->rc = rc = SQLITE_BUSY;
49115       goto vdbe_return;
49116     }
49117     case SQLITE_OK: {
49118       int flags = sqlite3BtreeFlags(pCur->pCursor);
49119       /* Sanity checking.  Only the lower four bits of the flags byte should
49120       ** be used.  Bit 3 (mask 0x08) is unpredictable.  The lower 3 bits
49121       ** (mask 0x07) should be either 5 (intkey+leafdata for tables) or
49122       ** 2 (zerodata for indices).  If these conditions are not met it can
49123       ** only mean that we are dealing with a corrupt database file
49124       */
49125       if( (flags & 0xf0)!=0 || ((flags & 0x07)!=5 && (flags & 0x07)!=2) ){
49126         rc = SQLITE_CORRUPT_BKPT;
49127         goto abort_due_to_error;
49128       }
49129       pCur->isTable = (flags & BTREE_INTKEY)!=0;
49130       pCur->isIndex = (flags & BTREE_ZERODATA)!=0;
49131       /* If P4==0 it means we are expected to open a table.  If P4!=0 then
49132       ** we expect to be opening an index.  If this is not what happened,
49133       ** then the database is corrupt
49134       */
49135       if( (pCur->isTable && pOp->p4type==P4_KEYINFO)
49136        || (pCur->isIndex && pOp->p4type!=P4_KEYINFO) ){
49137         rc = SQLITE_CORRUPT_BKPT;
49138         goto abort_due_to_error;
49139       }
49140       break;
49141     }
49142     case SQLITE_EMPTY: {
49143       pCur->isTable = pOp->p4type!=P4_KEYINFO;
49144       pCur->isIndex = !pCur->isTable;
49145       pCur->pCursor = 0;
49146       rc = SQLITE_OK;
49147       break;
49148     }
49149     default: {
49150       goto abort_due_to_error;
49151     }
49152   }
49153   break;
49154 }
49155
49156 /* Opcode: OpenEphemeral P1 P2 * P4 *
49157 **
49158 ** Open a new cursor P1 to a transient table.
49159 ** The cursor is always opened read/write even if 
49160 ** the main database is read-only.  The transient or virtual
49161 ** table is deleted automatically when the cursor is closed.
49162 **
49163 ** P2 is the number of columns in the virtual table.
49164 ** The cursor points to a BTree table if P4==0 and to a BTree index
49165 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
49166 ** that defines the format of keys in the index.
49167 **
49168 ** This opcode was once called OpenTemp.  But that created
49169 ** confusion because the term "temp table", might refer either
49170 ** to a TEMP table at the SQL level, or to a table opened by
49171 ** this opcode.  Then this opcode was call OpenVirtual.  But
49172 ** that created confusion with the whole virtual-table idea.
49173 */
49174 case OP_OpenEphemeral: {
49175   int i = pOp->p1;
49176   VdbeCursor *pCx;
49177   static const int openFlags = 
49178       SQLITE_OPEN_READWRITE |
49179       SQLITE_OPEN_CREATE |
49180       SQLITE_OPEN_EXCLUSIVE |
49181       SQLITE_OPEN_DELETEONCLOSE |
49182       SQLITE_OPEN_TRANSIENT_DB;
49183
49184   assert( i>=0 );
49185   pCx = allocateCursor(p, i, pOp, -1, 1);
49186   if( pCx==0 ) goto no_mem;
49187   pCx->nullRow = 1;
49188   rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, openFlags,
49189                            &pCx->pBt);
49190   if( rc==SQLITE_OK ){
49191     rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
49192   }
49193   if( rc==SQLITE_OK ){
49194     /* If a transient index is required, create it by calling
49195     ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
49196     ** opening it. If a transient table is required, just use the
49197     ** automatically created table with root-page 1 (an INTKEY table).
49198     */
49199     if( pOp->p4.pKeyInfo ){
49200       int pgno;
49201       assert( pOp->p4type==P4_KEYINFO );
49202       rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_ZERODATA); 
49203       if( rc==SQLITE_OK ){
49204         assert( pgno==MASTER_ROOT+1 );
49205         rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, 
49206                                 (KeyInfo*)pOp->p4.z, pCx->pCursor);
49207         pCx->pKeyInfo = pOp->p4.pKeyInfo;
49208         pCx->pKeyInfo->enc = ENC(p->db);
49209       }
49210       pCx->isTable = 0;
49211     }else{
49212       rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, pCx->pCursor);
49213       pCx->isTable = 1;
49214     }
49215   }
49216   pCx->isIndex = !pCx->isTable;
49217   break;
49218 }
49219
49220 /* Opcode: OpenPseudo P1 P2 * * *
49221 **
49222 ** Open a new cursor that points to a fake table that contains a single
49223 ** row of data.  Any attempt to write a second row of data causes the
49224 ** first row to be deleted.  All data is deleted when the cursor is
49225 ** closed.
49226 **
49227 ** A pseudo-table created by this opcode is useful for holding the
49228 ** NEW or OLD tables in a trigger.  Also used to hold the a single
49229 ** row output from the sorter so that the row can be decomposed into
49230 ** individual columns using the OP_Column opcode.
49231 **
49232 ** When OP_Insert is executed to insert a row in to the pseudo table,
49233 ** the pseudo-table cursor may or may not make it's own copy of the
49234 ** original row data. If P2 is 0, then the pseudo-table will copy the
49235 ** original row data. Otherwise, a pointer to the original memory cell
49236 ** is stored. In this case, the vdbe program must ensure that the 
49237 ** memory cell containing the row data is not overwritten until the
49238 ** pseudo table is closed (or a new row is inserted into it).
49239 */
49240 case OP_OpenPseudo: {
49241   int i = pOp->p1;
49242   VdbeCursor *pCx;
49243   assert( i>=0 );
49244   pCx = allocateCursor(p, i, &pOp[-1], -1, 0);
49245   if( pCx==0 ) goto no_mem;
49246   pCx->nullRow = 1;
49247   pCx->pseudoTable = 1;
49248   pCx->ephemPseudoTable = pOp->p2;
49249   pCx->isTable = 1;
49250   pCx->isIndex = 0;
49251   break;
49252 }
49253
49254 /* Opcode: Close P1 * * * *
49255 **
49256 ** Close a cursor previously opened as P1.  If P1 is not
49257 ** currently open, this instruction is a no-op.
49258 */
49259 case OP_Close: {
49260   int i = pOp->p1;
49261   assert( i>=0 && i<p->nCursor );
49262   sqlite3VdbeFreeCursor(p, p->apCsr[i]);
49263   p->apCsr[i] = 0;
49264   break;
49265 }
49266
49267 /* Opcode: MoveGe P1 P2 P3 P4 *
49268 **
49269 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
49270 ** use the integer value in register P3 as a key. If cursor P1 refers 
49271 ** to an SQL index, then P3 is the first in an array of P4 registers 
49272 ** that are used as an unpacked index key. 
49273 **
49274 ** Reposition cursor P1 so that  it points to the smallest entry that 
49275 ** is greater than or equal to the key value. If there are no records 
49276 ** greater than or equal to the key and P2 is not zero, then jump to P2.
49277 **
49278 ** A special feature of this opcode (and different from the
49279 ** related OP_MoveGt, OP_MoveLt, and OP_MoveLe) is that if P2 is
49280 ** zero and P1 is an SQL table (a b-tree with integer keys) then
49281 ** the seek is deferred until it is actually needed.  It might be
49282 ** the case that the cursor is never accessed.  By deferring the
49283 ** seek, we avoid unnecessary seeks.
49284 **
49285 ** See also: Found, NotFound, Distinct, MoveLt, MoveGt, MoveLe
49286 */
49287 /* Opcode: MoveGt P1 P2 P3 P4 *
49288 **
49289 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
49290 ** use the integer value in register P3 as a key. If cursor P1 refers 
49291 ** to an SQL index, then P3 is the first in an array of P4 registers 
49292 ** that are used as an unpacked index key. 
49293 **
49294 ** Reposition cursor P1 so that  it points to the smallest entry that 
49295 ** is greater than the key value. If there are no records greater than 
49296 ** the key and P2 is not zero, then jump to P2.
49297 **
49298 ** See also: Found, NotFound, Distinct, MoveLt, MoveGe, MoveLe
49299 */
49300 /* Opcode: MoveLt P1 P2 P3 P4 * 
49301 **
49302 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
49303 ** use the integer value in register P3 as a key. If cursor P1 refers 
49304 ** to an SQL index, then P3 is the first in an array of P4 registers 
49305 ** that are used as an unpacked index key. 
49306 **
49307 ** Reposition cursor P1 so that  it points to the largest entry that 
49308 ** is less than the key value. If there are no records less than 
49309 ** the key and P2 is not zero, then jump to P2.
49310 **
49311 ** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLe
49312 */
49313 /* Opcode: MoveLe P1 P2 P3 P4 *
49314 **
49315 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
49316 ** use the integer value in register P3 as a key. If cursor P1 refers 
49317 ** to an SQL index, then P3 is the first in an array of P4 registers 
49318 ** that are used as an unpacked index key. 
49319 **
49320 ** Reposition cursor P1 so that it points to the largest entry that 
49321 ** is less than or equal to the key value. If there are no records 
49322 ** less than or equal to the key and P2 is not zero, then jump to P2.
49323 **
49324 ** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLt
49325 */
49326 case OP_MoveLt:         /* jump, in3 */
49327 case OP_MoveLe:         /* jump, in3 */
49328 case OP_MoveGe:         /* jump, in3 */
49329 case OP_MoveGt: {       /* jump, in3 */
49330   int i = pOp->p1;
49331   VdbeCursor *pC;
49332
49333   assert( i>=0 && i<p->nCursor );
49334   pC = p->apCsr[i];
49335   assert( pC!=0 );
49336   if( pC->pCursor!=0 ){
49337     int res, oc;
49338     oc = pOp->opcode;
49339     pC->nullRow = 0;
49340     if( pC->isTable ){
49341       i64 iKey = sqlite3VdbeIntValue(pIn3);
49342       if( pOp->p2==0 ){
49343         assert( pOp->opcode==OP_MoveGe );
49344         pC->movetoTarget = iKey;
49345         pC->rowidIsValid = 0;
49346         pC->deferredMoveto = 1;
49347         break;
49348       }
49349       rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)iKey, 0, &res);
49350       if( rc!=SQLITE_OK ){
49351         goto abort_due_to_error;
49352       }
49353       pC->lastRowid = iKey;
49354       pC->rowidIsValid = res==0;
49355     }else{
49356       UnpackedRecord r;
49357       int nField = pOp->p4.i;
49358       assert( pOp->p4type==P4_INT32 );
49359       assert( nField>0 );
49360       r.pKeyInfo = pC->pKeyInfo;
49361       r.nField = nField;
49362       if( oc==OP_MoveGt || oc==OP_MoveLe ){
49363         r.flags = UNPACKED_INCRKEY;
49364       }else{
49365         r.flags = 0;
49366       }
49367       r.aMem = &p->aMem[pOp->p3];
49368       rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, &r, 0, 0, &res);
49369       if( rc!=SQLITE_OK ){
49370         goto abort_due_to_error;
49371       }
49372       pC->rowidIsValid = 0;
49373     }
49374     pC->deferredMoveto = 0;
49375     pC->cacheStatus = CACHE_STALE;
49376 #ifdef SQLITE_TEST
49377     sqlite3_search_count++;
49378 #endif
49379     if( oc==OP_MoveGe || oc==OP_MoveGt ){
49380       if( res<0 ){
49381         rc = sqlite3BtreeNext(pC->pCursor, &res);
49382         if( rc!=SQLITE_OK ) goto abort_due_to_error;
49383         pC->rowidIsValid = 0;
49384       }else{
49385         res = 0;
49386       }
49387     }else{
49388       assert( oc==OP_MoveLt || oc==OP_MoveLe );
49389       if( res>=0 ){
49390         rc = sqlite3BtreePrevious(pC->pCursor, &res);
49391         if( rc!=SQLITE_OK ) goto abort_due_to_error;
49392         pC->rowidIsValid = 0;
49393       }else{
49394         /* res might be negative because the table is empty.  Check to
49395         ** see if this is the case.
49396         */
49397         res = sqlite3BtreeEof(pC->pCursor);
49398       }
49399     }
49400     assert( pOp->p2>0 );
49401     if( res ){
49402       pc = pOp->p2 - 1;
49403     }
49404   }else if( !pC->pseudoTable ){
49405     /* This happens when attempting to open the sqlite3_master table
49406     ** for read access returns SQLITE_EMPTY. In this case always
49407     ** take the jump (since there are no records in the table).
49408     */
49409     pc = pOp->p2 - 1;
49410   }
49411   break;
49412 }
49413
49414 /* Opcode: Found P1 P2 P3 * *
49415 **
49416 ** Register P3 holds a blob constructed by MakeRecord.  P1 is an index.
49417 ** If an entry that matches the value in register p3 exists in P1 then
49418 ** jump to P2.  If the P3 value does not match any entry in P1
49419 ** then fall thru.  The P1 cursor is left pointing at the matching entry
49420 ** if it exists.
49421 **
49422 ** This instruction is used to implement the IN operator where the
49423 ** left-hand side is a SELECT statement.  P1 may be a true index, or it
49424 ** may be a temporary index that holds the results of the SELECT
49425 ** statement.   This instruction is also used to implement the
49426 ** DISTINCT keyword in SELECT statements.
49427 **
49428 ** This instruction checks if index P1 contains a record for which 
49429 ** the first N serialized values exactly match the N serialized values
49430 ** in the record in register P3, where N is the total number of values in
49431 ** the P3 record (the P3 record is a prefix of the P1 record). 
49432 **
49433 ** See also: NotFound, IsUnique, NotExists
49434 */
49435 /* Opcode: NotFound P1 P2 P3 * *
49436 **
49437 ** Register P3 holds a blob constructed by MakeRecord.  P1 is
49438 ** an index.  If no entry exists in P1 that matches the blob then jump
49439 ** to P2.  If an entry does existing, fall through.  The cursor is left
49440 ** pointing to the entry that matches.
49441 **
49442 ** See also: Found, NotExists, IsUnique
49443 */
49444 case OP_NotFound:       /* jump, in3 */
49445 case OP_Found: {        /* jump, in3 */
49446   int i = pOp->p1;
49447   int alreadyExists = 0;
49448   VdbeCursor *pC;
49449   assert( i>=0 && i<p->nCursor );
49450   assert( p->apCsr[i]!=0 );
49451   if( (pC = p->apCsr[i])->pCursor!=0 ){
49452     int res;
49453     UnpackedRecord *pIdxKey;
49454
49455     assert( pC->isTable==0 );
49456     assert( pIn3->flags & MEM_Blob );
49457     pIdxKey = sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z,
49458                                       aTempRec, sizeof(aTempRec));
49459     if( pIdxKey==0 ){
49460       goto no_mem;
49461     }
49462     if( pOp->opcode==OP_Found ){
49463       pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
49464     }
49465     rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, pIdxKey, 0, 0, &res);
49466     sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
49467     if( rc!=SQLITE_OK ){
49468       break;
49469     }
49470     alreadyExists = (res==0);
49471     pC->deferredMoveto = 0;
49472     pC->cacheStatus = CACHE_STALE;
49473   }
49474   if( pOp->opcode==OP_Found ){
49475     if( alreadyExists ) pc = pOp->p2 - 1;
49476   }else{
49477     if( !alreadyExists ) pc = pOp->p2 - 1;
49478   }
49479   break;
49480 }
49481
49482 /* Opcode: IsUnique P1 P2 P3 P4 *
49483 **
49484 ** The P3 register contains an integer record number.  Call this
49485 ** record number R.  The P4 register contains an index key created
49486 ** using MakeRecord.  Call it K.
49487 **
49488 ** P1 is an index.  So it has no data and its key consists of a
49489 ** record generated by OP_MakeRecord where the last field is the 
49490 ** rowid of the entry that the index refers to.
49491 ** 
49492 ** This instruction asks if there is an entry in P1 where the
49493 ** fields matches K but the rowid is different from R.
49494 ** If there is no such entry, then there is an immediate
49495 ** jump to P2.  If any entry does exist where the index string
49496 ** matches K but the record number is not R, then the record
49497 ** number for that entry is written into P3 and control
49498 ** falls through to the next instruction.
49499 **
49500 ** See also: NotFound, NotExists, Found
49501 */
49502 case OP_IsUnique: {        /* jump, in3 */
49503   int i = pOp->p1;
49504   VdbeCursor *pCx;
49505   BtCursor *pCrsr;
49506   Mem *pK;
49507   i64 R;
49508
49509   /* Pop the value R off the top of the stack
49510   */
49511   assert( pOp->p4type==P4_INT32 );
49512   assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
49513   pK = &p->aMem[pOp->p4.i];
49514   sqlite3VdbeMemIntegerify(pIn3);
49515   R = pIn3->u.i;
49516   assert( i>=0 && i<p->nCursor );
49517   pCx = p->apCsr[i];
49518   assert( pCx!=0 );
49519   pCrsr = pCx->pCursor;
49520   if( pCrsr!=0 ){
49521     int res;
49522     i64 v;                     /* The record number that matches K */
49523     UnpackedRecord *pIdxKey;   /* Unpacked version of P4 */
49524
49525     /* Make sure K is a string and make zKey point to K
49526     */
49527     assert( pK->flags & MEM_Blob );
49528     pIdxKey = sqlite3VdbeRecordUnpack(pCx->pKeyInfo, pK->n, pK->z,
49529                                       aTempRec, sizeof(aTempRec));
49530     if( pIdxKey==0 ){
49531       goto no_mem;
49532     }
49533     pIdxKey->flags |= UNPACKED_IGNORE_ROWID;
49534
49535     /* Search for an entry in P1 where all but the last rowid match K
49536     ** If there is no such entry, jump immediately to P2.
49537     */
49538     assert( pCx->deferredMoveto==0 );
49539     pCx->cacheStatus = CACHE_STALE;
49540     rc = sqlite3BtreeMovetoUnpacked(pCrsr, pIdxKey, 0, 0, &res);
49541     if( rc!=SQLITE_OK ){
49542       sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
49543       goto abort_due_to_error;
49544     }
49545     if( res<0 ){
49546       rc = sqlite3BtreeNext(pCrsr, &res);
49547       if( res ){
49548         pc = pOp->p2 - 1;
49549         sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
49550         break;
49551       }
49552     }
49553     rc = sqlite3VdbeIdxKeyCompare(pCx, pIdxKey, &res); 
49554     sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
49555     if( rc!=SQLITE_OK ) goto abort_due_to_error;
49556     if( res>0 ){
49557       pc = pOp->p2 - 1;
49558       break;
49559     }
49560
49561     /* At this point, pCrsr is pointing to an entry in P1 where all but
49562     ** the final entry (the rowid) matches K.  Check to see if the
49563     ** final rowid column is different from R.  If it equals R then jump
49564     ** immediately to P2.
49565     */
49566     rc = sqlite3VdbeIdxRowid(pCrsr, &v);
49567     if( rc!=SQLITE_OK ){
49568       goto abort_due_to_error;
49569     }
49570     if( v==R ){
49571       pc = pOp->p2 - 1;
49572       break;
49573     }
49574
49575     /* The final varint of the key is different from R.  Store it back
49576     ** into register R3.  (The record number of an entry that violates
49577     ** a UNIQUE constraint.)
49578     */
49579     pIn3->u.i = v;
49580     assert( pIn3->flags&MEM_Int );
49581   }
49582   break;
49583 }
49584
49585 /* Opcode: NotExists P1 P2 P3 * *
49586 **
49587 ** Use the content of register P3 as a integer key.  If a record 
49588 ** with that key does not exist in table of P1, then jump to P2. 
49589 ** If the record does exist, then fall thru.  The cursor is left 
49590 ** pointing to the record if it exists.
49591 **
49592 ** The difference between this operation and NotFound is that this
49593 ** operation assumes the key is an integer and that P1 is a table whereas
49594 ** NotFound assumes key is a blob constructed from MakeRecord and
49595 ** P1 is an index.
49596 **
49597 ** See also: Found, NotFound, IsUnique
49598 */
49599 case OP_NotExists: {        /* jump, in3 */
49600   int i = pOp->p1;
49601   VdbeCursor *pC;
49602   BtCursor *pCrsr;
49603   assert( i>=0 && i<p->nCursor );
49604   assert( p->apCsr[i]!=0 );
49605   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
49606     int res;
49607     u64 iKey;
49608     assert( pIn3->flags & MEM_Int );
49609     assert( p->apCsr[i]->isTable );
49610     iKey = intToKey(pIn3->u.i);
49611     rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0,&res);
49612     pC->lastRowid = pIn3->u.i;
49613     pC->rowidIsValid = res==0;
49614     pC->nullRow = 0;
49615     pC->cacheStatus = CACHE_STALE;
49616     /* res might be uninitialized if rc!=SQLITE_OK.  But if rc!=SQLITE_OK
49617     ** processing is about to abort so we really do not care whether or not
49618     ** the following jump is taken.  (In other words, do not stress over
49619     ** the error that valgrind sometimes shows on the next statement when
49620     ** running ioerr.test and similar failure-recovery test scripts.) */
49621     if( res!=0 ){
49622       pc = pOp->p2 - 1;
49623       assert( pC->rowidIsValid==0 );
49624     }
49625   }else if( !pC->pseudoTable ){
49626     /* This happens when an attempt to open a read cursor on the 
49627     ** sqlite_master table returns SQLITE_EMPTY.
49628     */
49629     assert( pC->isTable );
49630     pc = pOp->p2 - 1;
49631     assert( pC->rowidIsValid==0 );
49632   }
49633   break;
49634 }
49635
49636 /* Opcode: Sequence P1 P2 * * *
49637 **
49638 ** Find the next available sequence number for cursor P1.
49639 ** Write the sequence number into register P2.
49640 ** The sequence number on the cursor is incremented after this
49641 ** instruction.  
49642 */
49643 case OP_Sequence: {           /* out2-prerelease */
49644   int i = pOp->p1;
49645   assert( i>=0 && i<p->nCursor );
49646   assert( p->apCsr[i]!=0 );
49647   pOut->u.i = p->apCsr[i]->seqCount++;
49648   MemSetTypeFlag(pOut, MEM_Int);
49649   break;
49650 }
49651
49652
49653 /* Opcode: NewRowid P1 P2 P3 * *
49654 **
49655 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
49656 ** The record number is not previously used as a key in the database
49657 ** table that cursor P1 points to.  The new record number is written
49658 ** written to register P2.
49659 **
49660 ** If P3>0 then P3 is a register that holds the largest previously
49661 ** generated record number.  No new record numbers are allowed to be less
49662 ** than this value.  When this value reaches its maximum, a SQLITE_FULL
49663 ** error is generated.  The P3 register is updated with the generated
49664 ** record number.  This P3 mechanism is used to help implement the
49665 ** AUTOINCREMENT feature.
49666 */
49667 case OP_NewRowid: {           /* out2-prerelease */
49668   int i = pOp->p1;
49669   i64 v = 0;
49670   VdbeCursor *pC;
49671   assert( i>=0 && i<p->nCursor );
49672   assert( p->apCsr[i]!=0 );
49673   if( (pC = p->apCsr[i])->pCursor==0 ){
49674     /* The zero initialization above is all that is needed */
49675   }else{
49676     /* The next rowid or record number (different terms for the same
49677     ** thing) is obtained in a two-step algorithm.
49678     **
49679     ** First we attempt to find the largest existing rowid and add one
49680     ** to that.  But if the largest existing rowid is already the maximum
49681     ** positive integer, we have to fall through to the second
49682     ** probabilistic algorithm
49683     **
49684     ** The second algorithm is to select a rowid at random and see if
49685     ** it already exists in the table.  If it does not exist, we have
49686     ** succeeded.  If the random rowid does exist, we select a new one
49687     ** and try again, up to 1000 times.
49688     **
49689     ** For a table with less than 2 billion entries, the probability
49690     ** of not finding a unused rowid is about 1.0e-300.  This is a 
49691     ** non-zero probability, but it is still vanishingly small and should
49692     ** never cause a problem.  You are much, much more likely to have a
49693     ** hardware failure than for this algorithm to fail.
49694     **
49695     ** The analysis in the previous paragraph assumes that you have a good
49696     ** source of random numbers.  Is a library function like lrand48()
49697     ** good enough?  Maybe. Maybe not. It's hard to know whether there
49698     ** might be subtle bugs is some implementations of lrand48() that
49699     ** could cause problems. To avoid uncertainty, SQLite uses its own 
49700     ** random number generator based on the RC4 algorithm.
49701     **
49702     ** To promote locality of reference for repetitive inserts, the
49703     ** first few attempts at choosing a random rowid pick values just a little
49704     ** larger than the previous rowid.  This has been shown experimentally
49705     ** to double the speed of the COPY operation.
49706     */
49707     int res, rx=SQLITE_OK, cnt;
49708     i64 x;
49709     cnt = 0;
49710     if( (sqlite3BtreeFlags(pC->pCursor)&(BTREE_INTKEY|BTREE_ZERODATA)) !=
49711           BTREE_INTKEY ){
49712       rc = SQLITE_CORRUPT_BKPT;
49713       goto abort_due_to_error;
49714     }
49715     assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_INTKEY)!=0 );
49716     assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_ZERODATA)==0 );
49717
49718 #ifdef SQLITE_32BIT_ROWID
49719 #   define MAX_ROWID 0x7fffffff
49720 #else
49721     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
49722     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
49723     ** to provide the constant while making all compilers happy.
49724     */
49725 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
49726 #endif
49727
49728     if( !pC->useRandomRowid ){
49729       if( pC->nextRowidValid ){
49730         v = pC->nextRowid;
49731       }else{
49732         rc = sqlite3BtreeLast(pC->pCursor, &res);
49733         if( rc!=SQLITE_OK ){
49734           goto abort_due_to_error;
49735         }
49736         if( res ){
49737           v = 1;
49738         }else{
49739           sqlite3BtreeKeySize(pC->pCursor, &v);
49740           v = keyToInt(v);
49741           if( v==MAX_ROWID ){
49742             pC->useRandomRowid = 1;
49743           }else{
49744             v++;
49745           }
49746         }
49747       }
49748
49749 #ifndef SQLITE_OMIT_AUTOINCREMENT
49750       if( pOp->p3 ){
49751         Mem *pMem;
49752         assert( pOp->p3>0 && pOp->p3<=p->nMem ); /* P3 is a valid memory cell */
49753         pMem = &p->aMem[pOp->p3];
49754         REGISTER_TRACE(pOp->p3, pMem);
49755         sqlite3VdbeMemIntegerify(pMem);
49756         assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
49757         if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
49758           rc = SQLITE_FULL;
49759           goto abort_due_to_error;
49760         }
49761         if( v<pMem->u.i+1 ){
49762           v = pMem->u.i + 1;
49763         }
49764         pMem->u.i = v;
49765       }
49766 #endif
49767
49768       if( v<MAX_ROWID ){
49769         pC->nextRowidValid = 1;
49770         pC->nextRowid = v+1;
49771       }else{
49772         pC->nextRowidValid = 0;
49773       }
49774     }
49775     if( pC->useRandomRowid ){
49776       assert( pOp->p3==0 );  /* SQLITE_FULL must have occurred prior to this */
49777       v = db->priorNewRowid;
49778       cnt = 0;
49779       do{
49780         if( cnt==0 && (v&0xffffff)==v ){
49781           v++;
49782         }else{
49783           sqlite3_randomness(sizeof(v), &v);
49784           if( cnt<5 ) v &= 0xffffff;
49785         }
49786         if( v==0 ) continue;
49787         x = intToKey(v);
49788         rx = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)x, 0, &res);
49789         cnt++;
49790       }while( cnt<100 && rx==SQLITE_OK && res==0 );
49791       db->priorNewRowid = v;
49792       if( rx==SQLITE_OK && res==0 ){
49793         rc = SQLITE_FULL;
49794         goto abort_due_to_error;
49795       }
49796     }
49797     pC->rowidIsValid = 0;
49798     pC->deferredMoveto = 0;
49799     pC->cacheStatus = CACHE_STALE;
49800   }
49801   MemSetTypeFlag(pOut, MEM_Int);
49802   pOut->u.i = v;
49803   break;
49804 }
49805
49806 /* Opcode: Insert P1 P2 P3 P4 P5
49807 **
49808 ** Write an entry into the table of cursor P1.  A new entry is
49809 ** created if it doesn't already exist or the data for an existing
49810 ** entry is overwritten.  The data is the value stored register
49811 ** number P2. The key is stored in register P3. The key must
49812 ** be an integer.
49813 **
49814 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
49815 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
49816 ** then rowid is stored for subsequent return by the
49817 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
49818 **
49819 ** Parameter P4 may point to a string containing the table-name, or
49820 ** may be NULL. If it is not NULL, then the update-hook 
49821 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
49822 **
49823 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
49824 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
49825 ** and register P2 becomes ephemeral.  If the cursor is changed, the
49826 ** value of register P2 will then change.  Make sure this does not
49827 ** cause any problems.)
49828 **
49829 ** This instruction only works on tables.  The equivalent instruction
49830 ** for indices is OP_IdxInsert.
49831 */
49832 case OP_Insert: {
49833   Mem *pData = &p->aMem[pOp->p2];
49834   Mem *pKey = &p->aMem[pOp->p3];
49835
49836   i64 iKey;   /* The integer ROWID or key for the record to be inserted */
49837   int i = pOp->p1;
49838   VdbeCursor *pC;
49839   assert( i>=0 && i<p->nCursor );
49840   pC = p->apCsr[i];
49841   assert( pC!=0 );
49842   assert( pC->pCursor!=0 || pC->pseudoTable );
49843   assert( pKey->flags & MEM_Int );
49844   assert( pC->isTable );
49845   REGISTER_TRACE(pOp->p2, pData);
49846   REGISTER_TRACE(pOp->p3, pKey);
49847
49848   iKey = intToKey(pKey->u.i);
49849   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
49850   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = pKey->u.i;
49851   if( pC->nextRowidValid && pKey->u.i>=pC->nextRowid ){
49852     pC->nextRowidValid = 0;
49853   }
49854   if( pData->flags & MEM_Null ){
49855     pData->z = 0;
49856     pData->n = 0;
49857   }else{
49858     assert( pData->flags & (MEM_Blob|MEM_Str) );
49859   }
49860   if( pC->pseudoTable ){
49861     if( !pC->ephemPseudoTable ){
49862       sqlite3DbFree(db, pC->pData);
49863     }
49864     pC->iKey = iKey;
49865     pC->nData = pData->n;
49866     if( pData->z==pData->zMalloc || pC->ephemPseudoTable ){
49867       pC->pData = pData->z;
49868       if( !pC->ephemPseudoTable ){
49869         pData->flags &= ~MEM_Dyn;
49870         pData->flags |= MEM_Ephem;
49871         pData->zMalloc = 0;
49872       }
49873     }else{
49874       pC->pData = sqlite3Malloc( pC->nData+2 );
49875       if( !pC->pData ) goto no_mem;
49876       memcpy(pC->pData, pData->z, pC->nData);
49877       pC->pData[pC->nData] = 0;
49878       pC->pData[pC->nData+1] = 0;
49879     }
49880     pC->nullRow = 0;
49881   }else{
49882     int nZero;
49883     if( pData->flags & MEM_Zero ){
49884       nZero = pData->u.i;
49885     }else{
49886       nZero = 0;
49887     }
49888     rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
49889                             pData->z, pData->n, nZero,
49890                             pOp->p5 & OPFLAG_APPEND);
49891   }
49892   
49893   pC->rowidIsValid = 0;
49894   pC->deferredMoveto = 0;
49895   pC->cacheStatus = CACHE_STALE;
49896
49897   /* Invoke the update-hook if required. */
49898   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
49899     const char *zDb = db->aDb[pC->iDb].zName;
49900     const char *zTbl = pOp->p4.z;
49901     int op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
49902     assert( pC->isTable );
49903     db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
49904     assert( pC->iDb>=0 );
49905   }
49906   break;
49907 }
49908
49909 /* Opcode: Delete P1 P2 * P4 *
49910 **
49911 ** Delete the record at which the P1 cursor is currently pointing.
49912 **
49913 ** The cursor will be left pointing at either the next or the previous
49914 ** record in the table. If it is left pointing at the next record, then
49915 ** the next Next instruction will be a no-op.  Hence it is OK to delete
49916 ** a record from within an Next loop.
49917 **
49918 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
49919 ** incremented (otherwise not).
49920 **
49921 ** P1 must not be pseudo-table.  It has to be a real table with
49922 ** multiple rows.
49923 **
49924 ** If P4 is not NULL, then it is the name of the table that P1 is
49925 ** pointing to.  The update hook will be invoked, if it exists.
49926 ** If P4 is not NULL then the P1 cursor must have been positioned
49927 ** using OP_NotFound prior to invoking this opcode.
49928 */
49929 case OP_Delete: {
49930   int i = pOp->p1;
49931   i64 iKey;
49932   VdbeCursor *pC;
49933
49934   assert( i>=0 && i<p->nCursor );
49935   pC = p->apCsr[i];
49936   assert( pC!=0 );
49937   assert( pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
49938
49939   /* If the update-hook will be invoked, set iKey to the rowid of the
49940   ** row being deleted.
49941   */
49942   if( db->xUpdateCallback && pOp->p4.z ){
49943     assert( pC->isTable );
49944     assert( pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
49945     iKey = pC->lastRowid;
49946   }
49947
49948   rc = sqlite3VdbeCursorMoveto(pC);
49949   if( rc ) goto abort_due_to_error;
49950   rc = sqlite3BtreeDelete(pC->pCursor);
49951   pC->nextRowidValid = 0;
49952   pC->cacheStatus = CACHE_STALE;
49953
49954   /* Invoke the update-hook if required. */
49955   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
49956     const char *zDb = db->aDb[pC->iDb].zName;
49957     const char *zTbl = pOp->p4.z;
49958     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey);
49959     assert( pC->iDb>=0 );
49960   }
49961   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
49962   break;
49963 }
49964
49965 /* Opcode: ResetCount P1 * *
49966 **
49967 ** This opcode resets the VMs internal change counter to 0. If P1 is true,
49968 ** then the value of the change counter is copied to the database handle
49969 ** change counter (returned by subsequent calls to sqlite3_changes())
49970 ** before it is reset. This is used by trigger programs.
49971 */
49972 case OP_ResetCount: {
49973   if( pOp->p1 ){
49974     sqlite3VdbeSetChanges(db, p->nChange);
49975   }
49976   p->nChange = 0;
49977   break;
49978 }
49979
49980 /* Opcode: RowData P1 P2 * * *
49981 **
49982 ** Write into register P2 the complete row data for cursor P1.
49983 ** There is no interpretation of the data.  
49984 ** It is just copied onto the P2 register exactly as 
49985 ** it is found in the database file.
49986 **
49987 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
49988 ** of a real table, not a pseudo-table.
49989 */
49990 /* Opcode: RowKey P1 P2 * * *
49991 **
49992 ** Write into register P2 the complete row key for cursor P1.
49993 ** There is no interpretation of the data.  
49994 ** The key is copied onto the P3 register exactly as 
49995 ** it is found in the database file.
49996 **
49997 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
49998 ** of a real table, not a pseudo-table.
49999 */
50000 case OP_RowKey:
50001 case OP_RowData: {
50002   int i = pOp->p1;
50003   VdbeCursor *pC;
50004   BtCursor *pCrsr;
50005   u32 n;
50006
50007   pOut = &p->aMem[pOp->p2];
50008
50009   /* Note that RowKey and RowData are really exactly the same instruction */
50010   assert( i>=0 && i<p->nCursor );
50011   pC = p->apCsr[i];
50012   assert( pC->isTable || pOp->opcode==OP_RowKey );
50013   assert( pC->isIndex || pOp->opcode==OP_RowData );
50014   assert( pC!=0 );
50015   assert( pC->nullRow==0 );
50016   assert( pC->pseudoTable==0 );
50017   assert( pC->pCursor!=0 );
50018   pCrsr = pC->pCursor;
50019   rc = sqlite3VdbeCursorMoveto(pC);
50020   if( rc ) goto abort_due_to_error;
50021   if( pC->isIndex ){
50022     i64 n64;
50023     assert( !pC->isTable );
50024     sqlite3BtreeKeySize(pCrsr, &n64);
50025     if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
50026       goto too_big;
50027     }
50028     n = n64;
50029   }else{
50030     sqlite3BtreeDataSize(pCrsr, &n);
50031     if( (int)n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
50032       goto too_big;
50033     }
50034   }
50035   if( sqlite3VdbeMemGrow(pOut, n, 0) ){
50036     goto no_mem;
50037   }
50038   pOut->n = n;
50039   MemSetTypeFlag(pOut, MEM_Blob);
50040   if( pC->isIndex ){
50041     rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
50042   }else{
50043     rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
50044   }
50045   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
50046   UPDATE_MAX_BLOBSIZE(pOut);
50047   break;
50048 }
50049
50050 /* Opcode: Rowid P1 P2 * * *
50051 **
50052 ** Store in register P2 an integer which is the key of the table entry that
50053 ** P1 is currently point to.
50054 */
50055 case OP_Rowid: {                 /* out2-prerelease */
50056   int i = pOp->p1;
50057   VdbeCursor *pC;
50058   i64 v;
50059
50060   assert( i>=0 && i<p->nCursor );
50061   pC = p->apCsr[i];
50062   assert( pC!=0 );
50063   rc = sqlite3VdbeCursorMoveto(pC);
50064   if( rc ) goto abort_due_to_error;
50065   if( pC->rowidIsValid ){
50066     v = pC->lastRowid;
50067   }else if( pC->pseudoTable ){
50068     v = keyToInt(pC->iKey);
50069   }else if( pC->nullRow ){
50070     /* Leave the rowid set to a NULL */
50071     break;
50072   }else{
50073     assert( pC->pCursor!=0 );
50074     sqlite3BtreeKeySize(pC->pCursor, &v);
50075     v = keyToInt(v);
50076   }
50077   pOut->u.i = v;
50078   MemSetTypeFlag(pOut, MEM_Int);
50079   break;
50080 }
50081
50082 /* Opcode: NullRow P1 * * * *
50083 **
50084 ** Move the cursor P1 to a null row.  Any OP_Column operations
50085 ** that occur while the cursor is on the null row will always
50086 ** write a NULL.
50087 */
50088 case OP_NullRow: {
50089   int i = pOp->p1;
50090   VdbeCursor *pC;
50091
50092   assert( i>=0 && i<p->nCursor );
50093   pC = p->apCsr[i];
50094   assert( pC!=0 );
50095   pC->nullRow = 1;
50096   pC->rowidIsValid = 0;
50097   if( pC->pCursor ){
50098     sqlite3BtreeClearCursor(pC->pCursor);
50099   }
50100   break;
50101 }
50102
50103 /* Opcode: Last P1 P2 * * *
50104 **
50105 ** The next use of the Rowid or Column or Next instruction for P1 
50106 ** will refer to the last entry in the database table or index.
50107 ** If the table or index is empty and P2>0, then jump immediately to P2.
50108 ** If P2 is 0 or if the table or index is not empty, fall through
50109 ** to the following instruction.
50110 */
50111 case OP_Last: {        /* jump */
50112   int i = pOp->p1;
50113   VdbeCursor *pC;
50114   BtCursor *pCrsr;
50115   int res;
50116
50117   assert( i>=0 && i<p->nCursor );
50118   pC = p->apCsr[i];
50119   assert( pC!=0 );
50120   pCrsr = pC->pCursor;
50121   assert( pCrsr!=0 );
50122   rc = sqlite3BtreeLast(pCrsr, &res);
50123   pC->nullRow = res;
50124   pC->deferredMoveto = 0;
50125   pC->cacheStatus = CACHE_STALE;
50126   if( res && pOp->p2>0 ){
50127     pc = pOp->p2 - 1;
50128   }
50129   break;
50130 }
50131
50132
50133 /* Opcode: Sort P1 P2 * * *
50134 **
50135 ** This opcode does exactly the same thing as OP_Rewind except that
50136 ** it increments an undocumented global variable used for testing.
50137 **
50138 ** Sorting is accomplished by writing records into a sorting index,
50139 ** then rewinding that index and playing it back from beginning to
50140 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
50141 ** rewinding so that the global variable will be incremented and
50142 ** regression tests can determine whether or not the optimizer is
50143 ** correctly optimizing out sorts.
50144 */
50145 case OP_Sort: {        /* jump */
50146 #ifdef SQLITE_TEST
50147   sqlite3_sort_count++;
50148   sqlite3_search_count--;
50149 #endif
50150   p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
50151   /* Fall through into OP_Rewind */
50152 }
50153 /* Opcode: Rewind P1 P2 * * *
50154 **
50155 ** The next use of the Rowid or Column or Next instruction for P1 
50156 ** will refer to the first entry in the database table or index.
50157 ** If the table or index is empty and P2>0, then jump immediately to P2.
50158 ** If P2 is 0 or if the table or index is not empty, fall through
50159 ** to the following instruction.
50160 */
50161 case OP_Rewind: {        /* jump */
50162   int i = pOp->p1;
50163   VdbeCursor *pC;
50164   BtCursor *pCrsr;
50165   int res;
50166
50167   assert( i>=0 && i<p->nCursor );
50168   pC = p->apCsr[i];
50169   assert( pC!=0 );
50170   if( (pCrsr = pC->pCursor)!=0 ){
50171     rc = sqlite3BtreeFirst(pCrsr, &res);
50172     pC->atFirst = res==0;
50173     pC->deferredMoveto = 0;
50174     pC->cacheStatus = CACHE_STALE;
50175   }else{
50176     res = 1;
50177   }
50178   pC->nullRow = res;
50179   assert( pOp->p2>0 && pOp->p2<p->nOp );
50180   if( res ){
50181     pc = pOp->p2 - 1;
50182   }
50183   break;
50184 }
50185
50186 /* Opcode: Next P1 P2 * * *
50187 **
50188 ** Advance cursor P1 so that it points to the next key/data pair in its
50189 ** table or index.  If there are no more key/value pairs then fall through
50190 ** to the following instruction.  But if the cursor advance was successful,
50191 ** jump immediately to P2.
50192 **
50193 ** The P1 cursor must be for a real table, not a pseudo-table.
50194 **
50195 ** See also: Prev
50196 */
50197 /* Opcode: Prev P1 P2 * * *
50198 **
50199 ** Back up cursor P1 so that it points to the previous key/data pair in its
50200 ** table or index.  If there is no previous key/value pairs then fall through
50201 ** to the following instruction.  But if the cursor backup was successful,
50202 ** jump immediately to P2.
50203 **
50204 ** The P1 cursor must be for a real table, not a pseudo-table.
50205 */
50206 case OP_Prev:          /* jump */
50207 case OP_Next: {        /* jump */
50208   VdbeCursor *pC;
50209   BtCursor *pCrsr;
50210   int res;
50211
50212   CHECK_FOR_INTERRUPT;
50213   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
50214   pC = p->apCsr[pOp->p1];
50215   if( pC==0 ){
50216     break;  /* See ticket #2273 */
50217   }
50218   pCrsr = pC->pCursor;
50219   assert( pCrsr );
50220   res = 1;
50221   assert( pC->deferredMoveto==0 );
50222   rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(pCrsr, &res) :
50223                               sqlite3BtreePrevious(pCrsr, &res);
50224   pC->nullRow = res;
50225   pC->cacheStatus = CACHE_STALE;
50226   if( res==0 ){
50227     pc = pOp->p2 - 1;
50228     if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
50229 #ifdef SQLITE_TEST
50230     sqlite3_search_count++;
50231 #endif
50232   }
50233   pC->rowidIsValid = 0;
50234   break;
50235 }
50236
50237 /* Opcode: IdxInsert P1 P2 P3 * *
50238 **
50239 ** Register P2 holds a SQL index key made using the
50240 ** MakeIdxRec instructions.  This opcode writes that key
50241 ** into the index P1.  Data for the entry is nil.
50242 **
50243 ** P3 is a flag that provides a hint to the b-tree layer that this
50244 ** insert is likely to be an append.
50245 **
50246 ** This instruction only works for indices.  The equivalent instruction
50247 ** for tables is OP_Insert.
50248 */
50249 case OP_IdxInsert: {        /* in2 */
50250   int i = pOp->p1;
50251   VdbeCursor *pC;
50252   BtCursor *pCrsr;
50253   assert( i>=0 && i<p->nCursor );
50254   assert( p->apCsr[i]!=0 );
50255   assert( pIn2->flags & MEM_Blob );
50256   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
50257     assert( pC->isTable==0 );
50258     rc = ExpandBlob(pIn2);
50259     if( rc==SQLITE_OK ){
50260       int nKey = pIn2->n;
50261       const char *zKey = pIn2->z;
50262       rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3);
50263       assert( pC->deferredMoveto==0 );
50264       pC->cacheStatus = CACHE_STALE;
50265     }
50266   }
50267   break;
50268 }
50269
50270 /* Opcode: IdxDelete P1 P2 P3 * *
50271 **
50272 ** The content of P3 registers starting at register P2 form
50273 ** an unpacked index key. This opcode removes that entry from the 
50274 ** index opened by cursor P1.
50275 */
50276 case OP_IdxDelete: {
50277   int i = pOp->p1;
50278   VdbeCursor *pC;
50279   BtCursor *pCrsr;
50280   assert( pOp->p3>0 );
50281   assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem );
50282   assert( i>=0 && i<p->nCursor );
50283   assert( p->apCsr[i]!=0 );
50284   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
50285     int res;
50286     UnpackedRecord r;
50287     r.pKeyInfo = pC->pKeyInfo;
50288     r.nField = pOp->p3;
50289     r.flags = 0;
50290     r.aMem = &p->aMem[pOp->p2];
50291     rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
50292     if( rc==SQLITE_OK && res==0 ){
50293       rc = sqlite3BtreeDelete(pCrsr);
50294     }
50295     assert( pC->deferredMoveto==0 );
50296     pC->cacheStatus = CACHE_STALE;
50297   }
50298   break;
50299 }
50300
50301 /* Opcode: IdxRowid P1 P2 * * *
50302 **
50303 ** Write into register P2 an integer which is the last entry in the record at
50304 ** the end of the index key pointed to by cursor P1.  This integer should be
50305 ** the rowid of the table entry to which this index entry points.
50306 **
50307 ** See also: Rowid, MakeIdxRec.
50308 */
50309 case OP_IdxRowid: {              /* out2-prerelease */
50310   int i = pOp->p1;
50311   BtCursor *pCrsr;
50312   VdbeCursor *pC;
50313
50314   assert( i>=0 && i<p->nCursor );
50315   assert( p->apCsr[i]!=0 );
50316   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
50317     i64 rowid;
50318
50319     assert( pC->deferredMoveto==0 );
50320     assert( pC->isTable==0 );
50321     if( !pC->nullRow ){
50322       rc = sqlite3VdbeIdxRowid(pCrsr, &rowid);
50323       if( rc!=SQLITE_OK ){
50324         goto abort_due_to_error;
50325       }
50326       MemSetTypeFlag(pOut, MEM_Int);
50327       pOut->u.i = rowid;
50328     }
50329   }
50330   break;
50331 }
50332
50333 /* Opcode: IdxGE P1 P2 P3 P4 P5
50334 **
50335 ** The P4 register values beginning with P3 form an unpacked index 
50336 ** key that omits the ROWID.  Compare this key value against the index 
50337 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
50338 **
50339 ** If the P1 index entry is greater than or equal to the key value
50340 ** then jump to P2.  Otherwise fall through to the next instruction.
50341 **
50342 ** If P5 is non-zero then the key value is increased by an epsilon 
50343 ** prior to the comparison.  This make the opcode work like IdxGT except
50344 ** that if the key from register P3 is a prefix of the key in the cursor,
50345 ** the result is false whereas it would be true with IdxGT.
50346 */
50347 /* Opcode: IdxLT P1 P2 P3 * P5
50348 **
50349 ** The P4 register values beginning with P3 form an unpacked index 
50350 ** key that omits the ROWID.  Compare this key value against the index 
50351 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
50352 **
50353 ** If the P1 index entry is less than the key value then jump to P2.
50354 ** Otherwise fall through to the next instruction.
50355 **
50356 ** If P5 is non-zero then the key value is increased by an epsilon prior 
50357 ** to the comparison.  This makes the opcode work like IdxLE.
50358 */
50359 case OP_IdxLT:          /* jump, in3 */
50360 case OP_IdxGE: {        /* jump, in3 */
50361   int i= pOp->p1;
50362   VdbeCursor *pC;
50363
50364   assert( i>=0 && i<p->nCursor );
50365   assert( p->apCsr[i]!=0 );
50366   if( (pC = p->apCsr[i])->pCursor!=0 ){
50367     int res;
50368     UnpackedRecord r;
50369     assert( pC->deferredMoveto==0 );
50370     assert( pOp->p5==0 || pOp->p5==1 );
50371     assert( pOp->p4type==P4_INT32 );
50372     r.pKeyInfo = pC->pKeyInfo;
50373     r.nField = pOp->p4.i;
50374     if( pOp->p5 ){
50375       r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
50376     }else{
50377       r.flags = UNPACKED_IGNORE_ROWID;
50378     }
50379     r.aMem = &p->aMem[pOp->p3];
50380     rc = sqlite3VdbeIdxKeyCompare(pC, &r, &res);
50381     if( pOp->opcode==OP_IdxLT ){
50382       res = -res;
50383     }else{
50384       assert( pOp->opcode==OP_IdxGE );
50385       res++;
50386     }
50387     if( res>0 ){
50388       pc = pOp->p2 - 1 ;
50389     }
50390   }
50391   break;
50392 }
50393
50394 /* Opcode: Destroy P1 P2 P3 * *
50395 **
50396 ** Delete an entire database table or index whose root page in the database
50397 ** file is given by P1.
50398 **
50399 ** The table being destroyed is in the main database file if P3==0.  If
50400 ** P3==1 then the table to be clear is in the auxiliary database file
50401 ** that is used to store tables create using CREATE TEMPORARY TABLE.
50402 **
50403 ** If AUTOVACUUM is enabled then it is possible that another root page
50404 ** might be moved into the newly deleted root page in order to keep all
50405 ** root pages contiguous at the beginning of the database.  The former
50406 ** value of the root page that moved - its value before the move occurred -
50407 ** is stored in register P2.  If no page 
50408 ** movement was required (because the table being dropped was already 
50409 ** the last one in the database) then a zero is stored in register P2.
50410 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
50411 **
50412 ** See also: Clear
50413 */
50414 case OP_Destroy: {     /* out2-prerelease */
50415   int iMoved;
50416   int iCnt;
50417 #ifndef SQLITE_OMIT_VIRTUALTABLE
50418   Vdbe *pVdbe;
50419   iCnt = 0;
50420   for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
50421     if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->inVtabMethod<2 && pVdbe->pc>=0 ){
50422       iCnt++;
50423     }
50424   }
50425 #else
50426   iCnt = db->activeVdbeCnt;
50427 #endif
50428   if( iCnt>1 ){
50429     rc = SQLITE_LOCKED;
50430     p->errorAction = OE_Abort;
50431   }else{
50432     int iDb = pOp->p3;
50433     assert( iCnt==1 );
50434     assert( (p->btreeMask & (1<<iDb))!=0 );
50435     rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
50436     MemSetTypeFlag(pOut, MEM_Int);
50437     pOut->u.i = iMoved;
50438 #ifndef SQLITE_OMIT_AUTOVACUUM
50439     if( rc==SQLITE_OK && iMoved!=0 ){
50440       sqlite3RootPageMoved(&db->aDb[iDb], iMoved, pOp->p1);
50441     }
50442 #endif
50443   }
50444   break;
50445 }
50446
50447 /* Opcode: Clear P1 P2 P3
50448 **
50449 ** Delete all contents of the database table or index whose root page
50450 ** in the database file is given by P1.  But, unlike Destroy, do not
50451 ** remove the table or index from the database file.
50452 **
50453 ** The table being clear is in the main database file if P2==0.  If
50454 ** P2==1 then the table to be clear is in the auxiliary database file
50455 ** that is used to store tables create using CREATE TEMPORARY TABLE.
50456 **
50457 ** If the P3 value is non-zero, then the table refered to must be an
50458 ** intkey table (an SQL table, not an index). In this case the row change 
50459 ** count is incremented by the number of rows in the table being cleared. 
50460 ** If P3 is greater than zero, then the value stored in register P3 is
50461 ** also incremented by the number of rows in the table being cleared.
50462 **
50463 ** See also: Destroy
50464 */
50465 case OP_Clear: {
50466   int nChange = 0;
50467   assert( (p->btreeMask & (1<<pOp->p2))!=0 );
50468   rc = sqlite3BtreeClearTable(
50469       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
50470   );
50471   if( pOp->p3 ){
50472     p->nChange += nChange;
50473     if( pOp->p3>0 ){
50474       p->aMem[pOp->p3].u.i += nChange;
50475     }
50476   }
50477   break;
50478 }
50479
50480 /* Opcode: CreateTable P1 P2 * * *
50481 **
50482 ** Allocate a new table in the main database file if P1==0 or in the
50483 ** auxiliary database file if P1==1 or in an attached database if
50484 ** P1>1.  Write the root page number of the new table into
50485 ** register P2
50486 **
50487 ** The difference between a table and an index is this:  A table must
50488 ** have a 4-byte integer key and can have arbitrary data.  An index
50489 ** has an arbitrary key but no data.
50490 **
50491 ** See also: CreateIndex
50492 */
50493 /* Opcode: CreateIndex P1 P2 * * *
50494 **
50495 ** Allocate a new index in the main database file if P1==0 or in the
50496 ** auxiliary database file if P1==1 or in an attached database if
50497 ** P1>1.  Write the root page number of the new table into
50498 ** register P2.
50499 **
50500 ** See documentation on OP_CreateTable for additional information.
50501 */
50502 case OP_CreateIndex:            /* out2-prerelease */
50503 case OP_CreateTable: {          /* out2-prerelease */
50504   int pgno;
50505   int flags;
50506   Db *pDb;
50507   assert( pOp->p1>=0 && pOp->p1<db->nDb );
50508   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
50509   pDb = &db->aDb[pOp->p1];
50510   assert( pDb->pBt!=0 );
50511   if( pOp->opcode==OP_CreateTable ){
50512     /* flags = BTREE_INTKEY; */
50513     flags = BTREE_LEAFDATA|BTREE_INTKEY;
50514   }else{
50515     flags = BTREE_ZERODATA;
50516   }
50517   rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
50518   if( rc==SQLITE_OK ){
50519     pOut->u.i = pgno;
50520     MemSetTypeFlag(pOut, MEM_Int);
50521   }
50522   break;
50523 }
50524
50525 /* Opcode: ParseSchema P1 P2 * P4 *
50526 **
50527 ** Read and parse all entries from the SQLITE_MASTER table of database P1
50528 ** that match the WHERE clause P4.  P2 is the "force" flag.   Always do
50529 ** the parsing if P2 is true.  If P2 is false, then this routine is a
50530 ** no-op if the schema is not currently loaded.  In other words, if P2
50531 ** is false, the SQLITE_MASTER table is only parsed if the rest of the
50532 ** schema is already loaded into the symbol table.
50533 **
50534 ** This opcode invokes the parser to create a new virtual machine,
50535 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
50536 */
50537 case OP_ParseSchema: {
50538   char *zSql;
50539   int iDb = pOp->p1;
50540   const char *zMaster;
50541   InitData initData;
50542
50543   assert( iDb>=0 && iDb<db->nDb );
50544   if( !pOp->p2 && !DbHasProperty(db, iDb, DB_SchemaLoaded) ){
50545     break;
50546   }
50547   zMaster = SCHEMA_TABLE(iDb);
50548   initData.db = db;
50549   initData.iDb = pOp->p1;
50550   initData.pzErrMsg = &p->zErrMsg;
50551   zSql = sqlite3MPrintf(db,
50552      "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s",
50553      db->aDb[iDb].zName, zMaster, pOp->p4.z);
50554   if( zSql==0 ) goto no_mem;
50555   (void)sqlite3SafetyOff(db);
50556   assert( db->init.busy==0 );
50557   db->init.busy = 1;
50558   initData.rc = SQLITE_OK;
50559   assert( !db->mallocFailed );
50560   rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
50561   if( rc==SQLITE_OK ) rc = initData.rc;
50562   sqlite3DbFree(db, zSql);
50563   db->init.busy = 0;
50564   (void)sqlite3SafetyOn(db);
50565   if( rc==SQLITE_NOMEM ){
50566     goto no_mem;
50567   }
50568   break;  
50569 }
50570
50571 #if !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER)
50572 /* Opcode: LoadAnalysis P1 * * * *
50573 **
50574 ** Read the sqlite_stat1 table for database P1 and load the content
50575 ** of that table into the internal index hash table.  This will cause
50576 ** the analysis to be used when preparing all subsequent queries.
50577 */
50578 case OP_LoadAnalysis: {
50579   int iDb = pOp->p1;
50580   assert( iDb>=0 && iDb<db->nDb );
50581   rc = sqlite3AnalysisLoad(db, iDb);
50582   break;  
50583 }
50584 #endif /* !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER)  */
50585
50586 /* Opcode: DropTable P1 * * P4 *
50587 **
50588 ** Remove the internal (in-memory) data structures that describe
50589 ** the table named P4 in database P1.  This is called after a table
50590 ** is dropped in order to keep the internal representation of the
50591 ** schema consistent with what is on disk.
50592 */
50593 case OP_DropTable: {
50594   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
50595   break;
50596 }
50597
50598 /* Opcode: DropIndex P1 * * P4 *
50599 **
50600 ** Remove the internal (in-memory) data structures that describe
50601 ** the index named P4 in database P1.  This is called after an index
50602 ** is dropped in order to keep the internal representation of the
50603 ** schema consistent with what is on disk.
50604 */
50605 case OP_DropIndex: {
50606   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
50607   break;
50608 }
50609
50610 /* Opcode: DropTrigger P1 * * P4 *
50611 **
50612 ** Remove the internal (in-memory) data structures that describe
50613 ** the trigger named P4 in database P1.  This is called after a trigger
50614 ** is dropped in order to keep the internal representation of the
50615 ** schema consistent with what is on disk.
50616 */
50617 case OP_DropTrigger: {
50618   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
50619   break;
50620 }
50621
50622
50623 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
50624 /* Opcode: IntegrityCk P1 P2 P3 * P5
50625 **
50626 ** Do an analysis of the currently open database.  Store in
50627 ** register P1 the text of an error message describing any problems.
50628 ** If no problems are found, store a NULL in register P1.
50629 **
50630 ** The register P3 contains the maximum number of allowed errors.
50631 ** At most reg(P3) errors will be reported.
50632 ** In other words, the analysis stops as soon as reg(P1) errors are 
50633 ** seen.  Reg(P1) is updated with the number of errors remaining.
50634 **
50635 ** The root page numbers of all tables in the database are integer
50636 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
50637 ** total.
50638 **
50639 ** If P5 is not zero, the check is done on the auxiliary database
50640 ** file, not the main database file.
50641 **
50642 ** This opcode is used to implement the integrity_check pragma.
50643 */
50644 case OP_IntegrityCk: {
50645   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
50646   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
50647   int j;          /* Loop counter */
50648   int nErr;       /* Number of errors reported */
50649   char *z;        /* Text of the error report */
50650   Mem *pnErr;     /* Register keeping track of errors remaining */
50651   
50652   nRoot = pOp->p2;
50653   assert( nRoot>0 );
50654   aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) );
50655   if( aRoot==0 ) goto no_mem;
50656   assert( pOp->p3>0 && pOp->p3<=p->nMem );
50657   pnErr = &p->aMem[pOp->p3];
50658   assert( (pnErr->flags & MEM_Int)!=0 );
50659   assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
50660   pIn1 = &p->aMem[pOp->p1];
50661   for(j=0; j<nRoot; j++){
50662     aRoot[j] = sqlite3VdbeIntValue(&pIn1[j]);
50663   }
50664   aRoot[j] = 0;
50665   assert( pOp->p5<db->nDb );
50666   assert( (p->btreeMask & (1<<pOp->p5))!=0 );
50667   z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
50668                                  pnErr->u.i, &nErr);
50669   sqlite3DbFree(db, aRoot);
50670   pnErr->u.i -= nErr;
50671   sqlite3VdbeMemSetNull(pIn1);
50672   if( nErr==0 ){
50673     assert( z==0 );
50674   }else if( z==0 ){
50675     goto no_mem;
50676   }else{
50677     sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
50678   }
50679   UPDATE_MAX_BLOBSIZE(pIn1);
50680   sqlite3VdbeChangeEncoding(pIn1, encoding);
50681   break;
50682 }
50683 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
50684
50685 /* Opcode: FifoWrite P1 * * * *
50686 **
50687 ** Write the integer from register P1 into the Fifo.
50688 */
50689 case OP_FifoWrite: {        /* in1 */
50690   p->sFifo.db = db;
50691   if( sqlite3VdbeFifoPush(&p->sFifo, sqlite3VdbeIntValue(pIn1))==SQLITE_NOMEM ){
50692     goto no_mem;
50693   }
50694   break;
50695 }
50696
50697 /* Opcode: FifoRead P1 P2 * * *
50698 **
50699 ** Attempt to read a single integer from the Fifo.  Store that
50700 ** integer in register P1.
50701 ** 
50702 ** If the Fifo is empty jump to P2.
50703 */
50704 case OP_FifoRead: {         /* jump */
50705   CHECK_FOR_INTERRUPT;
50706   assert( pOp->p1>0 && pOp->p1<=p->nMem );
50707   pOut = &p->aMem[pOp->p1];
50708   MemSetTypeFlag(pOut, MEM_Int);
50709   if( sqlite3VdbeFifoPop(&p->sFifo, &pOut->u.i)==SQLITE_DONE ){
50710     pc = pOp->p2 - 1;
50711   }
50712   break;
50713 }
50714
50715 #ifndef SQLITE_OMIT_TRIGGER
50716 /* Opcode: ContextPush * * * 
50717 **
50718 ** Save the current Vdbe context such that it can be restored by a ContextPop
50719 ** opcode. The context stores the last insert row id, the last statement change
50720 ** count, and the current statement change count.
50721 */
50722 case OP_ContextPush: {
50723   int i = p->contextStackTop++;
50724   Context *pContext;
50725
50726   assert( i>=0 );
50727   /* FIX ME: This should be allocated as part of the vdbe at compile-time */
50728   if( i>=p->contextStackDepth ){
50729     p->contextStackDepth = i+1;
50730     p->contextStack = sqlite3DbReallocOrFree(db, p->contextStack,
50731                                           sizeof(Context)*(i+1));
50732     if( p->contextStack==0 ) goto no_mem;
50733   }
50734   pContext = &p->contextStack[i];
50735   pContext->lastRowid = db->lastRowid;
50736   pContext->nChange = p->nChange;
50737   pContext->sFifo = p->sFifo;
50738   sqlite3VdbeFifoInit(&p->sFifo, db);
50739   break;
50740 }
50741
50742 /* Opcode: ContextPop * * * 
50743 **
50744 ** Restore the Vdbe context to the state it was in when contextPush was last
50745 ** executed. The context stores the last insert row id, the last statement
50746 ** change count, and the current statement change count.
50747 */
50748 case OP_ContextPop: {
50749   Context *pContext = &p->contextStack[--p->contextStackTop];
50750   assert( p->contextStackTop>=0 );
50751   db->lastRowid = pContext->lastRowid;
50752   p->nChange = pContext->nChange;
50753   sqlite3VdbeFifoClear(&p->sFifo);
50754   p->sFifo = pContext->sFifo;
50755   break;
50756 }
50757 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
50758
50759 #ifndef SQLITE_OMIT_AUTOINCREMENT
50760 /* Opcode: MemMax P1 P2 * * *
50761 **
50762 ** Set the value of register P1 to the maximum of its current value
50763 ** and the value in register P2.
50764 **
50765 ** This instruction throws an error if the memory cell is not initially
50766 ** an integer.
50767 */
50768 case OP_MemMax: {        /* in1, in2 */
50769   sqlite3VdbeMemIntegerify(pIn1);
50770   sqlite3VdbeMemIntegerify(pIn2);
50771   if( pIn1->u.i<pIn2->u.i){
50772     pIn1->u.i = pIn2->u.i;
50773   }
50774   break;
50775 }
50776 #endif /* SQLITE_OMIT_AUTOINCREMENT */
50777
50778 /* Opcode: IfPos P1 P2 * * *
50779 **
50780 ** If the value of register P1 is 1 or greater, jump to P2.
50781 **
50782 ** It is illegal to use this instruction on a register that does
50783 ** not contain an integer.  An assertion fault will result if you try.
50784 */
50785 case OP_IfPos: {        /* jump, in1 */
50786   assert( pIn1->flags&MEM_Int );
50787   if( pIn1->u.i>0 ){
50788      pc = pOp->p2 - 1;
50789   }
50790   break;
50791 }
50792
50793 /* Opcode: IfNeg P1 P2 * * *
50794 **
50795 ** If the value of register P1 is less than zero, jump to P2. 
50796 **
50797 ** It is illegal to use this instruction on a register that does
50798 ** not contain an integer.  An assertion fault will result if you try.
50799 */
50800 case OP_IfNeg: {        /* jump, in1 */
50801   assert( pIn1->flags&MEM_Int );
50802   if( pIn1->u.i<0 ){
50803      pc = pOp->p2 - 1;
50804   }
50805   break;
50806 }
50807
50808 /* Opcode: IfZero P1 P2 * * *
50809 **
50810 ** If the value of register P1 is exactly 0, jump to P2. 
50811 **
50812 ** It is illegal to use this instruction on a register that does
50813 ** not contain an integer.  An assertion fault will result if you try.
50814 */
50815 case OP_IfZero: {        /* jump, in1 */
50816   assert( pIn1->flags&MEM_Int );
50817   if( pIn1->u.i==0 ){
50818      pc = pOp->p2 - 1;
50819   }
50820   break;
50821 }
50822
50823 /* Opcode: AggStep * P2 P3 P4 P5
50824 **
50825 ** Execute the step function for an aggregate.  The
50826 ** function has P5 arguments.   P4 is a pointer to the FuncDef
50827 ** structure that specifies the function.  Use register
50828 ** P3 as the accumulator.
50829 **
50830 ** The P5 arguments are taken from register P2 and its
50831 ** successors.
50832 */
50833 case OP_AggStep: {
50834   int n = pOp->p5;
50835   int i;
50836   Mem *pMem, *pRec;
50837   sqlite3_context ctx;
50838   sqlite3_value **apVal;
50839
50840   assert( n>=0 );
50841   pRec = &p->aMem[pOp->p2];
50842   apVal = p->apArg;
50843   assert( apVal || n==0 );
50844   for(i=0; i<n; i++, pRec++){
50845     apVal[i] = pRec;
50846     storeTypeInfo(pRec, encoding);
50847   }
50848   ctx.pFunc = pOp->p4.pFunc;
50849   assert( pOp->p3>0 && pOp->p3<=p->nMem );
50850   ctx.pMem = pMem = &p->aMem[pOp->p3];
50851   pMem->n++;
50852   ctx.s.flags = MEM_Null;
50853   ctx.s.z = 0;
50854   ctx.s.zMalloc = 0;
50855   ctx.s.xDel = 0;
50856   ctx.s.db = db;
50857   ctx.isError = 0;
50858   ctx.pColl = 0;
50859   if( ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
50860     assert( pOp>p->aOp );
50861     assert( pOp[-1].p4type==P4_COLLSEQ );
50862     assert( pOp[-1].opcode==OP_CollSeq );
50863     ctx.pColl = pOp[-1].p4.pColl;
50864   }
50865   (ctx.pFunc->xStep)(&ctx, n, apVal);
50866   if( ctx.isError ){
50867     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s));
50868     rc = ctx.isError;
50869   }
50870   sqlite3VdbeMemRelease(&ctx.s);
50871   break;
50872 }
50873
50874 /* Opcode: AggFinal P1 P2 * P4 *
50875 **
50876 ** Execute the finalizer function for an aggregate.  P1 is
50877 ** the memory location that is the accumulator for the aggregate.
50878 **
50879 ** P2 is the number of arguments that the step function takes and
50880 ** P4 is a pointer to the FuncDef for this function.  The P2
50881 ** argument is not used by this opcode.  It is only there to disambiguate
50882 ** functions that can take varying numbers of arguments.  The
50883 ** P4 argument is only needed for the degenerate case where
50884 ** the step function was not previously called.
50885 */
50886 case OP_AggFinal: {
50887   Mem *pMem;
50888   assert( pOp->p1>0 && pOp->p1<=p->nMem );
50889   pMem = &p->aMem[pOp->p1];
50890   assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
50891   rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
50892   if( rc==SQLITE_ERROR ){
50893     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(pMem));
50894   }
50895   sqlite3VdbeChangeEncoding(pMem, encoding);
50896   UPDATE_MAX_BLOBSIZE(pMem);
50897   if( sqlite3VdbeMemTooBig(pMem) ){
50898     goto too_big;
50899   }
50900   break;
50901 }
50902
50903
50904 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
50905 /* Opcode: Vacuum * * * * *
50906 **
50907 ** Vacuum the entire database.  This opcode will cause other virtual
50908 ** machines to be created and run.  It may not be called from within
50909 ** a transaction.
50910 */
50911 case OP_Vacuum: {
50912   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse; 
50913   rc = sqlite3RunVacuum(&p->zErrMsg, db);
50914   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
50915   break;
50916 }
50917 #endif
50918
50919 #if !defined(SQLITE_OMIT_AUTOVACUUM)
50920 /* Opcode: IncrVacuum P1 P2 * * *
50921 **
50922 ** Perform a single step of the incremental vacuum procedure on
50923 ** the P1 database. If the vacuum has finished, jump to instruction
50924 ** P2. Otherwise, fall through to the next instruction.
50925 */
50926 case OP_IncrVacuum: {        /* jump */
50927   Btree *pBt;
50928
50929   assert( pOp->p1>=0 && pOp->p1<db->nDb );
50930   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
50931   pBt = db->aDb[pOp->p1].pBt;
50932   rc = sqlite3BtreeIncrVacuum(pBt);
50933   if( rc==SQLITE_DONE ){
50934     pc = pOp->p2 - 1;
50935     rc = SQLITE_OK;
50936   }
50937   break;
50938 }
50939 #endif
50940
50941 /* Opcode: Expire P1 * * * *
50942 **
50943 ** Cause precompiled statements to become expired. An expired statement
50944 ** fails with an error code of SQLITE_SCHEMA if it is ever executed 
50945 ** (via sqlite3_step()).
50946 ** 
50947 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
50948 ** then only the currently executing statement is affected. 
50949 */
50950 case OP_Expire: {
50951   if( !pOp->p1 ){
50952     sqlite3ExpirePreparedStatements(db);
50953   }else{
50954     p->expired = 1;
50955   }
50956   break;
50957 }
50958
50959 #ifndef SQLITE_OMIT_SHARED_CACHE
50960 /* Opcode: TableLock P1 P2 P3 P4 *
50961 **
50962 ** Obtain a lock on a particular table. This instruction is only used when
50963 ** the shared-cache feature is enabled. 
50964 **
50965 ** If P1 is  the index of the database in sqlite3.aDb[] of the database
50966 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
50967 ** a write lock if P3==1.
50968 **
50969 ** P2 contains the root-page of the table to lock.
50970 **
50971 ** P4 contains a pointer to the name of the table being locked. This is only
50972 ** used to generate an error message if the lock cannot be obtained.
50973 */
50974 case OP_TableLock: {
50975   int p1 = pOp->p1; 
50976   u8 isWriteLock = pOp->p3;
50977   assert( p1>=0 && p1<db->nDb );
50978   assert( (p->btreeMask & (1<<p1))!=0 );
50979   assert( isWriteLock==0 || isWriteLock==1 );
50980   rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
50981   if( rc==SQLITE_LOCKED ){
50982     const char *z = pOp->p4.z;
50983     sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
50984   }
50985   break;
50986 }
50987 #endif /* SQLITE_OMIT_SHARED_CACHE */
50988
50989 #ifndef SQLITE_OMIT_VIRTUALTABLE
50990 /* Opcode: VBegin * * * P4 *
50991 **
50992 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the 
50993 ** xBegin method for that table.
50994 **
50995 ** Also, whether or not P4 is set, check that this is not being called from
50996 ** within a callback to a virtual table xSync() method. If it is, set the
50997 ** error code to SQLITE_LOCKED.
50998 */
50999 case OP_VBegin: {
51000   sqlite3_vtab *pVtab = pOp->p4.pVtab;
51001   rc = sqlite3VtabBegin(db, pVtab);
51002   if( pVtab ){
51003     sqlite3DbFree(db, p->zErrMsg);
51004     p->zErrMsg = pVtab->zErrMsg;
51005     pVtab->zErrMsg = 0;
51006   }
51007   break;
51008 }
51009 #endif /* SQLITE_OMIT_VIRTUALTABLE */
51010
51011 #ifndef SQLITE_OMIT_VIRTUALTABLE
51012 /* Opcode: VCreate P1 * * P4 *
51013 **
51014 ** P4 is the name of a virtual table in database P1. Call the xCreate method
51015 ** for that table.
51016 */
51017 case OP_VCreate: {
51018   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
51019   break;
51020 }
51021 #endif /* SQLITE_OMIT_VIRTUALTABLE */
51022
51023 #ifndef SQLITE_OMIT_VIRTUALTABLE
51024 /* Opcode: VDestroy P1 * * P4 *
51025 **
51026 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
51027 ** of that table.
51028 */
51029 case OP_VDestroy: {
51030   p->inVtabMethod = 2;
51031   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
51032   p->inVtabMethod = 0;
51033   break;
51034 }
51035 #endif /* SQLITE_OMIT_VIRTUALTABLE */
51036
51037 #ifndef SQLITE_OMIT_VIRTUALTABLE
51038 /* Opcode: VOpen P1 * * P4 *
51039 **
51040 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
51041 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
51042 ** table and stores that cursor in P1.
51043 */
51044 case OP_VOpen: {
51045   VdbeCursor *pCur = 0;
51046   sqlite3_vtab_cursor *pVtabCursor = 0;
51047
51048   sqlite3_vtab *pVtab = pOp->p4.pVtab;
51049   sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
51050
51051   assert(pVtab && pModule);
51052   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
51053   rc = pModule->xOpen(pVtab, &pVtabCursor);
51054   sqlite3DbFree(db, p->zErrMsg);
51055   p->zErrMsg = pVtab->zErrMsg;
51056   pVtab->zErrMsg = 0;
51057   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
51058   if( SQLITE_OK==rc ){
51059     /* Initialize sqlite3_vtab_cursor base class */
51060     pVtabCursor->pVtab = pVtab;
51061
51062     /* Initialise vdbe cursor object */
51063     pCur = allocateCursor(p, pOp->p1, &pOp[-1], -1, 0);
51064     if( pCur ){
51065       pCur->pVtabCursor = pVtabCursor;
51066       pCur->pModule = pVtabCursor->pVtab->pModule;
51067     }else{
51068       db->mallocFailed = 1;
51069       pModule->xClose(pVtabCursor);
51070     }
51071   }
51072   break;
51073 }
51074 #endif /* SQLITE_OMIT_VIRTUALTABLE */
51075
51076 #ifndef SQLITE_OMIT_VIRTUALTABLE
51077 /* Opcode: VFilter P1 P2 P3 P4 *
51078 **
51079 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
51080 ** the filtered result set is empty.
51081 **
51082 ** P4 is either NULL or a string that was generated by the xBestIndex
51083 ** method of the module.  The interpretation of the P4 string is left
51084 ** to the module implementation.
51085 **
51086 ** This opcode invokes the xFilter method on the virtual table specified
51087 ** by P1.  The integer query plan parameter to xFilter is stored in register
51088 ** P3. Register P3+1 stores the argc parameter to be passed to the
51089 ** xFilter method. Registers P3+2..P3+1+argc are the argc
51090 ** additional parameters which are passed to
51091 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
51092 **
51093 ** A jump is made to P2 if the result set after filtering would be empty.
51094 */
51095 case OP_VFilter: {   /* jump */
51096   int nArg;
51097   int iQuery;
51098   const sqlite3_module *pModule;
51099   Mem *pQuery = &p->aMem[pOp->p3];
51100   Mem *pArgc = &pQuery[1];
51101   sqlite3_vtab_cursor *pVtabCursor;
51102   sqlite3_vtab *pVtab;
51103
51104   VdbeCursor *pCur = p->apCsr[pOp->p1];
51105
51106   REGISTER_TRACE(pOp->p3, pQuery);
51107   assert( pCur->pVtabCursor );
51108   pVtabCursor = pCur->pVtabCursor;
51109   pVtab = pVtabCursor->pVtab;
51110   pModule = pVtab->pModule;
51111
51112   /* Grab the index number and argc parameters */
51113   assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
51114   nArg = pArgc->u.i;
51115   iQuery = pQuery->u.i;
51116
51117   /* Invoke the xFilter method */
51118   {
51119     int res = 0;
51120     int i;
51121     Mem **apArg = p->apArg;
51122     for(i = 0; i<nArg; i++){
51123       apArg[i] = &pArgc[i+1];
51124       storeTypeInfo(apArg[i], 0);
51125     }
51126
51127     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
51128     sqlite3VtabLock(pVtab);
51129     p->inVtabMethod = 1;
51130     rc = pModule->xFilter(pVtabCursor, iQuery, pOp->p4.z, nArg, apArg);
51131     p->inVtabMethod = 0;
51132     sqlite3DbFree(db, p->zErrMsg);
51133     p->zErrMsg = pVtab->zErrMsg;
51134     pVtab->zErrMsg = 0;
51135     sqlite3VtabUnlock(db, pVtab);
51136     if( rc==SQLITE_OK ){
51137       res = pModule->xEof(pVtabCursor);
51138     }
51139     if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
51140
51141     if( res ){
51142       pc = pOp->p2 - 1;
51143     }
51144   }
51145   pCur->nullRow = 0;
51146
51147   break;
51148 }
51149 #endif /* SQLITE_OMIT_VIRTUALTABLE */
51150
51151 #ifndef SQLITE_OMIT_VIRTUALTABLE
51152 /* Opcode: VRowid P1 P2 * * *
51153 **
51154 ** Store into register P2  the rowid of
51155 ** the virtual-table that the P1 cursor is pointing to.
51156 */
51157 case OP_VRowid: {             /* out2-prerelease */
51158   sqlite3_vtab *pVtab;
51159   const sqlite3_module *pModule;
51160   sqlite_int64 iRow;
51161   VdbeCursor *pCur = p->apCsr[pOp->p1];
51162
51163   assert( pCur->pVtabCursor );
51164   if( pCur->nullRow ){
51165     break;
51166   }
51167   pVtab = pCur->pVtabCursor->pVtab;
51168   pModule = pVtab->pModule;
51169   assert( pModule->xRowid );
51170   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
51171   rc = pModule->xRowid(pCur->pVtabCursor, &iRow);
51172   sqlite3DbFree(db, p->zErrMsg);
51173   p->zErrMsg = pVtab->zErrMsg;
51174   pVtab->zErrMsg = 0;
51175   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
51176   MemSetTypeFlag(pOut, MEM_Int);
51177   pOut->u.i = iRow;
51178   break;
51179 }
51180 #endif /* SQLITE_OMIT_VIRTUALTABLE */
51181
51182 #ifndef SQLITE_OMIT_VIRTUALTABLE
51183 /* Opcode: VColumn P1 P2 P3 * *
51184 **
51185 ** Store the value of the P2-th column of
51186 ** the row of the virtual-table that the 
51187 ** P1 cursor is pointing to into register P3.
51188 */
51189 case OP_VColumn: {
51190   sqlite3_vtab *pVtab;
51191   const sqlite3_module *pModule;
51192   Mem *pDest;
51193   sqlite3_context sContext;
51194
51195   VdbeCursor *pCur = p->apCsr[pOp->p1];
51196   assert( pCur->pVtabCursor );
51197   assert( pOp->p3>0 && pOp->p3<=p->nMem );
51198   pDest = &p->aMem[pOp->p3];
51199   if( pCur->nullRow ){
51200     sqlite3VdbeMemSetNull(pDest);
51201     break;
51202   }
51203   pVtab = pCur->pVtabCursor->pVtab;
51204   pModule = pVtab->pModule;
51205   assert( pModule->xColumn );
51206   memset(&sContext, 0, sizeof(sContext));
51207
51208   /* The output cell may already have a buffer allocated. Move
51209   ** the current contents to sContext.s so in case the user-function 
51210   ** can use the already allocated buffer instead of allocating a 
51211   ** new one.
51212   */
51213   sqlite3VdbeMemMove(&sContext.s, pDest);
51214   MemSetTypeFlag(&sContext.s, MEM_Null);
51215
51216   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
51217   rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
51218   sqlite3DbFree(db, p->zErrMsg);
51219   p->zErrMsg = pVtab->zErrMsg;
51220   pVtab->zErrMsg = 0;
51221
51222   /* Copy the result of the function to the P3 register. We
51223   ** do this regardless of whether or not an error occured to ensure any
51224   ** dynamic allocation in sContext.s (a Mem struct) is  released.
51225   */
51226   sqlite3VdbeChangeEncoding(&sContext.s, encoding);
51227   REGISTER_TRACE(pOp->p3, pDest);
51228   sqlite3VdbeMemMove(pDest, &sContext.s);
51229   UPDATE_MAX_BLOBSIZE(pDest);
51230
51231   if( sqlite3SafetyOn(db) ){
51232     goto abort_due_to_misuse;
51233   }
51234   if( sqlite3VdbeMemTooBig(pDest) ){
51235     goto too_big;
51236   }
51237   break;
51238 }
51239 #endif /* SQLITE_OMIT_VIRTUALTABLE */
51240
51241 #ifndef SQLITE_OMIT_VIRTUALTABLE
51242 /* Opcode: VNext P1 P2 * * *
51243 **
51244 ** Advance virtual table P1 to the next row in its result set and
51245 ** jump to instruction P2.  Or, if the virtual table has reached
51246 ** the end of its result set, then fall through to the next instruction.
51247 */
51248 case OP_VNext: {   /* jump */
51249   sqlite3_vtab *pVtab;
51250   const sqlite3_module *pModule;
51251   int res = 0;
51252
51253   VdbeCursor *pCur = p->apCsr[pOp->p1];
51254   assert( pCur->pVtabCursor );
51255   if( pCur->nullRow ){
51256     break;
51257   }
51258   pVtab = pCur->pVtabCursor->pVtab;
51259   pModule = pVtab->pModule;
51260   assert( pModule->xNext );
51261
51262   /* Invoke the xNext() method of the module. There is no way for the
51263   ** underlying implementation to return an error if one occurs during
51264   ** xNext(). Instead, if an error occurs, true is returned (indicating that 
51265   ** data is available) and the error code returned when xColumn or
51266   ** some other method is next invoked on the save virtual table cursor.
51267   */
51268   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
51269   sqlite3VtabLock(pVtab);
51270   p->inVtabMethod = 1;
51271   rc = pModule->xNext(pCur->pVtabCursor);
51272   p->inVtabMethod = 0;
51273   sqlite3DbFree(db, p->zErrMsg);
51274   p->zErrMsg = pVtab->zErrMsg;
51275   pVtab->zErrMsg = 0;
51276   sqlite3VtabUnlock(db, pVtab);
51277   if( rc==SQLITE_OK ){
51278     res = pModule->xEof(pCur->pVtabCursor);
51279   }
51280   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
51281
51282   if( !res ){
51283     /* If there is data, jump to P2 */
51284     pc = pOp->p2 - 1;
51285   }
51286   break;
51287 }
51288 #endif /* SQLITE_OMIT_VIRTUALTABLE */
51289
51290 #ifndef SQLITE_OMIT_VIRTUALTABLE
51291 /* Opcode: VRename P1 * * P4 *
51292 **
51293 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
51294 ** This opcode invokes the corresponding xRename method. The value
51295 ** in register P1 is passed as the zName argument to the xRename method.
51296 */
51297 case OP_VRename: {
51298   sqlite3_vtab *pVtab = pOp->p4.pVtab;
51299   Mem *pName = &p->aMem[pOp->p1];
51300   assert( pVtab->pModule->xRename );
51301   REGISTER_TRACE(pOp->p1, pName);
51302
51303   Stringify(pName, encoding);
51304
51305   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
51306   sqlite3VtabLock(pVtab);
51307   rc = pVtab->pModule->xRename(pVtab, pName->z);
51308   sqlite3DbFree(db, p->zErrMsg);
51309   p->zErrMsg = pVtab->zErrMsg;
51310   pVtab->zErrMsg = 0;
51311   sqlite3VtabUnlock(db, pVtab);
51312   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
51313
51314   break;
51315 }
51316 #endif
51317
51318 #ifndef SQLITE_OMIT_VIRTUALTABLE
51319 /* Opcode: VUpdate P1 P2 P3 P4 *
51320 **
51321 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
51322 ** This opcode invokes the corresponding xUpdate method. P2 values
51323 ** are contiguous memory cells starting at P3 to pass to the xUpdate 
51324 ** invocation. The value in register (P3+P2-1) corresponds to the 
51325 ** p2th element of the argv array passed to xUpdate.
51326 **
51327 ** The xUpdate method will do a DELETE or an INSERT or both.
51328 ** The argv[0] element (which corresponds to memory cell P3)
51329 ** is the rowid of a row to delete.  If argv[0] is NULL then no 
51330 ** deletion occurs.  The argv[1] element is the rowid of the new 
51331 ** row.  This can be NULL to have the virtual table select the new 
51332 ** rowid for itself.  The subsequent elements in the array are 
51333 ** the values of columns in the new row.
51334 **
51335 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
51336 ** a row to delete.
51337 **
51338 ** P1 is a boolean flag. If it is set to true and the xUpdate call
51339 ** is successful, then the value returned by sqlite3_last_insert_rowid() 
51340 ** is set to the value of the rowid for the row just inserted.
51341 */
51342 case OP_VUpdate: {
51343   sqlite3_vtab *pVtab = pOp->p4.pVtab;
51344   sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
51345   int nArg = pOp->p2;
51346   assert( pOp->p4type==P4_VTAB );
51347   if( pModule->xUpdate==0 ){
51348     sqlite3SetString(&p->zErrMsg, db, "read-only table");
51349     rc = SQLITE_ERROR;
51350   }else{
51351     int i;
51352     sqlite_int64 rowid;
51353     Mem **apArg = p->apArg;
51354     Mem *pX = &p->aMem[pOp->p3];
51355     for(i=0; i<nArg; i++){
51356       storeTypeInfo(pX, 0);
51357       apArg[i] = pX;
51358       pX++;
51359     }
51360     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
51361     sqlite3VtabLock(pVtab);
51362     rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
51363     sqlite3DbFree(db, p->zErrMsg);
51364     p->zErrMsg = pVtab->zErrMsg;
51365     pVtab->zErrMsg = 0;
51366     sqlite3VtabUnlock(db, pVtab);
51367     if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
51368     if( pOp->p1 && rc==SQLITE_OK ){
51369       assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
51370       db->lastRowid = rowid;
51371     }
51372     p->nChange++;
51373   }
51374   break;
51375 }
51376 #endif /* SQLITE_OMIT_VIRTUALTABLE */
51377
51378 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
51379 /* Opcode: Pagecount P1 P2 * * *
51380 **
51381 ** Write the current number of pages in database P1 to memory cell P2.
51382 */
51383 case OP_Pagecount: {            /* out2-prerelease */
51384   int p1 = pOp->p1; 
51385   int nPage;
51386   Pager *pPager = sqlite3BtreePager(db->aDb[p1].pBt);
51387
51388   rc = sqlite3PagerPagecount(pPager, &nPage);
51389   if( rc==SQLITE_OK ){
51390     pOut->flags = MEM_Int;
51391     pOut->u.i = nPage;
51392   }
51393   break;
51394 }
51395 #endif
51396
51397 #ifndef SQLITE_OMIT_TRACE
51398 /* Opcode: Trace * * * P4 *
51399 **
51400 ** If tracing is enabled (by the sqlite3_trace()) interface, then
51401 ** the UTF-8 string contained in P4 is emitted on the trace callback.
51402 */
51403 case OP_Trace: {
51404   if( pOp->p4.z ){
51405     if( db->xTrace ){
51406       db->xTrace(db->pTraceArg, pOp->p4.z);
51407     }
51408 #ifdef SQLITE_DEBUG
51409     if( (db->flags & SQLITE_SqlTrace)!=0 ){
51410       sqlite3DebugPrintf("SQL-trace: %s\n", pOp->p4.z);
51411     }
51412 #endif /* SQLITE_DEBUG */
51413   }
51414   break;
51415 }
51416 #endif
51417
51418
51419 /* Opcode: Noop * * * * *
51420 **
51421 ** Do nothing.  This instruction is often useful as a jump
51422 ** destination.
51423 */
51424 /*
51425 ** The magic Explain opcode are only inserted when explain==2 (which
51426 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
51427 ** This opcode records information from the optimizer.  It is the
51428 ** the same as a no-op.  This opcodesnever appears in a real VM program.
51429 */
51430 default: {          /* This is really OP_Noop and OP_Explain */
51431   break;
51432 }
51433
51434 /*****************************************************************************
51435 ** The cases of the switch statement above this line should all be indented
51436 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
51437 ** readability.  From this point on down, the normal indentation rules are
51438 ** restored.
51439 *****************************************************************************/
51440     }
51441
51442 #ifdef VDBE_PROFILE
51443     {
51444       u64 elapsed = sqlite3Hwtime() - start;
51445       pOp->cycles += elapsed;
51446       pOp->cnt++;
51447 #if 0
51448         fprintf(stdout, "%10llu ", elapsed);
51449         sqlite3VdbePrintOp(stdout, origPc, &p->aOp[origPc]);
51450 #endif
51451     }
51452 #endif
51453
51454     /* The following code adds nothing to the actual functionality
51455     ** of the program.  It is only here for testing and debugging.
51456     ** On the other hand, it does burn CPU cycles every time through
51457     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
51458     */
51459 #ifndef NDEBUG
51460     assert( pc>=-1 && pc<p->nOp );
51461
51462 #ifdef SQLITE_DEBUG
51463     if( p->trace ){
51464       if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
51465       if( opProperty & OPFLG_OUT2_PRERELEASE ){
51466         registerTrace(p->trace, pOp->p2, pOut);
51467       }
51468       if( opProperty & OPFLG_OUT3 ){
51469         registerTrace(p->trace, pOp->p3, pOut);
51470       }
51471     }
51472 #endif  /* SQLITE_DEBUG */
51473 #endif  /* NDEBUG */
51474   }  /* The end of the for(;;) loop the loops through opcodes */
51475
51476   /* If we reach this point, it means that execution is finished with
51477   ** an error of some kind.
51478   */
51479 vdbe_error_halt:
51480   assert( rc );
51481   p->rc = rc;
51482   sqlite3VdbeHalt(p);
51483   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
51484   rc = SQLITE_ERROR;
51485
51486   /* This is the only way out of this procedure.  We have to
51487   ** release the mutexes on btrees that were acquired at the
51488   ** top. */
51489 vdbe_return:
51490   sqlite3BtreeMutexArrayLeave(&p->aMutex);
51491   return rc;
51492
51493   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
51494   ** is encountered.
51495   */
51496 too_big:
51497   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
51498   rc = SQLITE_TOOBIG;
51499   goto vdbe_error_halt;
51500
51501   /* Jump to here if a malloc() fails.
51502   */
51503 no_mem:
51504   db->mallocFailed = 1;
51505   sqlite3SetString(&p->zErrMsg, db, "out of memory");
51506   rc = SQLITE_NOMEM;
51507   goto vdbe_error_halt;
51508
51509   /* Jump to here for an SQLITE_MISUSE error.
51510   */
51511 abort_due_to_misuse:
51512   rc = SQLITE_MISUSE;
51513   /* Fall thru into abort_due_to_error */
51514
51515   /* Jump to here for any other kind of fatal error.  The "rc" variable
51516   ** should hold the error number.
51517   */
51518 abort_due_to_error:
51519   assert( p->zErrMsg==0 );
51520   if( db->mallocFailed ) rc = SQLITE_NOMEM;
51521   if( rc!=SQLITE_IOERR_NOMEM ){
51522     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
51523   }
51524   goto vdbe_error_halt;
51525
51526   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
51527   ** flag.
51528   */
51529 abort_due_to_interrupt:
51530   assert( db->u1.isInterrupted );
51531   rc = SQLITE_INTERRUPT;
51532   p->rc = rc;
51533   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
51534   goto vdbe_error_halt;
51535 }
51536
51537 /************** End of vdbe.c ************************************************/
51538 /************** Begin file vdbeblob.c ****************************************/
51539 /*
51540 ** 2007 May 1
51541 **
51542 ** The author disclaims copyright to this source code.  In place of
51543 ** a legal notice, here is a blessing:
51544 **
51545 **    May you do good and not evil.
51546 **    May you find forgiveness for yourself and forgive others.
51547 **    May you share freely, never taking more than you give.
51548 **
51549 *************************************************************************
51550 **
51551 ** This file contains code used to implement incremental BLOB I/O.
51552 **
51553 ** $Id: vdbeblob.c,v 1.26 2008/10/02 14:49:02 danielk1977 Exp $
51554 */
51555
51556
51557 #ifndef SQLITE_OMIT_INCRBLOB
51558
51559 /*
51560 ** Valid sqlite3_blob* handles point to Incrblob structures.
51561 */
51562 typedef struct Incrblob Incrblob;
51563 struct Incrblob {
51564   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
51565   int nByte;              /* Size of open blob, in bytes */
51566   int iOffset;            /* Byte offset of blob in cursor data */
51567   BtCursor *pCsr;         /* Cursor pointing at blob row */
51568   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
51569   sqlite3 *db;            /* The associated database */
51570 };
51571
51572 /*
51573 ** Open a blob handle.
51574 */
51575 SQLITE_API int sqlite3_blob_open(
51576   sqlite3* db,            /* The database connection */
51577   const char *zDb,        /* The attached database containing the blob */
51578   const char *zTable,     /* The table containing the blob */
51579   const char *zColumn,    /* The column containing the blob */
51580   sqlite_int64 iRow,      /* The row containing the glob */
51581   int flags,              /* True -> read/write access, false -> read-only */
51582   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
51583 ){
51584   int nAttempt = 0;
51585   int iCol;               /* Index of zColumn in row-record */
51586
51587   /* This VDBE program seeks a btree cursor to the identified 
51588   ** db/table/row entry. The reason for using a vdbe program instead
51589   ** of writing code to use the b-tree layer directly is that the
51590   ** vdbe program will take advantage of the various transaction,
51591   ** locking and error handling infrastructure built into the vdbe.
51592   **
51593   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
51594   ** Code external to the Vdbe then "borrows" the b-tree cursor and
51595   ** uses it to implement the blob_read(), blob_write() and 
51596   ** blob_bytes() functions.
51597   **
51598   ** The sqlite3_blob_close() function finalizes the vdbe program,
51599   ** which closes the b-tree cursor and (possibly) commits the 
51600   ** transaction.
51601   */
51602   static const VdbeOpList openBlob[] = {
51603     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
51604     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
51605
51606     /* One of the following two instructions is replaced by an
51607     ** OP_Noop before exection.
51608     */
51609     {OP_SetNumColumns, 0, 0, 0},   /* 2: Num cols for cursor */
51610     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
51611     {OP_SetNumColumns, 0, 0, 0},   /* 4: Num cols for cursor */
51612     {OP_OpenWrite, 0, 0, 0},       /* 5: Open cursor 0 for read/write */
51613
51614     {OP_Variable, 1, 1, 0},        /* 6: Push the rowid to the stack */
51615     {OP_NotExists, 0, 10, 1},      /* 7: Seek the cursor */
51616     {OP_Column, 0, 0, 1},          /* 8  */
51617     {OP_ResultRow, 1, 0, 0},       /* 9  */
51618     {OP_Close, 0, 0, 0},           /* 10  */
51619     {OP_Halt, 0, 0, 0},            /* 11 */
51620   };
51621
51622   Vdbe *v = 0;
51623   int rc = SQLITE_OK;
51624   char zErr[128];
51625
51626   zErr[0] = 0;
51627   sqlite3_mutex_enter(db->mutex);
51628   do {
51629     Parse sParse;
51630     Table *pTab;
51631
51632     memset(&sParse, 0, sizeof(Parse));
51633     sParse.db = db;
51634
51635     if( sqlite3SafetyOn(db) ){
51636       sqlite3_mutex_leave(db->mutex);
51637       return SQLITE_MISUSE;
51638     }
51639
51640     sqlite3BtreeEnterAll(db);
51641     pTab = sqlite3LocateTable(&sParse, 0, zTable, zDb);
51642     if( pTab && IsVirtual(pTab) ){
51643       pTab = 0;
51644       sqlite3ErrorMsg(&sParse, "cannot open virtual table: %s", zTable);
51645     }
51646 #ifndef SQLITE_OMIT_VIEW
51647     if( pTab && pTab->pSelect ){
51648       pTab = 0;
51649       sqlite3ErrorMsg(&sParse, "cannot open view: %s", zTable);
51650     }
51651 #endif
51652     if( !pTab ){
51653       if( sParse.zErrMsg ){
51654         sqlite3_snprintf(sizeof(zErr), zErr, "%s", sParse.zErrMsg);
51655       }
51656       sqlite3DbFree(db, sParse.zErrMsg);
51657       rc = SQLITE_ERROR;
51658       (void)sqlite3SafetyOff(db);
51659       sqlite3BtreeLeaveAll(db);
51660       goto blob_open_out;
51661     }
51662
51663     /* Now search pTab for the exact column. */
51664     for(iCol=0; iCol < pTab->nCol; iCol++) {
51665       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
51666         break;
51667       }
51668     }
51669     if( iCol==pTab->nCol ){
51670       sqlite3_snprintf(sizeof(zErr), zErr, "no such column: \"%s\"", zColumn);
51671       rc = SQLITE_ERROR;
51672       (void)sqlite3SafetyOff(db);
51673       sqlite3BtreeLeaveAll(db);
51674       goto blob_open_out;
51675     }
51676
51677     /* If the value is being opened for writing, check that the
51678     ** column is not indexed. It is against the rules to open an
51679     ** indexed column for writing.
51680     */
51681     if( flags ){
51682       Index *pIdx;
51683       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
51684         int j;
51685         for(j=0; j<pIdx->nColumn; j++){
51686           if( pIdx->aiColumn[j]==iCol ){
51687             sqlite3_snprintf(sizeof(zErr), zErr,
51688                              "cannot open indexed column for writing");
51689             rc = SQLITE_ERROR;
51690             (void)sqlite3SafetyOff(db);
51691             sqlite3BtreeLeaveAll(db);
51692             goto blob_open_out;
51693           }
51694         }
51695       }
51696     }
51697
51698     v = sqlite3VdbeCreate(db);
51699     if( v ){
51700       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
51701       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
51702
51703       /* Configure the OP_Transaction */
51704       sqlite3VdbeChangeP1(v, 0, iDb);
51705       sqlite3VdbeChangeP2(v, 0, (flags ? 1 : 0));
51706
51707       /* Configure the OP_VerifyCookie */
51708       sqlite3VdbeChangeP1(v, 1, iDb);
51709       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
51710
51711       /* Make sure a mutex is held on the table to be accessed */
51712       sqlite3VdbeUsesBtree(v, iDb); 
51713
51714       /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
51715       ** parameter of the other to pTab->tnum. 
51716       */
51717       sqlite3VdbeChangeToNoop(v, (flags ? 3 : 5), 1);
51718       sqlite3VdbeChangeP2(v, (flags ? 5 : 3), pTab->tnum);
51719       sqlite3VdbeChangeP3(v, (flags ? 5 : 3), iDb);
51720
51721       /* Configure the OP_SetNumColumns. Configure the cursor to
51722       ** think that the table has one more column than it really
51723       ** does. An OP_Column to retrieve this imaginary column will
51724       ** always return an SQL NULL. This is useful because it means
51725       ** we can invoke OP_Column to fill in the vdbe cursors type 
51726       ** and offset cache without causing any IO.
51727       */
51728       sqlite3VdbeChangeP2(v, flags ? 4 : 2, pTab->nCol+1);
51729       sqlite3VdbeChangeP2(v, 8, pTab->nCol);
51730       if( !db->mallocFailed ){
51731         sqlite3VdbeMakeReady(v, 1, 1, 1, 0);
51732       }
51733     }
51734    
51735     sqlite3BtreeLeaveAll(db);
51736     rc = sqlite3SafetyOff(db);
51737     if( rc!=SQLITE_OK || db->mallocFailed ){
51738       goto blob_open_out;
51739     }
51740
51741     sqlite3_bind_int64((sqlite3_stmt *)v, 1, iRow);
51742     rc = sqlite3_step((sqlite3_stmt *)v);
51743     if( rc!=SQLITE_ROW ){
51744       nAttempt++;
51745       rc = sqlite3_finalize((sqlite3_stmt *)v);
51746       sqlite3_snprintf(sizeof(zErr), zErr, sqlite3_errmsg(db));
51747       v = 0;
51748     }
51749   } while( nAttempt<5 && rc==SQLITE_SCHEMA );
51750
51751   if( rc==SQLITE_ROW ){
51752     /* The row-record has been opened successfully. Check that the
51753     ** column in question contains text or a blob. If it contains
51754     ** text, it is up to the caller to get the encoding right.
51755     */
51756     Incrblob *pBlob;
51757     u32 type = v->apCsr[0]->aType[iCol];
51758
51759     if( type<12 ){
51760       sqlite3_snprintf(sizeof(zErr), zErr, "cannot open value of type %s",
51761           type==0?"null": type==7?"real": "integer"
51762       );
51763       rc = SQLITE_ERROR;
51764       goto blob_open_out;
51765     }
51766     pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
51767     if( db->mallocFailed ){
51768       sqlite3DbFree(db, pBlob);
51769       goto blob_open_out;
51770     }
51771     pBlob->flags = flags;
51772     pBlob->pCsr =  v->apCsr[0]->pCursor;
51773     sqlite3BtreeEnterCursor(pBlob->pCsr);
51774     sqlite3BtreeCacheOverflow(pBlob->pCsr);
51775     sqlite3BtreeLeaveCursor(pBlob->pCsr);
51776     pBlob->pStmt = (sqlite3_stmt *)v;
51777     pBlob->iOffset = v->apCsr[0]->aOffset[iCol];
51778     pBlob->nByte = sqlite3VdbeSerialTypeLen(type);
51779     pBlob->db = db;
51780     *ppBlob = (sqlite3_blob *)pBlob;
51781     rc = SQLITE_OK;
51782   }else if( rc==SQLITE_OK ){
51783     sqlite3_snprintf(sizeof(zErr), zErr, "no such rowid: %lld", iRow);
51784     rc = SQLITE_ERROR;
51785   }
51786
51787 blob_open_out:
51788   zErr[sizeof(zErr)-1] = '\0';
51789   if( rc!=SQLITE_OK || db->mallocFailed ){
51790     sqlite3_finalize((sqlite3_stmt *)v);
51791   }
51792   sqlite3Error(db, rc, (rc==SQLITE_OK?0:zErr));
51793   rc = sqlite3ApiExit(db, rc);
51794   sqlite3_mutex_leave(db->mutex);
51795   return rc;
51796 }
51797
51798 /*
51799 ** Close a blob handle that was previously created using
51800 ** sqlite3_blob_open().
51801 */
51802 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
51803   Incrblob *p = (Incrblob *)pBlob;
51804   int rc;
51805
51806   rc = sqlite3_finalize(p->pStmt);
51807   sqlite3DbFree(p->db, p);
51808   return rc;
51809 }
51810
51811 /*
51812 ** Perform a read or write operation on a blob
51813 */
51814 static int blobReadWrite(
51815   sqlite3_blob *pBlob, 
51816   void *z, 
51817   int n, 
51818   int iOffset, 
51819   int (*xCall)(BtCursor*, u32, u32, void*)
51820 ){
51821   int rc;
51822   Incrblob *p = (Incrblob *)pBlob;
51823   Vdbe *v;
51824   sqlite3 *db = p->db;  
51825
51826   sqlite3_mutex_enter(db->mutex);
51827   v = (Vdbe*)p->pStmt;
51828
51829   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
51830     /* Request is out of range. Return a transient error. */
51831     rc = SQLITE_ERROR;
51832     sqlite3Error(db, SQLITE_ERROR, 0);
51833   } else if( v==0 ){
51834     /* If there is no statement handle, then the blob-handle has
51835     ** already been invalidated. Return SQLITE_ABORT in this case.
51836     */
51837     rc = SQLITE_ABORT;
51838   }else{
51839     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
51840     ** returned, clean-up the statement handle.
51841     */
51842     assert( db == v->db );
51843     sqlite3BtreeEnterCursor(p->pCsr);
51844     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
51845     sqlite3BtreeLeaveCursor(p->pCsr);
51846     if( rc==SQLITE_ABORT ){
51847       sqlite3VdbeFinalize(v);
51848       p->pStmt = 0;
51849     }else{
51850       db->errCode = rc;
51851       v->rc = rc;
51852     }
51853   }
51854   rc = sqlite3ApiExit(db, rc);
51855   sqlite3_mutex_leave(db->mutex);
51856   return rc;
51857 }
51858
51859 /*
51860 ** Read data from a blob handle.
51861 */
51862 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
51863   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
51864 }
51865
51866 /*
51867 ** Write data to a blob handle.
51868 */
51869 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
51870   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
51871 }
51872
51873 /*
51874 ** Query a blob handle for the size of the data.
51875 **
51876 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
51877 ** so no mutex is required for access.
51878 */
51879 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
51880   Incrblob *p = (Incrblob *)pBlob;
51881   return p->nByte;
51882 }
51883
51884 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
51885
51886 /************** End of vdbeblob.c ********************************************/
51887 /************** Begin file journal.c *****************************************/
51888 /*
51889 ** 2007 August 22
51890 **
51891 ** The author disclaims copyright to this source code.  In place of
51892 ** a legal notice, here is a blessing:
51893 **
51894 **    May you do good and not evil.
51895 **    May you find forgiveness for yourself and forgive others.
51896 **    May you share freely, never taking more than you give.
51897 **
51898 *************************************************************************
51899 **
51900 ** @(#) $Id: journal.c,v 1.8 2008/05/01 18:01:47 drh Exp $
51901 */
51902
51903 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
51904
51905 /*
51906 ** This file implements a special kind of sqlite3_file object used
51907 ** by SQLite to create journal files if the atomic-write optimization
51908 ** is enabled.
51909 **
51910 ** The distinctive characteristic of this sqlite3_file is that the
51911 ** actual on disk file is created lazily. When the file is created,
51912 ** the caller specifies a buffer size for an in-memory buffer to
51913 ** be used to service read() and write() requests. The actual file
51914 ** on disk is not created or populated until either:
51915 **
51916 **   1) The in-memory representation grows too large for the allocated 
51917 **      buffer, or
51918 **   2) The xSync() method is called.
51919 */
51920
51921
51922
51923 /*
51924 ** A JournalFile object is a subclass of sqlite3_file used by
51925 ** as an open file handle for journal files.
51926 */
51927 struct JournalFile {
51928   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
51929   int nBuf;                       /* Size of zBuf[] in bytes */
51930   char *zBuf;                     /* Space to buffer journal writes */
51931   int iSize;                      /* Amount of zBuf[] currently used */
51932   int flags;                      /* xOpen flags */
51933   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
51934   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
51935   const char *zJournal;           /* Name of the journal file */
51936 };
51937 typedef struct JournalFile JournalFile;
51938
51939 /*
51940 ** If it does not already exists, create and populate the on-disk file 
51941 ** for JournalFile p.
51942 */
51943 static int createFile(JournalFile *p){
51944   int rc = SQLITE_OK;
51945   if( !p->pReal ){
51946     sqlite3_file *pReal = (sqlite3_file *)&p[1];
51947     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
51948     if( rc==SQLITE_OK ){
51949       p->pReal = pReal;
51950       if( p->iSize>0 ){
51951         assert(p->iSize<=p->nBuf);
51952         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
51953       }
51954     }
51955   }
51956   return rc;
51957 }
51958
51959 /*
51960 ** Close the file.
51961 */
51962 static int jrnlClose(sqlite3_file *pJfd){
51963   JournalFile *p = (JournalFile *)pJfd;
51964   if( p->pReal ){
51965     sqlite3OsClose(p->pReal);
51966   }
51967   sqlite3_free(p->zBuf);
51968   return SQLITE_OK;
51969 }
51970
51971 /*
51972 ** Read data from the file.
51973 */
51974 static int jrnlRead(
51975   sqlite3_file *pJfd,    /* The journal file from which to read */
51976   void *zBuf,            /* Put the results here */
51977   int iAmt,              /* Number of bytes to read */
51978   sqlite_int64 iOfst     /* Begin reading at this offset */
51979 ){
51980   int rc = SQLITE_OK;
51981   JournalFile *p = (JournalFile *)pJfd;
51982   if( p->pReal ){
51983     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
51984   }else{
51985     assert( iAmt+iOfst<=p->iSize );
51986     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
51987   }
51988   return rc;
51989 }
51990
51991 /*
51992 ** Write data to the file.
51993 */
51994 static int jrnlWrite(
51995   sqlite3_file *pJfd,    /* The journal file into which to write */
51996   const void *zBuf,      /* Take data to be written from here */
51997   int iAmt,              /* Number of bytes to write */
51998   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
51999 ){
52000   int rc = SQLITE_OK;
52001   JournalFile *p = (JournalFile *)pJfd;
52002   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
52003     rc = createFile(p);
52004   }
52005   if( rc==SQLITE_OK ){
52006     if( p->pReal ){
52007       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
52008     }else{
52009       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
52010       if( p->iSize<(iOfst+iAmt) ){
52011         p->iSize = (iOfst+iAmt);
52012       }
52013     }
52014   }
52015   return rc;
52016 }
52017
52018 /*
52019 ** Truncate the file.
52020 */
52021 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
52022   int rc = SQLITE_OK;
52023   JournalFile *p = (JournalFile *)pJfd;
52024   if( p->pReal ){
52025     rc = sqlite3OsTruncate(p->pReal, size);
52026   }else if( size<p->iSize ){
52027     p->iSize = size;
52028   }
52029   return rc;
52030 }
52031
52032 /*
52033 ** Sync the file.
52034 */
52035 static int jrnlSync(sqlite3_file *pJfd, int flags){
52036   int rc;
52037   JournalFile *p = (JournalFile *)pJfd;
52038   if( p->pReal ){
52039     rc = sqlite3OsSync(p->pReal, flags);
52040   }else{
52041     rc = SQLITE_OK;
52042   }
52043   return rc;
52044 }
52045
52046 /*
52047 ** Query the size of the file in bytes.
52048 */
52049 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
52050   int rc = SQLITE_OK;
52051   JournalFile *p = (JournalFile *)pJfd;
52052   if( p->pReal ){
52053     rc = sqlite3OsFileSize(p->pReal, pSize);
52054   }else{
52055     *pSize = (sqlite_int64) p->iSize;
52056   }
52057   return rc;
52058 }
52059
52060 /*
52061 ** Table of methods for JournalFile sqlite3_file object.
52062 */
52063 static struct sqlite3_io_methods JournalFileMethods = {
52064   1,             /* iVersion */
52065   jrnlClose,     /* xClose */
52066   jrnlRead,      /* xRead */
52067   jrnlWrite,     /* xWrite */
52068   jrnlTruncate,  /* xTruncate */
52069   jrnlSync,      /* xSync */
52070   jrnlFileSize,  /* xFileSize */
52071   0,             /* xLock */
52072   0,             /* xUnlock */
52073   0,             /* xCheckReservedLock */
52074   0,             /* xFileControl */
52075   0,             /* xSectorSize */
52076   0              /* xDeviceCharacteristics */
52077 };
52078
52079 /* 
52080 ** Open a journal file.
52081 */
52082 SQLITE_PRIVATE int sqlite3JournalOpen(
52083   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
52084   const char *zName,         /* Name of the journal file */
52085   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
52086   int flags,                 /* Opening flags */
52087   int nBuf                   /* Bytes buffered before opening the file */
52088 ){
52089   JournalFile *p = (JournalFile *)pJfd;
52090   memset(p, 0, sqlite3JournalSize(pVfs));
52091   if( nBuf>0 ){
52092     p->zBuf = sqlite3MallocZero(nBuf);
52093     if( !p->zBuf ){
52094       return SQLITE_NOMEM;
52095     }
52096   }else{
52097     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
52098   }
52099   p->pMethod = &JournalFileMethods;
52100   p->nBuf = nBuf;
52101   p->flags = flags;
52102   p->zJournal = zName;
52103   p->pVfs = pVfs;
52104   return SQLITE_OK;
52105 }
52106
52107 /*
52108 ** If the argument p points to a JournalFile structure, and the underlying
52109 ** file has not yet been created, create it now.
52110 */
52111 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
52112   if( p->pMethods!=&JournalFileMethods ){
52113     return SQLITE_OK;
52114   }
52115   return createFile((JournalFile *)p);
52116 }
52117
52118 /* 
52119 ** Return the number of bytes required to store a JournalFile that uses vfs
52120 ** pVfs to create the underlying on-disk files.
52121 */
52122 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
52123   return (pVfs->szOsFile+sizeof(JournalFile));
52124 }
52125 #endif
52126
52127 /************** End of journal.c *********************************************/
52128 /************** Begin file memjournal.c **************************************/
52129 /*
52130 ** 2008 October 7
52131 **
52132 ** The author disclaims copyright to this source code.  In place of
52133 ** a legal notice, here is a blessing:
52134 **
52135 **    May you do good and not evil.
52136 **    May you find forgiveness for yourself and forgive others.
52137 **    May you share freely, never taking more than you give.
52138 **
52139 *************************************************************************
52140 **
52141 ** This file contains code use to implement an in-memory rollback journal.
52142 ** The in-memory rollback journal is used to journal transactions for
52143 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
52144 **
52145 ** @(#) $Id: memjournal.c,v 1.5 2008/11/19 16:52:44 danielk1977 Exp $
52146 */
52147
52148 /* Forward references to internal structures */
52149 typedef struct MemJournal MemJournal;
52150 typedef struct FilePoint FilePoint;
52151 typedef struct FileChunk FileChunk;
52152
52153 /* Space to hold the rollback journal is allocated in increments of
52154 ** this many bytes.
52155 */
52156 #define JOURNAL_CHUNKSIZE 1024
52157
52158 /* Macro to find the minimum of two numeric values.
52159 */
52160 #ifndef MIN
52161 # define MIN(x,y) ((x)<(y)?(x):(y))
52162 #endif
52163
52164 /*
52165 ** The rollback journal is composed of a linked list of these structures.
52166 */
52167 struct FileChunk {
52168   FileChunk *pNext;               /* Next chunk in the journal */
52169   u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
52170 };
52171
52172 /*
52173 ** An instance of this object serves as a cursor into the rollback journal.
52174 ** The cursor can be either for reading or writing.
52175 */
52176 struct FilePoint {
52177   sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
52178   FileChunk *pChunk;              /* Specific chunk into which cursor points */
52179 };
52180
52181 /*
52182 ** This subclass is a subclass of sqlite3_file.  Each open memory-journal
52183 ** is an instance of this class.
52184 */
52185 struct MemJournal {
52186   sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
52187   FileChunk *pFirst;              /* Head of in-memory chunk-list */
52188   FilePoint endpoint;             /* Pointer to the end of the file */
52189   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
52190 };
52191
52192 /*
52193 ** Read data from the file.
52194 */
52195 static int memjrnlRead(
52196   sqlite3_file *pJfd,    /* The journal file from which to read */
52197   void *zBuf,            /* Put the results here */
52198   int iAmt,              /* Number of bytes to read */
52199   sqlite_int64 iOfst     /* Begin reading at this offset */
52200 ){
52201   MemJournal *p = (MemJournal *)pJfd;
52202   u8 *zOut = zBuf;
52203   int nRead = iAmt;
52204   int iChunkOffset;
52205   FileChunk *pChunk;
52206
52207   assert( iOfst+iAmt<=p->endpoint.iOffset );
52208
52209   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
52210     sqlite3_int64 iOff = 0;
52211     for(pChunk=p->pFirst; 
52212         pChunk && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
52213         pChunk=pChunk->pNext
52214     ){
52215       iOff += JOURNAL_CHUNKSIZE;
52216     }
52217   }else{
52218     pChunk = p->readpoint.pChunk;
52219   }
52220
52221   iChunkOffset = (iOfst%JOURNAL_CHUNKSIZE);
52222   do {
52223     int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
52224     int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
52225     memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
52226     zOut += nCopy;
52227     nRead -= iSpace;
52228     iChunkOffset = 0;
52229   } while( nRead>=0 && (pChunk=pChunk->pNext) && nRead>0 );
52230   p->readpoint.iOffset = iOfst+iAmt;
52231   p->readpoint.pChunk = pChunk;
52232
52233   return SQLITE_OK;
52234 }
52235
52236 /*
52237 ** Write data to the file.
52238 */
52239 static int memjrnlWrite(
52240   sqlite3_file *pJfd,    /* The journal file into which to write */
52241   const void *zBuf,      /* Take data to be written from here */
52242   int iAmt,              /* Number of bytes to write */
52243   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
52244 ){
52245   MemJournal *p = (MemJournal *)pJfd;
52246   int nWrite = iAmt;
52247   u8 *zWrite = (u8 *)zBuf;
52248
52249   /* An in-memory journal file should only ever be appended to. Random
52250   ** access writes are not required by sqlite.
52251   */
52252   assert(iOfst==p->endpoint.iOffset);
52253   UNUSED_PARAMETER(iOfst);
52254
52255   while( nWrite>0 ){
52256     FileChunk *pChunk = p->endpoint.pChunk;
52257     int iChunkOffset = p->endpoint.iOffset%JOURNAL_CHUNKSIZE;
52258     int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
52259
52260     if( iChunkOffset==0 ){
52261       /* New chunk is required to extend the file. */
52262       FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
52263       if( !pNew ){
52264         return SQLITE_IOERR_NOMEM;
52265       }
52266       pNew->pNext = 0;
52267       if( pChunk ){
52268         assert( p->pFirst );
52269         pChunk->pNext = pNew;
52270       }else{
52271         assert( !p->pFirst );
52272         p->pFirst = pNew;
52273       }
52274       p->endpoint.pChunk = pNew;
52275     }
52276
52277     memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
52278     zWrite += iSpace;
52279     nWrite -= iSpace;
52280     p->endpoint.iOffset += iSpace;
52281   }
52282
52283   return SQLITE_OK;
52284 }
52285
52286 /*
52287 ** Truncate the file.
52288 */
52289 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
52290   MemJournal *p = (MemJournal *)pJfd;
52291   FileChunk *pChunk;
52292   assert(size==0);
52293   UNUSED_PARAMETER(size);
52294   pChunk = p->pFirst;
52295   while( pChunk ){
52296     FileChunk *pTmp = pChunk;
52297     pChunk = pChunk->pNext;
52298     sqlite3_free(pTmp);
52299   }
52300   sqlite3MemJournalOpen(pJfd);
52301   return SQLITE_OK;
52302 }
52303
52304 /*
52305 ** Close the file.
52306 */
52307 static int memjrnlClose(sqlite3_file *pJfd){
52308   memjrnlTruncate(pJfd, 0);
52309   return SQLITE_OK;
52310 }
52311
52312
52313 /*
52314 ** Sync the file.
52315 */
52316 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
52317   UNUSED_PARAMETER2(NotUsed, NotUsed2);
52318   return SQLITE_OK;
52319 }
52320
52321 /*
52322 ** Query the size of the file in bytes.
52323 */
52324 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
52325   MemJournal *p = (MemJournal *)pJfd;
52326   *pSize = (sqlite_int64) p->endpoint.iOffset;
52327   return SQLITE_OK;
52328 }
52329
52330 /*
52331 ** Table of methods for MemJournal sqlite3_file object.
52332 */
52333 static struct sqlite3_io_methods MemJournalMethods = {
52334   1,                /* iVersion */
52335   memjrnlClose,     /* xClose */
52336   memjrnlRead,      /* xRead */
52337   memjrnlWrite,     /* xWrite */
52338   memjrnlTruncate,  /* xTruncate */
52339   memjrnlSync,      /* xSync */
52340   memjrnlFileSize,  /* xFileSize */
52341   0,                /* xLock */
52342   0,                /* xUnlock */
52343   0,                /* xCheckReservedLock */
52344   0,                /* xFileControl */
52345   0,                /* xSectorSize */
52346   0                 /* xDeviceCharacteristics */
52347 };
52348
52349 /* 
52350 ** Open a journal file.
52351 */
52352 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
52353   MemJournal *p = (MemJournal *)pJfd;
52354   memset(p, 0, sqlite3MemJournalSize());
52355   p->pMethod = &MemJournalMethods;
52356 }
52357
52358 /*
52359 ** Return true if the file-handle passed as an argument is 
52360 ** an in-memory journal 
52361 */
52362 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
52363   return pJfd->pMethods==&MemJournalMethods;
52364 }
52365
52366 /* 
52367 ** Return the number of bytes required to store a MemJournal that uses vfs
52368 ** pVfs to create the underlying on-disk files.
52369 */
52370 SQLITE_PRIVATE int sqlite3MemJournalSize(){
52371   return sizeof(MemJournal);
52372 }
52373
52374 /************** End of memjournal.c ******************************************/
52375 /************** Begin file walker.c ******************************************/
52376 /*
52377 ** 2008 August 16
52378 **
52379 ** The author disclaims copyright to this source code.  In place of
52380 ** a legal notice, here is a blessing:
52381 **
52382 **    May you do good and not evil.
52383 **    May you find forgiveness for yourself and forgive others.
52384 **    May you share freely, never taking more than you give.
52385 **
52386 *************************************************************************
52387 ** This file contains routines used for walking the parser tree for
52388 ** an SQL statement.
52389 **
52390 ** $Id: walker.c,v 1.1 2008/08/20 16:35:10 drh Exp $
52391 */
52392
52393
52394 /*
52395 ** Walk an expression tree.  Invoke the callback once for each node
52396 ** of the expression, while decending.  (In other words, the callback
52397 ** is invoked before visiting children.)
52398 **
52399 ** The return value from the callback should be one of the WRC_*
52400 ** constants to specify how to proceed with the walk.
52401 **
52402 **    WRC_Continue      Continue descending down the tree.
52403 **
52404 **    WRC_Prune         Do not descend into child nodes.  But allow
52405 **                      the walk to continue with sibling nodes.
52406 **
52407 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
52408 **                      return the top-level walk call.
52409 **
52410 ** The return value from this routine is WRC_Abort to abandon the tree walk
52411 ** and WRC_Continue to continue.
52412 */
52413 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
52414   int rc;
52415   if( pExpr==0 ) return WRC_Continue;
52416   rc = pWalker->xExprCallback(pWalker, pExpr);
52417   if( rc==WRC_Continue ){
52418     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
52419     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
52420     if( sqlite3WalkExprList(pWalker, pExpr->pList) ) return WRC_Abort;
52421     if( sqlite3WalkSelect(pWalker, pExpr->pSelect) ){
52422       return WRC_Abort;
52423     }
52424   }
52425   return rc & WRC_Abort;
52426 }
52427
52428 /*
52429 ** Call sqlite3WalkExpr() for every expression in list p or until
52430 ** an abort request is seen.
52431 */
52432 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
52433   int i, rc = WRC_Continue;
52434   struct ExprList_item *pItem;
52435   if( p ){
52436     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
52437       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
52438     }
52439   }
52440   return rc & WRC_Continue;
52441 }
52442
52443 /*
52444 ** Walk all expressions associated with SELECT statement p.  Do
52445 ** not invoke the SELECT callback on p, but do (of course) invoke
52446 ** any expr callbacks and SELECT callbacks that come from subqueries.
52447 ** Return WRC_Abort or WRC_Continue.
52448 */
52449 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
52450   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
52451   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
52452   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
52453   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
52454   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
52455   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
52456   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
52457   return WRC_Continue;
52458 }
52459
52460 /*
52461 ** Walk the parse trees associated with all subqueries in the
52462 ** FROM clause of SELECT statement p.  Do not invoke the select
52463 ** callback on p, but do invoke it on each FROM clause subquery
52464 ** and on any subqueries further down in the tree.  Return 
52465 ** WRC_Abort or WRC_Continue;
52466 */
52467 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
52468   SrcList *pSrc;
52469   int i;
52470   struct SrcList_item *pItem;
52471
52472   pSrc = p->pSrc;
52473   if( pSrc ){
52474     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
52475       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
52476         return WRC_Abort;
52477       }
52478     }
52479   }
52480   return WRC_Continue;
52481
52482
52483 /*
52484 ** Call sqlite3WalkExpr() for every expression in Select statement p.
52485 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
52486 ** on the compound select chain, p->pPrior.
52487 **
52488 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
52489 ** there is an abort request.
52490 **
52491 ** If the Walker does not have an xSelectCallback() then this routine
52492 ** is a no-op returning WRC_Continue.
52493 */
52494 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
52495   int rc;
52496   if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
52497   rc = WRC_Continue;
52498   while( p  ){
52499     rc = pWalker->xSelectCallback(pWalker, p);
52500     if( rc ) break;
52501     if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
52502     if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
52503     p = p->pPrior;
52504   }
52505   return rc & WRC_Abort;
52506 }
52507
52508 /************** End of walker.c **********************************************/
52509 /************** Begin file resolve.c *****************************************/
52510 /*
52511 ** 2008 August 18
52512 **
52513 ** The author disclaims copyright to this source code.  In place of
52514 ** a legal notice, here is a blessing:
52515 **
52516 **    May you do good and not evil.
52517 **    May you find forgiveness for yourself and forgive others.
52518 **    May you share freely, never taking more than you give.
52519 **
52520 *************************************************************************
52521 **
52522 ** This file contains routines used for walking the parser tree and
52523 ** resolve all identifiers by associating them with a particular
52524 ** table and column.
52525 **
52526 ** $Id: resolve.c,v 1.11 2008/11/17 19:18:55 danielk1977 Exp $
52527 */
52528
52529 /*
52530 ** Turn the pExpr expression into an alias for the iCol-th column of the
52531 ** result set in pEList.
52532 **
52533 ** If the result set column is a simple column reference, then this routine
52534 ** makes an exact copy.  But for any other kind of expression, this
52535 ** routine make a copy of the result set column as the argument to the
52536 ** TK_AS operator.  The TK_AS operator causes the expression to be
52537 ** evaluated just once and then reused for each alias.
52538 **
52539 ** The reason for suppressing the TK_AS term when the expression is a simple
52540 ** column reference is so that the column reference will be recognized as
52541 ** usable by indices within the WHERE clause processing logic. 
52542 **
52543 ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
52544 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
52545 **
52546 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
52547 **
52548 ** Is equivalent to:
52549 **
52550 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
52551 **
52552 ** The result of random()%5 in the GROUP BY clause is probably different
52553 ** from the result in the result-set.  We might fix this someday.  Or
52554 ** then again, we might not...
52555 */
52556 static void resolveAlias(
52557   Parse *pParse,         /* Parsing context */
52558   ExprList *pEList,      /* A result set */
52559   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
52560   Expr *pExpr,           /* Transform this into an alias to the result set */
52561   const char *zType      /* "GROUP" or "ORDER" or "" */
52562 ){
52563   Expr *pOrig;           /* The iCol-th column of the result set */
52564   Expr *pDup;            /* Copy of pOrig */
52565   sqlite3 *db;           /* The database connection */
52566
52567   assert( iCol>=0 && iCol<pEList->nExpr );
52568   pOrig = pEList->a[iCol].pExpr;
52569   assert( pOrig!=0 );
52570   assert( pOrig->flags & EP_Resolved );
52571   db = pParse->db;
52572   pDup = sqlite3ExprDup(db, pOrig);
52573   if( pDup==0 ) return;
52574   if( pDup->op!=TK_COLUMN && zType[0]!='G' ){
52575     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
52576     if( pDup==0 ) return;
52577     if( pEList->a[iCol].iAlias==0 ){
52578       pEList->a[iCol].iAlias = ++pParse->nAlias;
52579     }
52580     pDup->iTable = pEList->a[iCol].iAlias;
52581   }
52582   if( pExpr->flags & EP_ExpCollate ){
52583     pDup->pColl = pExpr->pColl;
52584     pDup->flags |= EP_ExpCollate;
52585   }
52586   sqlite3ExprClear(db, pExpr);
52587   memcpy(pExpr, pDup, sizeof(*pExpr));
52588   sqlite3DbFree(db, pDup);
52589 }
52590
52591 /*
52592 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
52593 ** that name in the set of source tables in pSrcList and make the pExpr 
52594 ** expression node refer back to that source column.  The following changes
52595 ** are made to pExpr:
52596 **
52597 **    pExpr->iDb           Set the index in db->aDb[] of the database X
52598 **                         (even if X is implied).
52599 **    pExpr->iTable        Set to the cursor number for the table obtained
52600 **                         from pSrcList.
52601 **    pExpr->pTab          Points to the Table structure of X.Y (even if
52602 **                         X and/or Y are implied.)
52603 **    pExpr->iColumn       Set to the column number within the table.
52604 **    pExpr->op            Set to TK_COLUMN.
52605 **    pExpr->pLeft         Any expression this points to is deleted
52606 **    pExpr->pRight        Any expression this points to is deleted.
52607 **
52608 ** The pDbToken is the name of the database (the "X").  This value may be
52609 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
52610 ** can be used.  The pTableToken is the name of the table (the "Y").  This
52611 ** value can be NULL if pDbToken is also NULL.  If pTableToken is NULL it
52612 ** means that the form of the name is Z and that columns from any table
52613 ** can be used.
52614 **
52615 ** If the name cannot be resolved unambiguously, leave an error message
52616 ** in pParse and return non-zero.  Return zero on success.
52617 */
52618 static int lookupName(
52619   Parse *pParse,       /* The parsing context */
52620   Token *pDbToken,     /* Name of the database containing table, or NULL */
52621   Token *pTableToken,  /* Name of table containing column, or NULL */
52622   Token *pColumnToken, /* Name of the column. */
52623   NameContext *pNC,    /* The name context used to resolve the name */
52624   Expr *pExpr          /* Make this EXPR node point to the selected column */
52625 ){
52626   char *zDb = 0;       /* Name of the database.  The "X" in X.Y.Z */
52627   char *zTab = 0;      /* Name of the table.  The "Y" in X.Y.Z or Y.Z */
52628   char *zCol = 0;      /* Name of the column.  The "Z" */
52629   int i, j;            /* Loop counters */
52630   int cnt = 0;                      /* Number of matching column names */
52631   int cntTab = 0;                   /* Number of matching table names */
52632   sqlite3 *db = pParse->db;         /* The database connection */
52633   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
52634   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
52635   NameContext *pTopNC = pNC;        /* First namecontext in the list */
52636   Schema *pSchema = 0;              /* Schema of the expression */
52637
52638   assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
52639
52640   /* Dequote and zero-terminate the names */
52641   zDb = sqlite3NameFromToken(db, pDbToken);
52642   zTab = sqlite3NameFromToken(db, pTableToken);
52643   zCol = sqlite3NameFromToken(db, pColumnToken);
52644   if( db->mallocFailed ){
52645     goto lookupname_end;
52646   }
52647
52648   /* Initialize the node to no-match */
52649   pExpr->iTable = -1;
52650   pExpr->pTab = 0;
52651
52652   /* Start at the inner-most context and move outward until a match is found */
52653   while( pNC && cnt==0 ){
52654     ExprList *pEList;
52655     SrcList *pSrcList = pNC->pSrcList;
52656
52657     if( pSrcList ){
52658       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
52659         Table *pTab;
52660         int iDb;
52661         Column *pCol;
52662   
52663         pTab = pItem->pTab;
52664         assert( pTab!=0 && pTab->zName!=0 );
52665         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
52666         assert( pTab->nCol>0 );
52667         if( zTab ){
52668           if( pItem->zAlias ){
52669             char *zTabName = pItem->zAlias;
52670             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
52671           }else{
52672             char *zTabName = pTab->zName;
52673             if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
52674             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
52675               continue;
52676             }
52677           }
52678         }
52679         if( 0==(cntTab++) ){
52680           pExpr->iTable = pItem->iCursor;
52681           pExpr->pTab = pTab;
52682           pSchema = pTab->pSchema;
52683           pMatch = pItem;
52684         }
52685         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
52686           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
52687             IdList *pUsing;
52688             cnt++;
52689             pExpr->iTable = pItem->iCursor;
52690             pExpr->pTab = pTab;
52691             pMatch = pItem;
52692             pSchema = pTab->pSchema;
52693             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
52694             pExpr->iColumn = j==pTab->iPKey ? -1 : j;
52695             if( i<pSrcList->nSrc-1 ){
52696               if( pItem[1].jointype & JT_NATURAL ){
52697                 /* If this match occurred in the left table of a natural join,
52698                 ** then skip the right table to avoid a duplicate match */
52699                 pItem++;
52700                 i++;
52701               }else if( (pUsing = pItem[1].pUsing)!=0 ){
52702                 /* If this match occurs on a column that is in the USING clause
52703                 ** of a join, skip the search of the right table of the join
52704                 ** to avoid a duplicate match there. */
52705                 int k;
52706                 for(k=0; k<pUsing->nId; k++){
52707                   if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
52708                     pItem++;
52709                     i++;
52710                     break;
52711                   }
52712                 }
52713               }
52714             }
52715             break;
52716           }
52717         }
52718       }
52719     }
52720
52721 #ifndef SQLITE_OMIT_TRIGGER
52722     /* If we have not already resolved the name, then maybe 
52723     ** it is a new.* or old.* trigger argument reference
52724     */
52725     if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
52726       TriggerStack *pTriggerStack = pParse->trigStack;
52727       Table *pTab = 0;
52728       u32 *piColMask;
52729       if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
52730         pExpr->iTable = pTriggerStack->newIdx;
52731         assert( pTriggerStack->pTab );
52732         pTab = pTriggerStack->pTab;
52733         piColMask = &(pTriggerStack->newColMask);
52734       }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
52735         pExpr->iTable = pTriggerStack->oldIdx;
52736         assert( pTriggerStack->pTab );
52737         pTab = pTriggerStack->pTab;
52738         piColMask = &(pTriggerStack->oldColMask);
52739       }
52740
52741       if( pTab ){ 
52742         int iCol;
52743         Column *pCol = pTab->aCol;
52744
52745         pSchema = pTab->pSchema;
52746         cntTab++;
52747         for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) {
52748           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
52749             cnt++;
52750             pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
52751             pExpr->pTab = pTab;
52752             if( iCol>=0 ){
52753               testcase( iCol==31 );
52754               testcase( iCol==32 );
52755               *piColMask |= ((u32)1<<iCol) | (iCol>=32?0xffffffff:0);
52756             }
52757             break;
52758           }
52759         }
52760       }
52761     }
52762 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
52763
52764     /*
52765     ** Perhaps the name is a reference to the ROWID
52766     */
52767     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
52768       cnt = 1;
52769       pExpr->iColumn = -1;
52770       pExpr->affinity = SQLITE_AFF_INTEGER;
52771     }
52772
52773     /*
52774     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
52775     ** might refer to an result-set alias.  This happens, for example, when
52776     ** we are resolving names in the WHERE clause of the following command:
52777     **
52778     **     SELECT a+b AS x FROM table WHERE x<10;
52779     **
52780     ** In cases like this, replace pExpr with a copy of the expression that
52781     ** forms the result set entry ("a+b" in the example) and return immediately.
52782     ** Note that the expression in the result set should have already been
52783     ** resolved by the time the WHERE clause is resolved.
52784     */
52785     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
52786       for(j=0; j<pEList->nExpr; j++){
52787         char *zAs = pEList->a[j].zName;
52788         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
52789           Expr *pOrig;
52790           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
52791           assert( pExpr->pList==0 );
52792           assert( pExpr->pSelect==0 );
52793           pOrig = pEList->a[j].pExpr;
52794           if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
52795             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
52796             sqlite3DbFree(db, zCol);
52797             return 2;
52798           }
52799           resolveAlias(pParse, pEList, j, pExpr, "");
52800           cnt = 1;
52801           pMatch = 0;
52802           assert( zTab==0 && zDb==0 );
52803           goto lookupname_end_2;
52804         }
52805       } 
52806     }
52807
52808     /* Advance to the next name context.  The loop will exit when either
52809     ** we have a match (cnt>0) or when we run out of name contexts.
52810     */
52811     if( cnt==0 ){
52812       pNC = pNC->pNext;
52813     }
52814   }
52815
52816   /*
52817   ** If X and Y are NULL (in other words if only the column name Z is
52818   ** supplied) and the value of Z is enclosed in double-quotes, then
52819   ** Z is a string literal if it doesn't match any column names.  In that
52820   ** case, we need to return right away and not make any changes to
52821   ** pExpr.
52822   **
52823   ** Because no reference was made to outer contexts, the pNC->nRef
52824   ** fields are not changed in any context.
52825   */
52826   if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
52827     sqlite3DbFree(db, zCol);
52828     pExpr->op = TK_STRING;
52829     pExpr->pTab = 0;
52830     return 0;
52831   }
52832
52833   /*
52834   ** cnt==0 means there was not match.  cnt>1 means there were two or
52835   ** more matches.  Either way, we have an error.
52836   */
52837   if( cnt!=1 ){
52838     const char *zErr;
52839     zErr = cnt==0 ? "no such column" : "ambiguous column name";
52840     if( zDb ){
52841       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
52842     }else if( zTab ){
52843       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
52844     }else{
52845       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
52846     }
52847     pTopNC->nErr++;
52848   }
52849
52850   /* If a column from a table in pSrcList is referenced, then record
52851   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
52852   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
52853   ** column number is greater than the number of bits in the bitmask
52854   ** then set the high-order bit of the bitmask.
52855   */
52856   if( pExpr->iColumn>=0 && pMatch!=0 ){
52857     int n = pExpr->iColumn;
52858     testcase( n==BMS-1 );
52859     if( n>=BMS ){
52860       n = BMS-1;
52861     }
52862     assert( pMatch->iCursor==pExpr->iTable );
52863     pMatch->colUsed |= ((Bitmask)1)<<n;
52864   }
52865
52866 lookupname_end:
52867   /* Clean up and return
52868   */
52869   sqlite3DbFree(db, zDb);
52870   sqlite3DbFree(db, zTab);
52871   sqlite3ExprDelete(db, pExpr->pLeft);
52872   pExpr->pLeft = 0;
52873   sqlite3ExprDelete(db, pExpr->pRight);
52874   pExpr->pRight = 0;
52875   pExpr->op = TK_COLUMN;
52876 lookupname_end_2:
52877   sqlite3DbFree(db, zCol);
52878   if( cnt==1 ){
52879     assert( pNC!=0 );
52880     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
52881     /* Increment the nRef value on all name contexts from TopNC up to
52882     ** the point where the name matched. */
52883     for(;;){
52884       assert( pTopNC!=0 );
52885       pTopNC->nRef++;
52886       if( pTopNC==pNC ) break;
52887       pTopNC = pTopNC->pNext;
52888     }
52889     return 0;
52890   } else {
52891     return 1;
52892   }
52893 }
52894
52895 /*
52896 ** This routine is callback for sqlite3WalkExpr().
52897 **
52898 ** Resolve symbolic names into TK_COLUMN operators for the current
52899 ** node in the expression tree.  Return 0 to continue the search down
52900 ** the tree or 2 to abort the tree walk.
52901 **
52902 ** This routine also does error checking and name resolution for
52903 ** function names.  The operator for aggregate functions is changed
52904 ** to TK_AGG_FUNCTION.
52905 */
52906 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
52907   NameContext *pNC;
52908   Parse *pParse;
52909
52910   pNC = pWalker->u.pNC;
52911   assert( pNC!=0 );
52912   pParse = pNC->pParse;
52913   assert( pParse==pWalker->pParse );
52914
52915   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
52916   ExprSetProperty(pExpr, EP_Resolved);
52917 #ifndef NDEBUG
52918   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
52919     SrcList *pSrcList = pNC->pSrcList;
52920     int i;
52921     for(i=0; i<pNC->pSrcList->nSrc; i++){
52922       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
52923     }
52924   }
52925 #endif
52926   switch( pExpr->op ){
52927
52928 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
52929     /* The special operator TK_ROW means use the rowid for the first
52930     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
52931     ** clause processing on UPDATE and DELETE statements.
52932     */
52933     case TK_ROW: {
52934       SrcList *pSrcList = pNC->pSrcList;
52935       struct SrcList_item *pItem;
52936       assert( pSrcList && pSrcList->nSrc==1 );
52937       pItem = pSrcList->a; 
52938       pExpr->op = TK_COLUMN;
52939       pExpr->pTab = pItem->pTab;
52940       pExpr->iTable = pItem->iCursor;
52941       pExpr->iColumn = -1;
52942       pExpr->affinity = SQLITE_AFF_INTEGER;
52943       break;
52944     }
52945 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
52946
52947     /* A lone identifier is the name of a column.
52948     */
52949     case TK_ID: {
52950       lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr);
52951       return WRC_Prune;
52952     }
52953   
52954     /* A table name and column name:     ID.ID
52955     ** Or a database, table and column:  ID.ID.ID
52956     */
52957     case TK_DOT: {
52958       Token *pColumn;
52959       Token *pTable;
52960       Token *pDb;
52961       Expr *pRight;
52962
52963       /* if( pSrcList==0 ) break; */
52964       pRight = pExpr->pRight;
52965       if( pRight->op==TK_ID ){
52966         pDb = 0;
52967         pTable = &pExpr->pLeft->token;
52968         pColumn = &pRight->token;
52969       }else{
52970         assert( pRight->op==TK_DOT );
52971         pDb = &pExpr->pLeft->token;
52972         pTable = &pRight->pLeft->token;
52973         pColumn = &pRight->pRight->token;
52974       }
52975       lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr);
52976       return WRC_Prune;
52977     }
52978
52979     /* Resolve function names
52980     */
52981     case TK_CONST_FUNC:
52982     case TK_FUNCTION: {
52983       ExprList *pList = pExpr->pList;    /* The argument list */
52984       int n = pList ? pList->nExpr : 0;  /* Number of arguments */
52985       int no_such_func = 0;       /* True if no such function exists */
52986       int wrong_num_args = 0;     /* True if wrong number of arguments */
52987       int is_agg = 0;             /* True if is an aggregate function */
52988       int auth;                   /* Authorization to use the function */
52989       int nId;                    /* Number of characters in function name */
52990       const char *zId;            /* The function name. */
52991       FuncDef *pDef;              /* Information about the function */
52992       int enc = ENC(pParse->db);  /* The database encoding */
52993
52994       zId = (char*)pExpr->token.z;
52995       nId = pExpr->token.n;
52996       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
52997       if( pDef==0 ){
52998         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
52999         if( pDef==0 ){
53000           no_such_func = 1;
53001         }else{
53002           wrong_num_args = 1;
53003         }
53004       }else{
53005         is_agg = pDef->xFunc==0;
53006       }
53007 #ifndef SQLITE_OMIT_AUTHORIZATION
53008       if( pDef ){
53009         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
53010         if( auth!=SQLITE_OK ){
53011           if( auth==SQLITE_DENY ){
53012             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
53013                                     pDef->zName);
53014             pNC->nErr++;
53015           }
53016           pExpr->op = TK_NULL;
53017           return WRC_Prune;
53018         }
53019       }
53020 #endif
53021       if( is_agg && !pNC->allowAgg ){
53022         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
53023         pNC->nErr++;
53024         is_agg = 0;
53025       }else if( no_such_func ){
53026         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
53027         pNC->nErr++;
53028       }else if( wrong_num_args ){
53029         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
53030              nId, zId);
53031         pNC->nErr++;
53032       }
53033       if( is_agg ){
53034         pExpr->op = TK_AGG_FUNCTION;
53035         pNC->hasAgg = 1;
53036       }
53037       if( is_agg ) pNC->allowAgg = 0;
53038       sqlite3WalkExprList(pWalker, pList);
53039       if( is_agg ) pNC->allowAgg = 1;
53040       /* FIX ME:  Compute pExpr->affinity based on the expected return
53041       ** type of the function 
53042       */
53043       return WRC_Prune;
53044     }
53045 #ifndef SQLITE_OMIT_SUBQUERY
53046     case TK_SELECT:
53047     case TK_EXISTS:
53048 #endif
53049     case TK_IN: {
53050       if( pExpr->pSelect ){
53051         int nRef = pNC->nRef;
53052 #ifndef SQLITE_OMIT_CHECK
53053         if( pNC->isCheck ){
53054           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
53055         }
53056 #endif
53057         sqlite3WalkSelect(pWalker, pExpr->pSelect);
53058         assert( pNC->nRef>=nRef );
53059         if( nRef!=pNC->nRef ){
53060           ExprSetProperty(pExpr, EP_VarSelect);
53061         }
53062       }
53063       break;
53064     }
53065 #ifndef SQLITE_OMIT_CHECK
53066     case TK_VARIABLE: {
53067       if( pNC->isCheck ){
53068         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
53069       }
53070       break;
53071     }
53072 #endif
53073   }
53074   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
53075 }
53076
53077 /*
53078 ** pEList is a list of expressions which are really the result set of the
53079 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
53080 ** This routine checks to see if pE is a simple identifier which corresponds
53081 ** to the AS-name of one of the terms of the expression list.  If it is,
53082 ** this routine return an integer between 1 and N where N is the number of
53083 ** elements in pEList, corresponding to the matching entry.  If there is
53084 ** no match, or if pE is not a simple identifier, then this routine
53085 ** return 0.
53086 **
53087 ** pEList has been resolved.  pE has not.
53088 */
53089 static int resolveAsName(
53090   Parse *pParse,     /* Parsing context for error messages */
53091   ExprList *pEList,  /* List of expressions to scan */
53092   Expr *pE           /* Expression we are trying to match */
53093 ){
53094   int i;             /* Loop counter */
53095
53096   if( pE->op==TK_ID || (pE->op==TK_STRING && pE->token.z[0]!='\'') ){
53097     sqlite3 *db = pParse->db;
53098     char *zCol = sqlite3NameFromToken(db, &pE->token);
53099     if( zCol==0 ){
53100       return -1;
53101     }
53102     for(i=0; i<pEList->nExpr; i++){
53103       char *zAs = pEList->a[i].zName;
53104       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
53105         sqlite3DbFree(db, zCol);
53106         return i+1;
53107       }
53108     }
53109     sqlite3DbFree(db, zCol);
53110   }
53111   return 0;
53112 }
53113
53114 /*
53115 ** pE is a pointer to an expression which is a single term in the
53116 ** ORDER BY of a compound SELECT.  The expression has not been
53117 ** name resolved.
53118 **
53119 ** At the point this routine is called, we already know that the
53120 ** ORDER BY term is not an integer index into the result set.  That
53121 ** case is handled by the calling routine.
53122 **
53123 ** Attempt to match pE against result set columns in the left-most
53124 ** SELECT statement.  Return the index i of the matching column,
53125 ** as an indication to the caller that it should sort by the i-th column.
53126 ** The left-most column is 1.  In other words, the value returned is the
53127 ** same integer value that would be used in the SQL statement to indicate
53128 ** the column.
53129 **
53130 ** If there is no match, return 0.  Return -1 if an error occurs.
53131 */
53132 static int resolveOrderByTermToExprList(
53133   Parse *pParse,     /* Parsing context for error messages */
53134   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
53135   Expr *pE           /* The specific ORDER BY term */
53136 ){
53137   int i;             /* Loop counter */
53138   ExprList *pEList;  /* The columns of the result set */
53139   NameContext nc;    /* Name context for resolving pE */
53140
53141   assert( sqlite3ExprIsInteger(pE, &i)==0 );
53142   pEList = pSelect->pEList;
53143
53144   /* Resolve all names in the ORDER BY term expression
53145   */
53146   memset(&nc, 0, sizeof(nc));
53147   nc.pParse = pParse;
53148   nc.pSrcList = pSelect->pSrc;
53149   nc.pEList = pEList;
53150   nc.allowAgg = 1;
53151   nc.nErr = 0;
53152   if( sqlite3ResolveExprNames(&nc, pE) ){
53153     sqlite3ErrorClear(pParse);
53154     return 0;
53155   }
53156
53157   /* Try to match the ORDER BY expression against an expression
53158   ** in the result set.  Return an 1-based index of the matching
53159   ** result-set entry.
53160   */
53161   for(i=0; i<pEList->nExpr; i++){
53162     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){
53163       return i+1;
53164     }
53165   }
53166
53167   /* If no match, return 0. */
53168   return 0;
53169 }
53170
53171 /*
53172 ** Generate an ORDER BY or GROUP BY term out-of-range error.
53173 */
53174 static void resolveOutOfRangeError(
53175   Parse *pParse,         /* The error context into which to write the error */
53176   const char *zType,     /* "ORDER" or "GROUP" */
53177   int i,                 /* The index (1-based) of the term out of range */
53178   int mx                 /* Largest permissible value of i */
53179 ){
53180   sqlite3ErrorMsg(pParse, 
53181     "%r %s BY term out of range - should be "
53182     "between 1 and %d", i, zType, mx);
53183 }
53184
53185 /*
53186 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
53187 ** each term of the ORDER BY clause is a constant integer between 1
53188 ** and N where N is the number of columns in the compound SELECT.
53189 **
53190 ** ORDER BY terms that are already an integer between 1 and N are
53191 ** unmodified.  ORDER BY terms that are integers outside the range of
53192 ** 1 through N generate an error.  ORDER BY terms that are expressions
53193 ** are matched against result set expressions of compound SELECT
53194 ** beginning with the left-most SELECT and working toward the right.
53195 ** At the first match, the ORDER BY expression is transformed into
53196 ** the integer column number.
53197 **
53198 ** Return the number of errors seen.
53199 */
53200 static int resolveCompoundOrderBy(
53201   Parse *pParse,        /* Parsing context.  Leave error messages here */
53202   Select *pSelect       /* The SELECT statement containing the ORDER BY */
53203 ){
53204   int i;
53205   ExprList *pOrderBy;
53206   ExprList *pEList;
53207   sqlite3 *db;
53208   int moreToDo = 1;
53209
53210   pOrderBy = pSelect->pOrderBy;
53211   if( pOrderBy==0 ) return 0;
53212   db = pParse->db;
53213 #if SQLITE_MAX_COLUMN
53214   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
53215     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
53216     return 1;
53217   }
53218 #endif
53219   for(i=0; i<pOrderBy->nExpr; i++){
53220     pOrderBy->a[i].done = 0;
53221   }
53222   pSelect->pNext = 0;
53223   while( pSelect->pPrior ){
53224     pSelect->pPrior->pNext = pSelect;
53225     pSelect = pSelect->pPrior;
53226   }
53227   while( pSelect && moreToDo ){
53228     struct ExprList_item *pItem;
53229     moreToDo = 0;
53230     pEList = pSelect->pEList;
53231     assert( pEList!=0 );
53232     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
53233       int iCol = -1;
53234       Expr *pE, *pDup;
53235       if( pItem->done ) continue;
53236       pE = pItem->pExpr;
53237       if( sqlite3ExprIsInteger(pE, &iCol) ){
53238         if( iCol<0 || iCol>pEList->nExpr ){
53239           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
53240           return 1;
53241         }
53242       }else{
53243         iCol = resolveAsName(pParse, pEList, pE);
53244         if( iCol==0 ){
53245           pDup = sqlite3ExprDup(db, pE);
53246           if( !db->mallocFailed ){
53247             assert(pDup);
53248             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
53249           }
53250           sqlite3ExprDelete(db, pDup);
53251         }
53252         if( iCol<0 ){
53253           return 1;
53254         }
53255       }
53256       if( iCol>0 ){
53257         CollSeq *pColl = pE->pColl;
53258         int flags = pE->flags & EP_ExpCollate;
53259         sqlite3ExprDelete(db, pE);
53260         pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0, 0, 0);
53261         if( pE==0 ) return 1;
53262         pE->pColl = pColl;
53263         pE->flags |= EP_IntValue | flags;
53264         pE->iTable = iCol;
53265         pItem->iCol = iCol;
53266         pItem->done = 1;
53267       }else{
53268         moreToDo = 1;
53269       }
53270     }
53271     pSelect = pSelect->pNext;
53272   }
53273   for(i=0; i<pOrderBy->nExpr; i++){
53274     if( pOrderBy->a[i].done==0 ){
53275       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
53276             "column in the result set", i+1);
53277       return 1;
53278     }
53279   }
53280   return 0;
53281 }
53282
53283 /*
53284 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
53285 ** the SELECT statement pSelect.  If any term is reference to a
53286 ** result set expression (as determined by the ExprList.a.iCol field)
53287 ** then convert that term into a copy of the corresponding result set
53288 ** column.
53289 **
53290 ** If any errors are detected, add an error message to pParse and
53291 ** return non-zero.  Return zero if no errors are seen.
53292 */
53293 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
53294   Parse *pParse,        /* Parsing context.  Leave error messages here */
53295   Select *pSelect,      /* The SELECT statement containing the clause */
53296   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
53297   const char *zType     /* "ORDER" or "GROUP" */
53298 ){
53299   int i;
53300   sqlite3 *db = pParse->db;
53301   ExprList *pEList;
53302   struct ExprList_item *pItem;
53303
53304   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
53305 #if SQLITE_MAX_COLUMN
53306   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
53307     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
53308     return 1;
53309   }
53310 #endif
53311   pEList = pSelect->pEList;
53312   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
53313   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
53314     if( pItem->iCol ){
53315       if( pItem->iCol>pEList->nExpr ){
53316         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
53317         return 1;
53318       }
53319       resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
53320     }
53321   }
53322   return 0;
53323 }
53324
53325 /*
53326 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
53327 ** The Name context of the SELECT statement is pNC.  zType is either
53328 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
53329 **
53330 ** This routine resolves each term of the clause into an expression.
53331 ** If the order-by term is an integer I between 1 and N (where N is the
53332 ** number of columns in the result set of the SELECT) then the expression
53333 ** in the resolution is a copy of the I-th result-set expression.  If
53334 ** the order-by term is an identify that corresponds to the AS-name of
53335 ** a result-set expression, then the term resolves to a copy of the
53336 ** result-set expression.  Otherwise, the expression is resolved in
53337 ** the usual way - using sqlite3ResolveExprNames().
53338 **
53339 ** This routine returns the number of errors.  If errors occur, then
53340 ** an appropriate error message might be left in pParse.  (OOM errors
53341 ** excepted.)
53342 */
53343 static int resolveOrderGroupBy(
53344   NameContext *pNC,     /* The name context of the SELECT statement */
53345   Select *pSelect,      /* The SELECT statement holding pOrderBy */
53346   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
53347   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
53348 ){
53349   int i;                         /* Loop counter */
53350   int iCol;                      /* Column number */
53351   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
53352   Parse *pParse;                 /* Parsing context */
53353   int nResult;                   /* Number of terms in the result set */
53354
53355   if( pOrderBy==0 ) return 0;
53356   nResult = pSelect->pEList->nExpr;
53357   pParse = pNC->pParse;
53358   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
53359     Expr *pE = pItem->pExpr;
53360     iCol = resolveAsName(pParse, pSelect->pEList, pE);
53361     if( iCol<0 ){
53362       return 1;  /* OOM error */
53363     }
53364     if( iCol>0 ){
53365       /* If an AS-name match is found, mark this ORDER BY column as being
53366       ** a copy of the iCol-th result-set column.  The subsequent call to
53367       ** sqlite3ResolveOrderGroupBy() will convert the expression to a
53368       ** copy of the iCol-th result-set expression. */
53369       pItem->iCol = iCol;
53370       continue;
53371     }
53372     if( sqlite3ExprIsInteger(pE, &iCol) ){
53373       /* The ORDER BY term is an integer constant.  Again, set the column
53374       ** number so that sqlite3ResolveOrderGroupBy() will convert the
53375       ** order-by term to a copy of the result-set expression */
53376       if( iCol<1 ){
53377         resolveOutOfRangeError(pParse, zType, i+1, nResult);
53378         return 1;
53379       }
53380       pItem->iCol = iCol;
53381       continue;
53382     }
53383
53384     /* Otherwise, treat the ORDER BY term as an ordinary expression */
53385     pItem->iCol = 0;
53386     if( sqlite3ResolveExprNames(pNC, pE) ){
53387       return 1;
53388     }
53389   }
53390   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
53391 }
53392
53393 /*
53394 ** Resolve names in the SELECT statement p and all of its descendents.
53395 */
53396 static int resolveSelectStep(Walker *pWalker, Select *p){
53397   NameContext *pOuterNC;  /* Context that contains this SELECT */
53398   NameContext sNC;        /* Name context of this SELECT */
53399   int isCompound;         /* True if p is a compound select */
53400   int nCompound;          /* Number of compound terms processed so far */
53401   Parse *pParse;          /* Parsing context */
53402   ExprList *pEList;       /* Result set expression list */
53403   int i;                  /* Loop counter */
53404   ExprList *pGroupBy;     /* The GROUP BY clause */
53405   Select *pLeftmost;      /* Left-most of SELECT of a compound */
53406   sqlite3 *db;            /* Database connection */
53407   
53408
53409   assert( p!=0 );
53410   if( p->selFlags & SF_Resolved ){
53411     return WRC_Prune;
53412   }
53413   pOuterNC = pWalker->u.pNC;
53414   pParse = pWalker->pParse;
53415   db = pParse->db;
53416
53417   /* Normally sqlite3SelectExpand() will be called first and will have
53418   ** already expanded this SELECT.  However, if this is a subquery within
53419   ** an expression, sqlite3ResolveExprNames() will be called without a
53420   ** prior call to sqlite3SelectExpand().  When that happens, let
53421   ** sqlite3SelectPrep() do all of the processing for this SELECT.
53422   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
53423   ** this routine in the correct order.
53424   */
53425   if( (p->selFlags & SF_Expanded)==0 ){
53426     sqlite3SelectPrep(pParse, p, pOuterNC);
53427     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
53428   }
53429
53430   isCompound = p->pPrior!=0;
53431   nCompound = 0;
53432   pLeftmost = p;
53433   while( p ){
53434     assert( (p->selFlags & SF_Expanded)!=0 );
53435     assert( (p->selFlags & SF_Resolved)==0 );
53436     p->selFlags |= SF_Resolved;
53437
53438     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
53439     ** are not allowed to refer to any names, so pass an empty NameContext.
53440     */
53441     memset(&sNC, 0, sizeof(sNC));
53442     sNC.pParse = pParse;
53443     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
53444         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
53445       return WRC_Abort;
53446     }
53447   
53448     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
53449     ** resolve the result-set expression list.
53450     */
53451     sNC.allowAgg = 1;
53452     sNC.pSrcList = p->pSrc;
53453     sNC.pNext = pOuterNC;
53454   
53455     /* Resolve names in the result set. */
53456     pEList = p->pEList;
53457     assert( pEList!=0 );
53458     for(i=0; i<pEList->nExpr; i++){
53459       Expr *pX = pEList->a[i].pExpr;
53460       if( sqlite3ResolveExprNames(&sNC, pX) ){
53461         return WRC_Abort;
53462       }
53463     }
53464   
53465     /* Recursively resolve names in all subqueries
53466     */
53467     for(i=0; i<p->pSrc->nSrc; i++){
53468       struct SrcList_item *pItem = &p->pSrc->a[i];
53469       if( pItem->pSelect ){
53470         const char *zSavedContext = pParse->zAuthContext;
53471         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
53472         sqlite3ResolveSelectNames(pParse, pItem->pSelect, &sNC);
53473         pParse->zAuthContext = zSavedContext;
53474         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
53475       }
53476     }
53477   
53478     /* If there are no aggregate functions in the result-set, and no GROUP BY 
53479     ** expression, do not allow aggregates in any of the other expressions.
53480     */
53481     assert( (p->selFlags & SF_Aggregate)==0 );
53482     pGroupBy = p->pGroupBy;
53483     if( pGroupBy || sNC.hasAgg ){
53484       p->selFlags |= SF_Aggregate;
53485     }else{
53486       sNC.allowAgg = 0;
53487     }
53488   
53489     /* If a HAVING clause is present, then there must be a GROUP BY clause.
53490     */
53491     if( p->pHaving && !pGroupBy ){
53492       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
53493       return WRC_Abort;
53494     }
53495   
53496     /* Add the expression list to the name-context before parsing the
53497     ** other expressions in the SELECT statement. This is so that
53498     ** expressions in the WHERE clause (etc.) can refer to expressions by
53499     ** aliases in the result set.
53500     **
53501     ** Minor point: If this is the case, then the expression will be
53502     ** re-evaluated for each reference to it.
53503     */
53504     sNC.pEList = p->pEList;
53505     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
53506        sqlite3ResolveExprNames(&sNC, p->pHaving)
53507     ){
53508       return WRC_Abort;
53509     }
53510
53511     /* The ORDER BY and GROUP BY clauses may not refer to terms in
53512     ** outer queries 
53513     */
53514     sNC.pNext = 0;
53515     sNC.allowAgg = 1;
53516
53517     /* Process the ORDER BY clause for singleton SELECT statements.
53518     ** The ORDER BY clause for compounds SELECT statements is handled
53519     ** below, after all of the result-sets for all of the elements of
53520     ** the compound have been resolved.
53521     */
53522     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
53523       return WRC_Abort;
53524     }
53525     if( db->mallocFailed ){
53526       return WRC_Abort;
53527     }
53528   
53529     /* Resolve the GROUP BY clause.  At the same time, make sure 
53530     ** the GROUP BY clause does not contain aggregate functions.
53531     */
53532     if( pGroupBy ){
53533       struct ExprList_item *pItem;
53534     
53535       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
53536         return WRC_Abort;
53537       }
53538       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
53539         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
53540           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
53541               "the GROUP BY clause");
53542           return WRC_Abort;
53543         }
53544       }
53545     }
53546
53547     /* Advance to the next term of the compound
53548     */
53549     p = p->pPrior;
53550     nCompound++;
53551   }
53552
53553   /* Resolve the ORDER BY on a compound SELECT after all terms of
53554   ** the compound have been resolved.
53555   */
53556   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
53557     return WRC_Abort;
53558   }
53559
53560   return WRC_Prune;
53561 }
53562
53563 /*
53564 ** This routine walks an expression tree and resolves references to
53565 ** table columns and result-set columns.  At the same time, do error
53566 ** checking on function usage and set a flag if any aggregate functions
53567 ** are seen.
53568 **
53569 ** To resolve table columns references we look for nodes (or subtrees) of the 
53570 ** form X.Y.Z or Y.Z or just Z where
53571 **
53572 **      X:   The name of a database.  Ex:  "main" or "temp" or
53573 **           the symbolic name assigned to an ATTACH-ed database.
53574 **
53575 **      Y:   The name of a table in a FROM clause.  Or in a trigger
53576 **           one of the special names "old" or "new".
53577 **
53578 **      Z:   The name of a column in table Y.
53579 **
53580 ** The node at the root of the subtree is modified as follows:
53581 **
53582 **    Expr.op        Changed to TK_COLUMN
53583 **    Expr.pTab      Points to the Table object for X.Y
53584 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
53585 **    Expr.iTable    The VDBE cursor number for X.Y
53586 **
53587 **
53588 ** To resolve result-set references, look for expression nodes of the
53589 ** form Z (with no X and Y prefix) where the Z matches the right-hand
53590 ** size of an AS clause in the result-set of a SELECT.  The Z expression
53591 ** is replaced by a copy of the left-hand side of the result-set expression.
53592 ** Table-name and function resolution occurs on the substituted expression
53593 ** tree.  For example, in:
53594 **
53595 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
53596 **
53597 ** The "x" term of the order by is replaced by "a+b" to render:
53598 **
53599 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
53600 **
53601 ** Function calls are checked to make sure that the function is 
53602 ** defined and that the correct number of arguments are specified.
53603 ** If the function is an aggregate function, then the pNC->hasAgg is
53604 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
53605 ** If an expression contains aggregate functions then the EP_Agg
53606 ** property on the expression is set.
53607 **
53608 ** An error message is left in pParse if anything is amiss.  The number
53609 ** if errors is returned.
53610 */
53611 SQLITE_PRIVATE int sqlite3ResolveExprNames( 
53612   NameContext *pNC,       /* Namespace to resolve expressions in. */
53613   Expr *pExpr             /* The expression to be analyzed. */
53614 ){
53615   int savedHasAgg;
53616   Walker w;
53617
53618   if( pExpr==0 ) return 0;
53619 #if SQLITE_MAX_EXPR_DEPTH>0
53620   {
53621     Parse *pParse = pNC->pParse;
53622     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
53623       return 1;
53624     }
53625     pParse->nHeight += pExpr->nHeight;
53626   }
53627 #endif
53628   savedHasAgg = pNC->hasAgg;
53629   pNC->hasAgg = 0;
53630   w.xExprCallback = resolveExprStep;
53631   w.xSelectCallback = resolveSelectStep;
53632   w.pParse = pNC->pParse;
53633   w.u.pNC = pNC;
53634   sqlite3WalkExpr(&w, pExpr);
53635 #if SQLITE_MAX_EXPR_DEPTH>0
53636   pNC->pParse->nHeight -= pExpr->nHeight;
53637 #endif
53638   if( pNC->nErr>0 ){
53639     ExprSetProperty(pExpr, EP_Error);
53640   }
53641   if( pNC->hasAgg ){
53642     ExprSetProperty(pExpr, EP_Agg);
53643   }else if( savedHasAgg ){
53644     pNC->hasAgg = 1;
53645   }
53646   return ExprHasProperty(pExpr, EP_Error);
53647 }
53648
53649
53650 /*
53651 ** Resolve all names in all expressions of a SELECT and in all
53652 ** decendents of the SELECT, including compounds off of p->pPrior,
53653 ** subqueries in expressions, and subqueries used as FROM clause
53654 ** terms.
53655 **
53656 ** See sqlite3ResolveExprNames() for a description of the kinds of
53657 ** transformations that occur.
53658 **
53659 ** All SELECT statements should have been expanded using
53660 ** sqlite3SelectExpand() prior to invoking this routine.
53661 */
53662 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
53663   Parse *pParse,         /* The parser context */
53664   Select *p,             /* The SELECT statement being coded. */
53665   NameContext *pOuterNC  /* Name context for parent SELECT statement */
53666 ){
53667   Walker w;
53668
53669   assert( p!=0 );
53670   w.xExprCallback = resolveExprStep;
53671   w.xSelectCallback = resolveSelectStep;
53672   w.pParse = pParse;
53673   w.u.pNC = pOuterNC;
53674   sqlite3WalkSelect(&w, p);
53675 }
53676
53677 /************** End of resolve.c *********************************************/
53678 /************** Begin file expr.c ********************************************/
53679 /*
53680 ** 2001 September 15
53681 **
53682 ** The author disclaims copyright to this source code.  In place of
53683 ** a legal notice, here is a blessing:
53684 **
53685 **    May you do good and not evil.
53686 **    May you find forgiveness for yourself and forgive others.
53687 **    May you share freely, never taking more than you give.
53688 **
53689 *************************************************************************
53690 ** This file contains routines used for analyzing expressions and
53691 ** for generating VDBE code that evaluates expressions in SQLite.
53692 **
53693 ** $Id: expr.c,v 1.404 2008/11/19 16:52:44 danielk1977 Exp $
53694 */
53695
53696 /*
53697 ** Return the 'affinity' of the expression pExpr if any.
53698 **
53699 ** If pExpr is a column, a reference to a column via an 'AS' alias,
53700 ** or a sub-select with a column as the return value, then the 
53701 ** affinity of that column is returned. Otherwise, 0x00 is returned,
53702 ** indicating no affinity for the expression.
53703 **
53704 ** i.e. the WHERE clause expresssions in the following statements all
53705 ** have an affinity:
53706 **
53707 ** CREATE TABLE t1(a);
53708 ** SELECT * FROM t1 WHERE a;
53709 ** SELECT a AS b FROM t1 WHERE b;
53710 ** SELECT * FROM t1 WHERE (select a from t1);
53711 */
53712 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
53713   int op = pExpr->op;
53714   if( op==TK_SELECT ){
53715     return sqlite3ExprAffinity(pExpr->pSelect->pEList->a[0].pExpr);
53716   }
53717 #ifndef SQLITE_OMIT_CAST
53718   if( op==TK_CAST ){
53719     return sqlite3AffinityType(&pExpr->token);
53720   }
53721 #endif
53722   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) 
53723    && pExpr->pTab!=0
53724   ){
53725     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
53726     ** a TK_COLUMN but was previously evaluated and cached in a register */
53727     int j = pExpr->iColumn;
53728     if( j<0 ) return SQLITE_AFF_INTEGER;
53729     assert( pExpr->pTab && j<pExpr->pTab->nCol );
53730     return pExpr->pTab->aCol[j].affinity;
53731   }
53732   return pExpr->affinity;
53733 }
53734
53735 /*
53736 ** Set the collating sequence for expression pExpr to be the collating
53737 ** sequence named by pToken.   Return a pointer to the revised expression.
53738 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
53739 ** flag.  An explicit collating sequence will override implicit
53740 ** collating sequences.
53741 */
53742 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pCollName){
53743   char *zColl = 0;            /* Dequoted name of collation sequence */
53744   CollSeq *pColl;
53745   sqlite3 *db = pParse->db;
53746   zColl = sqlite3NameFromToken(db, pCollName);
53747   if( pExpr && zColl ){
53748     pColl = sqlite3LocateCollSeq(pParse, zColl, -1);
53749     if( pColl ){
53750       pExpr->pColl = pColl;
53751       pExpr->flags |= EP_ExpCollate;
53752     }
53753   }
53754   sqlite3DbFree(db, zColl);
53755   return pExpr;
53756 }
53757
53758 /*
53759 ** Return the default collation sequence for the expression pExpr. If
53760 ** there is no default collation type, return 0.
53761 */
53762 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
53763   CollSeq *pColl = 0;
53764   Expr *p = pExpr;
53765   while( p ){
53766     int op;
53767     pColl = p->pColl;
53768     if( pColl ) break;
53769     op = p->op;
53770     if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) && p->pTab!=0 ){
53771       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
53772       ** a TK_COLUMN but was previously evaluated and cached in a register */
53773       const char *zColl;
53774       int j = p->iColumn;
53775       if( j>=0 ){
53776         sqlite3 *db = pParse->db;
53777         zColl = p->pTab->aCol[j].zColl;
53778         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, -1, 0);
53779         pExpr->pColl = pColl;
53780       }
53781       break;
53782     }
53783     if( op!=TK_CAST && op!=TK_UPLUS ){
53784       break;
53785     }
53786     p = p->pLeft;
53787   }
53788   if( sqlite3CheckCollSeq(pParse, pColl) ){ 
53789     pColl = 0;
53790   }
53791   return pColl;
53792 }
53793
53794 /*
53795 ** pExpr is an operand of a comparison operator.  aff2 is the
53796 ** type affinity of the other operand.  This routine returns the
53797 ** type affinity that should be used for the comparison operator.
53798 */
53799 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
53800   char aff1 = sqlite3ExprAffinity(pExpr);
53801   if( aff1 && aff2 ){
53802     /* Both sides of the comparison are columns. If one has numeric
53803     ** affinity, use that. Otherwise use no affinity.
53804     */
53805     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
53806       return SQLITE_AFF_NUMERIC;
53807     }else{
53808       return SQLITE_AFF_NONE;
53809     }
53810   }else if( !aff1 && !aff2 ){
53811     /* Neither side of the comparison is a column.  Compare the
53812     ** results directly.
53813     */
53814     return SQLITE_AFF_NONE;
53815   }else{
53816     /* One side is a column, the other is not. Use the columns affinity. */
53817     assert( aff1==0 || aff2==0 );
53818     return (aff1 + aff2);
53819   }
53820 }
53821
53822 /*
53823 ** pExpr is a comparison operator.  Return the type affinity that should
53824 ** be applied to both operands prior to doing the comparison.
53825 */
53826 static char comparisonAffinity(Expr *pExpr){
53827   char aff;
53828   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
53829           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
53830           pExpr->op==TK_NE );
53831   assert( pExpr->pLeft );
53832   aff = sqlite3ExprAffinity(pExpr->pLeft);
53833   if( pExpr->pRight ){
53834     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
53835   }
53836   else if( pExpr->pSelect ){
53837     aff = sqlite3CompareAffinity(pExpr->pSelect->pEList->a[0].pExpr, aff);
53838   }
53839   else if( !aff ){
53840     aff = SQLITE_AFF_NONE;
53841   }
53842   return aff;
53843 }
53844
53845 /*
53846 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
53847 ** idx_affinity is the affinity of an indexed column. Return true
53848 ** if the index with affinity idx_affinity may be used to implement
53849 ** the comparison in pExpr.
53850 */
53851 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
53852   char aff = comparisonAffinity(pExpr);
53853   switch( aff ){
53854     case SQLITE_AFF_NONE:
53855       return 1;
53856     case SQLITE_AFF_TEXT:
53857       return idx_affinity==SQLITE_AFF_TEXT;
53858     default:
53859       return sqlite3IsNumericAffinity(idx_affinity);
53860   }
53861 }
53862
53863 /*
53864 ** Return the P5 value that should be used for a binary comparison
53865 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
53866 */
53867 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
53868   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
53869   aff = sqlite3CompareAffinity(pExpr1, aff) | jumpIfNull;
53870   return aff;
53871 }
53872
53873 /*
53874 ** Return a pointer to the collation sequence that should be used by
53875 ** a binary comparison operator comparing pLeft and pRight.
53876 **
53877 ** If the left hand expression has a collating sequence type, then it is
53878 ** used. Otherwise the collation sequence for the right hand expression
53879 ** is used, or the default (BINARY) if neither expression has a collating
53880 ** type.
53881 **
53882 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
53883 ** it is not considered.
53884 */
53885 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
53886   Parse *pParse, 
53887   Expr *pLeft, 
53888   Expr *pRight
53889 ){
53890   CollSeq *pColl;
53891   assert( pLeft );
53892   if( pLeft->flags & EP_ExpCollate ){
53893     assert( pLeft->pColl );
53894     pColl = pLeft->pColl;
53895   }else if( pRight && pRight->flags & EP_ExpCollate ){
53896     assert( pRight->pColl );
53897     pColl = pRight->pColl;
53898   }else{
53899     pColl = sqlite3ExprCollSeq(pParse, pLeft);
53900     if( !pColl ){
53901       pColl = sqlite3ExprCollSeq(pParse, pRight);
53902     }
53903   }
53904   return pColl;
53905 }
53906
53907 /*
53908 ** Generate the operands for a comparison operation.  Before
53909 ** generating the code for each operand, set the EP_AnyAff
53910 ** flag on the expression so that it will be able to used a
53911 ** cached column value that has previously undergone an
53912 ** affinity change.
53913 */
53914 static void codeCompareOperands(
53915   Parse *pParse,    /* Parsing and code generating context */
53916   Expr *pLeft,      /* The left operand */
53917   int *pRegLeft,    /* Register where left operand is stored */
53918   int *pFreeLeft,   /* Free this register when done */
53919   Expr *pRight,     /* The right operand */
53920   int *pRegRight,   /* Register where right operand is stored */
53921   int *pFreeRight   /* Write temp register for right operand there */
53922 ){
53923   while( pLeft->op==TK_UPLUS ) pLeft = pLeft->pLeft;
53924   pLeft->flags |= EP_AnyAff;
53925   *pRegLeft = sqlite3ExprCodeTemp(pParse, pLeft, pFreeLeft);
53926   while( pRight->op==TK_UPLUS ) pRight = pRight->pLeft;
53927   pRight->flags |= EP_AnyAff;
53928   *pRegRight = sqlite3ExprCodeTemp(pParse, pRight, pFreeRight);
53929 }
53930
53931 /*
53932 ** Generate code for a comparison operator.
53933 */
53934 static int codeCompare(
53935   Parse *pParse,    /* The parsing (and code generating) context */
53936   Expr *pLeft,      /* The left operand */
53937   Expr *pRight,     /* The right operand */
53938   int opcode,       /* The comparison opcode */
53939   int in1, int in2, /* Register holding operands */
53940   int dest,         /* Jump here if true.  */
53941   int jumpIfNull    /* If true, jump if either operand is NULL */
53942 ){
53943   int p5;
53944   int addr;
53945   CollSeq *p4;
53946
53947   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
53948   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
53949   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
53950                            (void*)p4, P4_COLLSEQ);
53951   sqlite3VdbeChangeP5(pParse->pVdbe, p5);
53952   if( (p5 & SQLITE_AFF_MASK)!=SQLITE_AFF_NONE ){
53953     sqlite3ExprCacheAffinityChange(pParse, in1, 1);
53954     sqlite3ExprCacheAffinityChange(pParse, in2, 1);
53955   }
53956   return addr;
53957 }
53958
53959 #if SQLITE_MAX_EXPR_DEPTH>0
53960 /*
53961 ** Check that argument nHeight is less than or equal to the maximum
53962 ** expression depth allowed. If it is not, leave an error message in
53963 ** pParse.
53964 */
53965 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
53966   int rc = SQLITE_OK;
53967   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
53968   if( nHeight>mxHeight ){
53969     sqlite3ErrorMsg(pParse, 
53970        "Expression tree is too large (maximum depth %d)", mxHeight
53971     );
53972     rc = SQLITE_ERROR;
53973   }
53974   return rc;
53975 }
53976
53977 /* The following three functions, heightOfExpr(), heightOfExprList()
53978 ** and heightOfSelect(), are used to determine the maximum height
53979 ** of any expression tree referenced by the structure passed as the
53980 ** first argument.
53981 **
53982 ** If this maximum height is greater than the current value pointed
53983 ** to by pnHeight, the second parameter, then set *pnHeight to that
53984 ** value.
53985 */
53986 static void heightOfExpr(Expr *p, int *pnHeight){
53987   if( p ){
53988     if( p->nHeight>*pnHeight ){
53989       *pnHeight = p->nHeight;
53990     }
53991   }
53992 }
53993 static void heightOfExprList(ExprList *p, int *pnHeight){
53994   if( p ){
53995     int i;
53996     for(i=0; i<p->nExpr; i++){
53997       heightOfExpr(p->a[i].pExpr, pnHeight);
53998     }
53999   }
54000 }
54001 static void heightOfSelect(Select *p, int *pnHeight){
54002   if( p ){
54003     heightOfExpr(p->pWhere, pnHeight);
54004     heightOfExpr(p->pHaving, pnHeight);
54005     heightOfExpr(p->pLimit, pnHeight);
54006     heightOfExpr(p->pOffset, pnHeight);
54007     heightOfExprList(p->pEList, pnHeight);
54008     heightOfExprList(p->pGroupBy, pnHeight);
54009     heightOfExprList(p->pOrderBy, pnHeight);
54010     heightOfSelect(p->pPrior, pnHeight);
54011   }
54012 }
54013
54014 /*
54015 ** Set the Expr.nHeight variable in the structure passed as an 
54016 ** argument. An expression with no children, Expr.pList or 
54017 ** Expr.pSelect member has a height of 1. Any other expression
54018 ** has a height equal to the maximum height of any other 
54019 ** referenced Expr plus one.
54020 */
54021 static void exprSetHeight(Expr *p){
54022   int nHeight = 0;
54023   heightOfExpr(p->pLeft, &nHeight);
54024   heightOfExpr(p->pRight, &nHeight);
54025   heightOfExprList(p->pList, &nHeight);
54026   heightOfSelect(p->pSelect, &nHeight);
54027   p->nHeight = nHeight + 1;
54028 }
54029
54030 /*
54031 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
54032 ** the height is greater than the maximum allowed expression depth,
54033 ** leave an error in pParse.
54034 */
54035 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
54036   exprSetHeight(p);
54037   sqlite3ExprCheckHeight(pParse, p->nHeight);
54038 }
54039
54040 /*
54041 ** Return the maximum height of any expression tree referenced
54042 ** by the select statement passed as an argument.
54043 */
54044 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
54045   int nHeight = 0;
54046   heightOfSelect(p, &nHeight);
54047   return nHeight;
54048 }
54049 #else
54050   #define exprSetHeight(y)
54051 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
54052
54053 /*
54054 ** Construct a new expression node and return a pointer to it.  Memory
54055 ** for this node is obtained from sqlite3_malloc().  The calling function
54056 ** is responsible for making sure the node eventually gets freed.
54057 */
54058 SQLITE_PRIVATE Expr *sqlite3Expr(
54059   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
54060   int op,                 /* Expression opcode */
54061   Expr *pLeft,            /* Left operand */
54062   Expr *pRight,           /* Right operand */
54063   const Token *pToken     /* Argument token */
54064 ){
54065   Expr *pNew;
54066   pNew = sqlite3DbMallocZero(db, sizeof(Expr));
54067   if( pNew==0 ){
54068     /* When malloc fails, delete pLeft and pRight. Expressions passed to 
54069     ** this function must always be allocated with sqlite3Expr() for this 
54070     ** reason. 
54071     */
54072     sqlite3ExprDelete(db, pLeft);
54073     sqlite3ExprDelete(db, pRight);
54074     return 0;
54075   }
54076   pNew->op = op;
54077   pNew->pLeft = pLeft;
54078   pNew->pRight = pRight;
54079   pNew->iAgg = -1;
54080   pNew->span.z = (u8*)"";
54081   if( pToken ){
54082     assert( pToken->dyn==0 );
54083     pNew->span = pNew->token = *pToken;
54084   }else if( pLeft ){
54085     if( pRight ){
54086       if( pRight->span.dyn==0 && pLeft->span.dyn==0 ){
54087         sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
54088       }
54089       if( pRight->flags & EP_ExpCollate ){
54090         pNew->flags |= EP_ExpCollate;
54091         pNew->pColl = pRight->pColl;
54092       }
54093     }
54094     if( pLeft->flags & EP_ExpCollate ){
54095       pNew->flags |= EP_ExpCollate;
54096       pNew->pColl = pLeft->pColl;
54097     }
54098   }
54099
54100   exprSetHeight(pNew);
54101   return pNew;
54102 }
54103
54104 /*
54105 ** Works like sqlite3Expr() except that it takes an extra Parse*
54106 ** argument and notifies the associated connection object if malloc fails.
54107 */
54108 SQLITE_PRIVATE Expr *sqlite3PExpr(
54109   Parse *pParse,          /* Parsing context */
54110   int op,                 /* Expression opcode */
54111   Expr *pLeft,            /* Left operand */
54112   Expr *pRight,           /* Right operand */
54113   const Token *pToken     /* Argument token */
54114 ){
54115   Expr *p = sqlite3Expr(pParse->db, op, pLeft, pRight, pToken);
54116   if( p ){
54117     sqlite3ExprCheckHeight(pParse, p->nHeight);
54118   }
54119   return p;
54120 }
54121
54122 /*
54123 ** When doing a nested parse, you can include terms in an expression
54124 ** that look like this:   #1 #2 ...  These terms refer to registers
54125 ** in the virtual machine.  #N is the N-th register.
54126 **
54127 ** This routine is called by the parser to deal with on of those terms.
54128 ** It immediately generates code to store the value in a memory location.
54129 ** The returns an expression that will code to extract the value from
54130 ** that memory location as needed.
54131 */
54132 SQLITE_PRIVATE Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
54133   Vdbe *v = pParse->pVdbe;
54134   Expr *p;
54135   if( pParse->nested==0 ){
54136     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
54137     return sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
54138   }
54139   if( v==0 ) return 0;
54140   p = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, pToken);
54141   if( p==0 ){
54142     return 0;  /* Malloc failed */
54143   }
54144   p->iTable = atoi((char*)&pToken->z[1]);
54145   return p;
54146 }
54147
54148 /*
54149 ** Join two expressions using an AND operator.  If either expression is
54150 ** NULL, then just return the other expression.
54151 */
54152 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
54153   if( pLeft==0 ){
54154     return pRight;
54155   }else if( pRight==0 ){
54156     return pLeft;
54157   }else{
54158     return sqlite3Expr(db, TK_AND, pLeft, pRight, 0);
54159   }
54160 }
54161
54162 /*
54163 ** Set the Expr.span field of the given expression to span all
54164 ** text between the two given tokens.  Both tokens must be pointing
54165 ** at the same string.
54166 */
54167 SQLITE_PRIVATE void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
54168   assert( pRight!=0 );
54169   assert( pLeft!=0 );
54170   if( pExpr ){
54171     pExpr->span.z = pLeft->z;
54172     pExpr->span.n = pRight->n + (pRight->z - pLeft->z);
54173   }
54174 }
54175
54176 /*
54177 ** Construct a new expression node for a function with multiple
54178 ** arguments.
54179 */
54180 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
54181   Expr *pNew;
54182   sqlite3 *db = pParse->db;
54183   assert( pToken );
54184   pNew = sqlite3DbMallocZero(db, sizeof(Expr) );
54185   if( pNew==0 ){
54186     sqlite3ExprListDelete(db, pList); /* Avoid leaking memory when malloc fails */
54187     return 0;
54188   }
54189   pNew->op = TK_FUNCTION;
54190   pNew->pList = pList;
54191   assert( pToken->dyn==0 );
54192   pNew->token = *pToken;
54193   pNew->span = pNew->token;
54194
54195   sqlite3ExprSetHeight(pParse, pNew);
54196   return pNew;
54197 }
54198
54199 /*
54200 ** Assign a variable number to an expression that encodes a wildcard
54201 ** in the original SQL statement.  
54202 **
54203 ** Wildcards consisting of a single "?" are assigned the next sequential
54204 ** variable number.
54205 **
54206 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
54207 ** sure "nnn" is not too be to avoid a denial of service attack when
54208 ** the SQL statement comes from an external source.
54209 **
54210 ** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
54211 ** as the previous instance of the same wildcard.  Or if this is the first
54212 ** instance of the wildcard, the next sequenial variable number is
54213 ** assigned.
54214 */
54215 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
54216   Token *pToken;
54217   sqlite3 *db = pParse->db;
54218
54219   if( pExpr==0 ) return;
54220   pToken = &pExpr->token;
54221   assert( pToken->n>=1 );
54222   assert( pToken->z!=0 );
54223   assert( pToken->z[0]!=0 );
54224   if( pToken->n==1 ){
54225     /* Wildcard of the form "?".  Assign the next variable number */
54226     pExpr->iTable = ++pParse->nVar;
54227   }else if( pToken->z[0]=='?' ){
54228     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
54229     ** use it as the variable number */
54230     int i;
54231     pExpr->iTable = i = atoi((char*)&pToken->z[1]);
54232     testcase( i==0 );
54233     testcase( i==1 );
54234     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
54235     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
54236     if( i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
54237       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
54238           db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
54239     }
54240     if( i>pParse->nVar ){
54241       pParse->nVar = i;
54242     }
54243   }else{
54244     /* Wildcards of the form ":aaa" or "$aaa".  Reuse the same variable
54245     ** number as the prior appearance of the same name, or if the name
54246     ** has never appeared before, reuse the same variable number
54247     */
54248     int i, n;
54249     n = pToken->n;
54250     for(i=0; i<pParse->nVarExpr; i++){
54251       Expr *pE;
54252       if( (pE = pParse->apVarExpr[i])!=0
54253           && pE->token.n==n
54254           && memcmp(pE->token.z, pToken->z, n)==0 ){
54255         pExpr->iTable = pE->iTable;
54256         break;
54257       }
54258     }
54259     if( i>=pParse->nVarExpr ){
54260       pExpr->iTable = ++pParse->nVar;
54261       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
54262         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
54263         pParse->apVarExpr =
54264             sqlite3DbReallocOrFree(
54265               db,
54266               pParse->apVarExpr,
54267               pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
54268             );
54269       }
54270       if( !db->mallocFailed ){
54271         assert( pParse->apVarExpr!=0 );
54272         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
54273       }
54274     }
54275   } 
54276   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
54277     sqlite3ErrorMsg(pParse, "too many SQL variables");
54278   }
54279 }
54280
54281 /*
54282 ** Clear an expression structure without deleting the structure itself.
54283 ** Substructure is deleted.
54284 */
54285 SQLITE_PRIVATE void sqlite3ExprClear(sqlite3 *db, Expr *p){
54286   if( p->span.dyn ) sqlite3DbFree(db, (char*)p->span.z);
54287   if( p->token.dyn ) sqlite3DbFree(db, (char*)p->token.z);
54288   sqlite3ExprDelete(db, p->pLeft);
54289   sqlite3ExprDelete(db, p->pRight);
54290   sqlite3ExprListDelete(db, p->pList);
54291   sqlite3SelectDelete(db, p->pSelect);
54292 }
54293
54294 /*
54295 ** Recursively delete an expression tree.
54296 */
54297 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
54298   if( p==0 ) return;
54299   sqlite3ExprClear(db, p);
54300   sqlite3DbFree(db, p);
54301 }
54302
54303 /*
54304 ** The Expr.token field might be a string literal that is quoted.
54305 ** If so, remove the quotation marks.
54306 */
54307 SQLITE_PRIVATE void sqlite3DequoteExpr(sqlite3 *db, Expr *p){
54308   if( ExprHasAnyProperty(p, EP_Dequoted) ){
54309     return;
54310   }
54311   ExprSetProperty(p, EP_Dequoted);
54312   if( p->token.dyn==0 ){
54313     sqlite3TokenCopy(db, &p->token, &p->token);
54314   }
54315   sqlite3Dequote((char*)p->token.z);
54316 }
54317
54318 /*
54319 ** The following group of routines make deep copies of expressions,
54320 ** expression lists, ID lists, and select statements.  The copies can
54321 ** be deleted (by being passed to their respective ...Delete() routines)
54322 ** without effecting the originals.
54323 **
54324 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
54325 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
54326 ** by subsequent calls to sqlite*ListAppend() routines.
54327 **
54328 ** Any tables that the SrcList might point to are not duplicated.
54329 */
54330 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p){
54331   Expr *pNew;
54332   if( p==0 ) return 0;
54333   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
54334   if( pNew==0 ) return 0;
54335   memcpy(pNew, p, sizeof(*pNew));
54336   if( p->token.z!=0 ){
54337     pNew->token.z = (u8*)sqlite3DbStrNDup(db, (char*)p->token.z, p->token.n);
54338     pNew->token.dyn = 1;
54339   }else{
54340     assert( pNew->token.z==0 );
54341   }
54342   pNew->span.z = 0;
54343   pNew->pLeft = sqlite3ExprDup(db, p->pLeft);
54344   pNew->pRight = sqlite3ExprDup(db, p->pRight);
54345   pNew->pList = sqlite3ExprListDup(db, p->pList);
54346   pNew->pSelect = sqlite3SelectDup(db, p->pSelect);
54347   return pNew;
54348 }
54349 SQLITE_PRIVATE void sqlite3TokenCopy(sqlite3 *db, Token *pTo, Token *pFrom){
54350   if( pTo->dyn ) sqlite3DbFree(db, (char*)pTo->z);
54351   if( pFrom->z ){
54352     pTo->n = pFrom->n;
54353     pTo->z = (u8*)sqlite3DbStrNDup(db, (char*)pFrom->z, pFrom->n);
54354     pTo->dyn = 1;
54355   }else{
54356     pTo->z = 0;
54357   }
54358 }
54359 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p){
54360   ExprList *pNew;
54361   struct ExprList_item *pItem, *pOldItem;
54362   int i;
54363   if( p==0 ) return 0;
54364   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
54365   if( pNew==0 ) return 0;
54366   pNew->iECursor = 0;
54367   pNew->nExpr = pNew->nAlloc = p->nExpr;
54368   pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
54369   if( pItem==0 ){
54370     sqlite3DbFree(db, pNew);
54371     return 0;
54372   } 
54373   pOldItem = p->a;
54374   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
54375     Expr *pNewExpr, *pOldExpr;
54376     pItem->pExpr = pNewExpr = sqlite3ExprDup(db, pOldExpr = pOldItem->pExpr);
54377     if( pOldExpr->span.z!=0 && pNewExpr ){
54378       /* Always make a copy of the span for top-level expressions in the
54379       ** expression list.  The logic in SELECT processing that determines
54380       ** the names of columns in the result set needs this information */
54381       sqlite3TokenCopy(db, &pNewExpr->span, &pOldExpr->span);
54382     }
54383     assert( pNewExpr==0 || pNewExpr->span.z!=0 
54384             || pOldExpr->span.z==0
54385             || db->mallocFailed );
54386     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
54387     pItem->sortOrder = pOldItem->sortOrder;
54388     pItem->done = 0;
54389     pItem->iCol = pOldItem->iCol;
54390     pItem->iAlias = pOldItem->iAlias;
54391   }
54392   return pNew;
54393 }
54394
54395 /*
54396 ** If cursors, triggers, views and subqueries are all omitted from
54397 ** the build, then none of the following routines, except for 
54398 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
54399 ** called with a NULL argument.
54400 */
54401 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
54402  || !defined(SQLITE_OMIT_SUBQUERY)
54403 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p){
54404   SrcList *pNew;
54405   int i;
54406   int nByte;
54407   if( p==0 ) return 0;
54408   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
54409   pNew = sqlite3DbMallocRaw(db, nByte );
54410   if( pNew==0 ) return 0;
54411   pNew->nSrc = pNew->nAlloc = p->nSrc;
54412   for(i=0; i<p->nSrc; i++){
54413     struct SrcList_item *pNewItem = &pNew->a[i];
54414     struct SrcList_item *pOldItem = &p->a[i];
54415     Table *pTab;
54416     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
54417     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
54418     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
54419     pNewItem->jointype = pOldItem->jointype;
54420     pNewItem->iCursor = pOldItem->iCursor;
54421     pNewItem->isPopulated = pOldItem->isPopulated;
54422     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
54423     pNewItem->notIndexed = pOldItem->notIndexed;
54424     pNewItem->pIndex = pOldItem->pIndex;
54425     pTab = pNewItem->pTab = pOldItem->pTab;
54426     if( pTab ){
54427       pTab->nRef++;
54428     }
54429     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect);
54430     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn);
54431     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
54432     pNewItem->colUsed = pOldItem->colUsed;
54433   }
54434   return pNew;
54435 }
54436 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
54437   IdList *pNew;
54438   int i;
54439   if( p==0 ) return 0;
54440   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
54441   if( pNew==0 ) return 0;
54442   pNew->nId = pNew->nAlloc = p->nId;
54443   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
54444   if( pNew->a==0 ){
54445     sqlite3DbFree(db, pNew);
54446     return 0;
54447   }
54448   for(i=0; i<p->nId; i++){
54449     struct IdList_item *pNewItem = &pNew->a[i];
54450     struct IdList_item *pOldItem = &p->a[i];
54451     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
54452     pNewItem->idx = pOldItem->idx;
54453   }
54454   return pNew;
54455 }
54456 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p){
54457   Select *pNew;
54458   if( p==0 ) return 0;
54459   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
54460   if( pNew==0 ) return 0;
54461   pNew->pEList = sqlite3ExprListDup(db, p->pEList);
54462   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc);
54463   pNew->pWhere = sqlite3ExprDup(db, p->pWhere);
54464   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy);
54465   pNew->pHaving = sqlite3ExprDup(db, p->pHaving);
54466   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy);
54467   pNew->op = p->op;
54468   pNew->pPrior = sqlite3SelectDup(db, p->pPrior);
54469   pNew->pLimit = sqlite3ExprDup(db, p->pLimit);
54470   pNew->pOffset = sqlite3ExprDup(db, p->pOffset);
54471   pNew->iLimit = 0;
54472   pNew->iOffset = 0;
54473   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
54474   pNew->pRightmost = 0;
54475   pNew->addrOpenEphm[0] = -1;
54476   pNew->addrOpenEphm[1] = -1;
54477   pNew->addrOpenEphm[2] = -1;
54478   return pNew;
54479 }
54480 #else
54481 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p){
54482   assert( p==0 );
54483   return 0;
54484 }
54485 #endif
54486
54487
54488 /*
54489 ** Add a new element to the end of an expression list.  If pList is
54490 ** initially NULL, then create a new expression list.
54491 */
54492 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
54493   Parse *pParse,          /* Parsing context */
54494   ExprList *pList,        /* List to which to append. Might be NULL */
54495   Expr *pExpr,            /* Expression to be appended */
54496   Token *pName            /* AS keyword for the expression */
54497 ){
54498   sqlite3 *db = pParse->db;
54499   if( pList==0 ){
54500     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
54501     if( pList==0 ){
54502       goto no_mem;
54503     }
54504     assert( pList->nAlloc==0 );
54505   }
54506   if( pList->nAlloc<=pList->nExpr ){
54507     struct ExprList_item *a;
54508     int n = pList->nAlloc*2 + 4;
54509     a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
54510     if( a==0 ){
54511       goto no_mem;
54512     }
54513     pList->a = a;
54514     pList->nAlloc = n;
54515   }
54516   assert( pList->a!=0 );
54517   if( pExpr || pName ){
54518     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
54519     memset(pItem, 0, sizeof(*pItem));
54520     pItem->zName = sqlite3NameFromToken(db, pName);
54521     pItem->pExpr = pExpr;
54522     pItem->iAlias = 0;
54523   }
54524   return pList;
54525
54526 no_mem:     
54527   /* Avoid leaking memory if malloc has failed. */
54528   sqlite3ExprDelete(db, pExpr);
54529   sqlite3ExprListDelete(db, pList);
54530   return 0;
54531 }
54532
54533 /*
54534 ** If the expression list pEList contains more than iLimit elements,
54535 ** leave an error message in pParse.
54536 */
54537 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
54538   Parse *pParse,
54539   ExprList *pEList,
54540   const char *zObject
54541 ){
54542   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
54543   testcase( pEList && pEList->nExpr==mx );
54544   testcase( pEList && pEList->nExpr==mx+1 );
54545   if( pEList && pEList->nExpr>mx ){
54546     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
54547   }
54548 }
54549
54550 /*
54551 ** Delete an entire expression list.
54552 */
54553 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
54554   int i;
54555   struct ExprList_item *pItem;
54556   if( pList==0 ) return;
54557   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
54558   assert( pList->nExpr<=pList->nAlloc );
54559   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
54560     sqlite3ExprDelete(db, pItem->pExpr);
54561     sqlite3DbFree(db, pItem->zName);
54562   }
54563   sqlite3DbFree(db, pList->a);
54564   sqlite3DbFree(db, pList);
54565 }
54566
54567 /*
54568 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
54569 ** to an integer.  These routines are checking an expression to see
54570 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
54571 ** not constant.
54572 **
54573 ** These callback routines are used to implement the following:
54574 **
54575 **     sqlite3ExprIsConstant()
54576 **     sqlite3ExprIsConstantNotJoin()
54577 **     sqlite3ExprIsConstantOrFunction()
54578 **
54579 */
54580 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
54581
54582   /* If pWalker->u.i is 3 then any term of the expression that comes from
54583   ** the ON or USING clauses of a join disqualifies the expression
54584   ** from being considered constant. */
54585   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
54586     pWalker->u.i = 0;
54587     return WRC_Abort;
54588   }
54589
54590   switch( pExpr->op ){
54591     /* Consider functions to be constant if all their arguments are constant
54592     ** and pWalker->u.i==2 */
54593     case TK_FUNCTION:
54594       if( pWalker->u.i==2 ) return 0;
54595       /* Fall through */
54596     case TK_ID:
54597     case TK_COLUMN:
54598     case TK_DOT:
54599     case TK_AGG_FUNCTION:
54600     case TK_AGG_COLUMN:
54601 #ifndef SQLITE_OMIT_SUBQUERY
54602     case TK_SELECT:
54603     case TK_EXISTS:
54604       testcase( pExpr->op==TK_SELECT );
54605       testcase( pExpr->op==TK_EXISTS );
54606 #endif
54607       testcase( pExpr->op==TK_ID );
54608       testcase( pExpr->op==TK_COLUMN );
54609       testcase( pExpr->op==TK_DOT );
54610       testcase( pExpr->op==TK_AGG_FUNCTION );
54611       testcase( pExpr->op==TK_AGG_COLUMN );
54612       pWalker->u.i = 0;
54613       return WRC_Abort;
54614     default:
54615       return WRC_Continue;
54616   }
54617 }
54618 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
54619   UNUSED_PARAMETER(NotUsed);
54620   pWalker->u.i = 0;
54621   return WRC_Abort;
54622 }
54623 static int exprIsConst(Expr *p, int initFlag){
54624   Walker w;
54625   w.u.i = initFlag;
54626   w.xExprCallback = exprNodeIsConstant;
54627   w.xSelectCallback = selectNodeIsConstant;
54628   sqlite3WalkExpr(&w, p);
54629   return w.u.i;
54630 }
54631
54632 /*
54633 ** Walk an expression tree.  Return 1 if the expression is constant
54634 ** and 0 if it involves variables or function calls.
54635 **
54636 ** For the purposes of this function, a double-quoted string (ex: "abc")
54637 ** is considered a variable but a single-quoted string (ex: 'abc') is
54638 ** a constant.
54639 */
54640 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
54641   return exprIsConst(p, 1);
54642 }
54643
54644 /*
54645 ** Walk an expression tree.  Return 1 if the expression is constant
54646 ** that does no originate from the ON or USING clauses of a join.
54647 ** Return 0 if it involves variables or function calls or terms from
54648 ** an ON or USING clause.
54649 */
54650 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
54651   return exprIsConst(p, 3);
54652 }
54653
54654 /*
54655 ** Walk an expression tree.  Return 1 if the expression is constant
54656 ** or a function call with constant arguments.  Return and 0 if there
54657 ** are any variables.
54658 **
54659 ** For the purposes of this function, a double-quoted string (ex: "abc")
54660 ** is considered a variable but a single-quoted string (ex: 'abc') is
54661 ** a constant.
54662 */
54663 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
54664   return exprIsConst(p, 2);
54665 }
54666
54667 /*
54668 ** If the expression p codes a constant integer that is small enough
54669 ** to fit in a 32-bit integer, return 1 and put the value of the integer
54670 ** in *pValue.  If the expression is not an integer or if it is too big
54671 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
54672 */
54673 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
54674   int rc = 0;
54675   if( p->flags & EP_IntValue ){
54676     *pValue = p->iTable;
54677     return 1;
54678   }
54679   switch( p->op ){
54680     case TK_INTEGER: {
54681       rc = sqlite3GetInt32((char*)p->token.z, pValue);
54682       break;
54683     }
54684     case TK_UPLUS: {
54685       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
54686       break;
54687     }
54688     case TK_UMINUS: {
54689       int v;
54690       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
54691         *pValue = -v;
54692         rc = 1;
54693       }
54694       break;
54695     }
54696     default: break;
54697   }
54698   if( rc ){
54699     p->op = TK_INTEGER;
54700     p->flags |= EP_IntValue;
54701     p->iTable = *pValue;
54702   }
54703   return rc;
54704 }
54705
54706 /*
54707 ** Return TRUE if the given string is a row-id column name.
54708 */
54709 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
54710   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
54711   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
54712   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
54713   return 0;
54714 }
54715
54716 #ifdef SQLITE_TEST
54717   int sqlite3_enable_in_opt = 1;
54718 #else
54719   #define sqlite3_enable_in_opt 1
54720 #endif
54721
54722 /*
54723 ** Return true if the IN operator optimization is enabled and
54724 ** the SELECT statement p exists and is of the
54725 ** simple form:
54726 **
54727 **     SELECT <column> FROM <table>
54728 **
54729 ** If this is the case, it may be possible to use an existing table
54730 ** or index instead of generating an epheremal table.
54731 */
54732 #ifndef SQLITE_OMIT_SUBQUERY
54733 static int isCandidateForInOpt(Select *p){
54734   SrcList *pSrc;
54735   ExprList *pEList;
54736   Table *pTab;
54737   if( !sqlite3_enable_in_opt ) return 0; /* IN optimization must be enabled */
54738   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
54739   if( p->pPrior ) return 0;              /* Not a compound SELECT */
54740   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
54741       return 0; /* No DISTINCT keyword and no aggregate functions */
54742   }
54743   if( p->pGroupBy ) return 0;            /* Has no GROUP BY clause */
54744   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
54745   if( p->pOffset ) return 0;
54746   if( p->pWhere ) return 0;              /* Has no WHERE clause */
54747   pSrc = p->pSrc;
54748   if( pSrc==0 ) return 0;                /* A single table in the FROM clause */
54749   if( pSrc->nSrc!=1 ) return 0;
54750   if( pSrc->a[0].pSelect ) return 0;     /* FROM clause is not a subquery */
54751   pTab = pSrc->a[0].pTab;
54752   if( pTab==0 ) return 0;
54753   if( pTab->pSelect ) return 0;          /* FROM clause is not a view */
54754   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
54755   pEList = p->pEList;
54756   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
54757   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
54758   return 1;
54759 }
54760 #endif /* SQLITE_OMIT_SUBQUERY */
54761
54762 /*
54763 ** This function is used by the implementation of the IN (...) operator.
54764 ** It's job is to find or create a b-tree structure that may be used
54765 ** either to test for membership of the (...) set or to iterate through
54766 ** its members, skipping duplicates.
54767 **
54768 ** The cursor opened on the structure (database table, database index 
54769 ** or ephermal table) is stored in pX->iTable before this function returns.
54770 ** The returned value indicates the structure type, as follows:
54771 **
54772 **   IN_INDEX_ROWID - The cursor was opened on a database table.
54773 **   IN_INDEX_INDEX - The cursor was opened on a database index.
54774 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
54775 **                    populated epheremal table.
54776 **
54777 ** An existing structure may only be used if the SELECT is of the simple
54778 ** form:
54779 **
54780 **     SELECT <column> FROM <table>
54781 **
54782 ** If prNotFound parameter is 0, then the structure will be used to iterate
54783 ** through the set members, skipping any duplicates. In this case an
54784 ** epheremal table must be used unless the selected <column> is guaranteed
54785 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
54786 ** is unique by virtue of a constraint or implicit index.
54787 **
54788 ** If the prNotFound parameter is not 0, then the structure will be used 
54789 ** for fast set membership tests. In this case an epheremal table must 
54790 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can 
54791 ** be found with <column> as its left-most column.
54792 **
54793 ** When the structure is being used for set membership tests, the user
54794 ** needs to know whether or not the structure contains an SQL NULL 
54795 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
54796 ** If there is a chance that the structure may contain a NULL value at
54797 ** runtime, then a register is allocated and the register number written
54798 ** to *prNotFound. If there is no chance that the structure contains a
54799 ** NULL value, then *prNotFound is left unchanged.
54800 **
54801 ** If a register is allocated and its location stored in *prNotFound, then
54802 ** its initial value is NULL. If the structure does not remain constant
54803 ** for the duration of the query (i.e. the set is a correlated sub-select), 
54804 ** the value of the allocated register is reset to NULL each time the 
54805 ** structure is repopulated. This allows the caller to use vdbe code 
54806 ** equivalent to the following:
54807 **
54808 **   if( register==NULL ){
54809 **     has_null = <test if data structure contains null>
54810 **     register = 1
54811 **   }
54812 **
54813 ** in order to avoid running the <test if data structure contains null>
54814 ** test more often than is necessary.
54815 */
54816 #ifndef SQLITE_OMIT_SUBQUERY
54817 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
54818   Select *p;
54819   int eType = 0;
54820   int iTab = pParse->nTab++;
54821   int mustBeUnique = !prNotFound;
54822
54823   /* The follwing if(...) expression is true if the SELECT is of the 
54824   ** simple form:
54825   **
54826   **     SELECT <column> FROM <table>
54827   **
54828   ** If this is the case, it may be possible to use an existing table
54829   ** or index instead of generating an epheremal table.
54830   */
54831   p = pX->pSelect;
54832   if( isCandidateForInOpt(p) ){
54833     sqlite3 *db = pParse->db;
54834     Index *pIdx;
54835     Expr *pExpr = p->pEList->a[0].pExpr;
54836     int iCol = pExpr->iColumn;
54837     Vdbe *v = sqlite3GetVdbe(pParse);
54838
54839     /* This function is only called from two places. In both cases the vdbe
54840     ** has already been allocated. So assume sqlite3GetVdbe() is always
54841     ** successful here.
54842     */
54843     assert(v);
54844     if( iCol<0 ){
54845       int iMem = ++pParse->nMem;
54846       int iAddr;
54847       Table *pTab = p->pSrc->a[0].pTab;
54848       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
54849       sqlite3VdbeUsesBtree(v, iDb);
54850
54851       iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
54852       sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
54853
54854       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
54855       eType = IN_INDEX_ROWID;
54856
54857       sqlite3VdbeJumpHere(v, iAddr);
54858     }else{
54859       /* The collation sequence used by the comparison. If an index is to 
54860       ** be used in place of a temp-table, it must be ordered according
54861       ** to this collation sequence.
54862       */
54863       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
54864
54865       /* Check that the affinity that will be used to perform the 
54866       ** comparison is the same as the affinity of the column. If
54867       ** it is not, it is not possible to use any index.
54868       */
54869       Table *pTab = p->pSrc->a[0].pTab;
54870       char aff = comparisonAffinity(pX);
54871       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
54872
54873       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
54874         if( (pIdx->aiColumn[0]==iCol)
54875          && (pReq==sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], -1, 0))
54876          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
54877         ){
54878           int iDb;
54879           int iMem = ++pParse->nMem;
54880           int iAddr;
54881           char *pKey;
54882   
54883           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
54884           iDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
54885           sqlite3VdbeUsesBtree(v, iDb);
54886
54887           iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
54888           sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
54889   
54890           sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pIdx->nColumn);
54891           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
54892                                pKey,P4_KEYINFO_HANDOFF);
54893           VdbeComment((v, "%s", pIdx->zName));
54894           eType = IN_INDEX_INDEX;
54895
54896           sqlite3VdbeJumpHere(v, iAddr);
54897           if( prNotFound && !pTab->aCol[iCol].notNull ){
54898             *prNotFound = ++pParse->nMem;
54899           }
54900         }
54901       }
54902     }
54903   }
54904
54905   if( eType==0 ){
54906     int rMayHaveNull = 0;
54907     eType = IN_INDEX_EPH;
54908     if( prNotFound ){
54909       *prNotFound = rMayHaveNull = ++pParse->nMem;
54910     }else if( pX->pLeft->iColumn<0 && pX->pSelect==0 ){
54911       eType = IN_INDEX_ROWID;
54912     }
54913     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
54914   }else{
54915     pX->iTable = iTab;
54916   }
54917   return eType;
54918 }
54919 #endif
54920
54921 /*
54922 ** Generate code for scalar subqueries used as an expression
54923 ** and IN operators.  Examples:
54924 **
54925 **     (SELECT a FROM b)          -- subquery
54926 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
54927 **     x IN (4,5,11)              -- IN operator with list on right-hand side
54928 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
54929 **
54930 ** The pExpr parameter describes the expression that contains the IN
54931 ** operator or subquery.
54932 **
54933 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
54934 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
54935 ** to some integer key column of a table B-Tree. In this case, use an
54936 ** intkey B-Tree to store the set of IN(...) values instead of the usual
54937 ** (slower) variable length keys B-Tree.
54938 */
54939 #ifndef SQLITE_OMIT_SUBQUERY
54940 SQLITE_PRIVATE void sqlite3CodeSubselect(
54941   Parse *pParse, 
54942   Expr *pExpr, 
54943   int rMayHaveNull,
54944   int isRowid
54945 ){
54946   int testAddr = 0;                       /* One-time test address */
54947   Vdbe *v = sqlite3GetVdbe(pParse);
54948   if( v==0 ) return;
54949
54950
54951   /* This code must be run in its entirety every time it is encountered
54952   ** if any of the following is true:
54953   **
54954   **    *  The right-hand side is a correlated subquery
54955   **    *  The right-hand side is an expression list containing variables
54956   **    *  We are inside a trigger
54957   **
54958   ** If all of the above are false, then we can run this code just once
54959   ** save the results, and reuse the same result on subsequent invocations.
54960   */
54961   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
54962     int mem = ++pParse->nMem;
54963     sqlite3VdbeAddOp1(v, OP_If, mem);
54964     testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
54965     assert( testAddr>0 || pParse->db->mallocFailed );
54966   }
54967
54968   switch( pExpr->op ){
54969     case TK_IN: {
54970       char affinity;
54971       KeyInfo keyInfo;
54972       int addr;        /* Address of OP_OpenEphemeral instruction */
54973       Expr *pLeft = pExpr->pLeft;
54974
54975       if( rMayHaveNull ){
54976         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
54977       }
54978
54979       affinity = sqlite3ExprAffinity(pLeft);
54980
54981       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
54982       ** expression it is handled the same way. A virtual table is 
54983       ** filled with single-field index keys representing the results
54984       ** from the SELECT or the <exprlist>.
54985       **
54986       ** If the 'x' expression is a column value, or the SELECT...
54987       ** statement returns a column value, then the affinity of that
54988       ** column is used to build the index keys. If both 'x' and the
54989       ** SELECT... statement are columns, then numeric affinity is used
54990       ** if either column has NUMERIC or INTEGER affinity. If neither
54991       ** 'x' nor the SELECT... statement are columns, then numeric affinity
54992       ** is used.
54993       */
54994       pExpr->iTable = pParse->nTab++;
54995       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
54996       memset(&keyInfo, 0, sizeof(keyInfo));
54997       keyInfo.nField = 1;
54998
54999       if( pExpr->pSelect ){
55000         /* Case 1:     expr IN (SELECT ...)
55001         **
55002         ** Generate code to write the results of the select into the temporary
55003         ** table allocated and opened above.
55004         */
55005         SelectDest dest;
55006         ExprList *pEList;
55007
55008         assert( !isRowid );
55009         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
55010         dest.affinity = (int)affinity;
55011         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
55012         if( sqlite3Select(pParse, pExpr->pSelect, &dest) ){
55013           return;
55014         }
55015         pEList = pExpr->pSelect->pEList;
55016         if( pEList && pEList->nExpr>0 ){ 
55017           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
55018               pEList->a[0].pExpr);
55019         }
55020       }else if( pExpr->pList ){
55021         /* Case 2:     expr IN (exprlist)
55022         **
55023         ** For each expression, build an index key from the evaluation and
55024         ** store it in the temporary table. If <expr> is a column, then use
55025         ** that columns affinity when building index keys. If <expr> is not
55026         ** a column, use numeric affinity.
55027         */
55028         int i;
55029         ExprList *pList = pExpr->pList;
55030         struct ExprList_item *pItem;
55031         int r1, r2, r3;
55032
55033         if( !affinity ){
55034           affinity = SQLITE_AFF_NONE;
55035         }
55036         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
55037
55038         /* Loop through each expression in <exprlist>. */
55039         r1 = sqlite3GetTempReg(pParse);
55040         r2 = sqlite3GetTempReg(pParse);
55041         sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
55042         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
55043           Expr *pE2 = pItem->pExpr;
55044
55045           /* If the expression is not constant then we will need to
55046           ** disable the test that was generated above that makes sure
55047           ** this code only executes once.  Because for a non-constant
55048           ** expression we need to rerun this code each time.
55049           */
55050           if( testAddr && !sqlite3ExprIsConstant(pE2) ){
55051             sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
55052             testAddr = 0;
55053           }
55054
55055           /* Evaluate the expression and insert it into the temp table */
55056           pParse->disableColCache++;
55057           r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
55058           assert( pParse->disableColCache>0 );
55059           pParse->disableColCache--;
55060
55061           if( isRowid ){
55062             sqlite3VdbeAddOp2(v, OP_MustBeInt, r3, sqlite3VdbeCurrentAddr(v)+2);
55063             sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
55064           }else{
55065             sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
55066             sqlite3ExprCacheAffinityChange(pParse, r3, 1);
55067             sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
55068           }
55069         }
55070         sqlite3ReleaseTempReg(pParse, r1);
55071         sqlite3ReleaseTempReg(pParse, r2);
55072       }
55073       if( !isRowid ){
55074         sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
55075       }
55076       break;
55077     }
55078
55079     case TK_EXISTS:
55080     case TK_SELECT: {
55081       /* This has to be a scalar SELECT.  Generate code to put the
55082       ** value of this select in a memory cell and record the number
55083       ** of the memory cell in iColumn.
55084       */
55085       static const Token one = { (u8*)"1", 0, 1 };
55086       Select *pSel;
55087       SelectDest dest;
55088
55089       pSel = pExpr->pSelect;
55090       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
55091       if( pExpr->op==TK_SELECT ){
55092         dest.eDest = SRT_Mem;
55093         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
55094         VdbeComment((v, "Init subquery result"));
55095       }else{
55096         dest.eDest = SRT_Exists;
55097         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
55098         VdbeComment((v, "Init EXISTS result"));
55099       }
55100       sqlite3ExprDelete(pParse->db, pSel->pLimit);
55101       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one);
55102       if( sqlite3Select(pParse, pSel, &dest) ){
55103         return;
55104       }
55105       pExpr->iColumn = dest.iParm;
55106       break;
55107     }
55108   }
55109
55110   if( testAddr ){
55111     sqlite3VdbeJumpHere(v, testAddr-1);
55112   }
55113
55114   return;
55115 }
55116 #endif /* SQLITE_OMIT_SUBQUERY */
55117
55118 /*
55119 ** Duplicate an 8-byte value
55120 */
55121 static char *dup8bytes(Vdbe *v, const char *in){
55122   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
55123   if( out ){
55124     memcpy(out, in, 8);
55125   }
55126   return out;
55127 }
55128
55129 /*
55130 ** Generate an instruction that will put the floating point
55131 ** value described by z[0..n-1] into register iMem.
55132 **
55133 ** The z[] string will probably not be zero-terminated.  But the 
55134 ** z[n] character is guaranteed to be something that does not look
55135 ** like the continuation of the number.
55136 */
55137 static void codeReal(Vdbe *v, const char *z, int n, int negateFlag, int iMem){
55138   assert( z || v==0 || sqlite3VdbeDb(v)->mallocFailed );
55139   assert( !z || !isdigit(z[n]) );
55140   UNUSED_PARAMETER(n);
55141   if( z ){
55142     double value;
55143     char *zV;
55144     sqlite3AtoF(z, &value);
55145     if( sqlite3IsNaN(value) ){
55146       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem);
55147     }else{
55148       if( negateFlag ) value = -value;
55149       zV = dup8bytes(v, (char*)&value);
55150       sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
55151     }
55152   }
55153 }
55154
55155
55156 /*
55157 ** Generate an instruction that will put the integer describe by
55158 ** text z[0..n-1] into register iMem.
55159 **
55160 ** The z[] string will probably not be zero-terminated.  But the 
55161 ** z[n] character is guaranteed to be something that does not look
55162 ** like the continuation of the number.
55163 */
55164 static void codeInteger(Vdbe *v, Expr *pExpr, int negFlag, int iMem){
55165   const char *z;
55166   if( pExpr->flags & EP_IntValue ){
55167     int i = pExpr->iTable;
55168     if( negFlag ) i = -i;
55169     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
55170   }else if( (z = (char*)pExpr->token.z)!=0 ){
55171     int i;
55172     int n = pExpr->token.n;
55173     assert( !isdigit(z[n]) );
55174     if( sqlite3GetInt32(z, &i) ){
55175       if( negFlag ) i = -i;
55176       sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
55177     }else if( sqlite3FitsIn64Bits(z, negFlag) ){
55178       i64 value;
55179       char *zV;
55180       sqlite3Atoi64(z, &value);
55181       if( negFlag ) value = -value;
55182       zV = dup8bytes(v, (char*)&value);
55183       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
55184     }else{
55185       codeReal(v, z, n, negFlag, iMem);
55186     }
55187   }
55188 }
55189
55190
55191 /*
55192 ** Generate code that will extract the iColumn-th column from
55193 ** table pTab and store the column value in a register.  An effort
55194 ** is made to store the column value in register iReg, but this is
55195 ** not guaranteed.  The location of the column value is returned.
55196 **
55197 ** There must be an open cursor to pTab in iTable when this routine
55198 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
55199 **
55200 ** This routine might attempt to reuse the value of the column that
55201 ** has already been loaded into a register.  The value will always
55202 ** be used if it has not undergone any affinity changes.  But if
55203 ** an affinity change has occurred, then the cached value will only be
55204 ** used if allowAffChng is true.
55205 */
55206 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
55207   Parse *pParse,   /* Parsing and code generating context */
55208   Table *pTab,     /* Description of the table we are reading from */
55209   int iColumn,     /* Index of the table column */
55210   int iTable,      /* The cursor pointing to the table */
55211   int iReg,        /* Store results here */
55212   int allowAffChng /* True if prior affinity changes are OK */
55213 ){
55214   Vdbe *v = pParse->pVdbe;
55215   int i;
55216   struct yColCache *p;
55217
55218   for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
55219     if( p->iTable==iTable && p->iColumn==iColumn
55220            && (!p->affChange || allowAffChng) ){
55221 #if 0
55222       sqlite3VdbeAddOp0(v, OP_Noop);
55223       VdbeComment((v, "OPT: tab%d.col%d -> r%d", iTable, iColumn, p->iReg));
55224 #endif
55225       return p->iReg;
55226     }
55227   }  
55228   assert( v!=0 );
55229   if( iColumn<0 ){
55230     int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid;
55231     sqlite3VdbeAddOp2(v, op, iTable, iReg);
55232   }else if( pTab==0 ){
55233     sqlite3VdbeAddOp3(v, OP_Column, iTable, iColumn, iReg);
55234   }else{
55235     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
55236     sqlite3VdbeAddOp3(v, op, iTable, iColumn, iReg);
55237     sqlite3ColumnDefault(v, pTab, iColumn);
55238 #ifndef SQLITE_OMIT_FLOATING_POINT
55239     if( pTab->aCol[iColumn].affinity==SQLITE_AFF_REAL ){
55240       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
55241     }
55242 #endif
55243   }
55244   if( pParse->disableColCache==0 ){
55245     i = pParse->iColCache;
55246     p = &pParse->aColCache[i];
55247     p->iTable = iTable;
55248     p->iColumn = iColumn;
55249     p->iReg = iReg;
55250     p->affChange = 0;
55251     i++;
55252     if( i>=ArraySize(pParse->aColCache) ) i = 0;
55253     if( i>pParse->nColCache ) pParse->nColCache = i;
55254     pParse->iColCache = i;
55255   }
55256   return iReg;
55257 }
55258
55259 /*
55260 ** Clear all column cache entries associated with the vdbe
55261 ** cursor with cursor number iTable.
55262 */
55263 SQLITE_PRIVATE void sqlite3ExprClearColumnCache(Parse *pParse, int iTable){
55264   if( iTable<0 ){
55265     pParse->nColCache = 0;
55266     pParse->iColCache = 0;
55267   }else{
55268     int i;
55269     for(i=0; i<pParse->nColCache; i++){
55270       if( pParse->aColCache[i].iTable==iTable ){
55271         testcase( i==pParse->nColCache-1 );
55272         pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache];
55273         pParse->iColCache = pParse->nColCache;
55274       }
55275     }
55276   }
55277 }
55278
55279 /*
55280 ** Record the fact that an affinity change has occurred on iCount
55281 ** registers starting with iStart.
55282 */
55283 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
55284   int iEnd = iStart + iCount - 1;
55285   int i;
55286   for(i=0; i<pParse->nColCache; i++){
55287     int r = pParse->aColCache[i].iReg;
55288     if( r>=iStart && r<=iEnd ){
55289       pParse->aColCache[i].affChange = 1;
55290     }
55291   }
55292 }
55293
55294 /*
55295 ** Generate code to move content from registers iFrom...iFrom+nReg-1
55296 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
55297 */
55298 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
55299   int i;
55300   if( iFrom==iTo ) return;
55301   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
55302   for(i=0; i<pParse->nColCache; i++){
55303     int x = pParse->aColCache[i].iReg;
55304     if( x>=iFrom && x<iFrom+nReg ){
55305       pParse->aColCache[i].iReg += iTo-iFrom;
55306     }
55307   }
55308 }
55309
55310 /*
55311 ** Generate code to copy content from registers iFrom...iFrom+nReg-1
55312 ** over to iTo..iTo+nReg-1.
55313 */
55314 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
55315   int i;
55316   if( iFrom==iTo ) return;
55317   for(i=0; i<nReg; i++){
55318     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
55319   }
55320 }
55321
55322 /*
55323 ** Return true if any register in the range iFrom..iTo (inclusive)
55324 ** is used as part of the column cache.
55325 */
55326 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
55327   int i;
55328   for(i=0; i<pParse->nColCache; i++){
55329     int r = pParse->aColCache[i].iReg;
55330     if( r>=iFrom && r<=iTo ) return 1;
55331   }
55332   return 0;
55333 }
55334
55335 /*
55336 ** Theres is a value in register iCurrent.  We ultimately want
55337 ** the value to be in register iTarget.  It might be that
55338 ** iCurrent and iTarget are the same register.
55339 **
55340 ** We are going to modify the value, so we need to make sure it
55341 ** is not a cached register.  If iCurrent is a cached register,
55342 ** then try to move the value over to iTarget.  If iTarget is a
55343 ** cached register, then clear the corresponding cache line.
55344 **
55345 ** Return the register that the value ends up in.
55346 */
55347 SQLITE_PRIVATE int sqlite3ExprWritableRegister(Parse *pParse, int iCurrent, int iTarget){
55348   int i;
55349   assert( pParse->pVdbe!=0 );
55350   if( !usedAsColumnCache(pParse, iCurrent, iCurrent) ){
55351     return iCurrent;
55352   }
55353   if( iCurrent!=iTarget ){
55354     sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, iCurrent, iTarget);
55355   }
55356   for(i=0; i<pParse->nColCache; i++){
55357     if( pParse->aColCache[i].iReg==iTarget ){
55358       pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache];
55359       pParse->iColCache = pParse->nColCache;
55360     }
55361   }
55362   return iTarget;
55363 }
55364
55365 /*
55366 ** If the last instruction coded is an ephemeral copy of any of
55367 ** the registers in the nReg registers beginning with iReg, then
55368 ** convert the last instruction from OP_SCopy to OP_Copy.
55369 */
55370 SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){
55371   int addr;
55372   VdbeOp *pOp;
55373   Vdbe *v;
55374
55375   v = pParse->pVdbe;
55376   addr = sqlite3VdbeCurrentAddr(v);
55377   pOp = sqlite3VdbeGetOp(v, addr-1);
55378   assert( pOp || pParse->db->mallocFailed );
55379   if( pOp && pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1<iReg+nReg ){
55380     pOp->opcode = OP_Copy;
55381   }
55382 }
55383
55384 /*
55385 ** Generate code to store the value of the iAlias-th alias in register
55386 ** target.  The first time this is called, pExpr is evaluated to compute
55387 ** the value of the alias.  The value is stored in an auxiliary register
55388 ** and the number of that register is returned.  On subsequent calls,
55389 ** the register number is returned without generating any code.
55390 **
55391 ** Note that in order for this to work, code must be generated in the
55392 ** same order that it is executed.
55393 **
55394 ** Aliases are numbered starting with 1.  So iAlias is in the range
55395 ** of 1 to pParse->nAlias inclusive.  
55396 **
55397 ** pParse->aAlias[iAlias-1] records the register number where the value
55398 ** of the iAlias-th alias is stored.  If zero, that means that the
55399 ** alias has not yet been computed.
55400 */
55401 static int codeAlias(Parse *pParse, int iAlias, Expr *pExpr, int target){
55402   sqlite3 *db = pParse->db;
55403   int iReg;
55404   if( pParse->aAlias==0 ){
55405     pParse->aAlias = sqlite3DbMallocZero(db, 
55406                                  sizeof(pParse->aAlias[0])*pParse->nAlias );
55407     if( db->mallocFailed ) return 0;
55408   }
55409   assert( iAlias>0 && iAlias<=pParse->nAlias );
55410   iReg = pParse->aAlias[iAlias-1];
55411   if( iReg==0 ){
55412     if( pParse->disableColCache ){
55413       iReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
55414     }else{
55415       iReg = ++pParse->nMem;
55416       sqlite3ExprCode(pParse, pExpr, iReg);
55417       pParse->aAlias[iAlias-1] = iReg;
55418     }
55419   }
55420   return iReg;
55421 }
55422
55423 /*
55424 ** Generate code into the current Vdbe to evaluate the given
55425 ** expression.  Attempt to store the results in register "target".
55426 ** Return the register where results are stored.
55427 **
55428 ** With this routine, there is no guarantee that results will
55429 ** be stored in target.  The result might be stored in some other
55430 ** register if it is convenient to do so.  The calling function
55431 ** must check the return code and move the results to the desired
55432 ** register.
55433 */
55434 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
55435   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
55436   int op;                   /* The opcode being coded */
55437   int inReg = target;       /* Results stored in register inReg */
55438   int regFree1 = 0;         /* If non-zero free this temporary register */
55439   int regFree2 = 0;         /* If non-zero free this temporary register */
55440   int r1, r2, r3, r4;       /* Various register numbers */
55441   sqlite3 *db;
55442
55443   db = pParse->db;
55444   assert( v!=0 || db->mallocFailed );
55445   assert( target>0 && target<=pParse->nMem );
55446   if( v==0 ) return 0;
55447
55448   if( pExpr==0 ){
55449     op = TK_NULL;
55450   }else{
55451     op = pExpr->op;
55452   }
55453   switch( op ){
55454     case TK_AGG_COLUMN: {
55455       AggInfo *pAggInfo = pExpr->pAggInfo;
55456       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
55457       if( !pAggInfo->directMode ){
55458         assert( pCol->iMem>0 );
55459         inReg = pCol->iMem;
55460         break;
55461       }else if( pAggInfo->useSortingIdx ){
55462         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
55463                               pCol->iSorterColumn, target);
55464         break;
55465       }
55466       /* Otherwise, fall thru into the TK_COLUMN case */
55467     }
55468     case TK_COLUMN: {
55469       if( pExpr->iTable<0 ){
55470         /* This only happens when coding check constraints */
55471         assert( pParse->ckBase>0 );
55472         inReg = pExpr->iColumn + pParse->ckBase;
55473       }else{
55474         testcase( (pExpr->flags & EP_AnyAff)!=0 );
55475         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
55476                                  pExpr->iColumn, pExpr->iTable, target,
55477                                  pExpr->flags & EP_AnyAff);
55478       }
55479       break;
55480     }
55481     case TK_INTEGER: {
55482       codeInteger(v, pExpr, 0, target);
55483       break;
55484     }
55485     case TK_FLOAT: {
55486       codeReal(v, (char*)pExpr->token.z, pExpr->token.n, 0, target);
55487       break;
55488     }
55489     case TK_STRING: {
55490       sqlite3DequoteExpr(db, pExpr);
55491       sqlite3VdbeAddOp4(v,OP_String8, 0, target, 0,
55492                         (char*)pExpr->token.z, pExpr->token.n);
55493       break;
55494     }
55495     case TK_NULL: {
55496       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
55497       break;
55498     }
55499 #ifndef SQLITE_OMIT_BLOB_LITERAL
55500     case TK_BLOB: {
55501       int n;
55502       const char *z;
55503       char *zBlob;
55504       assert( pExpr->token.n>=3 );
55505       assert( pExpr->token.z[0]=='x' || pExpr->token.z[0]=='X' );
55506       assert( pExpr->token.z[1]=='\'' );
55507       assert( pExpr->token.z[pExpr->token.n-1]=='\'' );
55508       n = pExpr->token.n - 3;
55509       z = (char*)pExpr->token.z + 2;
55510       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
55511       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
55512       break;
55513     }
55514 #endif
55515     case TK_VARIABLE: {
55516       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iTable, target);
55517       if( pExpr->token.n>1 ){
55518         sqlite3VdbeChangeP4(v, -1, (char*)pExpr->token.z, pExpr->token.n);
55519       }
55520       break;
55521     }
55522     case TK_REGISTER: {
55523       inReg = pExpr->iTable;
55524       break;
55525     }
55526     case TK_AS: {
55527       inReg = codeAlias(pParse, pExpr->iTable, pExpr->pLeft, target);
55528       break;
55529     }
55530 #ifndef SQLITE_OMIT_CAST
55531     case TK_CAST: {
55532       /* Expressions of the form:   CAST(pLeft AS token) */
55533       int aff, to_op;
55534       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
55535       aff = sqlite3AffinityType(&pExpr->token);
55536       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
55537       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
55538       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
55539       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
55540       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
55541       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
55542       testcase( to_op==OP_ToText );
55543       testcase( to_op==OP_ToBlob );
55544       testcase( to_op==OP_ToNumeric );
55545       testcase( to_op==OP_ToInt );
55546       testcase( to_op==OP_ToReal );
55547       if( inReg!=target ){
55548         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
55549         inReg = target;
55550       }
55551       sqlite3VdbeAddOp1(v, to_op, inReg);
55552       testcase( usedAsColumnCache(pParse, inReg, inReg) );
55553       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
55554       break;
55555     }
55556 #endif /* SQLITE_OMIT_CAST */
55557     case TK_LT:
55558     case TK_LE:
55559     case TK_GT:
55560     case TK_GE:
55561     case TK_NE:
55562     case TK_EQ: {
55563       assert( TK_LT==OP_Lt );
55564       assert( TK_LE==OP_Le );
55565       assert( TK_GT==OP_Gt );
55566       assert( TK_GE==OP_Ge );
55567       assert( TK_EQ==OP_Eq );
55568       assert( TK_NE==OP_Ne );
55569       testcase( op==TK_LT );
55570       testcase( op==TK_LE );
55571       testcase( op==TK_GT );
55572       testcase( op==TK_GE );
55573       testcase( op==TK_EQ );
55574       testcase( op==TK_NE );
55575       codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
55576                                   pExpr->pRight, &r2, &regFree2);
55577       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
55578                   r1, r2, inReg, SQLITE_STOREP2);
55579       testcase( regFree1==0 );
55580       testcase( regFree2==0 );
55581       break;
55582     }
55583     case TK_AND:
55584     case TK_OR:
55585     case TK_PLUS:
55586     case TK_STAR:
55587     case TK_MINUS:
55588     case TK_REM:
55589     case TK_BITAND:
55590     case TK_BITOR:
55591     case TK_SLASH:
55592     case TK_LSHIFT:
55593     case TK_RSHIFT: 
55594     case TK_CONCAT: {
55595       assert( TK_AND==OP_And );
55596       assert( TK_OR==OP_Or );
55597       assert( TK_PLUS==OP_Add );
55598       assert( TK_MINUS==OP_Subtract );
55599       assert( TK_REM==OP_Remainder );
55600       assert( TK_BITAND==OP_BitAnd );
55601       assert( TK_BITOR==OP_BitOr );
55602       assert( TK_SLASH==OP_Divide );
55603       assert( TK_LSHIFT==OP_ShiftLeft );
55604       assert( TK_RSHIFT==OP_ShiftRight );
55605       assert( TK_CONCAT==OP_Concat );
55606       testcase( op==TK_AND );
55607       testcase( op==TK_OR );
55608       testcase( op==TK_PLUS );
55609       testcase( op==TK_MINUS );
55610       testcase( op==TK_REM );
55611       testcase( op==TK_BITAND );
55612       testcase( op==TK_BITOR );
55613       testcase( op==TK_SLASH );
55614       testcase( op==TK_LSHIFT );
55615       testcase( op==TK_RSHIFT );
55616       testcase( op==TK_CONCAT );
55617       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
55618       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
55619       sqlite3VdbeAddOp3(v, op, r2, r1, target);
55620       testcase( regFree1==0 );
55621       testcase( regFree2==0 );
55622       break;
55623     }
55624     case TK_UMINUS: {
55625       Expr *pLeft = pExpr->pLeft;
55626       assert( pLeft );
55627       if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){
55628         if( pLeft->op==TK_FLOAT ){
55629           codeReal(v, (char*)pLeft->token.z, pLeft->token.n, 1, target);
55630         }else{
55631           codeInteger(v, pLeft, 1, target);
55632         }
55633       }else{
55634         regFree1 = r1 = sqlite3GetTempReg(pParse);
55635         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
55636         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
55637         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
55638         testcase( regFree2==0 );
55639       }
55640       inReg = target;
55641       break;
55642     }
55643     case TK_BITNOT:
55644     case TK_NOT: {
55645       assert( TK_BITNOT==OP_BitNot );
55646       assert( TK_NOT==OP_Not );
55647       testcase( op==TK_BITNOT );
55648       testcase( op==TK_NOT );
55649       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
55650       testcase( inReg==target );
55651       testcase( usedAsColumnCache(pParse, inReg, inReg) );
55652       inReg = sqlite3ExprWritableRegister(pParse, inReg, target);
55653       sqlite3VdbeAddOp1(v, op, inReg);
55654       break;
55655     }
55656     case TK_ISNULL:
55657     case TK_NOTNULL: {
55658       int addr;
55659       assert( TK_ISNULL==OP_IsNull );
55660       assert( TK_NOTNULL==OP_NotNull );
55661       testcase( op==TK_ISNULL );
55662       testcase( op==TK_NOTNULL );
55663       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
55664       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
55665       testcase( regFree1==0 );
55666       addr = sqlite3VdbeAddOp1(v, op, r1);
55667       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
55668       sqlite3VdbeJumpHere(v, addr);
55669       break;
55670     }
55671     case TK_AGG_FUNCTION: {
55672       AggInfo *pInfo = pExpr->pAggInfo;
55673       if( pInfo==0 ){
55674         sqlite3ErrorMsg(pParse, "misuse of aggregate: %T",
55675             &pExpr->span);
55676       }else{
55677         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
55678       }
55679       break;
55680     }
55681     case TK_CONST_FUNC:
55682     case TK_FUNCTION: {
55683       ExprList *pList = pExpr->pList;
55684       int nExpr = pList ? pList->nExpr : 0;
55685       FuncDef *pDef;
55686       int nId;
55687       const char *zId;
55688       int constMask = 0;
55689       int i;
55690       u8 enc = ENC(db);
55691       CollSeq *pColl = 0;
55692
55693       testcase( op==TK_CONST_FUNC );
55694       testcase( op==TK_FUNCTION );
55695       zId = (char*)pExpr->token.z;
55696       nId = pExpr->token.n;
55697       pDef = sqlite3FindFunction(db, zId, nId, nExpr, enc, 0);
55698       assert( pDef!=0 );
55699       if( pList ){
55700         nExpr = pList->nExpr;
55701         r1 = sqlite3GetTempRange(pParse, nExpr);
55702         sqlite3ExprCodeExprList(pParse, pList, r1, 1);
55703       }else{
55704         nExpr = r1 = 0;
55705       }
55706 #ifndef SQLITE_OMIT_VIRTUALTABLE
55707       /* Possibly overload the function if the first argument is
55708       ** a virtual table column.
55709       **
55710       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
55711       ** second argument, not the first, as the argument to test to
55712       ** see if it is a column in a virtual table.  This is done because
55713       ** the left operand of infix functions (the operand we want to
55714       ** control overloading) ends up as the second argument to the
55715       ** function.  The expression "A glob B" is equivalent to 
55716       ** "glob(B,A).  We want to use the A in "A glob B" to test
55717       ** for function overloading.  But we use the B term in "glob(B,A)".
55718       */
55719       if( nExpr>=2 && (pExpr->flags & EP_InfixFunc) ){
55720         pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[1].pExpr);
55721       }else if( nExpr>0 ){
55722         pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[0].pExpr);
55723       }
55724 #endif
55725       for(i=0; i<nExpr && i<32; i++){
55726         if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
55727           constMask |= (1<<i);
55728         }
55729         if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
55730           pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
55731         }
55732       }
55733       if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
55734         if( !pColl ) pColl = db->pDfltColl; 
55735         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
55736       }
55737       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
55738                         (char*)pDef, P4_FUNCDEF);
55739       sqlite3VdbeChangeP5(v, nExpr);
55740       if( nExpr ){
55741         sqlite3ReleaseTempRange(pParse, r1, nExpr);
55742       }
55743       sqlite3ExprCacheAffinityChange(pParse, r1, nExpr);
55744       break;
55745     }
55746 #ifndef SQLITE_OMIT_SUBQUERY
55747     case TK_EXISTS:
55748     case TK_SELECT: {
55749       testcase( op==TK_EXISTS );
55750       testcase( op==TK_SELECT );
55751       if( pExpr->iColumn==0 ){
55752         sqlite3CodeSubselect(pParse, pExpr, 0, 0);
55753       }
55754       inReg = pExpr->iColumn;
55755       break;
55756     }
55757     case TK_IN: {
55758       int rNotFound = 0;
55759       int rMayHaveNull = 0;
55760       int j2, j3, j4, j5;
55761       char affinity;
55762       int eType;
55763
55764       VdbeNoopComment((v, "begin IN expr r%d", target));
55765       eType = sqlite3FindInIndex(pParse, pExpr, &rMayHaveNull);
55766       if( rMayHaveNull ){
55767         rNotFound = ++pParse->nMem;
55768       }
55769
55770       /* Figure out the affinity to use to create a key from the results
55771       ** of the expression. affinityStr stores a static string suitable for
55772       ** P4 of OP_MakeRecord.
55773       */
55774       affinity = comparisonAffinity(pExpr);
55775
55776
55777       /* Code the <expr> from "<expr> IN (...)". The temporary table
55778       ** pExpr->iTable contains the values that make up the (...) set.
55779       */
55780       pParse->disableColCache++;
55781       sqlite3ExprCode(pParse, pExpr->pLeft, target);
55782       pParse->disableColCache--;
55783       j2 = sqlite3VdbeAddOp1(v, OP_IsNull, target);
55784       if( eType==IN_INDEX_ROWID ){
55785         j3 = sqlite3VdbeAddOp1(v, OP_MustBeInt, target);
55786         j4 = sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, 0, target);
55787         sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
55788         j5 = sqlite3VdbeAddOp0(v, OP_Goto);
55789         sqlite3VdbeJumpHere(v, j3);
55790         sqlite3VdbeJumpHere(v, j4);
55791         sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
55792       }else{
55793         r2 = regFree2 = sqlite3GetTempReg(pParse);
55794
55795         /* Create a record and test for set membership. If the set contains
55796         ** the value, then jump to the end of the test code. The target
55797         ** register still contains the true (1) value written to it earlier.
55798         */
55799         sqlite3VdbeAddOp4(v, OP_MakeRecord, target, 1, r2, &affinity, 1);
55800         sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
55801         j5 = sqlite3VdbeAddOp3(v, OP_Found, pExpr->iTable, 0, r2);
55802
55803         /* If the set membership test fails, then the result of the 
55804         ** "x IN (...)" expression must be either 0 or NULL. If the set
55805         ** contains no NULL values, then the result is 0. If the set 
55806         ** contains one or more NULL values, then the result of the
55807         ** expression is also NULL.
55808         */
55809         if( rNotFound==0 ){
55810           /* This branch runs if it is known at compile time (now) that 
55811           ** the set contains no NULL values. This happens as the result
55812           ** of a "NOT NULL" constraint in the database schema. No need
55813           ** to test the data structure at runtime in this case.
55814           */
55815           sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
55816         }else{
55817           /* This block populates the rNotFound register with either NULL
55818           ** or 0 (an integer value). If the data structure contains one
55819           ** or more NULLs, then set rNotFound to NULL. Otherwise, set it
55820           ** to 0. If register rMayHaveNull is already set to some value
55821           ** other than NULL, then the test has already been run and 
55822           ** rNotFound is already populated.
55823           */
55824           static const char nullRecord[] = { 0x02, 0x00 };
55825           j3 = sqlite3VdbeAddOp1(v, OP_NotNull, rMayHaveNull);
55826           sqlite3VdbeAddOp2(v, OP_Null, 0, rNotFound);
55827           sqlite3VdbeAddOp4(v, OP_Blob, 2, rMayHaveNull, 0, 
55828                              nullRecord, P4_STATIC);
55829           j4 = sqlite3VdbeAddOp3(v, OP_Found, pExpr->iTable, 0, rMayHaveNull);
55830           sqlite3VdbeAddOp2(v, OP_Integer, 0, rNotFound);
55831           sqlite3VdbeJumpHere(v, j4);
55832           sqlite3VdbeJumpHere(v, j3);
55833
55834           /* Copy the value of register rNotFound (which is either NULL or 0)
55835           ** into the target register. This will be the result of the
55836           ** expression.
55837           */
55838           sqlite3VdbeAddOp2(v, OP_Copy, rNotFound, target);
55839         }
55840       }
55841       sqlite3VdbeJumpHere(v, j2);
55842       sqlite3VdbeJumpHere(v, j5);
55843       VdbeComment((v, "end IN expr r%d", target));
55844       break;
55845     }
55846 #endif
55847     /*
55848     **    x BETWEEN y AND z
55849     **
55850     ** This is equivalent to
55851     **
55852     **    x>=y AND x<=z
55853     **
55854     ** X is stored in pExpr->pLeft.
55855     ** Y is stored in pExpr->pList->a[0].pExpr.
55856     ** Z is stored in pExpr->pList->a[1].pExpr.
55857     */
55858     case TK_BETWEEN: {
55859       Expr *pLeft = pExpr->pLeft;
55860       struct ExprList_item *pLItem = pExpr->pList->a;
55861       Expr *pRight = pLItem->pExpr;
55862
55863       codeCompareOperands(pParse, pLeft, &r1, &regFree1,
55864                                   pRight, &r2, &regFree2);
55865       testcase( regFree1==0 );
55866       testcase( regFree2==0 );
55867       r3 = sqlite3GetTempReg(pParse);
55868       r4 = sqlite3GetTempReg(pParse);
55869       codeCompare(pParse, pLeft, pRight, OP_Ge,
55870                   r1, r2, r3, SQLITE_STOREP2);
55871       pLItem++;
55872       pRight = pLItem->pExpr;
55873       sqlite3ReleaseTempReg(pParse, regFree2);
55874       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
55875       testcase( regFree2==0 );
55876       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
55877       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
55878       sqlite3ReleaseTempReg(pParse, r3);
55879       sqlite3ReleaseTempReg(pParse, r4);
55880       break;
55881     }
55882     case TK_UPLUS: {
55883       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
55884       break;
55885     }
55886
55887     /*
55888     ** Form A:
55889     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
55890     **
55891     ** Form B:
55892     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
55893     **
55894     ** Form A is can be transformed into the equivalent form B as follows:
55895     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
55896     **        WHEN x=eN THEN rN ELSE y END
55897     **
55898     ** X (if it exists) is in pExpr->pLeft.
55899     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
55900     ** ELSE clause and no other term matches, then the result of the
55901     ** exprssion is NULL.
55902     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
55903     **
55904     ** The result of the expression is the Ri for the first matching Ei,
55905     ** or if there is no matching Ei, the ELSE term Y, or if there is
55906     ** no ELSE term, NULL.
55907     */
55908     case TK_CASE: {
55909       int endLabel;                     /* GOTO label for end of CASE stmt */
55910       int nextCase;                     /* GOTO label for next WHEN clause */
55911       int nExpr;                        /* 2x number of WHEN terms */
55912       int i;                            /* Loop counter */
55913       ExprList *pEList;                 /* List of WHEN terms */
55914       struct ExprList_item *aListelem;  /* Array of WHEN terms */
55915       Expr opCompare;                   /* The X==Ei expression */
55916       Expr cacheX;                      /* Cached expression X */
55917       Expr *pX;                         /* The X expression */
55918       Expr *pTest;                      /* X==Ei (form A) or just Ei (form B) */
55919
55920       assert(pExpr->pList);
55921       assert((pExpr->pList->nExpr % 2) == 0);
55922       assert(pExpr->pList->nExpr > 0);
55923       pEList = pExpr->pList;
55924       aListelem = pEList->a;
55925       nExpr = pEList->nExpr;
55926       endLabel = sqlite3VdbeMakeLabel(v);
55927       if( (pX = pExpr->pLeft)!=0 ){
55928         cacheX = *pX;
55929         testcase( pX->op==TK_COLUMN || pX->op==TK_REGISTER );
55930         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
55931         testcase( regFree1==0 );
55932         cacheX.op = TK_REGISTER;
55933         opCompare.op = TK_EQ;
55934         opCompare.pLeft = &cacheX;
55935         pTest = &opCompare;
55936       }
55937       pParse->disableColCache++;
55938       for(i=0; i<nExpr; i=i+2){
55939         if( pX ){
55940           opCompare.pRight = aListelem[i].pExpr;
55941         }else{
55942           pTest = aListelem[i].pExpr;
55943         }
55944         nextCase = sqlite3VdbeMakeLabel(v);
55945         testcase( pTest->op==TK_COLUMN || pTest->op==TK_REGISTER );
55946         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
55947         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
55948         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
55949         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
55950         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
55951         sqlite3VdbeResolveLabel(v, nextCase);
55952       }
55953       if( pExpr->pRight ){
55954         sqlite3ExprCode(pParse, pExpr->pRight, target);
55955       }else{
55956         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
55957       }
55958       sqlite3VdbeResolveLabel(v, endLabel);
55959       assert( pParse->disableColCache>0 );
55960       pParse->disableColCache--;
55961       break;
55962     }
55963 #ifndef SQLITE_OMIT_TRIGGER
55964     case TK_RAISE: {
55965       if( !pParse->trigStack ){
55966         sqlite3ErrorMsg(pParse,
55967                        "RAISE() may only be used within a trigger-program");
55968         return 0;
55969       }
55970       if( pExpr->iColumn!=OE_Ignore ){
55971          assert( pExpr->iColumn==OE_Rollback ||
55972                  pExpr->iColumn == OE_Abort ||
55973                  pExpr->iColumn == OE_Fail );
55974          sqlite3DequoteExpr(db, pExpr);
55975          sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn, 0,
55976                         (char*)pExpr->token.z, pExpr->token.n);
55977       } else {
55978          assert( pExpr->iColumn == OE_Ignore );
55979          sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0);
55980          sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
55981          VdbeComment((v, "raise(IGNORE)"));
55982       }
55983       break;
55984     }
55985 #endif
55986   }
55987   sqlite3ReleaseTempReg(pParse, regFree1);
55988   sqlite3ReleaseTempReg(pParse, regFree2);
55989   return inReg;
55990 }
55991
55992 /*
55993 ** Generate code to evaluate an expression and store the results
55994 ** into a register.  Return the register number where the results
55995 ** are stored.
55996 **
55997 ** If the register is a temporary register that can be deallocated,
55998 ** then write its number into *pReg.  If the result register is not
55999 ** a temporary, then set *pReg to zero.
56000 */
56001 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
56002   int r1 = sqlite3GetTempReg(pParse);
56003   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
56004   if( r2==r1 ){
56005     *pReg = r1;
56006   }else{
56007     sqlite3ReleaseTempReg(pParse, r1);
56008     *pReg = 0;
56009   }
56010   return r2;
56011 }
56012
56013 /*
56014 ** Generate code that will evaluate expression pExpr and store the
56015 ** results in register target.  The results are guaranteed to appear
56016 ** in register target.
56017 */
56018 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
56019   int inReg;
56020
56021   assert( target>0 && target<=pParse->nMem );
56022   inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
56023   assert( pParse->pVdbe || pParse->db->mallocFailed );
56024   if( inReg!=target && pParse->pVdbe ){
56025     sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
56026   }
56027   return target;
56028 }
56029
56030 /*
56031 ** Generate code that evalutes the given expression and puts the result
56032 ** in register target.
56033 **
56034 ** Also make a copy of the expression results into another "cache" register
56035 ** and modify the expression so that the next time it is evaluated,
56036 ** the result is a copy of the cache register.
56037 **
56038 ** This routine is used for expressions that are used multiple 
56039 ** times.  They are evaluated once and the results of the expression
56040 ** are reused.
56041 */
56042 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
56043   Vdbe *v = pParse->pVdbe;
56044   int inReg;
56045   inReg = sqlite3ExprCode(pParse, pExpr, target);
56046   assert( target>0 );
56047   if( pExpr->op!=TK_REGISTER ){  
56048     int iMem;
56049     iMem = ++pParse->nMem;
56050     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
56051     pExpr->iTable = iMem;
56052     pExpr->op = TK_REGISTER;
56053   }
56054   return inReg;
56055 }
56056
56057 /*
56058 ** Return TRUE if pExpr is an constant expression that is appropriate
56059 ** for factoring out of a loop.  Appropriate expressions are:
56060 **
56061 **    *  Any expression that evaluates to two or more opcodes.
56062 **
56063 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, 
56064 **       or OP_Variable that does not need to be placed in a 
56065 **       specific register.
56066 **
56067 ** There is no point in factoring out single-instruction constant
56068 ** expressions that need to be placed in a particular register.  
56069 ** We could factor them out, but then we would end up adding an
56070 ** OP_SCopy instruction to move the value into the correct register
56071 ** later.  We might as well just use the original instruction and
56072 ** avoid the OP_SCopy.
56073 */
56074 static int isAppropriateForFactoring(Expr *p){
56075   if( !sqlite3ExprIsConstantNotJoin(p) ){
56076     return 0;  /* Only constant expressions are appropriate for factoring */
56077   }
56078   if( (p->flags & EP_FixedDest)==0 ){
56079     return 1;  /* Any constant without a fixed destination is appropriate */
56080   }
56081   while( p->op==TK_UPLUS ) p = p->pLeft;
56082   switch( p->op ){
56083 #ifndef SQLITE_OMIT_BLOB_LITERAL
56084     case TK_BLOB:
56085 #endif
56086     case TK_VARIABLE:
56087     case TK_INTEGER:
56088     case TK_FLOAT:
56089     case TK_NULL:
56090     case TK_STRING: {
56091       testcase( p->op==TK_BLOB );
56092       testcase( p->op==TK_VARIABLE );
56093       testcase( p->op==TK_INTEGER );
56094       testcase( p->op==TK_FLOAT );
56095       testcase( p->op==TK_NULL );
56096       testcase( p->op==TK_STRING );
56097       /* Single-instruction constants with a fixed destination are
56098       ** better done in-line.  If we factor them, they will just end
56099       ** up generating an OP_SCopy to move the value to the destination
56100       ** register. */
56101       return 0;
56102     }
56103     case TK_UMINUS: {
56104        if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
56105          return 0;
56106        }
56107        break;
56108     }
56109     default: {
56110       break;
56111     }
56112   }
56113   return 1;
56114 }
56115
56116 /*
56117 ** If pExpr is a constant expression that is appropriate for
56118 ** factoring out of a loop, then evaluate the expression
56119 ** into a register and convert the expression into a TK_REGISTER
56120 ** expression.
56121 */
56122 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
56123   Parse *pParse = pWalker->pParse;
56124   switch( pExpr->op ){
56125     case TK_REGISTER: {
56126       return 1;
56127     }
56128     case TK_FUNCTION:
56129     case TK_AGG_FUNCTION:
56130     case TK_CONST_FUNC: {
56131       /* The arguments to a function have a fixed destination.
56132       ** Mark them this way to avoid generated unneeded OP_SCopy
56133       ** instructions. 
56134       */
56135       ExprList *pList = pExpr->pList;
56136       if( pList ){
56137         int i = pList->nExpr;
56138         struct ExprList_item *pItem = pList->a;
56139         for(; i>0; i--, pItem++){
56140           if( pItem->pExpr ) pItem->pExpr->flags |= EP_FixedDest;
56141         }
56142       }
56143       break;
56144     }
56145   }
56146   if( isAppropriateForFactoring(pExpr) ){
56147     int r1 = ++pParse->nMem;
56148     int r2;
56149     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
56150     if( r1!=r2 ) sqlite3ReleaseTempReg(pParse, r1);
56151     pExpr->op = TK_REGISTER;
56152     pExpr->iTable = r2;
56153     return WRC_Prune;
56154   }
56155   return WRC_Continue;
56156 }
56157
56158 /*
56159 ** Preevaluate constant subexpressions within pExpr and store the
56160 ** results in registers.  Modify pExpr so that the constant subexpresions
56161 ** are TK_REGISTER opcodes that refer to the precomputed values.
56162 */
56163 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
56164   Walker w;
56165   w.xExprCallback = evalConstExpr;
56166   w.xSelectCallback = 0;
56167   w.pParse = pParse;
56168   sqlite3WalkExpr(&w, pExpr);
56169 }
56170
56171
56172 /*
56173 ** Generate code that pushes the value of every element of the given
56174 ** expression list into a sequence of registers beginning at target.
56175 **
56176 ** Return the number of elements evaluated.
56177 */
56178 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
56179   Parse *pParse,     /* Parsing context */
56180   ExprList *pList,   /* The expression list to be coded */
56181   int target,        /* Where to write results */
56182   int doHardCopy     /* Make a hard copy of every element */
56183 ){
56184   struct ExprList_item *pItem;
56185   int i, n;
56186   assert( pList!=0 );
56187   assert( target>0 );
56188   n = pList->nExpr;
56189   for(pItem=pList->a, i=0; i<n; i++, pItem++){
56190     if( pItem->iAlias ){
56191       int iReg = codeAlias(pParse, pItem->iAlias, pItem->pExpr, target+i);
56192       Vdbe *v = sqlite3GetVdbe(pParse);
56193       if( iReg!=target+i ){
56194         sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target+i);
56195       }
56196     }else{
56197       sqlite3ExprCode(pParse, pItem->pExpr, target+i);
56198     }
56199     if( doHardCopy ){
56200       sqlite3ExprHardCopy(pParse, target, n);
56201     }
56202   }
56203   return n;
56204 }
56205
56206 /*
56207 ** Generate code for a boolean expression such that a jump is made
56208 ** to the label "dest" if the expression is true but execution
56209 ** continues straight thru if the expression is false.
56210 **
56211 ** If the expression evaluates to NULL (neither true nor false), then
56212 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
56213 **
56214 ** This code depends on the fact that certain token values (ex: TK_EQ)
56215 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
56216 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
56217 ** the make process cause these values to align.  Assert()s in the code
56218 ** below verify that the numbers are aligned correctly.
56219 */
56220 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
56221   Vdbe *v = pParse->pVdbe;
56222   int op = 0;
56223   int regFree1 = 0;
56224   int regFree2 = 0;
56225   int r1, r2;
56226
56227   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
56228   if( v==0 || pExpr==0 ) return;
56229   op = pExpr->op;
56230   switch( op ){
56231     case TK_AND: {
56232       int d2 = sqlite3VdbeMakeLabel(v);
56233       testcase( jumpIfNull==0 );
56234       testcase( pParse->disableColCache==0 );
56235       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
56236       pParse->disableColCache++;
56237       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
56238       assert( pParse->disableColCache>0 );
56239       pParse->disableColCache--;
56240       sqlite3VdbeResolveLabel(v, d2);
56241       break;
56242     }
56243     case TK_OR: {
56244       testcase( jumpIfNull==0 );
56245       testcase( pParse->disableColCache==0 );
56246       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
56247       pParse->disableColCache++;
56248       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
56249       assert( pParse->disableColCache>0 );
56250       pParse->disableColCache--;
56251       break;
56252     }
56253     case TK_NOT: {
56254       testcase( jumpIfNull==0 );
56255       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
56256       break;
56257     }
56258     case TK_LT:
56259     case TK_LE:
56260     case TK_GT:
56261     case TK_GE:
56262     case TK_NE:
56263     case TK_EQ: {
56264       assert( TK_LT==OP_Lt );
56265       assert( TK_LE==OP_Le );
56266       assert( TK_GT==OP_Gt );
56267       assert( TK_GE==OP_Ge );
56268       assert( TK_EQ==OP_Eq );
56269       assert( TK_NE==OP_Ne );
56270       testcase( op==TK_LT );
56271       testcase( op==TK_LE );
56272       testcase( op==TK_GT );
56273       testcase( op==TK_GE );
56274       testcase( op==TK_EQ );
56275       testcase( op==TK_NE );
56276       testcase( jumpIfNull==0 );
56277       codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
56278                                   pExpr->pRight, &r2, &regFree2);
56279       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
56280                   r1, r2, dest, jumpIfNull);
56281       testcase( regFree1==0 );
56282       testcase( regFree2==0 );
56283       break;
56284     }
56285     case TK_ISNULL:
56286     case TK_NOTNULL: {
56287       assert( TK_ISNULL==OP_IsNull );
56288       assert( TK_NOTNULL==OP_NotNull );
56289       testcase( op==TK_ISNULL );
56290       testcase( op==TK_NOTNULL );
56291       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
56292       sqlite3VdbeAddOp2(v, op, r1, dest);
56293       testcase( regFree1==0 );
56294       break;
56295     }
56296     case TK_BETWEEN: {
56297       /*    x BETWEEN y AND z
56298       **
56299       ** Is equivalent to 
56300       **
56301       **    x>=y AND x<=z
56302       **
56303       ** Code it as such, taking care to do the common subexpression
56304       ** elementation of x.
56305       */
56306       Expr exprAnd;
56307       Expr compLeft;
56308       Expr compRight;
56309       Expr exprX;
56310
56311       exprX = *pExpr->pLeft;
56312       exprAnd.op = TK_AND;
56313       exprAnd.pLeft = &compLeft;
56314       exprAnd.pRight = &compRight;
56315       compLeft.op = TK_GE;
56316       compLeft.pLeft = &exprX;
56317       compLeft.pRight = pExpr->pList->a[0].pExpr;
56318       compRight.op = TK_LE;
56319       compRight.pLeft = &exprX;
56320       compRight.pRight = pExpr->pList->a[1].pExpr;
56321       exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
56322       testcase( regFree1==0 );
56323       exprX.op = TK_REGISTER;
56324       testcase( jumpIfNull==0 );
56325       sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
56326       break;
56327     }
56328     default: {
56329       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
56330       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
56331       testcase( regFree1==0 );
56332       testcase( jumpIfNull==0 );
56333       break;
56334     }
56335   }
56336   sqlite3ReleaseTempReg(pParse, regFree1);
56337   sqlite3ReleaseTempReg(pParse, regFree2);  
56338 }
56339
56340 /*
56341 ** Generate code for a boolean expression such that a jump is made
56342 ** to the label "dest" if the expression is false but execution
56343 ** continues straight thru if the expression is true.
56344 **
56345 ** If the expression evaluates to NULL (neither true nor false) then
56346 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
56347 ** is 0.
56348 */
56349 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
56350   Vdbe *v = pParse->pVdbe;
56351   int op = 0;
56352   int regFree1 = 0;
56353   int regFree2 = 0;
56354   int r1, r2;
56355
56356   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
56357   if( v==0 || pExpr==0 ) return;
56358
56359   /* The value of pExpr->op and op are related as follows:
56360   **
56361   **       pExpr->op            op
56362   **       ---------          ----------
56363   **       TK_ISNULL          OP_NotNull
56364   **       TK_NOTNULL         OP_IsNull
56365   **       TK_NE              OP_Eq
56366   **       TK_EQ              OP_Ne
56367   **       TK_GT              OP_Le
56368   **       TK_LE              OP_Gt
56369   **       TK_GE              OP_Lt
56370   **       TK_LT              OP_Ge
56371   **
56372   ** For other values of pExpr->op, op is undefined and unused.
56373   ** The value of TK_ and OP_ constants are arranged such that we
56374   ** can compute the mapping above using the following expression.
56375   ** Assert()s verify that the computation is correct.
56376   */
56377   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
56378
56379   /* Verify correct alignment of TK_ and OP_ constants
56380   */
56381   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
56382   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
56383   assert( pExpr->op!=TK_NE || op==OP_Eq );
56384   assert( pExpr->op!=TK_EQ || op==OP_Ne );
56385   assert( pExpr->op!=TK_LT || op==OP_Ge );
56386   assert( pExpr->op!=TK_LE || op==OP_Gt );
56387   assert( pExpr->op!=TK_GT || op==OP_Le );
56388   assert( pExpr->op!=TK_GE || op==OP_Lt );
56389
56390   switch( pExpr->op ){
56391     case TK_AND: {
56392       testcase( jumpIfNull==0 );
56393       testcase( pParse->disableColCache==0 );
56394       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
56395       pParse->disableColCache++;
56396       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
56397       assert( pParse->disableColCache>0 );
56398       pParse->disableColCache--;
56399       break;
56400     }
56401     case TK_OR: {
56402       int d2 = sqlite3VdbeMakeLabel(v);
56403       testcase( jumpIfNull==0 );
56404       testcase( pParse->disableColCache==0 );
56405       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
56406       pParse->disableColCache++;
56407       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
56408       assert( pParse->disableColCache>0 );
56409       pParse->disableColCache--;
56410       sqlite3VdbeResolveLabel(v, d2);
56411       break;
56412     }
56413     case TK_NOT: {
56414       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
56415       break;
56416     }
56417     case TK_LT:
56418     case TK_LE:
56419     case TK_GT:
56420     case TK_GE:
56421     case TK_NE:
56422     case TK_EQ: {
56423       testcase( op==TK_LT );
56424       testcase( op==TK_LE );
56425       testcase( op==TK_GT );
56426       testcase( op==TK_GE );
56427       testcase( op==TK_EQ );
56428       testcase( op==TK_NE );
56429       testcase( jumpIfNull==0 );
56430       codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
56431                                   pExpr->pRight, &r2, &regFree2);
56432       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
56433                   r1, r2, dest, jumpIfNull);
56434       testcase( regFree1==0 );
56435       testcase( regFree2==0 );
56436       break;
56437     }
56438     case TK_ISNULL:
56439     case TK_NOTNULL: {
56440       testcase( op==TK_ISNULL );
56441       testcase( op==TK_NOTNULL );
56442       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
56443       sqlite3VdbeAddOp2(v, op, r1, dest);
56444       testcase( regFree1==0 );
56445       break;
56446     }
56447     case TK_BETWEEN: {
56448       /*    x BETWEEN y AND z
56449       **
56450       ** Is equivalent to 
56451       **
56452       **    x>=y AND x<=z
56453       **
56454       ** Code it as such, taking care to do the common subexpression
56455       ** elementation of x.
56456       */
56457       Expr exprAnd;
56458       Expr compLeft;
56459       Expr compRight;
56460       Expr exprX;
56461
56462       exprX = *pExpr->pLeft;
56463       exprAnd.op = TK_AND;
56464       exprAnd.pLeft = &compLeft;
56465       exprAnd.pRight = &compRight;
56466       compLeft.op = TK_GE;
56467       compLeft.pLeft = &exprX;
56468       compLeft.pRight = pExpr->pList->a[0].pExpr;
56469       compRight.op = TK_LE;
56470       compRight.pLeft = &exprX;
56471       compRight.pRight = pExpr->pList->a[1].pExpr;
56472       exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
56473       testcase( regFree1==0 );
56474       exprX.op = TK_REGISTER;
56475       testcase( jumpIfNull==0 );
56476       sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
56477       break;
56478     }
56479     default: {
56480       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
56481       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
56482       testcase( regFree1==0 );
56483       testcase( jumpIfNull==0 );
56484       break;
56485     }
56486   }
56487   sqlite3ReleaseTempReg(pParse, regFree1);
56488   sqlite3ReleaseTempReg(pParse, regFree2);
56489 }
56490
56491 /*
56492 ** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
56493 ** if they are identical and return FALSE if they differ in any way.
56494 **
56495 ** Sometimes this routine will return FALSE even if the two expressions
56496 ** really are equivalent.  If we cannot prove that the expressions are
56497 ** identical, we return FALSE just to be safe.  So if this routine
56498 ** returns false, then you do not really know for certain if the two
56499 ** expressions are the same.  But if you get a TRUE return, then you
56500 ** can be sure the expressions are the same.  In the places where
56501 ** this routine is used, it does not hurt to get an extra FALSE - that
56502 ** just might result in some slightly slower code.  But returning
56503 ** an incorrect TRUE could lead to a malfunction.
56504 */
56505 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
56506   int i;
56507   if( pA==0||pB==0 ){
56508     return pB==pA;
56509   }
56510   if( pA->op!=pB->op ) return 0;
56511   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
56512   if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
56513   if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
56514   if( pA->pList ){
56515     if( pB->pList==0 ) return 0;
56516     if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
56517     for(i=0; i<pA->pList->nExpr; i++){
56518       if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
56519         return 0;
56520       }
56521     }
56522   }else if( pB->pList ){
56523     return 0;
56524   }
56525   if( pA->pSelect || pB->pSelect ) return 0;
56526   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
56527   if( pA->op!=TK_COLUMN && pA->token.z ){
56528     if( pB->token.z==0 ) return 0;
56529     if( pB->token.n!=pA->token.n ) return 0;
56530     if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){
56531       return 0;
56532     }
56533   }
56534   return 1;
56535 }
56536
56537
56538 /*
56539 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
56540 ** the new element.  Return a negative number if malloc fails.
56541 */
56542 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
56543   int i;
56544   pInfo->aCol = sqlite3ArrayAllocate(
56545        db,
56546        pInfo->aCol,
56547        sizeof(pInfo->aCol[0]),
56548        3,
56549        &pInfo->nColumn,
56550        &pInfo->nColumnAlloc,
56551        &i
56552   );
56553   return i;
56554 }    
56555
56556 /*
56557 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
56558 ** the new element.  Return a negative number if malloc fails.
56559 */
56560 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
56561   int i;
56562   pInfo->aFunc = sqlite3ArrayAllocate(
56563        db, 
56564        pInfo->aFunc,
56565        sizeof(pInfo->aFunc[0]),
56566        3,
56567        &pInfo->nFunc,
56568        &pInfo->nFuncAlloc,
56569        &i
56570   );
56571   return i;
56572 }    
56573
56574 /*
56575 ** This is the xExprCallback for a tree walker.  It is used to
56576 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
56577 ** for additional information.
56578 */
56579 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
56580   int i;
56581   NameContext *pNC = pWalker->u.pNC;
56582   Parse *pParse = pNC->pParse;
56583   SrcList *pSrcList = pNC->pSrcList;
56584   AggInfo *pAggInfo = pNC->pAggInfo;
56585
56586   switch( pExpr->op ){
56587     case TK_AGG_COLUMN:
56588     case TK_COLUMN: {
56589       testcase( pExpr->op==TK_AGG_COLUMN );
56590       testcase( pExpr->op==TK_COLUMN );
56591       /* Check to see if the column is in one of the tables in the FROM
56592       ** clause of the aggregate query */
56593       if( pSrcList ){
56594         struct SrcList_item *pItem = pSrcList->a;
56595         for(i=0; i<pSrcList->nSrc; i++, pItem++){
56596           struct AggInfo_col *pCol;
56597           if( pExpr->iTable==pItem->iCursor ){
56598             /* If we reach this point, it means that pExpr refers to a table
56599             ** that is in the FROM clause of the aggregate query.  
56600             **
56601             ** Make an entry for the column in pAggInfo->aCol[] if there
56602             ** is not an entry there already.
56603             */
56604             int k;
56605             pCol = pAggInfo->aCol;
56606             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
56607               if( pCol->iTable==pExpr->iTable &&
56608                   pCol->iColumn==pExpr->iColumn ){
56609                 break;
56610               }
56611             }
56612             if( (k>=pAggInfo->nColumn)
56613              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
56614             ){
56615               pCol = &pAggInfo->aCol[k];
56616               pCol->pTab = pExpr->pTab;
56617               pCol->iTable = pExpr->iTable;
56618               pCol->iColumn = pExpr->iColumn;
56619               pCol->iMem = ++pParse->nMem;
56620               pCol->iSorterColumn = -1;
56621               pCol->pExpr = pExpr;
56622               if( pAggInfo->pGroupBy ){
56623                 int j, n;
56624                 ExprList *pGB = pAggInfo->pGroupBy;
56625                 struct ExprList_item *pTerm = pGB->a;
56626                 n = pGB->nExpr;
56627                 for(j=0; j<n; j++, pTerm++){
56628                   Expr *pE = pTerm->pExpr;
56629                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
56630                       pE->iColumn==pExpr->iColumn ){
56631                     pCol->iSorterColumn = j;
56632                     break;
56633                   }
56634                 }
56635               }
56636               if( pCol->iSorterColumn<0 ){
56637                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
56638               }
56639             }
56640             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
56641             ** because it was there before or because we just created it).
56642             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
56643             ** pAggInfo->aCol[] entry.
56644             */
56645             pExpr->pAggInfo = pAggInfo;
56646             pExpr->op = TK_AGG_COLUMN;
56647             pExpr->iAgg = k;
56648             break;
56649           } /* endif pExpr->iTable==pItem->iCursor */
56650         } /* end loop over pSrcList */
56651       }
56652       return WRC_Prune;
56653     }
56654     case TK_AGG_FUNCTION: {
56655       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
56656       ** to be ignored */
56657       if( pNC->nDepth==0 ){
56658         /* Check to see if pExpr is a duplicate of another aggregate 
56659         ** function that is already in the pAggInfo structure
56660         */
56661         struct AggInfo_func *pItem = pAggInfo->aFunc;
56662         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
56663           if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
56664             break;
56665           }
56666         }
56667         if( i>=pAggInfo->nFunc ){
56668           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
56669           */
56670           u8 enc = ENC(pParse->db);
56671           i = addAggInfoFunc(pParse->db, pAggInfo);
56672           if( i>=0 ){
56673             pItem = &pAggInfo->aFunc[i];
56674             pItem->pExpr = pExpr;
56675             pItem->iMem = ++pParse->nMem;
56676             pItem->pFunc = sqlite3FindFunction(pParse->db,
56677                    (char*)pExpr->token.z, pExpr->token.n,
56678                    pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
56679             if( pExpr->flags & EP_Distinct ){
56680               pItem->iDistinct = pParse->nTab++;
56681             }else{
56682               pItem->iDistinct = -1;
56683             }
56684           }
56685         }
56686         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
56687         */
56688         pExpr->iAgg = i;
56689         pExpr->pAggInfo = pAggInfo;
56690         return WRC_Prune;
56691       }
56692     }
56693   }
56694   return WRC_Continue;
56695 }
56696 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
56697   NameContext *pNC = pWalker->u.pNC;
56698   if( pNC->nDepth==0 ){
56699     pNC->nDepth++;
56700     sqlite3WalkSelect(pWalker, pSelect);
56701     pNC->nDepth--;
56702     return WRC_Prune;
56703   }else{
56704     return WRC_Continue;
56705   }
56706 }
56707
56708 /*
56709 ** Analyze the given expression looking for aggregate functions and
56710 ** for variables that need to be added to the pParse->aAgg[] array.
56711 ** Make additional entries to the pParse->aAgg[] array as necessary.
56712 **
56713 ** This routine should only be called after the expression has been
56714 ** analyzed by sqlite3ResolveExprNames().
56715 */
56716 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
56717   Walker w;
56718   w.xExprCallback = analyzeAggregate;
56719   w.xSelectCallback = analyzeAggregatesInSelect;
56720   w.u.pNC = pNC;
56721   sqlite3WalkExpr(&w, pExpr);
56722 }
56723
56724 /*
56725 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
56726 ** expression list.  Return the number of errors.
56727 **
56728 ** If an error is found, the analysis is cut short.
56729 */
56730 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
56731   struct ExprList_item *pItem;
56732   int i;
56733   if( pList ){
56734     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
56735       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
56736     }
56737   }
56738 }
56739
56740 /*
56741 ** Allocate or deallocate temporary use registers during code generation.
56742 */
56743 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
56744   if( pParse->nTempReg==0 ){
56745     return ++pParse->nMem;
56746   }
56747   return pParse->aTempReg[--pParse->nTempReg];
56748 }
56749 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
56750   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
56751     sqlite3ExprWritableRegister(pParse, iReg, iReg);
56752     pParse->aTempReg[pParse->nTempReg++] = iReg;
56753   }
56754 }
56755
56756 /*
56757 ** Allocate or deallocate a block of nReg consecutive registers
56758 */
56759 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
56760   int i, n;
56761   i = pParse->iRangeReg;
56762   n = pParse->nRangeReg;
56763   if( nReg<=n && !usedAsColumnCache(pParse, i, i+n-1) ){
56764     pParse->iRangeReg += nReg;
56765     pParse->nRangeReg -= nReg;
56766   }else{
56767     i = pParse->nMem+1;
56768     pParse->nMem += nReg;
56769   }
56770   return i;
56771 }
56772 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
56773   if( nReg>pParse->nRangeReg ){
56774     pParse->nRangeReg = nReg;
56775     pParse->iRangeReg = iReg;
56776   }
56777 }
56778
56779 /************** End of expr.c ************************************************/
56780 /************** Begin file alter.c *******************************************/
56781 /*
56782 ** 2005 February 15
56783 **
56784 ** The author disclaims copyright to this source code.  In place of
56785 ** a legal notice, here is a blessing:
56786 **
56787 **    May you do good and not evil.
56788 **    May you find forgiveness for yourself and forgive others.
56789 **    May you share freely, never taking more than you give.
56790 **
56791 *************************************************************************
56792 ** This file contains C code routines that used to generate VDBE code
56793 ** that implements the ALTER TABLE command.
56794 **
56795 ** $Id: alter.c,v 1.50 2008/11/19 09:05:27 danielk1977 Exp $
56796 */
56797
56798 /*
56799 ** The code in this file only exists if we are not omitting the
56800 ** ALTER TABLE logic from the build.
56801 */
56802 #ifndef SQLITE_OMIT_ALTERTABLE
56803
56804
56805 /*
56806 ** This function is used by SQL generated to implement the 
56807 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
56808 ** CREATE INDEX command. The second is a table name. The table name in 
56809 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
56810 ** argument and the result returned. Examples:
56811 **
56812 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
56813 **     -> 'CREATE TABLE def(a, b, c)'
56814 **
56815 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
56816 **     -> 'CREATE INDEX i ON def(a, b, c)'
56817 */
56818 static void renameTableFunc(
56819   sqlite3_context *context,
56820   int NotUsed,
56821   sqlite3_value **argv
56822 ){
56823   unsigned char const *zSql = sqlite3_value_text(argv[0]);
56824   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
56825
56826   int token;
56827   Token tname;
56828   unsigned char const *zCsr = zSql;
56829   int len = 0;
56830   char *zRet;
56831
56832   sqlite3 *db = sqlite3_context_db_handle(context);
56833
56834   UNUSED_PARAMETER(NotUsed);
56835
56836   /* The principle used to locate the table name in the CREATE TABLE 
56837   ** statement is that the table name is the first non-space token that
56838   ** is immediately followed by a TK_LP or TK_USING token.
56839   */
56840   if( zSql ){
56841     do {
56842       if( !*zCsr ){
56843         /* Ran out of input before finding an opening bracket. Return NULL. */
56844         return;
56845       }
56846
56847       /* Store the token that zCsr points to in tname. */
56848       tname.z = zCsr;
56849       tname.n = len;
56850
56851       /* Advance zCsr to the next token. Store that token type in 'token',
56852       ** and its length in 'len' (to be used next iteration of this loop).
56853       */
56854       do {
56855         zCsr += len;
56856         len = sqlite3GetToken(zCsr, &token);
56857       } while( token==TK_SPACE );
56858       assert( len>0 );
56859     } while( token!=TK_LP && token!=TK_USING );
56860
56861     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", tname.z - zSql, zSql, 
56862        zTableName, tname.z+tname.n);
56863     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
56864   }
56865 }
56866
56867 #ifndef SQLITE_OMIT_TRIGGER
56868 /* This function is used by SQL generated to implement the
56869 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
56870 ** statement. The second is a table name. The table name in the CREATE 
56871 ** TRIGGER statement is replaced with the third argument and the result 
56872 ** returned. This is analagous to renameTableFunc() above, except for CREATE
56873 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
56874 */
56875 static void renameTriggerFunc(
56876   sqlite3_context *context,
56877   int NotUsed,
56878   sqlite3_value **argv
56879 ){
56880   unsigned char const *zSql = sqlite3_value_text(argv[0]);
56881   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
56882
56883   int token;
56884   Token tname;
56885   int dist = 3;
56886   unsigned char const *zCsr = zSql;
56887   int len = 0;
56888   char *zRet;
56889   sqlite3 *db = sqlite3_context_db_handle(context);
56890
56891   UNUSED_PARAMETER(NotUsed);
56892
56893   /* The principle used to locate the table name in the CREATE TRIGGER 
56894   ** statement is that the table name is the first token that is immediatedly
56895   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
56896   ** of TK_WHEN, TK_BEGIN or TK_FOR.
56897   */
56898   if( zSql ){
56899     do {
56900
56901       if( !*zCsr ){
56902         /* Ran out of input before finding the table name. Return NULL. */
56903         return;
56904       }
56905
56906       /* Store the token that zCsr points to in tname. */
56907       tname.z = zCsr;
56908       tname.n = len;
56909
56910       /* Advance zCsr to the next token. Store that token type in 'token',
56911       ** and its length in 'len' (to be used next iteration of this loop).
56912       */
56913       do {
56914         zCsr += len;
56915         len = sqlite3GetToken(zCsr, &token);
56916       }while( token==TK_SPACE );
56917       assert( len>0 );
56918
56919       /* Variable 'dist' stores the number of tokens read since the most
56920       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN 
56921       ** token is read and 'dist' equals 2, the condition stated above
56922       ** to be met.
56923       **
56924       ** Note that ON cannot be a database, table or column name, so
56925       ** there is no need to worry about syntax like 
56926       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
56927       */
56928       dist++;
56929       if( token==TK_DOT || token==TK_ON ){
56930         dist = 0;
56931       }
56932     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
56933
56934     /* Variable tname now contains the token that is the old table-name
56935     ** in the CREATE TRIGGER statement.
56936     */
56937     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", tname.z - zSql, zSql, 
56938        zTableName, tname.z+tname.n);
56939     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
56940   }
56941 }
56942 #endif   /* !SQLITE_OMIT_TRIGGER */
56943
56944 /*
56945 ** Register built-in functions used to help implement ALTER TABLE
56946 */
56947 SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3 *db){
56948   sqlite3CreateFunc(db, "sqlite_rename_table", 2, SQLITE_UTF8, 0,
56949                          renameTableFunc, 0, 0);
56950 #ifndef SQLITE_OMIT_TRIGGER
56951   sqlite3CreateFunc(db, "sqlite_rename_trigger", 2, SQLITE_UTF8, 0,
56952                          renameTriggerFunc, 0, 0);
56953 #endif
56954 }
56955
56956 /*
56957 ** Generate the text of a WHERE expression which can be used to select all
56958 ** temporary triggers on table pTab from the sqlite_temp_master table. If
56959 ** table pTab has no temporary triggers, or is itself stored in the 
56960 ** temporary database, NULL is returned.
56961 */
56962 static char *whereTempTriggers(Parse *pParse, Table *pTab){
56963   Trigger *pTrig;
56964   char *zWhere = 0;
56965   char *tmp = 0;
56966   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
56967
56968   /* If the table is not located in the temp-db (in which case NULL is 
56969   ** returned, loop through the tables list of triggers. For each trigger
56970   ** that is not part of the temp-db schema, add a clause to the WHERE 
56971   ** expression being built up in zWhere.
56972   */
56973   if( pTab->pSchema!=pTempSchema ){
56974     sqlite3 *db = pParse->db;
56975     for( pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext ){
56976       if( pTrig->pSchema==pTempSchema ){
56977         if( !zWhere ){
56978           zWhere = sqlite3MPrintf(db, "name=%Q", pTrig->name);
56979         }else{
56980           tmp = zWhere;
56981           zWhere = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, pTrig->name);
56982           sqlite3DbFree(db, tmp);
56983         }
56984       }
56985     }
56986   }
56987   return zWhere;
56988 }
56989
56990 /*
56991 ** Generate code to drop and reload the internal representation of table
56992 ** pTab from the database, including triggers and temporary triggers.
56993 ** Argument zName is the name of the table in the database schema at
56994 ** the time the generated code is executed. This can be different from
56995 ** pTab->zName if this function is being called to code part of an 
56996 ** "ALTER TABLE RENAME TO" statement.
56997 */
56998 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
56999   Vdbe *v;
57000   char *zWhere;
57001   int iDb;                   /* Index of database containing pTab */
57002 #ifndef SQLITE_OMIT_TRIGGER
57003   Trigger *pTrig;
57004 #endif
57005
57006   v = sqlite3GetVdbe(pParse);
57007   if( !v ) return;
57008   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
57009   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
57010   assert( iDb>=0 );
57011
57012 #ifndef SQLITE_OMIT_TRIGGER
57013   /* Drop any table triggers from the internal schema. */
57014   for(pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext){
57015     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
57016     assert( iTrigDb==iDb || iTrigDb==1 );
57017     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->name, 0);
57018   }
57019 #endif
57020
57021   /* Drop the table and index from the internal schema */
57022   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
57023
57024   /* Reload the table, index and permanent trigger schemas. */
57025   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
57026   if( !zWhere ) return;
57027   sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
57028
57029 #ifndef SQLITE_OMIT_TRIGGER
57030   /* Now, if the table is not stored in the temp database, reload any temp 
57031   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. 
57032   */
57033   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
57034     sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
57035   }
57036 #endif
57037 }
57038
57039 /*
57040 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
57041 ** command. 
57042 */
57043 SQLITE_PRIVATE void sqlite3AlterRenameTable(
57044   Parse *pParse,            /* Parser context. */
57045   SrcList *pSrc,            /* The table to rename. */
57046   Token *pName              /* The new table name. */
57047 ){
57048   int iDb;                  /* Database that contains the table */
57049   char *zDb;                /* Name of database iDb */
57050   Table *pTab;              /* Table being renamed */
57051   char *zName = 0;          /* NULL-terminated version of pName */ 
57052   sqlite3 *db = pParse->db; /* Database connection */
57053   int nTabName;             /* Number of UTF-8 characters in zTabName */
57054   const char *zTabName;     /* Original name of the table */
57055   Vdbe *v;
57056 #ifndef SQLITE_OMIT_TRIGGER
57057   char *zWhere = 0;         /* Where clause to locate temp triggers */
57058 #endif
57059   int isVirtualRename = 0;  /* True if this is a v-table with an xRename() */
57060   
57061   if( db->mallocFailed ) goto exit_rename_table;
57062   assert( pSrc->nSrc==1 );
57063   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
57064
57065   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
57066   if( !pTab ) goto exit_rename_table;
57067   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
57068   zDb = db->aDb[iDb].zName;
57069
57070   /* Get a NULL terminated version of the new table name. */
57071   zName = sqlite3NameFromToken(db, pName);
57072   if( !zName ) goto exit_rename_table;
57073
57074   /* Check that a table or index named 'zName' does not already exist
57075   ** in database iDb. If so, this is an error.
57076   */
57077   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
57078     sqlite3ErrorMsg(pParse, 
57079         "there is already another table or index with this name: %s", zName);
57080     goto exit_rename_table;
57081   }
57082
57083   /* Make sure it is not a system table being altered, or a reserved name
57084   ** that the table is being renamed to.
57085   */
57086   if( strlen(pTab->zName)>6 && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7) ){
57087     sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
57088     goto exit_rename_table;
57089   }
57090   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
57091     goto exit_rename_table;
57092   }
57093
57094 #ifndef SQLITE_OMIT_VIEW
57095   if( pTab->pSelect ){
57096     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
57097     goto exit_rename_table;
57098   }
57099 #endif
57100
57101 #ifndef SQLITE_OMIT_AUTHORIZATION
57102   /* Invoke the authorization callback. */
57103   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
57104     goto exit_rename_table;
57105   }
57106 #endif
57107
57108 #ifndef SQLITE_OMIT_VIRTUALTABLE
57109   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
57110     goto exit_rename_table;
57111   }
57112   if( IsVirtual(pTab) && pTab->pMod->pModule->xRename ){
57113     isVirtualRename = 1;
57114   }
57115 #endif
57116
57117   /* Begin a transaction and code the VerifyCookie for database iDb. 
57118   ** Then modify the schema cookie (since the ALTER TABLE modifies the
57119   ** schema). Open a statement transaction if the table is a virtual
57120   ** table.
57121   */
57122   v = sqlite3GetVdbe(pParse);
57123   if( v==0 ){
57124     goto exit_rename_table;
57125   }
57126   sqlite3BeginWriteOperation(pParse, isVirtualRename, iDb);
57127   sqlite3ChangeCookie(pParse, iDb);
57128
57129   /* If this is a virtual table, invoke the xRename() function if
57130   ** one is defined. The xRename() callback will modify the names
57131   ** of any resources used by the v-table implementation (including other
57132   ** SQLite tables) that are identified by the name of the virtual table.
57133   */
57134 #ifndef SQLITE_OMIT_VIRTUALTABLE
57135   if( isVirtualRename ){
57136     int i = ++pParse->nMem;
57137     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
57138     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pTab->pVtab, P4_VTAB);
57139   }
57140 #endif
57141
57142   /* figure out how many UTF-8 characters are in zName */
57143   zTabName = pTab->zName;
57144   nTabName = sqlite3Utf8CharLen(zTabName, -1);
57145
57146   /* Modify the sqlite_master table to use the new table name. */
57147   sqlite3NestedParse(pParse,
57148       "UPDATE %Q.%s SET "
57149 #ifdef SQLITE_OMIT_TRIGGER
57150           "sql = sqlite_rename_table(sql, %Q), "
57151 #else
57152           "sql = CASE "
57153             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
57154             "ELSE sqlite_rename_table(sql, %Q) END, "
57155 #endif
57156           "tbl_name = %Q, "
57157           "name = CASE "
57158             "WHEN type='table' THEN %Q "
57159             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
57160              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
57161             "ELSE name END "
57162       "WHERE tbl_name=%Q AND "
57163           "(type='table' OR type='index' OR type='trigger');", 
57164       zDb, SCHEMA_TABLE(iDb), zName, zName, zName, 
57165 #ifndef SQLITE_OMIT_TRIGGER
57166       zName,
57167 #endif
57168       zName, nTabName, zTabName
57169   );
57170
57171 #ifndef SQLITE_OMIT_AUTOINCREMENT
57172   /* If the sqlite_sequence table exists in this database, then update 
57173   ** it with the new table name.
57174   */
57175   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
57176     sqlite3NestedParse(pParse,
57177         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
57178         zDb, zName, pTab->zName);
57179   }
57180 #endif
57181
57182 #ifndef SQLITE_OMIT_TRIGGER
57183   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
57184   ** table. Don't do this if the table being ALTERed is itself located in
57185   ** the temp database.
57186   */
57187   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
57188     sqlite3NestedParse(pParse, 
57189         "UPDATE sqlite_temp_master SET "
57190             "sql = sqlite_rename_trigger(sql, %Q), "
57191             "tbl_name = %Q "
57192             "WHERE %s;", zName, zName, zWhere);
57193     sqlite3DbFree(db, zWhere);
57194   }
57195 #endif
57196
57197   /* Drop and reload the internal table schema. */
57198   reloadTableSchema(pParse, pTab, zName);
57199
57200 exit_rename_table:
57201   sqlite3SrcListDelete(db, pSrc);
57202   sqlite3DbFree(db, zName);
57203 }
57204
57205
57206 /*
57207 ** This function is called after an "ALTER TABLE ... ADD" statement
57208 ** has been parsed. Argument pColDef contains the text of the new
57209 ** column definition.
57210 **
57211 ** The Table structure pParse->pNewTable was extended to include
57212 ** the new column during parsing.
57213 */
57214 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
57215   Table *pNew;              /* Copy of pParse->pNewTable */
57216   Table *pTab;              /* Table being altered */
57217   int iDb;                  /* Database number */
57218   const char *zDb;          /* Database name */
57219   const char *zTab;         /* Table name */
57220   char *zCol;               /* Null-terminated column definition */
57221   Column *pCol;             /* The new column */
57222   Expr *pDflt;              /* Default value for the new column */
57223   sqlite3 *db;              /* The database connection; */
57224
57225   db = pParse->db;
57226   if( pParse->nErr || db->mallocFailed ) return;
57227   pNew = pParse->pNewTable;
57228   assert( pNew );
57229
57230   assert( sqlite3BtreeHoldsAllMutexes(db) );
57231   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
57232   zDb = db->aDb[iDb].zName;
57233   zTab = pNew->zName;
57234   pCol = &pNew->aCol[pNew->nCol-1];
57235   pDflt = pCol->pDflt;
57236   pTab = sqlite3FindTable(db, zTab, zDb);
57237   assert( pTab );
57238
57239 #ifndef SQLITE_OMIT_AUTHORIZATION
57240   /* Invoke the authorization callback. */
57241   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
57242     return;
57243   }
57244 #endif
57245
57246   /* If the default value for the new column was specified with a 
57247   ** literal NULL, then set pDflt to 0. This simplifies checking
57248   ** for an SQL NULL default below.
57249   */
57250   if( pDflt && pDflt->op==TK_NULL ){
57251     pDflt = 0;
57252   }
57253
57254   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
57255   ** If there is a NOT NULL constraint, then the default value for the
57256   ** column must not be NULL.
57257   */
57258   if( pCol->isPrimKey ){
57259     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
57260     return;
57261   }
57262   if( pNew->pIndex ){
57263     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
57264     return;
57265   }
57266   if( pCol->notNull && !pDflt ){
57267     sqlite3ErrorMsg(pParse, 
57268         "Cannot add a NOT NULL column with default value NULL");
57269     return;
57270   }
57271
57272   /* Ensure the default expression is something that sqlite3ValueFromExpr()
57273   ** can handle (i.e. not CURRENT_TIME etc.)
57274   */
57275   if( pDflt ){
57276     sqlite3_value *pVal;
57277     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
57278       db->mallocFailed = 1;
57279       return;
57280     }
57281     if( !pVal ){
57282       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
57283       return;
57284     }
57285     sqlite3ValueFree(pVal);
57286   }
57287
57288   /* Modify the CREATE TABLE statement. */
57289   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
57290   if( zCol ){
57291     char *zEnd = &zCol[pColDef->n-1];
57292     while( (zEnd>zCol && *zEnd==';') || isspace(*(unsigned char *)zEnd) ){
57293       *zEnd-- = '\0';
57294     }
57295     sqlite3NestedParse(pParse, 
57296         "UPDATE \"%w\".%s SET "
57297           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
57298         "WHERE type = 'table' AND name = %Q", 
57299       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
57300       zTab
57301     );
57302     sqlite3DbFree(db, zCol);
57303   }
57304
57305   /* If the default value of the new column is NULL, then set the file
57306   ** format to 2. If the default value of the new column is not NULL,
57307   ** the file format becomes 3.
57308   */
57309   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
57310
57311   /* Reload the schema of the modified table. */
57312   reloadTableSchema(pParse, pTab, pTab->zName);
57313 }
57314
57315 /*
57316 ** This function is called by the parser after the table-name in
57317 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
57318 ** pSrc is the full-name of the table being altered.
57319 **
57320 ** This routine makes a (partial) copy of the Table structure
57321 ** for the table being altered and sets Parse.pNewTable to point
57322 ** to it. Routines called by the parser as the column definition
57323 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
57324 ** the copy. The copy of the Table structure is deleted by tokenize.c 
57325 ** after parsing is finished.
57326 **
57327 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
57328 ** coding the "ALTER TABLE ... ADD" statement.
57329 */
57330 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
57331   Table *pNew;
57332   Table *pTab;
57333   Vdbe *v;
57334   int iDb;
57335   int i;
57336   int nAlloc;
57337   sqlite3 *db = pParse->db;
57338
57339   /* Look up the table being altered. */
57340   assert( pParse->pNewTable==0 );
57341   assert( sqlite3BtreeHoldsAllMutexes(db) );
57342   if( db->mallocFailed ) goto exit_begin_add_column;
57343   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
57344   if( !pTab ) goto exit_begin_add_column;
57345
57346 #ifndef SQLITE_OMIT_VIRTUALTABLE
57347   if( IsVirtual(pTab) ){
57348     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
57349     goto exit_begin_add_column;
57350   }
57351 #endif
57352
57353   /* Make sure this is not an attempt to ALTER a view. */
57354   if( pTab->pSelect ){
57355     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
57356     goto exit_begin_add_column;
57357   }
57358
57359   assert( pTab->addColOffset>0 );
57360   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
57361
57362   /* Put a copy of the Table struct in Parse.pNewTable for the
57363   ** sqlite3AddColumn() function and friends to modify.
57364   */
57365   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
57366   if( !pNew ) goto exit_begin_add_column;
57367   pParse->pNewTable = pNew;
57368   pNew->nRef = 1;
57369   pNew->db = db;
57370   pNew->nCol = pTab->nCol;
57371   assert( pNew->nCol>0 );
57372   nAlloc = (((pNew->nCol-1)/8)*8)+8;
57373   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
57374   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
57375   pNew->zName = sqlite3DbStrDup(db, pTab->zName);
57376   if( !pNew->aCol || !pNew->zName ){
57377     db->mallocFailed = 1;
57378     goto exit_begin_add_column;
57379   }
57380   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
57381   for(i=0; i<pNew->nCol; i++){
57382     Column *pCol = &pNew->aCol[i];
57383     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
57384     pCol->zColl = 0;
57385     pCol->zType = 0;
57386     pCol->pDflt = 0;
57387   }
57388   pNew->pSchema = db->aDb[iDb].pSchema;
57389   pNew->addColOffset = pTab->addColOffset;
57390   pNew->nRef = 1;
57391
57392   /* Begin a transaction and increment the schema cookie.  */
57393   sqlite3BeginWriteOperation(pParse, 0, iDb);
57394   v = sqlite3GetVdbe(pParse);
57395   if( !v ) goto exit_begin_add_column;
57396   sqlite3ChangeCookie(pParse, iDb);
57397
57398 exit_begin_add_column:
57399   sqlite3SrcListDelete(db, pSrc);
57400   return;
57401 }
57402 #endif  /* SQLITE_ALTER_TABLE */
57403
57404 /************** End of alter.c ***********************************************/
57405 /************** Begin file analyze.c *****************************************/
57406 /*
57407 ** 2005 July 8
57408 **
57409 ** The author disclaims copyright to this source code.  In place of
57410 ** a legal notice, here is a blessing:
57411 **
57412 **    May you do good and not evil.
57413 **    May you find forgiveness for yourself and forgive others.
57414 **    May you share freely, never taking more than you give.
57415 **
57416 *************************************************************************
57417 ** This file contains code associated with the ANALYZE command.
57418 **
57419 ** @(#) $Id: analyze.c,v 1.46 2008/11/19 16:52:44 danielk1977 Exp $
57420 */
57421 #ifndef SQLITE_OMIT_ANALYZE
57422
57423 /*
57424 ** This routine generates code that opens the sqlite_stat1 table on cursor
57425 ** iStatCur.
57426 **
57427 ** If the sqlite_stat1 tables does not previously exist, it is created.
57428 ** If it does previously exist, all entires associated with table zWhere
57429 ** are removed.  If zWhere==0 then all entries are removed.
57430 */
57431 static void openStatTable(
57432   Parse *pParse,          /* Parsing context */
57433   int iDb,                /* The database we are looking in */
57434   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
57435   const char *zWhere      /* Delete entries associated with this table */
57436 ){
57437   sqlite3 *db = pParse->db;
57438   Db *pDb;
57439   int iRootPage;
57440   int createStat1 = 0;
57441   Table *pStat;
57442   Vdbe *v = sqlite3GetVdbe(pParse);
57443
57444   if( v==0 ) return;
57445   assert( sqlite3BtreeHoldsAllMutexes(db) );
57446   assert( sqlite3VdbeDb(v)==db );
57447   pDb = &db->aDb[iDb];
57448   if( (pStat = sqlite3FindTable(db, "sqlite_stat1", pDb->zName))==0 ){
57449     /* The sqlite_stat1 tables does not exist.  Create it.  
57450     ** Note that a side-effect of the CREATE TABLE statement is to leave
57451     ** the rootpage of the new table in register pParse->regRoot.  This is
57452     ** important because the OpenWrite opcode below will be needing it. */
57453     sqlite3NestedParse(pParse,
57454       "CREATE TABLE %Q.sqlite_stat1(tbl,idx,stat)",
57455       pDb->zName
57456     );
57457     iRootPage = pParse->regRoot;
57458     createStat1 = 1;  /* Cause rootpage to be taken from top of stack */
57459   }else if( zWhere ){
57460     /* The sqlite_stat1 table exists.  Delete all entries associated with
57461     ** the table zWhere. */
57462     sqlite3NestedParse(pParse,
57463        "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q",
57464        pDb->zName, zWhere
57465     );
57466     iRootPage = pStat->tnum;
57467   }else{
57468     /* The sqlite_stat1 table already exists.  Delete all rows. */
57469     iRootPage = pStat->tnum;
57470     sqlite3VdbeAddOp2(v, OP_Clear, pStat->tnum, iDb);
57471   }
57472
57473   /* Open the sqlite_stat1 table for writing. Unless it was created
57474   ** by this vdbe program, lock it for writing at the shared-cache level. 
57475   ** If this vdbe did create the sqlite_stat1 table, then it must have 
57476   ** already obtained a schema-lock, making the write-lock redundant.
57477   */
57478   if( !createStat1 ){
57479     sqlite3TableLock(pParse, iDb, iRootPage, 1, "sqlite_stat1");
57480   }
57481   sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, 3);
57482   sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur, iRootPage, iDb);
57483   sqlite3VdbeChangeP5(v, createStat1);
57484 }
57485
57486 /*
57487 ** Generate code to do an analysis of all indices associated with
57488 ** a single table.
57489 */
57490 static void analyzeOneTable(
57491   Parse *pParse,   /* Parser context */
57492   Table *pTab,     /* Table whose indices are to be analyzed */
57493   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
57494   int iMem         /* Available memory locations begin here */
57495 ){
57496   Index *pIdx;     /* An index to being analyzed */
57497   int iIdxCur;     /* Index of VdbeCursor for index being analyzed */
57498   int nCol;        /* Number of columns in the index */
57499   Vdbe *v;         /* The virtual machine being built up */
57500   int i;           /* Loop counter */
57501   int topOfLoop;   /* The top of the loop */
57502   int endOfLoop;   /* The end of the loop */
57503   int addr;        /* The address of an instruction */
57504   int iDb;         /* Index of database containing pTab */
57505
57506   v = sqlite3GetVdbe(pParse);
57507   if( v==0 || pTab==0 || pTab->pIndex==0 ){
57508     /* Do no analysis for tables that have no indices */
57509     return;
57510   }
57511   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
57512   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
57513   assert( iDb>=0 );
57514 #ifndef SQLITE_OMIT_AUTHORIZATION
57515   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
57516       pParse->db->aDb[iDb].zName ) ){
57517     return;
57518   }
57519 #endif
57520
57521   /* Establish a read-lock on the table at the shared-cache level. */
57522   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
57523
57524   iIdxCur = pParse->nTab;
57525   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
57526     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
57527     int regFields;    /* Register block for building records */
57528     int regRec;       /* Register holding completed record */
57529     int regTemp;      /* Temporary use register */
57530     int regCol;       /* Content of a column from the table being analyzed */
57531     int regRowid;     /* Rowid for the inserted record */
57532     int regF2;
57533
57534     /* Open a cursor to the index to be analyzed
57535     */
57536     assert( iDb==sqlite3SchemaToIndex(pParse->db, pIdx->pSchema) );
57537     nCol = pIdx->nColumn;
57538     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, nCol+1);
57539     sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
57540         (char *)pKey, P4_KEYINFO_HANDOFF);
57541     VdbeComment((v, "%s", pIdx->zName));
57542     regFields = iMem+nCol*2;
57543     regTemp = regRowid = regCol = regFields+3;
57544     regRec = regCol+1;
57545     if( regRec>pParse->nMem ){
57546       pParse->nMem = regRec;
57547     }
57548
57549     /* Memory cells are used as follows:
57550     **
57551     **    mem[iMem]:             The total number of rows in the table.
57552     **    mem[iMem+1]:           Number of distinct values in column 1
57553     **    ...
57554     **    mem[iMem+nCol]:        Number of distinct values in column N
57555     **    mem[iMem+nCol+1]       Last observed value of column 1
57556     **    ...
57557     **    mem[iMem+nCol+nCol]:   Last observed value of column N
57558     **
57559     ** Cells iMem through iMem+nCol are initialized to 0.  The others
57560     ** are initialized to NULL.
57561     */
57562     for(i=0; i<=nCol; i++){
57563       sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
57564     }
57565     for(i=0; i<nCol; i++){
57566       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
57567     }
57568
57569     /* Do the analysis.
57570     */
57571     endOfLoop = sqlite3VdbeMakeLabel(v);
57572     sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
57573     topOfLoop = sqlite3VdbeCurrentAddr(v);
57574     sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
57575     for(i=0; i<nCol; i++){
57576       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
57577       sqlite3VdbeAddOp3(v, OP_Ne, regCol, 0, iMem+nCol+i+1);
57578       /**** TODO:  add collating sequence *****/
57579       sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
57580     }
57581     sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
57582     for(i=0; i<nCol; i++){
57583       sqlite3VdbeJumpHere(v, topOfLoop + 2*(i + 1));
57584       sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
57585       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
57586     }
57587     sqlite3VdbeResolveLabel(v, endOfLoop);
57588     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
57589     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
57590
57591     /* Store the results.  
57592     **
57593     ** The result is a single row of the sqlite_stat1 table.  The first
57594     ** two columns are the names of the table and index.  The third column
57595     ** is a string composed of a list of integer statistics about the
57596     ** index.  The first integer in the list is the total number of entires
57597     ** in the index.  There is one additional integer in the list for each
57598     ** column of the table.  This additional integer is a guess of how many
57599     ** rows of the table the index will select.  If D is the count of distinct
57600     ** values and K is the total number of rows, then the integer is computed
57601     ** as:
57602     **
57603     **        I = (K+D-1)/D
57604     **
57605     ** If K==0 then no entry is made into the sqlite_stat1 table.  
57606     ** If K>0 then it is always the case the D>0 so division by zero
57607     ** is never possible.
57608     */
57609     addr = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
57610     sqlite3VdbeAddOp4(v, OP_String8, 0, regFields, 0, pTab->zName, 0);
57611     sqlite3VdbeAddOp4(v, OP_String8, 0, regFields+1, 0, pIdx->zName, 0);
57612     regF2 = regFields+2;
57613     sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regF2);
57614     for(i=0; i<nCol; i++){
57615       sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
57616       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regF2, regF2);
57617       sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
57618       sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
57619       sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
57620       sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
57621       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regF2, regF2);
57622     }
57623     sqlite3VdbeAddOp4(v, OP_MakeRecord, regFields, 3, regRec, "aaa", 0);
57624     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
57625     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
57626     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
57627     sqlite3VdbeJumpHere(v, addr);
57628   }
57629 }
57630
57631 /*
57632 ** Generate code that will cause the most recent index analysis to
57633 ** be laoded into internal hash tables where is can be used.
57634 */
57635 static void loadAnalysis(Parse *pParse, int iDb){
57636   Vdbe *v = sqlite3GetVdbe(pParse);
57637   if( v ){
57638     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
57639   }
57640 }
57641
57642 /*
57643 ** Generate code that will do an analysis of an entire database
57644 */
57645 static void analyzeDatabase(Parse *pParse, int iDb){
57646   sqlite3 *db = pParse->db;
57647   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
57648   HashElem *k;
57649   int iStatCur;
57650   int iMem;
57651
57652   sqlite3BeginWriteOperation(pParse, 0, iDb);
57653   iStatCur = pParse->nTab++;
57654   openStatTable(pParse, iDb, iStatCur, 0);
57655   iMem = pParse->nMem+1;
57656   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
57657     Table *pTab = (Table*)sqliteHashData(k);
57658     analyzeOneTable(pParse, pTab, iStatCur, iMem);
57659   }
57660   loadAnalysis(pParse, iDb);
57661 }
57662
57663 /*
57664 ** Generate code that will do an analysis of a single table in
57665 ** a database.
57666 */
57667 static void analyzeTable(Parse *pParse, Table *pTab){
57668   int iDb;
57669   int iStatCur;
57670
57671   assert( pTab!=0 );
57672   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
57673   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
57674   sqlite3BeginWriteOperation(pParse, 0, iDb);
57675   iStatCur = pParse->nTab++;
57676   openStatTable(pParse, iDb, iStatCur, pTab->zName);
57677   analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem+1);
57678   loadAnalysis(pParse, iDb);
57679 }
57680
57681 /*
57682 ** Generate code for the ANALYZE command.  The parser calls this routine
57683 ** when it recognizes an ANALYZE command.
57684 **
57685 **        ANALYZE                            -- 1
57686 **        ANALYZE  <database>                -- 2
57687 **        ANALYZE  ?<database>.?<tablename>  -- 3
57688 **
57689 ** Form 1 causes all indices in all attached databases to be analyzed.
57690 ** Form 2 analyzes all indices the single database named.
57691 ** Form 3 analyzes all indices associated with the named table.
57692 */
57693 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
57694   sqlite3 *db = pParse->db;
57695   int iDb;
57696   int i;
57697   char *z, *zDb;
57698   Table *pTab;
57699   Token *pTableName;
57700
57701   /* Read the database schema. If an error occurs, leave an error message
57702   ** and code in pParse and return NULL. */
57703   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
57704   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
57705     return;
57706   }
57707
57708   if( pName1==0 ){
57709     /* Form 1:  Analyze everything */
57710     for(i=0; i<db->nDb; i++){
57711       if( i==1 ) continue;  /* Do not analyze the TEMP database */
57712       analyzeDatabase(pParse, i);
57713     }
57714   }else if( pName2==0 || pName2->n==0 ){
57715     /* Form 2:  Analyze the database or table named */
57716     iDb = sqlite3FindDb(db, pName1);
57717     if( iDb>=0 ){
57718       analyzeDatabase(pParse, iDb);
57719     }else{
57720       z = sqlite3NameFromToken(db, pName1);
57721       if( z ){
57722         pTab = sqlite3LocateTable(pParse, 0, z, 0);
57723         sqlite3DbFree(db, z);
57724         if( pTab ){
57725           analyzeTable(pParse, pTab);
57726         }
57727       }
57728     }
57729   }else{
57730     /* Form 3: Analyze the fully qualified table name */
57731     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
57732     if( iDb>=0 ){
57733       zDb = db->aDb[iDb].zName;
57734       z = sqlite3NameFromToken(db, pTableName);
57735       if( z ){
57736         pTab = sqlite3LocateTable(pParse, 0, z, zDb);
57737         sqlite3DbFree(db, z);
57738         if( pTab ){
57739           analyzeTable(pParse, pTab);
57740         }
57741       }
57742     }   
57743   }
57744 }
57745
57746 /*
57747 ** Used to pass information from the analyzer reader through to the
57748 ** callback routine.
57749 */
57750 typedef struct analysisInfo analysisInfo;
57751 struct analysisInfo {
57752   sqlite3 *db;
57753   const char *zDatabase;
57754 };
57755
57756 /*
57757 ** This callback is invoked once for each index when reading the
57758 ** sqlite_stat1 table.  
57759 **
57760 **     argv[0] = name of the index
57761 **     argv[1] = results of analysis - on integer for each column
57762 */
57763 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
57764   analysisInfo *pInfo = (analysisInfo*)pData;
57765   Index *pIndex;
57766   int i, c;
57767   unsigned int v;
57768   const char *z;
57769
57770   assert( argc==2 );
57771   UNUSED_PARAMETER2(NotUsed, argc);
57772
57773   if( argv==0 || argv[0]==0 || argv[1]==0 ){
57774     return 0;
57775   }
57776   pIndex = sqlite3FindIndex(pInfo->db, argv[0], pInfo->zDatabase);
57777   if( pIndex==0 ){
57778     return 0;
57779   }
57780   z = argv[1];
57781   for(i=0; *z && i<=pIndex->nColumn; i++){
57782     v = 0;
57783     while( (c=z[0])>='0' && c<='9' ){
57784       v = v*10 + c - '0';
57785       z++;
57786     }
57787     pIndex->aiRowEst[i] = v;
57788     if( *z==' ' ) z++;
57789   }
57790   return 0;
57791 }
57792
57793 /*
57794 ** Load the content of the sqlite_stat1 table into the index hash tables.
57795 */
57796 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
57797   analysisInfo sInfo;
57798   HashElem *i;
57799   char *zSql;
57800   int rc;
57801
57802   assert( iDb>=0 && iDb<db->nDb );
57803   assert( db->aDb[iDb].pBt!=0 );
57804   assert( sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
57805
57806   /* Clear any prior statistics */
57807   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
57808     Index *pIdx = sqliteHashData(i);
57809     sqlite3DefaultRowEst(pIdx);
57810   }
57811
57812   /* Check to make sure the sqlite_stat1 table existss */
57813   sInfo.db = db;
57814   sInfo.zDatabase = db->aDb[iDb].zName;
57815   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
57816      return SQLITE_ERROR;
57817   }
57818
57819
57820   /* Load new statistics out of the sqlite_stat1 table */
57821   zSql = sqlite3MPrintf(db, "SELECT idx, stat FROM %Q.sqlite_stat1",
57822                         sInfo.zDatabase);
57823   (void)sqlite3SafetyOff(db);
57824   rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
57825   (void)sqlite3SafetyOn(db);
57826   sqlite3DbFree(db, zSql);
57827   return rc;
57828 }
57829
57830
57831 #endif /* SQLITE_OMIT_ANALYZE */
57832
57833 /************** End of analyze.c *********************************************/
57834 /************** Begin file attach.c ******************************************/
57835 /*
57836 ** 2003 April 6
57837 **
57838 ** The author disclaims copyright to this source code.  In place of
57839 ** a legal notice, here is a blessing:
57840 **
57841 **    May you do good and not evil.
57842 **    May you find forgiveness for yourself and forgive others.
57843 **    May you share freely, never taking more than you give.
57844 **
57845 *************************************************************************
57846 ** This file contains code used to implement the ATTACH and DETACH commands.
57847 **
57848 ** $Id: attach.c,v 1.80 2008/11/19 09:05:27 danielk1977 Exp $
57849 */
57850
57851 #ifndef SQLITE_OMIT_ATTACH
57852 /*
57853 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
57854 ** is slightly different from resolving a normal SQL expression, because simple
57855 ** identifiers are treated as strings, not possible column names or aliases.
57856 **
57857 ** i.e. if the parser sees:
57858 **
57859 **     ATTACH DATABASE abc AS def
57860 **
57861 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
57862 ** looking for columns of the same name.
57863 **
57864 ** This only applies to the root node of pExpr, so the statement:
57865 **
57866 **     ATTACH DATABASE abc||def AS 'db2'
57867 **
57868 ** will fail because neither abc or def can be resolved.
57869 */
57870 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
57871 {
57872   int rc = SQLITE_OK;
57873   if( pExpr ){
57874     if( pExpr->op!=TK_ID ){
57875       rc = sqlite3ResolveExprNames(pName, pExpr);
57876       if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
57877         sqlite3ErrorMsg(pName->pParse, "invalid name: \"%T\"", &pExpr->span);
57878         return SQLITE_ERROR;
57879       }
57880     }else{
57881       pExpr->op = TK_STRING;
57882     }
57883   }
57884   return rc;
57885 }
57886
57887 /*
57888 ** An SQL user-function registered to do the work of an ATTACH statement. The
57889 ** three arguments to the function come directly from an attach statement:
57890 **
57891 **     ATTACH DATABASE x AS y KEY z
57892 **
57893 **     SELECT sqlite_attach(x, y, z)
57894 **
57895 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
57896 ** third argument.
57897 */
57898 static void attachFunc(
57899   sqlite3_context *context,
57900   int NotUsed,
57901   sqlite3_value **argv
57902 ){
57903   int i;
57904   int rc = 0;
57905   sqlite3 *db = sqlite3_context_db_handle(context);
57906   const char *zName;
57907   const char *zFile;
57908   Db *aNew;
57909   char *zErrDyn = 0;
57910   char zErr[128];
57911
57912   UNUSED_PARAMETER(NotUsed);
57913
57914   zFile = (const char *)sqlite3_value_text(argv[0]);
57915   zName = (const char *)sqlite3_value_text(argv[1]);
57916   if( zFile==0 ) zFile = "";
57917   if( zName==0 ) zName = "";
57918
57919   /* Check for the following errors:
57920   **
57921   **     * Too many attached databases,
57922   **     * Transaction currently open
57923   **     * Specified database name already being used.
57924   */
57925   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
57926     sqlite3_snprintf(
57927       sizeof(zErr), zErr, "too many attached databases - max %d", 
57928       db->aLimit[SQLITE_LIMIT_ATTACHED]
57929     );
57930     goto attach_error;
57931   }
57932   if( !db->autoCommit ){
57933     sqlite3_snprintf(sizeof(zErr), zErr,
57934                      "cannot ATTACH database within transaction");
57935     goto attach_error;
57936   }
57937   for(i=0; i<db->nDb; i++){
57938     char *z = db->aDb[i].zName;
57939     if( z && zName && sqlite3StrICmp(z, zName)==0 ){
57940       sqlite3_snprintf(sizeof(zErr), zErr, 
57941                        "database %s is already in use", zName);
57942       goto attach_error;
57943     }
57944   }
57945
57946   /* Allocate the new entry in the db->aDb[] array and initialise the schema
57947   ** hash tables.
57948   */
57949   if( db->aDb==db->aDbStatic ){
57950     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
57951     if( aNew==0 ) return;
57952     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
57953   }else{
57954     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
57955     if( aNew==0 ) return;
57956   }
57957   db->aDb = aNew;
57958   aNew = &db->aDb[db->nDb++];
57959   memset(aNew, 0, sizeof(*aNew));
57960
57961   /* Open the database file. If the btree is successfully opened, use
57962   ** it to obtain the database schema. At this point the schema may
57963   ** or may not be initialised.
57964   */
57965   rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE,
57966                            db->openFlags | SQLITE_OPEN_MAIN_DB,
57967                            &aNew->pBt);
57968   if( rc==SQLITE_OK ){
57969     Pager *pPager;
57970     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
57971     if( !aNew->pSchema ){
57972       rc = SQLITE_NOMEM;
57973     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
57974       sqlite3_snprintf(sizeof(zErr), zErr, 
57975         "attached databases must use the same text encoding as main database");
57976       goto attach_error;
57977     }
57978     pPager = sqlite3BtreePager(aNew->pBt);
57979     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
57980     sqlite3PagerJournalMode(pPager, db->dfltJournalMode);
57981   }
57982   aNew->zName = sqlite3DbStrDup(db, zName);
57983   aNew->safety_level = 3;
57984
57985 #if SQLITE_HAS_CODEC
57986   {
57987     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
57988     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
57989     int nKey;
57990     char *zKey;
57991     int t = sqlite3_value_type(argv[2]);
57992     switch( t ){
57993       case SQLITE_INTEGER:
57994       case SQLITE_FLOAT:
57995         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
57996         rc = SQLITE_ERROR;
57997         break;
57998         
57999       case SQLITE_TEXT:
58000       case SQLITE_BLOB:
58001         nKey = sqlite3_value_bytes(argv[2]);
58002         zKey = (char *)sqlite3_value_blob(argv[2]);
58003         sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
58004         break;
58005
58006       case SQLITE_NULL:
58007         /* No key specified.  Use the key from the main database */
58008         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
58009         sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
58010         break;
58011     }
58012   }
58013 #endif
58014
58015   /* If the file was opened successfully, read the schema for the new database.
58016   ** If this fails, or if opening the file failed, then close the file and 
58017   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
58018   ** we found it.
58019   */
58020   if( rc==SQLITE_OK ){
58021     (void)sqlite3SafetyOn(db);
58022     sqlite3BtreeEnterAll(db);
58023     rc = sqlite3Init(db, &zErrDyn);
58024     sqlite3BtreeLeaveAll(db);
58025     (void)sqlite3SafetyOff(db);
58026   }
58027   if( rc ){
58028     int iDb = db->nDb - 1;
58029     assert( iDb>=2 );
58030     if( db->aDb[iDb].pBt ){
58031       sqlite3BtreeClose(db->aDb[iDb].pBt);
58032       db->aDb[iDb].pBt = 0;
58033       db->aDb[iDb].pSchema = 0;
58034     }
58035     sqlite3ResetInternalSchema(db, 0);
58036     db->nDb = iDb;
58037     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
58038       db->mallocFailed = 1;
58039       sqlite3_snprintf(sizeof(zErr),zErr, "out of memory");
58040     }else{
58041       sqlite3_snprintf(sizeof(zErr),zErr, "unable to open database: %s", zFile);
58042     }
58043     goto attach_error;
58044   }
58045   
58046   return;
58047
58048 attach_error:
58049   /* Return an error if we get here */
58050   if( zErrDyn ){
58051     sqlite3_result_error(context, zErrDyn, -1);
58052     sqlite3DbFree(db, zErrDyn);
58053   }else{
58054     zErr[sizeof(zErr)-1] = 0;
58055     sqlite3_result_error(context, zErr, -1);
58056   }
58057   if( rc ) sqlite3_result_error_code(context, rc);
58058 }
58059
58060 /*
58061 ** An SQL user-function registered to do the work of an DETACH statement. The
58062 ** three arguments to the function come directly from a detach statement:
58063 **
58064 **     DETACH DATABASE x
58065 **
58066 **     SELECT sqlite_detach(x)
58067 */
58068 static void detachFunc(
58069   sqlite3_context *context,
58070   int NotUsed,
58071   sqlite3_value **argv
58072 ){
58073   const char *zName = (const char *)sqlite3_value_text(argv[0]);
58074   sqlite3 *db = sqlite3_context_db_handle(context);
58075   int i;
58076   Db *pDb = 0;
58077   char zErr[128];
58078
58079   UNUSED_PARAMETER(NotUsed);
58080
58081   if( zName==0 ) zName = "";
58082   for(i=0; i<db->nDb; i++){
58083     pDb = &db->aDb[i];
58084     if( pDb->pBt==0 ) continue;
58085     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
58086   }
58087
58088   if( i>=db->nDb ){
58089     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
58090     goto detach_error;
58091   }
58092   if( i<2 ){
58093     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
58094     goto detach_error;
58095   }
58096   if( !db->autoCommit ){
58097     sqlite3_snprintf(sizeof(zErr), zErr,
58098                      "cannot DETACH database within transaction");
58099     goto detach_error;
58100   }
58101   if( sqlite3BtreeIsInReadTrans(pDb->pBt) ){
58102     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
58103     goto detach_error;
58104   }
58105
58106   sqlite3BtreeClose(pDb->pBt);
58107   pDb->pBt = 0;
58108   pDb->pSchema = 0;
58109   sqlite3ResetInternalSchema(db, 0);
58110   return;
58111
58112 detach_error:
58113   sqlite3_result_error(context, zErr, -1);
58114 }
58115
58116 /*
58117 ** This procedure generates VDBE code for a single invocation of either the
58118 ** sqlite_detach() or sqlite_attach() SQL user functions.
58119 */
58120 static void codeAttach(
58121   Parse *pParse,       /* The parser context */
58122   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
58123   FuncDef *pFunc,      /* FuncDef wrapper for detachFunc() or attachFunc() */
58124   Expr *pAuthArg,      /* Expression to pass to authorization callback */
58125   Expr *pFilename,     /* Name of database file */
58126   Expr *pDbname,       /* Name of the database to use internally */
58127   Expr *pKey           /* Database key for encryption extension */
58128 ){
58129   int rc;
58130   NameContext sName;
58131   Vdbe *v;
58132   sqlite3* db = pParse->db;
58133   int regArgs;
58134
58135 #ifndef SQLITE_OMIT_AUTHORIZATION
58136   assert( db->mallocFailed || pAuthArg );
58137   if( pAuthArg ){
58138     char *zAuthArg = sqlite3NameFromToken(db, &pAuthArg->span);
58139     if( !zAuthArg ){
58140       goto attach_end;
58141     }
58142     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
58143     sqlite3DbFree(db, zAuthArg);
58144     if(rc!=SQLITE_OK ){
58145       goto attach_end;
58146     }
58147   }
58148 #endif /* SQLITE_OMIT_AUTHORIZATION */
58149
58150   memset(&sName, 0, sizeof(NameContext));
58151   sName.pParse = pParse;
58152
58153   if( 
58154       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
58155       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
58156       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
58157   ){
58158     pParse->nErr++;
58159     goto attach_end;
58160   }
58161
58162   v = sqlite3GetVdbe(pParse);
58163   regArgs = sqlite3GetTempRange(pParse, 4);
58164   sqlite3ExprCode(pParse, pFilename, regArgs);
58165   sqlite3ExprCode(pParse, pDbname, regArgs+1);
58166   sqlite3ExprCode(pParse, pKey, regArgs+2);
58167
58168   assert( v || db->mallocFailed );
58169   if( v ){
58170     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
58171     sqlite3VdbeChangeP5(v, pFunc->nArg);
58172     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
58173
58174     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
58175     ** statement only). For DETACH, set it to false (expire all existing
58176     ** statements).
58177     */
58178     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
58179   }
58180   
58181 attach_end:
58182   sqlite3ExprDelete(db, pFilename);
58183   sqlite3ExprDelete(db, pDbname);
58184   sqlite3ExprDelete(db, pKey);
58185 }
58186
58187 /*
58188 ** Called by the parser to compile a DETACH statement.
58189 **
58190 **     DETACH pDbname
58191 */
58192 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
58193   static FuncDef detach_func = {
58194     1,                /* nArg */
58195     SQLITE_UTF8,      /* iPrefEnc */
58196     0,                /* flags */
58197     0,                /* pUserData */
58198     0,                /* pNext */
58199     detachFunc,       /* xFunc */
58200     0,                /* xStep */
58201     0,                /* xFinalize */
58202     "sqlite_detach",  /* zName */
58203     0                 /* pHash */
58204   };
58205   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
58206 }
58207
58208 /*
58209 ** Called by the parser to compile an ATTACH statement.
58210 **
58211 **     ATTACH p AS pDbname KEY pKey
58212 */
58213 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
58214   static FuncDef attach_func = {
58215     3,                /* nArg */
58216     SQLITE_UTF8,      /* iPrefEnc */
58217     0,                /* flags */
58218     0,                /* pUserData */
58219     0,                /* pNext */
58220     attachFunc,       /* xFunc */
58221     0,                /* xStep */
58222     0,                /* xFinalize */
58223     "sqlite_attach",  /* zName */
58224     0                 /* pHash */
58225   };
58226   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
58227 }
58228 #endif /* SQLITE_OMIT_ATTACH */
58229
58230 /*
58231 ** Initialize a DbFixer structure.  This routine must be called prior
58232 ** to passing the structure to one of the sqliteFixAAAA() routines below.
58233 **
58234 ** The return value indicates whether or not fixation is required.  TRUE
58235 ** means we do need to fix the database references, FALSE means we do not.
58236 */
58237 SQLITE_PRIVATE int sqlite3FixInit(
58238   DbFixer *pFix,      /* The fixer to be initialized */
58239   Parse *pParse,      /* Error messages will be written here */
58240   int iDb,            /* This is the database that must be used */
58241   const char *zType,  /* "view", "trigger", or "index" */
58242   const Token *pName  /* Name of the view, trigger, or index */
58243 ){
58244   sqlite3 *db;
58245
58246   if( iDb<0 || iDb==1 ) return 0;
58247   db = pParse->db;
58248   assert( db->nDb>iDb );
58249   pFix->pParse = pParse;
58250   pFix->zDb = db->aDb[iDb].zName;
58251   pFix->zType = zType;
58252   pFix->pName = pName;
58253   return 1;
58254 }
58255
58256 /*
58257 ** The following set of routines walk through the parse tree and assign
58258 ** a specific database to all table references where the database name
58259 ** was left unspecified in the original SQL statement.  The pFix structure
58260 ** must have been initialized by a prior call to sqlite3FixInit().
58261 **
58262 ** These routines are used to make sure that an index, trigger, or
58263 ** view in one database does not refer to objects in a different database.
58264 ** (Exception: indices, triggers, and views in the TEMP database are
58265 ** allowed to refer to anything.)  If a reference is explicitly made
58266 ** to an object in a different database, an error message is added to
58267 ** pParse->zErrMsg and these routines return non-zero.  If everything
58268 ** checks out, these routines return 0.
58269 */
58270 SQLITE_PRIVATE int sqlite3FixSrcList(
58271   DbFixer *pFix,       /* Context of the fixation */
58272   SrcList *pList       /* The Source list to check and modify */
58273 ){
58274   int i;
58275   const char *zDb;
58276   struct SrcList_item *pItem;
58277
58278   if( pList==0 ) return 0;
58279   zDb = pFix->zDb;
58280   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
58281     if( pItem->zDatabase==0 ){
58282       pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
58283     }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
58284       sqlite3ErrorMsg(pFix->pParse,
58285          "%s %T cannot reference objects in database %s",
58286          pFix->zType, pFix->pName, pItem->zDatabase);
58287       return 1;
58288     }
58289 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
58290     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
58291     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
58292 #endif
58293   }
58294   return 0;
58295 }
58296 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
58297 SQLITE_PRIVATE int sqlite3FixSelect(
58298   DbFixer *pFix,       /* Context of the fixation */
58299   Select *pSelect      /* The SELECT statement to be fixed to one database */
58300 ){
58301   while( pSelect ){
58302     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
58303       return 1;
58304     }
58305     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
58306       return 1;
58307     }
58308     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
58309       return 1;
58310     }
58311     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
58312       return 1;
58313     }
58314     pSelect = pSelect->pPrior;
58315   }
58316   return 0;
58317 }
58318 SQLITE_PRIVATE int sqlite3FixExpr(
58319   DbFixer *pFix,     /* Context of the fixation */
58320   Expr *pExpr        /* The expression to be fixed to one database */
58321 ){
58322   while( pExpr ){
58323     if( sqlite3FixSelect(pFix, pExpr->pSelect) ){
58324       return 1;
58325     }
58326     if( sqlite3FixExprList(pFix, pExpr->pList) ){
58327       return 1;
58328     }
58329     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
58330       return 1;
58331     }
58332     pExpr = pExpr->pLeft;
58333   }
58334   return 0;
58335 }
58336 SQLITE_PRIVATE int sqlite3FixExprList(
58337   DbFixer *pFix,     /* Context of the fixation */
58338   ExprList *pList    /* The expression to be fixed to one database */
58339 ){
58340   int i;
58341   struct ExprList_item *pItem;
58342   if( pList==0 ) return 0;
58343   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
58344     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
58345       return 1;
58346     }
58347   }
58348   return 0;
58349 }
58350 #endif
58351
58352 #ifndef SQLITE_OMIT_TRIGGER
58353 SQLITE_PRIVATE int sqlite3FixTriggerStep(
58354   DbFixer *pFix,     /* Context of the fixation */
58355   TriggerStep *pStep /* The trigger step be fixed to one database */
58356 ){
58357   while( pStep ){
58358     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
58359       return 1;
58360     }
58361     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
58362       return 1;
58363     }
58364     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
58365       return 1;
58366     }
58367     pStep = pStep->pNext;
58368   }
58369   return 0;
58370 }
58371 #endif
58372
58373 /************** End of attach.c **********************************************/
58374 /************** Begin file auth.c ********************************************/
58375 /*
58376 ** 2003 January 11
58377 **
58378 ** The author disclaims copyright to this source code.  In place of
58379 ** a legal notice, here is a blessing:
58380 **
58381 **    May you do good and not evil.
58382 **    May you find forgiveness for yourself and forgive others.
58383 **    May you share freely, never taking more than you give.
58384 **
58385 *************************************************************************
58386 ** This file contains code used to implement the sqlite3_set_authorizer()
58387 ** API.  This facility is an optional feature of the library.  Embedded
58388 ** systems that do not need this facility may omit it by recompiling
58389 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
58390 **
58391 ** $Id: auth.c,v 1.29 2007/09/18 15:55:07 drh Exp $
58392 */
58393
58394 /*
58395 ** All of the code in this file may be omitted by defining a single
58396 ** macro.
58397 */
58398 #ifndef SQLITE_OMIT_AUTHORIZATION
58399
58400 /*
58401 ** Set or clear the access authorization function.
58402 **
58403 ** The access authorization function is be called during the compilation
58404 ** phase to verify that the user has read and/or write access permission on
58405 ** various fields of the database.  The first argument to the auth function
58406 ** is a copy of the 3rd argument to this routine.  The second argument
58407 ** to the auth function is one of these constants:
58408 **
58409 **       SQLITE_CREATE_INDEX
58410 **       SQLITE_CREATE_TABLE
58411 **       SQLITE_CREATE_TEMP_INDEX
58412 **       SQLITE_CREATE_TEMP_TABLE
58413 **       SQLITE_CREATE_TEMP_TRIGGER
58414 **       SQLITE_CREATE_TEMP_VIEW
58415 **       SQLITE_CREATE_TRIGGER
58416 **       SQLITE_CREATE_VIEW
58417 **       SQLITE_DELETE
58418 **       SQLITE_DROP_INDEX
58419 **       SQLITE_DROP_TABLE
58420 **       SQLITE_DROP_TEMP_INDEX
58421 **       SQLITE_DROP_TEMP_TABLE
58422 **       SQLITE_DROP_TEMP_TRIGGER
58423 **       SQLITE_DROP_TEMP_VIEW
58424 **       SQLITE_DROP_TRIGGER
58425 **       SQLITE_DROP_VIEW
58426 **       SQLITE_INSERT
58427 **       SQLITE_PRAGMA
58428 **       SQLITE_READ
58429 **       SQLITE_SELECT
58430 **       SQLITE_TRANSACTION
58431 **       SQLITE_UPDATE
58432 **
58433 ** The third and fourth arguments to the auth function are the name of
58434 ** the table and the column that are being accessed.  The auth function
58435 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
58436 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
58437 ** means that the SQL statement will never-run - the sqlite3_exec() call
58438 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
58439 ** should run but attempts to read the specified column will return NULL
58440 ** and attempts to write the column will be ignored.
58441 **
58442 ** Setting the auth function to NULL disables this hook.  The default
58443 ** setting of the auth function is NULL.
58444 */
58445 SQLITE_API int sqlite3_set_authorizer(
58446   sqlite3 *db,
58447   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
58448   void *pArg
58449 ){
58450   sqlite3_mutex_enter(db->mutex);
58451   db->xAuth = xAuth;
58452   db->pAuthArg = pArg;
58453   sqlite3ExpirePreparedStatements(db);
58454   sqlite3_mutex_leave(db->mutex);
58455   return SQLITE_OK;
58456 }
58457
58458 /*
58459 ** Write an error message into pParse->zErrMsg that explains that the
58460 ** user-supplied authorization function returned an illegal value.
58461 */
58462 static void sqliteAuthBadReturnCode(Parse *pParse, int rc){
58463   sqlite3ErrorMsg(pParse, "illegal return value (%d) from the "
58464     "authorization function - should be SQLITE_OK, SQLITE_IGNORE, "
58465     "or SQLITE_DENY", rc);
58466   pParse->rc = SQLITE_ERROR;
58467 }
58468
58469 /*
58470 ** The pExpr should be a TK_COLUMN expression.  The table referred to
58471 ** is in pTabList or else it is the NEW or OLD table of a trigger.  
58472 ** Check to see if it is OK to read this particular column.
58473 **
58474 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
58475 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
58476 ** then generate an error.
58477 */
58478 SQLITE_PRIVATE void sqlite3AuthRead(
58479   Parse *pParse,        /* The parser context */
58480   Expr *pExpr,          /* The expression to check authorization on */
58481   Schema *pSchema,      /* The schema of the expression */
58482   SrcList *pTabList     /* All table that pExpr might refer to */
58483 ){
58484   sqlite3 *db = pParse->db;
58485   int rc;
58486   Table *pTab = 0;      /* The table being read */
58487   const char *zCol;     /* Name of the column of the table */
58488   int iSrc;             /* Index in pTabList->a[] of table being read */
58489   const char *zDBase;   /* Name of database being accessed */
58490   TriggerStack *pStack; /* The stack of current triggers */
58491   int iDb;              /* The index of the database the expression refers to */
58492
58493   if( db->xAuth==0 ) return;
58494   if( pExpr->op!=TK_COLUMN ) return;
58495   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
58496   if( iDb<0 ){
58497     /* An attempt to read a column out of a subquery or other
58498     ** temporary table. */
58499     return;
58500   }
58501   for(iSrc=0; pTabList && iSrc<pTabList->nSrc; iSrc++){
58502     if( pExpr->iTable==pTabList->a[iSrc].iCursor ) break;
58503   }
58504   if( iSrc>=0 && pTabList && iSrc<pTabList->nSrc ){
58505     pTab = pTabList->a[iSrc].pTab;
58506   }else if( (pStack = pParse->trigStack)!=0 ){
58507     /* This must be an attempt to read the NEW or OLD pseudo-tables
58508     ** of a trigger.
58509     */
58510     assert( pExpr->iTable==pStack->newIdx || pExpr->iTable==pStack->oldIdx );
58511     pTab = pStack->pTab;
58512   }
58513   if( pTab==0 ) return;
58514   if( pExpr->iColumn>=0 ){
58515     assert( pExpr->iColumn<pTab->nCol );
58516     zCol = pTab->aCol[pExpr->iColumn].zName;
58517   }else if( pTab->iPKey>=0 ){
58518     assert( pTab->iPKey<pTab->nCol );
58519     zCol = pTab->aCol[pTab->iPKey].zName;
58520   }else{
58521     zCol = "ROWID";
58522   }
58523   assert( iDb>=0 && iDb<db->nDb );
58524   zDBase = db->aDb[iDb].zName;
58525   rc = db->xAuth(db->pAuthArg, SQLITE_READ, pTab->zName, zCol, zDBase, 
58526                  pParse->zAuthContext);
58527   if( rc==SQLITE_IGNORE ){
58528     pExpr->op = TK_NULL;
58529   }else if( rc==SQLITE_DENY ){
58530     if( db->nDb>2 || iDb!=0 ){
58531       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited", 
58532          zDBase, pTab->zName, zCol);
58533     }else{
58534       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited",pTab->zName,zCol);
58535     }
58536     pParse->rc = SQLITE_AUTH;
58537   }else if( rc!=SQLITE_OK ){
58538     sqliteAuthBadReturnCode(pParse, rc);
58539   }
58540 }
58541
58542 /*
58543 ** Do an authorization check using the code and arguments given.  Return
58544 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
58545 ** is returned, then the error count and error message in pParse are
58546 ** modified appropriately.
58547 */
58548 SQLITE_PRIVATE int sqlite3AuthCheck(
58549   Parse *pParse,
58550   int code,
58551   const char *zArg1,
58552   const char *zArg2,
58553   const char *zArg3
58554 ){
58555   sqlite3 *db = pParse->db;
58556   int rc;
58557
58558   /* Don't do any authorization checks if the database is initialising
58559   ** or if the parser is being invoked from within sqlite3_declare_vtab.
58560   */
58561   if( db->init.busy || IN_DECLARE_VTAB ){
58562     return SQLITE_OK;
58563   }
58564
58565   if( db->xAuth==0 ){
58566     return SQLITE_OK;
58567   }
58568   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
58569   if( rc==SQLITE_DENY ){
58570     sqlite3ErrorMsg(pParse, "not authorized");
58571     pParse->rc = SQLITE_AUTH;
58572   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
58573     rc = SQLITE_DENY;
58574     sqliteAuthBadReturnCode(pParse, rc);
58575   }
58576   return rc;
58577 }
58578
58579 /*
58580 ** Push an authorization context.  After this routine is called, the
58581 ** zArg3 argument to authorization callbacks will be zContext until
58582 ** popped.  Or if pParse==0, this routine is a no-op.
58583 */
58584 SQLITE_PRIVATE void sqlite3AuthContextPush(
58585   Parse *pParse,
58586   AuthContext *pContext, 
58587   const char *zContext
58588 ){
58589   pContext->pParse = pParse;
58590   if( pParse ){
58591     pContext->zAuthContext = pParse->zAuthContext;
58592     pParse->zAuthContext = zContext;
58593   }
58594 }
58595
58596 /*
58597 ** Pop an authorization context that was previously pushed
58598 ** by sqlite3AuthContextPush
58599 */
58600 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
58601   if( pContext->pParse ){
58602     pContext->pParse->zAuthContext = pContext->zAuthContext;
58603     pContext->pParse = 0;
58604   }
58605 }
58606
58607 #endif /* SQLITE_OMIT_AUTHORIZATION */
58608
58609 /************** End of auth.c ************************************************/
58610 /************** Begin file build.c *******************************************/
58611 /*
58612 ** 2001 September 15
58613 **
58614 ** The author disclaims copyright to this source code.  In place of
58615 ** a legal notice, here is a blessing:
58616 **
58617 **    May you do good and not evil.
58618 **    May you find forgiveness for yourself and forgive others.
58619 **    May you share freely, never taking more than you give.
58620 **
58621 *************************************************************************
58622 ** This file contains C code routines that are called by the SQLite parser
58623 ** when syntax rules are reduced.  The routines in this file handle the
58624 ** following kinds of SQL syntax:
58625 **
58626 **     CREATE TABLE
58627 **     DROP TABLE
58628 **     CREATE INDEX
58629 **     DROP INDEX
58630 **     creating ID lists
58631 **     BEGIN TRANSACTION
58632 **     COMMIT
58633 **     ROLLBACK
58634 **
58635 ** $Id: build.c,v 1.503 2008/11/17 19:18:55 danielk1977 Exp $
58636 */
58637
58638 /*
58639 ** This routine is called when a new SQL statement is beginning to
58640 ** be parsed.  Initialize the pParse structure as needed.
58641 */
58642 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
58643   pParse->explain = explainFlag;
58644   pParse->nVar = 0;
58645 }
58646
58647 #ifndef SQLITE_OMIT_SHARED_CACHE
58648 /*
58649 ** The TableLock structure is only used by the sqlite3TableLock() and
58650 ** codeTableLocks() functions.
58651 */
58652 struct TableLock {
58653   int iDb;             /* The database containing the table to be locked */
58654   int iTab;            /* The root page of the table to be locked */
58655   u8 isWriteLock;      /* True for write lock.  False for a read lock */
58656   const char *zName;   /* Name of the table */
58657 };
58658
58659 /*
58660 ** Record the fact that we want to lock a table at run-time.  
58661 **
58662 ** The table to be locked has root page iTab and is found in database iDb.
58663 ** A read or a write lock can be taken depending on isWritelock.
58664 **
58665 ** This routine just records the fact that the lock is desired.  The
58666 ** code to make the lock occur is generated by a later call to
58667 ** codeTableLocks() which occurs during sqlite3FinishCoding().
58668 */
58669 SQLITE_PRIVATE void sqlite3TableLock(
58670   Parse *pParse,     /* Parsing context */
58671   int iDb,           /* Index of the database containing the table to lock */
58672   int iTab,          /* Root page number of the table to be locked */
58673   u8 isWriteLock,    /* True for a write lock */
58674   const char *zName  /* Name of the table to be locked */
58675 ){
58676   int i;
58677   int nBytes;
58678   TableLock *p;
58679
58680   if( iDb<0 ){
58681     return;
58682   }
58683
58684   for(i=0; i<pParse->nTableLock; i++){
58685     p = &pParse->aTableLock[i];
58686     if( p->iDb==iDb && p->iTab==iTab ){
58687       p->isWriteLock = (p->isWriteLock || isWriteLock);
58688       return;
58689     }
58690   }
58691
58692   nBytes = sizeof(TableLock) * (pParse->nTableLock+1);
58693   pParse->aTableLock = 
58694       sqlite3DbReallocOrFree(pParse->db, pParse->aTableLock, nBytes);
58695   if( pParse->aTableLock ){
58696     p = &pParse->aTableLock[pParse->nTableLock++];
58697     p->iDb = iDb;
58698     p->iTab = iTab;
58699     p->isWriteLock = isWriteLock;
58700     p->zName = zName;
58701   }else{
58702     pParse->nTableLock = 0;
58703     pParse->db->mallocFailed = 1;
58704   }
58705 }
58706
58707 /*
58708 ** Code an OP_TableLock instruction for each table locked by the
58709 ** statement (configured by calls to sqlite3TableLock()).
58710 */
58711 static void codeTableLocks(Parse *pParse){
58712   int i;
58713   Vdbe *pVdbe; 
58714
58715   if( 0==(pVdbe = sqlite3GetVdbe(pParse)) ){
58716     return;
58717   }
58718
58719   for(i=0; i<pParse->nTableLock; i++){
58720     TableLock *p = &pParse->aTableLock[i];
58721     int p1 = p->iDb;
58722     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
58723                       p->zName, P4_STATIC);
58724   }
58725 }
58726 #else
58727   #define codeTableLocks(x)
58728 #endif
58729
58730 /*
58731 ** This routine is called after a single SQL statement has been
58732 ** parsed and a VDBE program to execute that statement has been
58733 ** prepared.  This routine puts the finishing touches on the
58734 ** VDBE program and resets the pParse structure for the next
58735 ** parse.
58736 **
58737 ** Note that if an error occurred, it might be the case that
58738 ** no VDBE code was generated.
58739 */
58740 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
58741   sqlite3 *db;
58742   Vdbe *v;
58743
58744   db = pParse->db;
58745   if( db->mallocFailed ) return;
58746   if( pParse->nested ) return;
58747   if( pParse->nErr ) return;
58748
58749   /* Begin by generating some termination code at the end of the
58750   ** vdbe program
58751   */
58752   v = sqlite3GetVdbe(pParse);
58753   if( v ){
58754     sqlite3VdbeAddOp0(v, OP_Halt);
58755
58756     /* The cookie mask contains one bit for each database file open.
58757     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
58758     ** set for each database that is used.  Generate code to start a
58759     ** transaction on each used database and to verify the schema cookie
58760     ** on each used database.
58761     */
58762     if( pParse->cookieGoto>0 ){
58763       u32 mask;
58764       int iDb;
58765       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
58766       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
58767         if( (mask & pParse->cookieMask)==0 ) continue;
58768         sqlite3VdbeUsesBtree(v, iDb);
58769         sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
58770         sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
58771       }
58772 #ifndef SQLITE_OMIT_VIRTUALTABLE
58773       {
58774         int i;
58775         for(i=0; i<pParse->nVtabLock; i++){
58776           char *vtab = (char *)pParse->apVtabLock[i]->pVtab;
58777           sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
58778         }
58779         pParse->nVtabLock = 0;
58780       }
58781 #endif
58782
58783       /* Once all the cookies have been verified and transactions opened, 
58784       ** obtain the required table-locks. This is a no-op unless the 
58785       ** shared-cache feature is enabled.
58786       */
58787       codeTableLocks(pParse);
58788       sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
58789     }
58790
58791 #ifndef SQLITE_OMIT_TRACE
58792     if( !db->init.busy ){
58793       /* Change the P4 argument of the first opcode (which will always be
58794       ** an OP_Trace) to be the complete text of the current SQL statement.
58795       */
58796       VdbeOp *pOp = sqlite3VdbeGetOp(v, 0);
58797       if( pOp && pOp->opcode==OP_Trace ){
58798         sqlite3VdbeChangeP4(v, 0, pParse->zSql, pParse->zTail-pParse->zSql);
58799       }
58800     }
58801 #endif /* SQLITE_OMIT_TRACE */
58802   }
58803
58804
58805   /* Get the VDBE program ready for execution
58806   */
58807   if( v && pParse->nErr==0 && !db->mallocFailed ){
58808 #ifdef SQLITE_DEBUG
58809     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
58810     sqlite3VdbeTrace(v, trace);
58811 #endif
58812     assert( pParse->disableColCache==0 );  /* Disables and re-enables match */
58813     sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem+3,
58814                          pParse->nTab+3, pParse->explain);
58815     pParse->rc = SQLITE_DONE;
58816     pParse->colNamesSet = 0;
58817   }else if( pParse->rc==SQLITE_OK ){
58818     pParse->rc = SQLITE_ERROR;
58819   }
58820   pParse->nTab = 0;
58821   pParse->nMem = 0;
58822   pParse->nSet = 0;
58823   pParse->nVar = 0;
58824   pParse->cookieMask = 0;
58825   pParse->cookieGoto = 0;
58826 }
58827
58828 /*
58829 ** Run the parser and code generator recursively in order to generate
58830 ** code for the SQL statement given onto the end of the pParse context
58831 ** currently under construction.  When the parser is run recursively
58832 ** this way, the final OP_Halt is not appended and other initialization
58833 ** and finalization steps are omitted because those are handling by the
58834 ** outermost parser.
58835 **
58836 ** Not everything is nestable.  This facility is designed to permit
58837 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
58838 ** care if you decide to try to use this routine for some other purposes.
58839 */
58840 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
58841   va_list ap;
58842   char *zSql;
58843   char *zErrMsg = 0;
58844   sqlite3 *db = pParse->db;
58845 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
58846   char saveBuf[SAVE_SZ];
58847
58848   if( pParse->nErr ) return;
58849   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
58850   va_start(ap, zFormat);
58851   zSql = sqlite3VMPrintf(db, zFormat, ap);
58852   va_end(ap);
58853   if( zSql==0 ){
58854     return;   /* A malloc must have failed */
58855   }
58856   pParse->nested++;
58857   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
58858   memset(&pParse->nVar, 0, SAVE_SZ);
58859   sqlite3RunParser(pParse, zSql, &zErrMsg);
58860   sqlite3DbFree(db, zErrMsg);
58861   sqlite3DbFree(db, zSql);
58862   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
58863   pParse->nested--;
58864 }
58865
58866 /*
58867 ** Locate the in-memory structure that describes a particular database
58868 ** table given the name of that table and (optionally) the name of the
58869 ** database containing the table.  Return NULL if not found.
58870 **
58871 ** If zDatabase is 0, all databases are searched for the table and the
58872 ** first matching table is returned.  (No checking for duplicate table
58873 ** names is done.)  The search order is TEMP first, then MAIN, then any
58874 ** auxiliary databases added using the ATTACH command.
58875 **
58876 ** See also sqlite3LocateTable().
58877 */
58878 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
58879   Table *p = 0;
58880   int i;
58881   int nName;
58882   assert( zName!=0 );
58883   nName = sqlite3Strlen(db, zName) + 1;
58884   for(i=OMIT_TEMPDB; i<db->nDb; i++){
58885     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
58886     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
58887     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
58888     if( p ) break;
58889   }
58890   return p;
58891 }
58892
58893 /*
58894 ** Locate the in-memory structure that describes a particular database
58895 ** table given the name of that table and (optionally) the name of the
58896 ** database containing the table.  Return NULL if not found.  Also leave an
58897 ** error message in pParse->zErrMsg.
58898 **
58899 ** The difference between this routine and sqlite3FindTable() is that this
58900 ** routine leaves an error message in pParse->zErrMsg where
58901 ** sqlite3FindTable() does not.
58902 */
58903 SQLITE_PRIVATE Table *sqlite3LocateTable(
58904   Parse *pParse,         /* context in which to report errors */
58905   int isView,            /* True if looking for a VIEW rather than a TABLE */
58906   const char *zName,     /* Name of the table we are looking for */
58907   const char *zDbase     /* Name of the database.  Might be NULL */
58908 ){
58909   Table *p;
58910
58911   /* Read the database schema. If an error occurs, leave an error message
58912   ** and code in pParse and return NULL. */
58913   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
58914     return 0;
58915   }
58916
58917   p = sqlite3FindTable(pParse->db, zName, zDbase);
58918   if( p==0 ){
58919     const char *zMsg = isView ? "no such view" : "no such table";
58920     if( zDbase ){
58921       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
58922     }else{
58923       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
58924     }
58925     pParse->checkSchema = 1;
58926   }
58927   return p;
58928 }
58929
58930 /*
58931 ** Locate the in-memory structure that describes 
58932 ** a particular index given the name of that index
58933 ** and the name of the database that contains the index.
58934 ** Return NULL if not found.
58935 **
58936 ** If zDatabase is 0, all databases are searched for the
58937 ** table and the first matching index is returned.  (No checking
58938 ** for duplicate index names is done.)  The search order is
58939 ** TEMP first, then MAIN, then any auxiliary databases added
58940 ** using the ATTACH command.
58941 */
58942 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
58943   Index *p = 0;
58944   int i;
58945   int nName = sqlite3Strlen(db, zName)+1;
58946   for(i=OMIT_TEMPDB; i<db->nDb; i++){
58947     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
58948     Schema *pSchema = db->aDb[j].pSchema;
58949     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
58950     assert( pSchema || (j==1 && !db->aDb[1].pBt) );
58951     if( pSchema ){
58952       p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
58953     }
58954     if( p ) break;
58955   }
58956   return p;
58957 }
58958
58959 /*
58960 ** Reclaim the memory used by an index
58961 */
58962 static void freeIndex(Index *p){
58963   sqlite3 *db = p->pTable->db;
58964   sqlite3DbFree(db, p->zColAff);
58965   sqlite3DbFree(db, p);
58966 }
58967
58968 /*
58969 ** Remove the given index from the index hash table, and free
58970 ** its memory structures.
58971 **
58972 ** The index is removed from the database hash tables but
58973 ** it is not unlinked from the Table that it indexes.
58974 ** Unlinking from the Table must be done by the calling function.
58975 */
58976 static void sqliteDeleteIndex(Index *p){
58977   Index *pOld;
58978   const char *zName = p->zName;
58979
58980   pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName, strlen(zName)+1, 0);
58981   assert( pOld==0 || pOld==p );
58982   freeIndex(p);
58983 }
58984
58985 /*
58986 ** For the index called zIdxName which is found in the database iDb,
58987 ** unlike that index from its Table then remove the index from
58988 ** the index hash table and free all memory structures associated
58989 ** with the index.
58990 */
58991 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
58992   Index *pIndex;
58993   int len;
58994   Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
58995
58996   len = sqlite3Strlen(db, zIdxName);
58997   pIndex = sqlite3HashInsert(pHash, zIdxName, len+1, 0);
58998   if( pIndex ){
58999     if( pIndex->pTable->pIndex==pIndex ){
59000       pIndex->pTable->pIndex = pIndex->pNext;
59001     }else{
59002       Index *p;
59003       for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
59004       if( p && p->pNext==pIndex ){
59005         p->pNext = pIndex->pNext;
59006       }
59007     }
59008     freeIndex(pIndex);
59009   }
59010   db->flags |= SQLITE_InternChanges;
59011 }
59012
59013 /*
59014 ** Erase all schema information from the in-memory hash tables of
59015 ** a single database.  This routine is called to reclaim memory
59016 ** before the database closes.  It is also called during a rollback
59017 ** if there were schema changes during the transaction or if a
59018 ** schema-cookie mismatch occurs.
59019 **
59020 ** If iDb<=0 then reset the internal schema tables for all database
59021 ** files.  If iDb>=2 then reset the internal schema for only the
59022 ** single file indicated.
59023 */
59024 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
59025   int i, j;
59026   assert( iDb>=0 && iDb<db->nDb );
59027
59028   if( iDb==0 ){
59029     sqlite3BtreeEnterAll(db);
59030   }
59031   for(i=iDb; i<db->nDb; i++){
59032     Db *pDb = &db->aDb[i];
59033     if( pDb->pSchema ){
59034       assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
59035       sqlite3SchemaFree(pDb->pSchema);
59036     }
59037     if( iDb>0 ) return;
59038   }
59039   assert( iDb==0 );
59040   db->flags &= ~SQLITE_InternChanges;
59041   sqlite3BtreeLeaveAll(db);
59042
59043   /* If one or more of the auxiliary database files has been closed,
59044   ** then remove them from the auxiliary database list.  We take the
59045   ** opportunity to do this here since we have just deleted all of the
59046   ** schema hash tables and therefore do not have to make any changes
59047   ** to any of those tables.
59048   */
59049   for(i=0; i<db->nDb; i++){
59050     struct Db *pDb = &db->aDb[i];
59051     if( pDb->pBt==0 ){
59052       if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
59053       pDb->pAux = 0;
59054     }
59055   }
59056   for(i=j=2; i<db->nDb; i++){
59057     struct Db *pDb = &db->aDb[i];
59058     if( pDb->pBt==0 ){
59059       sqlite3DbFree(db, pDb->zName);
59060       pDb->zName = 0;
59061       continue;
59062     }
59063     if( j<i ){
59064       db->aDb[j] = db->aDb[i];
59065     }
59066     j++;
59067   }
59068   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
59069   db->nDb = j;
59070   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
59071     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
59072     sqlite3DbFree(db, db->aDb);
59073     db->aDb = db->aDbStatic;
59074   }
59075 }
59076
59077 /*
59078 ** This routine is called when a commit occurs.
59079 */
59080 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
59081   db->flags &= ~SQLITE_InternChanges;
59082 }
59083
59084 /*
59085 ** Clear the column names from a table or view.
59086 */
59087 static void sqliteResetColumnNames(Table *pTable){
59088   int i;
59089   Column *pCol;
59090   sqlite3 *db = pTable->db;
59091   assert( pTable!=0 );
59092   if( (pCol = pTable->aCol)!=0 ){
59093     for(i=0; i<pTable->nCol; i++, pCol++){
59094       sqlite3DbFree(db, pCol->zName);
59095       sqlite3ExprDelete(db, pCol->pDflt);
59096       sqlite3DbFree(db, pCol->zType);
59097       sqlite3DbFree(db, pCol->zColl);
59098     }
59099     sqlite3DbFree(db, pTable->aCol);
59100   }
59101   pTable->aCol = 0;
59102   pTable->nCol = 0;
59103 }
59104
59105 /*
59106 ** Remove the memory data structures associated with the given
59107 ** Table.  No changes are made to disk by this routine.
59108 **
59109 ** This routine just deletes the data structure.  It does not unlink
59110 ** the table data structure from the hash table.  Nor does it remove
59111 ** foreign keys from the sqlite.aFKey hash table.  But it does destroy
59112 ** memory structures of the indices and foreign keys associated with 
59113 ** the table.
59114 */
59115 SQLITE_PRIVATE void sqlite3DeleteTable(Table *pTable){
59116   Index *pIndex, *pNext;
59117   FKey *pFKey, *pNextFKey;
59118   sqlite3 *db;
59119
59120   if( pTable==0 ) return;
59121   db = pTable->db;
59122
59123   /* Do not delete the table until the reference count reaches zero. */
59124   pTable->nRef--;
59125   if( pTable->nRef>0 ){
59126     return;
59127   }
59128   assert( pTable->nRef==0 );
59129
59130   /* Delete all indices associated with this table
59131   */
59132   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
59133     pNext = pIndex->pNext;
59134     assert( pIndex->pSchema==pTable->pSchema );
59135     sqliteDeleteIndex(pIndex);
59136   }
59137
59138 #ifndef SQLITE_OMIT_FOREIGN_KEY
59139   /* Delete all foreign keys associated with this table.  The keys
59140   ** should have already been unlinked from the pSchema->aFKey hash table 
59141   */
59142   for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
59143     pNextFKey = pFKey->pNextFrom;
59144     assert( sqlite3HashFind(&pTable->pSchema->aFKey,
59145                            pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey );
59146     sqlite3DbFree(db, pFKey);
59147   }
59148 #endif
59149
59150   /* Delete the Table structure itself.
59151   */
59152   sqliteResetColumnNames(pTable);
59153   sqlite3DbFree(db, pTable->zName);
59154   sqlite3DbFree(db, pTable->zColAff);
59155   sqlite3SelectDelete(db, pTable->pSelect);
59156 #ifndef SQLITE_OMIT_CHECK
59157   sqlite3ExprDelete(db, pTable->pCheck);
59158 #endif
59159   sqlite3VtabClear(pTable);
59160   sqlite3DbFree(db, pTable);
59161 }
59162
59163 /*
59164 ** Unlink the given table from the hash tables and the delete the
59165 ** table structure with all its indices and foreign keys.
59166 */
59167 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
59168   Table *p;
59169   FKey *pF1, *pF2;
59170   Db *pDb;
59171
59172   assert( db!=0 );
59173   assert( iDb>=0 && iDb<db->nDb );
59174   assert( zTabName && zTabName[0] );
59175   pDb = &db->aDb[iDb];
59176   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, strlen(zTabName)+1,0);
59177   if( p ){
59178 #ifndef SQLITE_OMIT_FOREIGN_KEY
59179     for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
59180       int nTo = strlen(pF1->zTo) + 1;
59181       pF2 = sqlite3HashFind(&pDb->pSchema->aFKey, pF1->zTo, nTo);
59182       if( pF2==pF1 ){
59183         sqlite3HashInsert(&pDb->pSchema->aFKey, pF1->zTo, nTo, pF1->pNextTo);
59184       }else{
59185         while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
59186         if( pF2 ){
59187           pF2->pNextTo = pF1->pNextTo;
59188         }
59189       }
59190     }
59191 #endif
59192     sqlite3DeleteTable(p);
59193   }
59194   db->flags |= SQLITE_InternChanges;
59195 }
59196
59197 /*
59198 ** Given a token, return a string that consists of the text of that
59199 ** token with any quotations removed.  Space to hold the returned string
59200 ** is obtained from sqliteMalloc() and must be freed by the calling
59201 ** function.
59202 **
59203 ** Tokens are often just pointers into the original SQL text and so
59204 ** are not \000 terminated and are not persistent.  The returned string
59205 ** is \000 terminated and is persistent.
59206 */
59207 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
59208   char *zName;
59209   if( pName ){
59210     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
59211     sqlite3Dequote(zName);
59212   }else{
59213     zName = 0;
59214   }
59215   return zName;
59216 }
59217
59218 /*
59219 ** Open the sqlite_master table stored in database number iDb for
59220 ** writing. The table is opened using cursor 0.
59221 */
59222 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
59223   Vdbe *v = sqlite3GetVdbe(p);
59224   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
59225   sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, 5);/* sqlite_master has 5 columns */
59226   sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
59227 }
59228
59229 /*
59230 ** The token *pName contains the name of a database (either "main" or
59231 ** "temp" or the name of an attached db). This routine returns the
59232 ** index of the named database in db->aDb[], or -1 if the named db 
59233 ** does not exist.
59234 */
59235 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
59236   int i = -1;    /* Database number */
59237   size_t n;      /* Number of characters in the name */
59238   Db *pDb;       /* A database whose name space is being searched */
59239   char *zName;   /* Name we are searching for */
59240
59241   zName = sqlite3NameFromToken(db, pName);
59242   if( zName ){
59243     n = strlen(zName);
59244     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
59245       if( (!OMIT_TEMPDB || i!=1 ) && n==strlen(pDb->zName) && 
59246           0==sqlite3StrICmp(pDb->zName, zName) ){
59247         break;
59248       }
59249     }
59250     sqlite3DbFree(db, zName);
59251   }
59252   return i;
59253 }
59254
59255 /* The table or view or trigger name is passed to this routine via tokens
59256 ** pName1 and pName2. If the table name was fully qualified, for example:
59257 **
59258 ** CREATE TABLE xxx.yyy (...);
59259 ** 
59260 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
59261 ** the table name is not fully qualified, i.e.:
59262 **
59263 ** CREATE TABLE yyy(...);
59264 **
59265 ** Then pName1 is set to "yyy" and pName2 is "".
59266 **
59267 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
59268 ** pName2) that stores the unqualified table name.  The index of the
59269 ** database "xxx" is returned.
59270 */
59271 SQLITE_PRIVATE int sqlite3TwoPartName(
59272   Parse *pParse,      /* Parsing and code generating context */
59273   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
59274   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
59275   Token **pUnqual     /* Write the unqualified object name here */
59276 ){
59277   int iDb;                    /* Database holding the object */
59278   sqlite3 *db = pParse->db;
59279
59280   if( pName2 && pName2->n>0 ){
59281     if( db->init.busy ) {
59282       sqlite3ErrorMsg(pParse, "corrupt database");
59283       pParse->nErr++;
59284       return -1;
59285     }
59286     *pUnqual = pName2;
59287     iDb = sqlite3FindDb(db, pName1);
59288     if( iDb<0 ){
59289       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
59290       pParse->nErr++;
59291       return -1;
59292     }
59293   }else{
59294     assert( db->init.iDb==0 || db->init.busy );
59295     iDb = db->init.iDb;
59296     *pUnqual = pName1;
59297   }
59298   return iDb;
59299 }
59300
59301 /*
59302 ** This routine is used to check if the UTF-8 string zName is a legal
59303 ** unqualified name for a new schema object (table, index, view or
59304 ** trigger). All names are legal except those that begin with the string
59305 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
59306 ** is reserved for internal use.
59307 */
59308 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
59309   if( !pParse->db->init.busy && pParse->nested==0 
59310           && (pParse->db->flags & SQLITE_WriteSchema)==0
59311           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
59312     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
59313     return SQLITE_ERROR;
59314   }
59315   return SQLITE_OK;
59316 }
59317
59318 /*
59319 ** Begin constructing a new table representation in memory.  This is
59320 ** the first of several action routines that get called in response
59321 ** to a CREATE TABLE statement.  In particular, this routine is called
59322 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
59323 ** flag is true if the table should be stored in the auxiliary database
59324 ** file instead of in the main database file.  This is normally the case
59325 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
59326 ** CREATE and TABLE.
59327 **
59328 ** The new table record is initialized and put in pParse->pNewTable.
59329 ** As more of the CREATE TABLE statement is parsed, additional action
59330 ** routines will be called to add more information to this record.
59331 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
59332 ** is called to complete the construction of the new table record.
59333 */
59334 SQLITE_PRIVATE void sqlite3StartTable(
59335   Parse *pParse,   /* Parser context */
59336   Token *pName1,   /* First part of the name of the table or view */
59337   Token *pName2,   /* Second part of the name of the table or view */
59338   int isTemp,      /* True if this is a TEMP table */
59339   int isView,      /* True if this is a VIEW */
59340   int isVirtual,   /* True if this is a VIRTUAL table */
59341   int noErr        /* Do nothing if table already exists */
59342 ){
59343   Table *pTable;
59344   char *zName = 0; /* The name of the new table */
59345   sqlite3 *db = pParse->db;
59346   Vdbe *v;
59347   int iDb;         /* Database number to create the table in */
59348   Token *pName;    /* Unqualified name of the table to create */
59349
59350   /* The table or view name to create is passed to this routine via tokens
59351   ** pName1 and pName2. If the table name was fully qualified, for example:
59352   **
59353   ** CREATE TABLE xxx.yyy (...);
59354   ** 
59355   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
59356   ** the table name is not fully qualified, i.e.:
59357   **
59358   ** CREATE TABLE yyy(...);
59359   **
59360   ** Then pName1 is set to "yyy" and pName2 is "".
59361   **
59362   ** The call below sets the pName pointer to point at the token (pName1 or
59363   ** pName2) that stores the unqualified table name. The variable iDb is
59364   ** set to the index of the database that the table or view is to be
59365   ** created in.
59366   */
59367   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
59368   if( iDb<0 ) return;
59369   if( !OMIT_TEMPDB && isTemp && iDb>1 ){
59370     /* If creating a temp table, the name may not be qualified */
59371     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
59372     return;
59373   }
59374   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
59375
59376   pParse->sNameToken = *pName;
59377   zName = sqlite3NameFromToken(db, pName);
59378   if( zName==0 ) return;
59379   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
59380     goto begin_table_error;
59381   }
59382   if( db->init.iDb==1 ) isTemp = 1;
59383 #ifndef SQLITE_OMIT_AUTHORIZATION
59384   assert( (isTemp & 1)==isTemp );
59385   {
59386     int code;
59387     char *zDb = db->aDb[iDb].zName;
59388     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
59389       goto begin_table_error;
59390     }
59391     if( isView ){
59392       if( !OMIT_TEMPDB && isTemp ){
59393         code = SQLITE_CREATE_TEMP_VIEW;
59394       }else{
59395         code = SQLITE_CREATE_VIEW;
59396       }
59397     }else{
59398       if( !OMIT_TEMPDB && isTemp ){
59399         code = SQLITE_CREATE_TEMP_TABLE;
59400       }else{
59401         code = SQLITE_CREATE_TABLE;
59402       }
59403     }
59404     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
59405       goto begin_table_error;
59406     }
59407   }
59408 #endif
59409
59410   /* Make sure the new table name does not collide with an existing
59411   ** index or table name in the same database.  Issue an error message if
59412   ** it does. The exception is if the statement being parsed was passed
59413   ** to an sqlite3_declare_vtab() call. In that case only the column names
59414   ** and types will be used, so there is no need to test for namespace
59415   ** collisions.
59416   */
59417   if( !IN_DECLARE_VTAB ){
59418     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
59419       goto begin_table_error;
59420     }
59421     pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
59422     if( pTable ){
59423       if( !noErr ){
59424         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
59425       }
59426       goto begin_table_error;
59427     }
59428     if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
59429       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
59430       goto begin_table_error;
59431     }
59432   }
59433
59434   pTable = sqlite3DbMallocZero(db, sizeof(Table));
59435   if( pTable==0 ){
59436     db->mallocFailed = 1;
59437     pParse->rc = SQLITE_NOMEM;
59438     pParse->nErr++;
59439     goto begin_table_error;
59440   }
59441   pTable->zName = zName;
59442   pTable->iPKey = -1;
59443   pTable->pSchema = db->aDb[iDb].pSchema;
59444   pTable->nRef = 1;
59445   pTable->db = db;
59446   if( pParse->pNewTable ) sqlite3DeleteTable(pParse->pNewTable);
59447   pParse->pNewTable = pTable;
59448
59449   /* If this is the magic sqlite_sequence table used by autoincrement,
59450   ** then record a pointer to this table in the main database structure
59451   ** so that INSERT can find the table easily.
59452   */
59453 #ifndef SQLITE_OMIT_AUTOINCREMENT
59454   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
59455     pTable->pSchema->pSeqTab = pTable;
59456   }
59457 #endif
59458
59459   /* Begin generating the code that will insert the table record into
59460   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
59461   ** and allocate the record number for the table entry now.  Before any
59462   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
59463   ** indices to be created and the table record must come before the 
59464   ** indices.  Hence, the record number for the table must be allocated
59465   ** now.
59466   */
59467   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
59468     int j1;
59469     int fileFormat;
59470     int reg1, reg2, reg3;
59471     sqlite3BeginWriteOperation(pParse, 0, iDb);
59472
59473 #ifndef SQLITE_OMIT_VIRTUALTABLE
59474     if( isVirtual ){
59475       sqlite3VdbeAddOp0(v, OP_VBegin);
59476     }
59477 #endif
59478
59479     /* If the file format and encoding in the database have not been set, 
59480     ** set them now.
59481     */
59482     reg1 = pParse->regRowid = ++pParse->nMem;
59483     reg2 = pParse->regRoot = ++pParse->nMem;
59484     reg3 = ++pParse->nMem;
59485     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, 1);   /* file_format */
59486     sqlite3VdbeUsesBtree(v, iDb);
59487     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
59488     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
59489                   1 : SQLITE_MAX_FILE_FORMAT;
59490     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
59491     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, reg3);
59492     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
59493     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 4, reg3);
59494     sqlite3VdbeJumpHere(v, j1);
59495
59496     /* This just creates a place-holder record in the sqlite_master table.
59497     ** The record created does not contain anything yet.  It will be replaced
59498     ** by the real entry in code generated at sqlite3EndTable().
59499     **
59500     ** The rowid for the new entry is left on the top of the stack.
59501     ** The rowid value is needed by the code that sqlite3EndTable will
59502     ** generate.
59503     */
59504 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
59505     if( isView || isVirtual ){
59506       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
59507     }else
59508 #endif
59509     {
59510       sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
59511     }
59512     sqlite3OpenMasterTable(pParse, iDb);
59513     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
59514     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
59515     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
59516     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
59517     sqlite3VdbeAddOp0(v, OP_Close);
59518   }
59519
59520   /* Normal (non-error) return. */
59521   return;
59522
59523   /* If an error occurs, we jump here */
59524 begin_table_error:
59525   sqlite3DbFree(db, zName);
59526   return;
59527 }
59528
59529 /*
59530 ** This macro is used to compare two strings in a case-insensitive manner.
59531 ** It is slightly faster than calling sqlite3StrICmp() directly, but
59532 ** produces larger code.
59533 **
59534 ** WARNING: This macro is not compatible with the strcmp() family. It
59535 ** returns true if the two strings are equal, otherwise false.
59536 */
59537 #define STRICMP(x, y) (\
59538 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
59539 sqlite3UpperToLower[*(unsigned char *)(y)]     \
59540 && sqlite3StrICmp((x)+1,(y)+1)==0 )
59541
59542 /*
59543 ** Add a new column to the table currently being constructed.
59544 **
59545 ** The parser calls this routine once for each column declaration
59546 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
59547 ** first to get things going.  Then this routine is called for each
59548 ** column.
59549 */
59550 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
59551   Table *p;
59552   int i;
59553   char *z;
59554   Column *pCol;
59555   sqlite3 *db = pParse->db;
59556   if( (p = pParse->pNewTable)==0 ) return;
59557 #if SQLITE_MAX_COLUMN
59558   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
59559     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
59560     return;
59561   }
59562 #endif
59563   z = sqlite3NameFromToken(pParse->db, pName);
59564   if( z==0 ) return;
59565   for(i=0; i<p->nCol; i++){
59566     if( STRICMP(z, p->aCol[i].zName) ){
59567       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
59568       sqlite3DbFree(db, z);
59569       return;
59570     }
59571   }
59572   if( (p->nCol & 0x7)==0 ){
59573     Column *aNew;
59574     aNew = sqlite3DbRealloc(pParse->db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
59575     if( aNew==0 ){
59576       sqlite3DbFree(db, z);
59577       return;
59578     }
59579     p->aCol = aNew;
59580   }
59581   pCol = &p->aCol[p->nCol];
59582   memset(pCol, 0, sizeof(p->aCol[0]));
59583   pCol->zName = z;
59584  
59585   /* If there is no type specified, columns have the default affinity
59586   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
59587   ** be called next to set pCol->affinity correctly.
59588   */
59589   pCol->affinity = SQLITE_AFF_NONE;
59590   p->nCol++;
59591 }
59592
59593 /*
59594 ** This routine is called by the parser while in the middle of
59595 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
59596 ** been seen on a column.  This routine sets the notNull flag on
59597 ** the column currently under construction.
59598 */
59599 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
59600   Table *p;
59601   int i;
59602   if( (p = pParse->pNewTable)==0 ) return;
59603   i = p->nCol-1;
59604   if( i>=0 ) p->aCol[i].notNull = onError;
59605 }
59606
59607 /*
59608 ** Scan the column type name zType (length nType) and return the
59609 ** associated affinity type.
59610 **
59611 ** This routine does a case-independent search of zType for the 
59612 ** substrings in the following table. If one of the substrings is
59613 ** found, the corresponding affinity is returned. If zType contains
59614 ** more than one of the substrings, entries toward the top of 
59615 ** the table take priority. For example, if zType is 'BLOBINT', 
59616 ** SQLITE_AFF_INTEGER is returned.
59617 **
59618 ** Substring     | Affinity
59619 ** --------------------------------
59620 ** 'INT'         | SQLITE_AFF_INTEGER
59621 ** 'CHAR'        | SQLITE_AFF_TEXT
59622 ** 'CLOB'        | SQLITE_AFF_TEXT
59623 ** 'TEXT'        | SQLITE_AFF_TEXT
59624 ** 'BLOB'        | SQLITE_AFF_NONE
59625 ** 'REAL'        | SQLITE_AFF_REAL
59626 ** 'FLOA'        | SQLITE_AFF_REAL
59627 ** 'DOUB'        | SQLITE_AFF_REAL
59628 **
59629 ** If none of the substrings in the above table are found,
59630 ** SQLITE_AFF_NUMERIC is returned.
59631 */
59632 SQLITE_PRIVATE char sqlite3AffinityType(const Token *pType){
59633   u32 h = 0;
59634   char aff = SQLITE_AFF_NUMERIC;
59635   const unsigned char *zIn = pType->z;
59636   const unsigned char *zEnd = &pType->z[pType->n];
59637
59638   while( zIn!=zEnd ){
59639     h = (h<<8) + sqlite3UpperToLower[*zIn];
59640     zIn++;
59641     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
59642       aff = SQLITE_AFF_TEXT; 
59643     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
59644       aff = SQLITE_AFF_TEXT;
59645     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
59646       aff = SQLITE_AFF_TEXT;
59647     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
59648         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
59649       aff = SQLITE_AFF_NONE;
59650 #ifndef SQLITE_OMIT_FLOATING_POINT
59651     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
59652         && aff==SQLITE_AFF_NUMERIC ){
59653       aff = SQLITE_AFF_REAL;
59654     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
59655         && aff==SQLITE_AFF_NUMERIC ){
59656       aff = SQLITE_AFF_REAL;
59657     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
59658         && aff==SQLITE_AFF_NUMERIC ){
59659       aff = SQLITE_AFF_REAL;
59660 #endif
59661     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
59662       aff = SQLITE_AFF_INTEGER;
59663       break;
59664     }
59665   }
59666
59667   return aff;
59668 }
59669
59670 /*
59671 ** This routine is called by the parser while in the middle of
59672 ** parsing a CREATE TABLE statement.  The pFirst token is the first
59673 ** token in the sequence of tokens that describe the type of the
59674 ** column currently under construction.   pLast is the last token
59675 ** in the sequence.  Use this information to construct a string
59676 ** that contains the typename of the column and store that string
59677 ** in zType.
59678 */ 
59679 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
59680   Table *p;
59681   int i;
59682   Column *pCol;
59683   sqlite3 *db;
59684
59685   if( (p = pParse->pNewTable)==0 ) return;
59686   i = p->nCol-1;
59687   if( i<0 ) return;
59688   pCol = &p->aCol[i];
59689   db = pParse->db;
59690   sqlite3DbFree(db, pCol->zType);
59691   pCol->zType = sqlite3NameFromToken(db, pType);
59692   pCol->affinity = sqlite3AffinityType(pType);
59693 }
59694
59695 /*
59696 ** The expression is the default value for the most recently added column
59697 ** of the table currently under construction.
59698 **
59699 ** Default value expressions must be constant.  Raise an exception if this
59700 ** is not the case.
59701 **
59702 ** This routine is called by the parser while in the middle of
59703 ** parsing a CREATE TABLE statement.
59704 */
59705 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){
59706   Table *p;
59707   Column *pCol;
59708   sqlite3 *db = pParse->db;
59709   if( (p = pParse->pNewTable)!=0 ){
59710     pCol = &(p->aCol[p->nCol-1]);
59711     if( !sqlite3ExprIsConstantOrFunction(pExpr) ){
59712       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
59713           pCol->zName);
59714     }else{
59715       Expr *pCopy;
59716       sqlite3ExprDelete(db, pCol->pDflt);
59717       pCol->pDflt = pCopy = sqlite3ExprDup(db, pExpr);
59718       if( pCopy ){
59719         sqlite3TokenCopy(db, &pCopy->span, &pExpr->span);
59720       }
59721     }
59722   }
59723   sqlite3ExprDelete(db, pExpr);
59724 }
59725
59726 /*
59727 ** Designate the PRIMARY KEY for the table.  pList is a list of names 
59728 ** of columns that form the primary key.  If pList is NULL, then the
59729 ** most recently added column of the table is the primary key.
59730 **
59731 ** A table can have at most one primary key.  If the table already has
59732 ** a primary key (and this is the second primary key) then create an
59733 ** error.
59734 **
59735 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
59736 ** then we will try to use that column as the rowid.  Set the Table.iPKey
59737 ** field of the table under construction to be the index of the
59738 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
59739 ** no INTEGER PRIMARY KEY.
59740 **
59741 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
59742 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
59743 */
59744 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
59745   Parse *pParse,    /* Parsing context */
59746   ExprList *pList,  /* List of field names to be indexed */
59747   int onError,      /* What to do with a uniqueness conflict */
59748   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
59749   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
59750 ){
59751   Table *pTab = pParse->pNewTable;
59752   char *zType = 0;
59753   int iCol = -1, i;
59754   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
59755   if( pTab->tabFlags & TF_HasPrimaryKey ){
59756     sqlite3ErrorMsg(pParse, 
59757       "table \"%s\" has more than one primary key", pTab->zName);
59758     goto primary_key_exit;
59759   }
59760   pTab->tabFlags |= TF_HasPrimaryKey;
59761   if( pList==0 ){
59762     iCol = pTab->nCol - 1;
59763     pTab->aCol[iCol].isPrimKey = 1;
59764   }else{
59765     for(i=0; i<pList->nExpr; i++){
59766       for(iCol=0; iCol<pTab->nCol; iCol++){
59767         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
59768           break;
59769         }
59770       }
59771       if( iCol<pTab->nCol ){
59772         pTab->aCol[iCol].isPrimKey = 1;
59773       }
59774     }
59775     if( pList->nExpr>1 ) iCol = -1;
59776   }
59777   if( iCol>=0 && iCol<pTab->nCol ){
59778     zType = pTab->aCol[iCol].zType;
59779   }
59780   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
59781         && sortOrder==SQLITE_SO_ASC ){
59782     pTab->iPKey = iCol;
59783     pTab->keyConf = onError;
59784     assert( autoInc==0 || autoInc==1 );
59785     pTab->tabFlags |= autoInc*TF_Autoincrement;
59786   }else if( autoInc ){
59787 #ifndef SQLITE_OMIT_AUTOINCREMENT
59788     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
59789        "INTEGER PRIMARY KEY");
59790 #endif
59791   }else{
59792     sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
59793     pList = 0;
59794   }
59795
59796 primary_key_exit:
59797   sqlite3ExprListDelete(pParse->db, pList);
59798   return;
59799 }
59800
59801 /*
59802 ** Add a new CHECK constraint to the table currently under construction.
59803 */
59804 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
59805   Parse *pParse,    /* Parsing context */
59806   Expr *pCheckExpr  /* The check expression */
59807 ){
59808   sqlite3 *db = pParse->db;
59809 #ifndef SQLITE_OMIT_CHECK
59810   Table *pTab = pParse->pNewTable;
59811   if( pTab && !IN_DECLARE_VTAB ){
59812     /* The CHECK expression must be duplicated so that tokens refer
59813     ** to malloced space and not the (ephemeral) text of the CREATE TABLE
59814     ** statement */
59815     pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, 
59816                                   sqlite3ExprDup(db, pCheckExpr));
59817   }
59818 #endif
59819   sqlite3ExprDelete(db, pCheckExpr);
59820 }
59821
59822 /*
59823 ** Set the collation function of the most recently parsed table column
59824 ** to the CollSeq given.
59825 */
59826 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
59827   Table *p;
59828   int i;
59829   char *zColl;              /* Dequoted name of collation sequence */
59830   sqlite3 *db;
59831
59832   if( (p = pParse->pNewTable)==0 ) return;
59833   i = p->nCol-1;
59834   db = pParse->db;
59835   zColl = sqlite3NameFromToken(db, pToken);
59836   if( !zColl ) return;
59837
59838   if( sqlite3LocateCollSeq(pParse, zColl, -1) ){
59839     Index *pIdx;
59840     p->aCol[i].zColl = zColl;
59841   
59842     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
59843     ** then an index may have been created on this column before the
59844     ** collation type was added. Correct this if it is the case.
59845     */
59846     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
59847       assert( pIdx->nColumn==1 );
59848       if( pIdx->aiColumn[0]==i ){
59849         pIdx->azColl[0] = p->aCol[i].zColl;
59850       }
59851     }
59852   }else{
59853     sqlite3DbFree(db, zColl);
59854   }
59855 }
59856
59857 /*
59858 ** This function returns the collation sequence for database native text
59859 ** encoding identified by the string zName, length nName.
59860 **
59861 ** If the requested collation sequence is not available, or not available
59862 ** in the database native encoding, the collation factory is invoked to
59863 ** request it. If the collation factory does not supply such a sequence,
59864 ** and the sequence is available in another text encoding, then that is
59865 ** returned instead.
59866 **
59867 ** If no versions of the requested collations sequence are available, or
59868 ** another error occurs, NULL is returned and an error message written into
59869 ** pParse.
59870 **
59871 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
59872 ** invokes the collation factory if the named collation cannot be found
59873 ** and generates an error message.
59874 */
59875 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
59876   sqlite3 *db = pParse->db;
59877   u8 enc = ENC(db);
59878   u8 initbusy = db->init.busy;
59879   CollSeq *pColl;
59880
59881   pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
59882   if( !initbusy && (!pColl || !pColl->xCmp) ){
59883     pColl = sqlite3GetCollSeq(db, pColl, zName, nName);
59884     if( !pColl ){
59885       if( nName<0 ){
59886         nName = sqlite3Strlen(db, zName);
59887       }
59888       sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName);
59889       pColl = 0;
59890     }
59891   }
59892
59893   return pColl;
59894 }
59895
59896
59897 /*
59898 ** Generate code that will increment the schema cookie.
59899 **
59900 ** The schema cookie is used to determine when the schema for the
59901 ** database changes.  After each schema change, the cookie value
59902 ** changes.  When a process first reads the schema it records the
59903 ** cookie.  Thereafter, whenever it goes to access the database,
59904 ** it checks the cookie to make sure the schema has not changed
59905 ** since it was last read.
59906 **
59907 ** This plan is not completely bullet-proof.  It is possible for
59908 ** the schema to change multiple times and for the cookie to be
59909 ** set back to prior value.  But schema changes are infrequent
59910 ** and the probability of hitting the same cookie value is only
59911 ** 1 chance in 2^32.  So we're safe enough.
59912 */
59913 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
59914   int r1 = sqlite3GetTempReg(pParse);
59915   sqlite3 *db = pParse->db;
59916   Vdbe *v = pParse->pVdbe;
59917   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
59918   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 0, r1);
59919   sqlite3ReleaseTempReg(pParse, r1);
59920 }
59921
59922 /*
59923 ** Measure the number of characters needed to output the given
59924 ** identifier.  The number returned includes any quotes used
59925 ** but does not include the null terminator.
59926 **
59927 ** The estimate is conservative.  It might be larger that what is
59928 ** really needed.
59929 */
59930 static int identLength(const char *z){
59931   int n;
59932   for(n=0; *z; n++, z++){
59933     if( *z=='"' ){ n++; }
59934   }
59935   return n + 2;
59936 }
59937
59938 /*
59939 ** Write an identifier onto the end of the given string.  Add
59940 ** quote characters as needed.
59941 */
59942 static void identPut(char *z, int *pIdx, char *zSignedIdent){
59943   unsigned char *zIdent = (unsigned char*)zSignedIdent;
59944   int i, j, needQuote;
59945   i = *pIdx;
59946   for(j=0; zIdent[j]; j++){
59947     if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
59948   }
59949   needQuote =  zIdent[j]!=0 || isdigit(zIdent[0])
59950                   || sqlite3KeywordCode(zIdent, j)!=TK_ID;
59951   if( needQuote ) z[i++] = '"';
59952   for(j=0; zIdent[j]; j++){
59953     z[i++] = zIdent[j];
59954     if( zIdent[j]=='"' ) z[i++] = '"';
59955   }
59956   if( needQuote ) z[i++] = '"';
59957   z[i] = 0;
59958   *pIdx = i;
59959 }
59960
59961 /*
59962 ** Generate a CREATE TABLE statement appropriate for the given
59963 ** table.  Memory to hold the text of the statement is obtained
59964 ** from sqliteMalloc() and must be freed by the calling function.
59965 */
59966 static char *createTableStmt(sqlite3 *db, Table *p, int isTemp){
59967   int i, k, n;
59968   char *zStmt;
59969   char *zSep, *zSep2, *zEnd, *z;
59970   Column *pCol;
59971   n = 0;
59972   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
59973     n += identLength(pCol->zName);
59974     z = pCol->zType;
59975     if( z ){
59976       n += (strlen(z) + 1);
59977     }
59978   }
59979   n += identLength(p->zName);
59980   if( n<50 ){
59981     zSep = "";
59982     zSep2 = ",";
59983     zEnd = ")";
59984   }else{
59985     zSep = "\n  ";
59986     zSep2 = ",\n  ";
59987     zEnd = "\n)";
59988   }
59989   n += 35 + 6*p->nCol;
59990   zStmt = sqlite3Malloc( n );
59991   if( zStmt==0 ){
59992     db->mallocFailed = 1;
59993     return 0;
59994   }
59995   sqlite3_snprintf(n, zStmt,
59996                   !OMIT_TEMPDB&&isTemp ? "CREATE TEMP TABLE ":"CREATE TABLE ");
59997   k = strlen(zStmt);
59998   identPut(zStmt, &k, p->zName);
59999   zStmt[k++] = '(';
60000   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
60001     sqlite3_snprintf(n-k, &zStmt[k], zSep);
60002     k += strlen(&zStmt[k]);
60003     zSep = zSep2;
60004     identPut(zStmt, &k, pCol->zName);
60005     if( (z = pCol->zType)!=0 ){
60006       zStmt[k++] = ' ';
60007       assert( (int)(strlen(z)+k+1)<=n );
60008       sqlite3_snprintf(n-k, &zStmt[k], "%s", z);
60009       k += strlen(z);
60010     }
60011   }
60012   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
60013   return zStmt;
60014 }
60015
60016 /*
60017 ** This routine is called to report the final ")" that terminates
60018 ** a CREATE TABLE statement.
60019 **
60020 ** The table structure that other action routines have been building
60021 ** is added to the internal hash tables, assuming no errors have
60022 ** occurred.
60023 **
60024 ** An entry for the table is made in the master table on disk, unless
60025 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
60026 ** it means we are reading the sqlite_master table because we just
60027 ** connected to the database or because the sqlite_master table has
60028 ** recently changed, so the entry for this table already exists in
60029 ** the sqlite_master table.  We do not want to create it again.
60030 **
60031 ** If the pSelect argument is not NULL, it means that this routine
60032 ** was called to create a table generated from a 
60033 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
60034 ** the new table will match the result set of the SELECT.
60035 */
60036 SQLITE_PRIVATE void sqlite3EndTable(
60037   Parse *pParse,          /* Parse context */
60038   Token *pCons,           /* The ',' token after the last column defn. */
60039   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
60040   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
60041 ){
60042   Table *p;
60043   sqlite3 *db = pParse->db;
60044   int iDb;
60045
60046   if( (pEnd==0 && pSelect==0) || pParse->nErr || db->mallocFailed ) {
60047     return;
60048   }
60049   p = pParse->pNewTable;
60050   if( p==0 ) return;
60051
60052   assert( !db->init.busy || !pSelect );
60053
60054   iDb = sqlite3SchemaToIndex(db, p->pSchema);
60055
60056 #ifndef SQLITE_OMIT_CHECK
60057   /* Resolve names in all CHECK constraint expressions.
60058   */
60059   if( p->pCheck ){
60060     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
60061     NameContext sNC;                /* Name context for pParse->pNewTable */
60062
60063     memset(&sNC, 0, sizeof(sNC));
60064     memset(&sSrc, 0, sizeof(sSrc));
60065     sSrc.nSrc = 1;
60066     sSrc.a[0].zName = p->zName;
60067     sSrc.a[0].pTab = p;
60068     sSrc.a[0].iCursor = -1;
60069     sNC.pParse = pParse;
60070     sNC.pSrcList = &sSrc;
60071     sNC.isCheck = 1;
60072     if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
60073       return;
60074     }
60075   }
60076 #endif /* !defined(SQLITE_OMIT_CHECK) */
60077
60078   /* If the db->init.busy is 1 it means we are reading the SQL off the
60079   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
60080   ** So do not write to the disk again.  Extract the root page number
60081   ** for the table from the db->init.newTnum field.  (The page number
60082   ** should have been put there by the sqliteOpenCb routine.)
60083   */
60084   if( db->init.busy ){
60085     p->tnum = db->init.newTnum;
60086   }
60087
60088   /* If not initializing, then create a record for the new table
60089   ** in the SQLITE_MASTER table of the database.  The record number
60090   ** for the new table entry should already be on the stack.
60091   **
60092   ** If this is a TEMPORARY table, write the entry into the auxiliary
60093   ** file instead of into the main database file.
60094   */
60095   if( !db->init.busy ){
60096     int n;
60097     Vdbe *v;
60098     char *zType;    /* "view" or "table" */
60099     char *zType2;   /* "VIEW" or "TABLE" */
60100     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
60101
60102     v = sqlite3GetVdbe(pParse);
60103     if( v==0 ) return;
60104
60105     sqlite3VdbeAddOp1(v, OP_Close, 0);
60106
60107     /* Create the rootpage for the new table and push it onto the stack.
60108     ** A view has no rootpage, so just push a zero onto the stack for
60109     ** views.  Initialize zType at the same time.
60110     */
60111     if( p->pSelect==0 ){
60112       /* A regular table */
60113       zType = "table";
60114       zType2 = "TABLE";
60115 #ifndef SQLITE_OMIT_VIEW
60116     }else{
60117       /* A view */
60118       zType = "view";
60119       zType2 = "VIEW";
60120 #endif
60121     }
60122
60123     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
60124     ** statement to populate the new table. The root-page number for the
60125     ** new table is on the top of the vdbe stack.
60126     **
60127     ** Once the SELECT has been coded by sqlite3Select(), it is in a
60128     ** suitable state to query for the column names and types to be used
60129     ** by the new table.
60130     **
60131     ** A shared-cache write-lock is not required to write to the new table,
60132     ** as a schema-lock must have already been obtained to create it. Since
60133     ** a schema-lock excludes all other database users, the write-lock would
60134     ** be redundant.
60135     */
60136     if( pSelect ){
60137       SelectDest dest;
60138       Table *pSelTab;
60139
60140       assert(pParse->nTab==0);
60141       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
60142       sqlite3VdbeChangeP5(v, 1);
60143       pParse->nTab = 2;
60144       sqlite3SelectDestInit(&dest, SRT_Table, 1);
60145       sqlite3Select(pParse, pSelect, &dest);
60146       sqlite3VdbeAddOp1(v, OP_Close, 1);
60147       if( pParse->nErr==0 ){
60148         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
60149         if( pSelTab==0 ) return;
60150         assert( p->aCol==0 );
60151         p->nCol = pSelTab->nCol;
60152         p->aCol = pSelTab->aCol;
60153         pSelTab->nCol = 0;
60154         pSelTab->aCol = 0;
60155         sqlite3DeleteTable(pSelTab);
60156       }
60157     }
60158
60159     /* Compute the complete text of the CREATE statement */
60160     if( pSelect ){
60161       zStmt = createTableStmt(db, p, p->pSchema==db->aDb[1].pSchema);
60162     }else{
60163       n = pEnd->z - pParse->sNameToken.z + 1;
60164       zStmt = sqlite3MPrintf(db, 
60165           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
60166       );
60167     }
60168
60169     /* A slot for the record has already been allocated in the 
60170     ** SQLITE_MASTER table.  We just need to update that slot with all
60171     ** the information we've collected.  The rowid for the preallocated
60172     ** slot is the 2nd item on the stack.  The top of the stack is the
60173     ** root page for the new table (or a 0 if this is a view).
60174     */
60175     sqlite3NestedParse(pParse,
60176       "UPDATE %Q.%s "
60177          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
60178        "WHERE rowid=#%d",
60179       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
60180       zType,
60181       p->zName,
60182       p->zName,
60183       pParse->regRoot,
60184       zStmt,
60185       pParse->regRowid
60186     );
60187     sqlite3DbFree(db, zStmt);
60188     sqlite3ChangeCookie(pParse, iDb);
60189
60190 #ifndef SQLITE_OMIT_AUTOINCREMENT
60191     /* Check to see if we need to create an sqlite_sequence table for
60192     ** keeping track of autoincrement keys.
60193     */
60194     if( p->tabFlags & TF_Autoincrement ){
60195       Db *pDb = &db->aDb[iDb];
60196       if( pDb->pSchema->pSeqTab==0 ){
60197         sqlite3NestedParse(pParse,
60198           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
60199           pDb->zName
60200         );
60201       }
60202     }
60203 #endif
60204
60205     /* Reparse everything to update our internal data structures */
60206     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
60207         sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
60208   }
60209
60210
60211   /* Add the table to the in-memory representation of the database.
60212   */
60213   if( db->init.busy && pParse->nErr==0 ){
60214     Table *pOld;
60215     FKey *pFKey; 
60216     Schema *pSchema = p->pSchema;
60217     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, strlen(p->zName)+1,p);
60218     if( pOld ){
60219       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
60220       db->mallocFailed = 1;
60221       return;
60222     }
60223 #ifndef SQLITE_OMIT_FOREIGN_KEY
60224     for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
60225       void *data;
60226       int nTo = strlen(pFKey->zTo) + 1;
60227       pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo);
60228       data = sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey);
60229       if( data==(void *)pFKey ){
60230         db->mallocFailed = 1;
60231       }
60232     }
60233 #endif
60234     pParse->pNewTable = 0;
60235     db->nTable++;
60236     db->flags |= SQLITE_InternChanges;
60237
60238 #ifndef SQLITE_OMIT_ALTERTABLE
60239     if( !p->pSelect ){
60240       const char *zName = (const char *)pParse->sNameToken.z;
60241       int nName;
60242       assert( !pSelect && pCons && pEnd );
60243       if( pCons->z==0 ){
60244         pCons = pEnd;
60245       }
60246       nName = (const char *)pCons->z - zName;
60247       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
60248     }
60249 #endif
60250   }
60251 }
60252
60253 #ifndef SQLITE_OMIT_VIEW
60254 /*
60255 ** The parser calls this routine in order to create a new VIEW
60256 */
60257 SQLITE_PRIVATE void sqlite3CreateView(
60258   Parse *pParse,     /* The parsing context */
60259   Token *pBegin,     /* The CREATE token that begins the statement */
60260   Token *pName1,     /* The token that holds the name of the view */
60261   Token *pName2,     /* The token that holds the name of the view */
60262   Select *pSelect,   /* A SELECT statement that will become the new view */
60263   int isTemp,        /* TRUE for a TEMPORARY view */
60264   int noErr          /* Suppress error messages if VIEW already exists */
60265 ){
60266   Table *p;
60267   int n;
60268   const unsigned char *z;
60269   Token sEnd;
60270   DbFixer sFix;
60271   Token *pName;
60272   int iDb;
60273   sqlite3 *db = pParse->db;
60274
60275   if( pParse->nVar>0 ){
60276     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
60277     sqlite3SelectDelete(db, pSelect);
60278     return;
60279   }
60280   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
60281   p = pParse->pNewTable;
60282   if( p==0 || pParse->nErr ){
60283     sqlite3SelectDelete(db, pSelect);
60284     return;
60285   }
60286   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
60287   iDb = sqlite3SchemaToIndex(db, p->pSchema);
60288   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
60289     && sqlite3FixSelect(&sFix, pSelect)
60290   ){
60291     sqlite3SelectDelete(db, pSelect);
60292     return;
60293   }
60294
60295   /* Make a copy of the entire SELECT statement that defines the view.
60296   ** This will force all the Expr.token.z values to be dynamically
60297   ** allocated rather than point to the input string - which means that
60298   ** they will persist after the current sqlite3_exec() call returns.
60299   */
60300   p->pSelect = sqlite3SelectDup(db, pSelect);
60301   sqlite3SelectDelete(db, pSelect);
60302   if( db->mallocFailed ){
60303     return;
60304   }
60305   if( !db->init.busy ){
60306     sqlite3ViewGetColumnNames(pParse, p);
60307   }
60308
60309   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
60310   ** the end.
60311   */
60312   sEnd = pParse->sLastToken;
60313   if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
60314     sEnd.z += sEnd.n;
60315   }
60316   sEnd.n = 0;
60317   n = sEnd.z - pBegin->z;
60318   z = (const unsigned char*)pBegin->z;
60319   while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
60320   sEnd.z = &z[n-1];
60321   sEnd.n = 1;
60322
60323   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
60324   sqlite3EndTable(pParse, 0, &sEnd, 0);
60325   return;
60326 }
60327 #endif /* SQLITE_OMIT_VIEW */
60328
60329 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
60330 /*
60331 ** The Table structure pTable is really a VIEW.  Fill in the names of
60332 ** the columns of the view in the pTable structure.  Return the number
60333 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
60334 */
60335 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
60336   Table *pSelTab;   /* A fake table from which we get the result set */
60337   Select *pSel;     /* Copy of the SELECT that implements the view */
60338   int nErr = 0;     /* Number of errors encountered */
60339   int n;            /* Temporarily holds the number of cursors assigned */
60340   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
60341   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
60342
60343   assert( pTable );
60344
60345 #ifndef SQLITE_OMIT_VIRTUALTABLE
60346   if( sqlite3VtabCallConnect(pParse, pTable) ){
60347     return SQLITE_ERROR;
60348   }
60349   if( IsVirtual(pTable) ) return 0;
60350 #endif
60351
60352 #ifndef SQLITE_OMIT_VIEW
60353   /* A positive nCol means the columns names for this view are
60354   ** already known.
60355   */
60356   if( pTable->nCol>0 ) return 0;
60357
60358   /* A negative nCol is a special marker meaning that we are currently
60359   ** trying to compute the column names.  If we enter this routine with
60360   ** a negative nCol, it means two or more views form a loop, like this:
60361   **
60362   **     CREATE VIEW one AS SELECT * FROM two;
60363   **     CREATE VIEW two AS SELECT * FROM one;
60364   **
60365   ** Actually, this error is caught previously and so the following test
60366   ** should always fail.  But we will leave it in place just to be safe.
60367   */
60368   if( pTable->nCol<0 ){
60369     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
60370     return 1;
60371   }
60372   assert( pTable->nCol>=0 );
60373
60374   /* If we get this far, it means we need to compute the table names.
60375   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
60376   ** "*" elements in the results set of the view and will assign cursors
60377   ** to the elements of the FROM clause.  But we do not want these changes
60378   ** to be permanent.  So the computation is done on a copy of the SELECT
60379   ** statement that defines the view.
60380   */
60381   assert( pTable->pSelect );
60382   pSel = sqlite3SelectDup(db, pTable->pSelect);
60383   if( pSel ){
60384     n = pParse->nTab;
60385     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
60386     pTable->nCol = -1;
60387 #ifndef SQLITE_OMIT_AUTHORIZATION
60388     xAuth = db->xAuth;
60389     db->xAuth = 0;
60390     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
60391     db->xAuth = xAuth;
60392 #else
60393     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
60394 #endif
60395     pParse->nTab = n;
60396     if( pSelTab ){
60397       assert( pTable->aCol==0 );
60398       pTable->nCol = pSelTab->nCol;
60399       pTable->aCol = pSelTab->aCol;
60400       pSelTab->nCol = 0;
60401       pSelTab->aCol = 0;
60402       sqlite3DeleteTable(pSelTab);
60403       pTable->pSchema->flags |= DB_UnresetViews;
60404     }else{
60405       pTable->nCol = 0;
60406       nErr++;
60407     }
60408     sqlite3SelectDelete(db, pSel);
60409   } else {
60410     nErr++;
60411   }
60412 #endif /* SQLITE_OMIT_VIEW */
60413   return nErr;  
60414 }
60415 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
60416
60417 #ifndef SQLITE_OMIT_VIEW
60418 /*
60419 ** Clear the column names from every VIEW in database idx.
60420 */
60421 static void sqliteViewResetAll(sqlite3 *db, int idx){
60422   HashElem *i;
60423   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
60424   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
60425     Table *pTab = sqliteHashData(i);
60426     if( pTab->pSelect ){
60427       sqliteResetColumnNames(pTab);
60428     }
60429   }
60430   DbClearProperty(db, idx, DB_UnresetViews);
60431 }
60432 #else
60433 # define sqliteViewResetAll(A,B)
60434 #endif /* SQLITE_OMIT_VIEW */
60435
60436 /*
60437 ** This function is called by the VDBE to adjust the internal schema
60438 ** used by SQLite when the btree layer moves a table root page. The
60439 ** root-page of a table or index in database iDb has changed from iFrom
60440 ** to iTo.
60441 **
60442 ** Ticket #1728:  The symbol table might still contain information
60443 ** on tables and/or indices that are the process of being deleted.
60444 ** If you are unlucky, one of those deleted indices or tables might
60445 ** have the same rootpage number as the real table or index that is
60446 ** being moved.  So we cannot stop searching after the first match 
60447 ** because the first match might be for one of the deleted indices
60448 ** or tables and not the table/index that is actually being moved.
60449 ** We must continue looping until all tables and indices with
60450 ** rootpage==iFrom have been converted to have a rootpage of iTo
60451 ** in order to be certain that we got the right one.
60452 */
60453 #ifndef SQLITE_OMIT_AUTOVACUUM
60454 SQLITE_PRIVATE void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
60455   HashElem *pElem;
60456   Hash *pHash;
60457
60458   pHash = &pDb->pSchema->tblHash;
60459   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
60460     Table *pTab = sqliteHashData(pElem);
60461     if( pTab->tnum==iFrom ){
60462       pTab->tnum = iTo;
60463     }
60464   }
60465   pHash = &pDb->pSchema->idxHash;
60466   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
60467     Index *pIdx = sqliteHashData(pElem);
60468     if( pIdx->tnum==iFrom ){
60469       pIdx->tnum = iTo;
60470     }
60471   }
60472 }
60473 #endif
60474
60475 /*
60476 ** Write code to erase the table with root-page iTable from database iDb.
60477 ** Also write code to modify the sqlite_master table and internal schema
60478 ** if a root-page of another table is moved by the btree-layer whilst
60479 ** erasing iTable (this can happen with an auto-vacuum database).
60480 */ 
60481 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
60482   Vdbe *v = sqlite3GetVdbe(pParse);
60483   int r1 = sqlite3GetTempReg(pParse);
60484   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
60485 #ifndef SQLITE_OMIT_AUTOVACUUM
60486   /* OP_Destroy stores an in integer r1. If this integer
60487   ** is non-zero, then it is the root page number of a table moved to
60488   ** location iTable. The following code modifies the sqlite_master table to
60489   ** reflect this.
60490   **
60491   ** The "#%d" in the SQL is a special constant that means whatever value
60492   ** is on the top of the stack.  See sqlite3RegisterExpr().
60493   */
60494   sqlite3NestedParse(pParse, 
60495      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
60496      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
60497 #endif
60498   sqlite3ReleaseTempReg(pParse, r1);
60499 }
60500
60501 /*
60502 ** Write VDBE code to erase table pTab and all associated indices on disk.
60503 ** Code to update the sqlite_master tables and internal schema definitions
60504 ** in case a root-page belonging to another table is moved by the btree layer
60505 ** is also added (this can happen with an auto-vacuum database).
60506 */
60507 static void destroyTable(Parse *pParse, Table *pTab){
60508 #ifdef SQLITE_OMIT_AUTOVACUUM
60509   Index *pIdx;
60510   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
60511   destroyRootPage(pParse, pTab->tnum, iDb);
60512   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
60513     destroyRootPage(pParse, pIdx->tnum, iDb);
60514   }
60515 #else
60516   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
60517   ** is not defined), then it is important to call OP_Destroy on the
60518   ** table and index root-pages in order, starting with the numerically 
60519   ** largest root-page number. This guarantees that none of the root-pages
60520   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
60521   ** following were coded:
60522   **
60523   ** OP_Destroy 4 0
60524   ** ...
60525   ** OP_Destroy 5 0
60526   **
60527   ** and root page 5 happened to be the largest root-page number in the
60528   ** database, then root page 5 would be moved to page 4 by the 
60529   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
60530   ** a free-list page.
60531   */
60532   int iTab = pTab->tnum;
60533   int iDestroyed = 0;
60534
60535   while( 1 ){
60536     Index *pIdx;
60537     int iLargest = 0;
60538
60539     if( iDestroyed==0 || iTab<iDestroyed ){
60540       iLargest = iTab;
60541     }
60542     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
60543       int iIdx = pIdx->tnum;
60544       assert( pIdx->pSchema==pTab->pSchema );
60545       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
60546         iLargest = iIdx;
60547       }
60548     }
60549     if( iLargest==0 ){
60550       return;
60551     }else{
60552       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
60553       destroyRootPage(pParse, iLargest, iDb);
60554       iDestroyed = iLargest;
60555     }
60556   }
60557 #endif
60558 }
60559
60560 /*
60561 ** This routine is called to do the work of a DROP TABLE statement.
60562 ** pName is the name of the table to be dropped.
60563 */
60564 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
60565   Table *pTab;
60566   Vdbe *v;
60567   sqlite3 *db = pParse->db;
60568   int iDb;
60569
60570   if( pParse->nErr || db->mallocFailed ){
60571     goto exit_drop_table;
60572   }
60573   assert( pName->nSrc==1 );
60574   pTab = sqlite3LocateTable(pParse, isView, 
60575                             pName->a[0].zName, pName->a[0].zDatabase);
60576
60577   if( pTab==0 ){
60578     if( noErr ){
60579       sqlite3ErrorClear(pParse);
60580     }
60581     goto exit_drop_table;
60582   }
60583   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
60584   assert( iDb>=0 && iDb<db->nDb );
60585
60586   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
60587   ** it is initialized.
60588   */
60589   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
60590     goto exit_drop_table;
60591   }
60592 #ifndef SQLITE_OMIT_AUTHORIZATION
60593   {
60594     int code;
60595     const char *zTab = SCHEMA_TABLE(iDb);
60596     const char *zDb = db->aDb[iDb].zName;
60597     const char *zArg2 = 0;
60598     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
60599       goto exit_drop_table;
60600     }
60601     if( isView ){
60602       if( !OMIT_TEMPDB && iDb==1 ){
60603         code = SQLITE_DROP_TEMP_VIEW;
60604       }else{
60605         code = SQLITE_DROP_VIEW;
60606       }
60607 #ifndef SQLITE_OMIT_VIRTUALTABLE
60608     }else if( IsVirtual(pTab) ){
60609       code = SQLITE_DROP_VTABLE;
60610       zArg2 = pTab->pMod->zName;
60611 #endif
60612     }else{
60613       if( !OMIT_TEMPDB && iDb==1 ){
60614         code = SQLITE_DROP_TEMP_TABLE;
60615       }else{
60616         code = SQLITE_DROP_TABLE;
60617       }
60618     }
60619     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
60620       goto exit_drop_table;
60621     }
60622     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
60623       goto exit_drop_table;
60624     }
60625   }
60626 #endif
60627   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
60628     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
60629     goto exit_drop_table;
60630   }
60631
60632 #ifndef SQLITE_OMIT_VIEW
60633   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
60634   ** on a table.
60635   */
60636   if( isView && pTab->pSelect==0 ){
60637     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
60638     goto exit_drop_table;
60639   }
60640   if( !isView && pTab->pSelect ){
60641     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
60642     goto exit_drop_table;
60643   }
60644 #endif
60645
60646   /* Generate code to remove the table from the master table
60647   ** on disk.
60648   */
60649   v = sqlite3GetVdbe(pParse);
60650   if( v ){
60651     Trigger *pTrigger;
60652     Db *pDb = &db->aDb[iDb];
60653     sqlite3BeginWriteOperation(pParse, 1, iDb);
60654
60655 #ifndef SQLITE_OMIT_VIRTUALTABLE
60656     if( IsVirtual(pTab) ){
60657       Vdbe *v = sqlite3GetVdbe(pParse);
60658       if( v ){
60659         sqlite3VdbeAddOp0(v, OP_VBegin);
60660       }
60661     }
60662 #endif
60663
60664     /* Drop all triggers associated with the table being dropped. Code
60665     ** is generated to remove entries from sqlite_master and/or
60666     ** sqlite_temp_master if required.
60667     */
60668     pTrigger = pTab->pTrigger;
60669     while( pTrigger ){
60670       assert( pTrigger->pSchema==pTab->pSchema || 
60671           pTrigger->pSchema==db->aDb[1].pSchema );
60672       sqlite3DropTriggerPtr(pParse, pTrigger);
60673       pTrigger = pTrigger->pNext;
60674     }
60675
60676 #ifndef SQLITE_OMIT_AUTOINCREMENT
60677     /* Remove any entries of the sqlite_sequence table associated with
60678     ** the table being dropped. This is done before the table is dropped
60679     ** at the btree level, in case the sqlite_sequence table needs to
60680     ** move as a result of the drop (can happen in auto-vacuum mode).
60681     */
60682     if( pTab->tabFlags & TF_Autoincrement ){
60683       sqlite3NestedParse(pParse,
60684         "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
60685         pDb->zName, pTab->zName
60686       );
60687     }
60688 #endif
60689
60690     /* Drop all SQLITE_MASTER table and index entries that refer to the
60691     ** table. The program name loops through the master table and deletes
60692     ** every row that refers to a table of the same name as the one being
60693     ** dropped. Triggers are handled seperately because a trigger can be
60694     ** created in the temp database that refers to a table in another
60695     ** database.
60696     */
60697     sqlite3NestedParse(pParse, 
60698         "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
60699         pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
60700
60701     /* Drop any statistics from the sqlite_stat1 table, if it exists */
60702     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
60703       sqlite3NestedParse(pParse,
60704         "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
60705       );
60706     }
60707
60708     if( !isView && !IsVirtual(pTab) ){
60709       destroyTable(pParse, pTab);
60710     }
60711
60712     /* Remove the table entry from SQLite's internal schema and modify
60713     ** the schema cookie.
60714     */
60715     if( IsVirtual(pTab) ){
60716       sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
60717     }
60718     sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
60719     sqlite3ChangeCookie(pParse, iDb);
60720   }
60721   sqliteViewResetAll(db, iDb);
60722
60723 exit_drop_table:
60724   sqlite3SrcListDelete(db, pName);
60725 }
60726
60727 /*
60728 ** This routine is called to create a new foreign key on the table
60729 ** currently under construction.  pFromCol determines which columns
60730 ** in the current table point to the foreign key.  If pFromCol==0 then
60731 ** connect the key to the last column inserted.  pTo is the name of
60732 ** the table referred to.  pToCol is a list of tables in the other
60733 ** pTo table that the foreign key points to.  flags contains all
60734 ** information about the conflict resolution algorithms specified
60735 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
60736 **
60737 ** An FKey structure is created and added to the table currently
60738 ** under construction in the pParse->pNewTable field.  The new FKey
60739 ** is not linked into db->aFKey at this point - that does not happen
60740 ** until sqlite3EndTable().
60741 **
60742 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
60743 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
60744 */
60745 SQLITE_PRIVATE void sqlite3CreateForeignKey(
60746   Parse *pParse,       /* Parsing context */
60747   ExprList *pFromCol,  /* Columns in this table that point to other table */
60748   Token *pTo,          /* Name of the other table */
60749   ExprList *pToCol,    /* Columns in the other table */
60750   int flags            /* Conflict resolution algorithms. */
60751 ){
60752   sqlite3 *db = pParse->db;
60753 #ifndef SQLITE_OMIT_FOREIGN_KEY
60754   FKey *pFKey = 0;
60755   Table *p = pParse->pNewTable;
60756   int nByte;
60757   int i;
60758   int nCol;
60759   char *z;
60760
60761   assert( pTo!=0 );
60762   if( p==0 || pParse->nErr || IN_DECLARE_VTAB ) goto fk_end;
60763   if( pFromCol==0 ){
60764     int iCol = p->nCol-1;
60765     if( iCol<0 ) goto fk_end;
60766     if( pToCol && pToCol->nExpr!=1 ){
60767       sqlite3ErrorMsg(pParse, "foreign key on %s"
60768          " should reference only one column of table %T",
60769          p->aCol[iCol].zName, pTo);
60770       goto fk_end;
60771     }
60772     nCol = 1;
60773   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
60774     sqlite3ErrorMsg(pParse,
60775         "number of columns in foreign key does not match the number of "
60776         "columns in the referenced table");
60777     goto fk_end;
60778   }else{
60779     nCol = pFromCol->nExpr;
60780   }
60781   nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
60782   if( pToCol ){
60783     for(i=0; i<pToCol->nExpr; i++){
60784       nByte += strlen(pToCol->a[i].zName) + 1;
60785     }
60786   }
60787   pFKey = sqlite3DbMallocZero(db, nByte );
60788   if( pFKey==0 ){
60789     goto fk_end;
60790   }
60791   pFKey->pFrom = p;
60792   pFKey->pNextFrom = p->pFKey;
60793   z = (char*)&pFKey[1];
60794   pFKey->aCol = (struct sColMap*)z;
60795   z += sizeof(struct sColMap)*nCol;
60796   pFKey->zTo = z;
60797   memcpy(z, pTo->z, pTo->n);
60798   z[pTo->n] = 0;
60799   z += pTo->n+1;
60800   pFKey->pNextTo = 0;
60801   pFKey->nCol = nCol;
60802   if( pFromCol==0 ){
60803     pFKey->aCol[0].iFrom = p->nCol-1;
60804   }else{
60805     for(i=0; i<nCol; i++){
60806       int j;
60807       for(j=0; j<p->nCol; j++){
60808         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
60809           pFKey->aCol[i].iFrom = j;
60810           break;
60811         }
60812       }
60813       if( j>=p->nCol ){
60814         sqlite3ErrorMsg(pParse, 
60815           "unknown column \"%s\" in foreign key definition", 
60816           pFromCol->a[i].zName);
60817         goto fk_end;
60818       }
60819     }
60820   }
60821   if( pToCol ){
60822     for(i=0; i<nCol; i++){
60823       int n = strlen(pToCol->a[i].zName);
60824       pFKey->aCol[i].zCol = z;
60825       memcpy(z, pToCol->a[i].zName, n);
60826       z[n] = 0;
60827       z += n+1;
60828     }
60829   }
60830   pFKey->isDeferred = 0;
60831   pFKey->deleteConf = flags & 0xff;
60832   pFKey->updateConf = (flags >> 8 ) & 0xff;
60833   pFKey->insertConf = (flags >> 16 ) & 0xff;
60834
60835   /* Link the foreign key to the table as the last step.
60836   */
60837   p->pFKey = pFKey;
60838   pFKey = 0;
60839
60840 fk_end:
60841   sqlite3DbFree(db, pFKey);
60842 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
60843   sqlite3ExprListDelete(db, pFromCol);
60844   sqlite3ExprListDelete(db, pToCol);
60845 }
60846
60847 /*
60848 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
60849 ** clause is seen as part of a foreign key definition.  The isDeferred
60850 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
60851 ** The behavior of the most recently created foreign key is adjusted
60852 ** accordingly.
60853 */
60854 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
60855 #ifndef SQLITE_OMIT_FOREIGN_KEY
60856   Table *pTab;
60857   FKey *pFKey;
60858   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
60859   pFKey->isDeferred = isDeferred;
60860 #endif
60861 }
60862
60863 /*
60864 ** Generate code that will erase and refill index *pIdx.  This is
60865 ** used to initialize a newly created index or to recompute the
60866 ** content of an index in response to a REINDEX command.
60867 **
60868 ** if memRootPage is not negative, it means that the index is newly
60869 ** created.  The register specified by memRootPage contains the
60870 ** root page number of the index.  If memRootPage is negative, then
60871 ** the index already exists and must be cleared before being refilled and
60872 ** the root page number of the index is taken from pIndex->tnum.
60873 */
60874 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
60875   Table *pTab = pIndex->pTable;  /* The table that is indexed */
60876   int iTab = pParse->nTab;       /* Btree cursor used for pTab */
60877   int iIdx = pParse->nTab+1;     /* Btree cursor used for pIndex */
60878   int addr1;                     /* Address of top of loop */
60879   int tnum;                      /* Root page of index */
60880   Vdbe *v;                       /* Generate code into this virtual machine */
60881   KeyInfo *pKey;                 /* KeyInfo for index */
60882   int regIdxKey;                 /* Registers containing the index key */
60883   int regRecord;                 /* Register holding assemblied index record */
60884   sqlite3 *db = pParse->db;      /* The database connection */
60885   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
60886
60887 #ifndef SQLITE_OMIT_AUTHORIZATION
60888   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
60889       db->aDb[iDb].zName ) ){
60890     return;
60891   }
60892 #endif
60893
60894   /* Require a write-lock on the table to perform this operation */
60895   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
60896
60897   v = sqlite3GetVdbe(pParse);
60898   if( v==0 ) return;
60899   if( memRootPage>=0 ){
60900     tnum = memRootPage;
60901   }else{
60902     tnum = pIndex->tnum;
60903     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
60904   }
60905   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
60906   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
60907                     (char *)pKey, P4_KEYINFO_HANDOFF);
60908   if( memRootPage>=0 ){
60909     sqlite3VdbeChangeP5(v, 1);
60910   }
60911   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
60912   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
60913   regRecord = sqlite3GetTempReg(pParse);
60914   regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
60915   if( pIndex->onError!=OE_None ){
60916     int j1, j2;
60917     int regRowid;
60918
60919     regRowid = regIdxKey + pIndex->nColumn;
60920     j1 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdxKey, 0, pIndex->nColumn);
60921     j2 = sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx,
60922                            0, regRowid, SQLITE_INT_TO_PTR(regRecord), P4_INT32);
60923     sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort, 0,
60924                     "indexed columns are not unique", P4_STATIC);
60925     sqlite3VdbeJumpHere(v, j1);
60926     sqlite3VdbeJumpHere(v, j2);
60927   }
60928   sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
60929   sqlite3ReleaseTempReg(pParse, regRecord);
60930   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
60931   sqlite3VdbeJumpHere(v, addr1);
60932   sqlite3VdbeAddOp1(v, OP_Close, iTab);
60933   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
60934 }
60935
60936 /*
60937 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
60938 ** and pTblList is the name of the table that is to be indexed.  Both will 
60939 ** be NULL for a primary key or an index that is created to satisfy a
60940 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
60941 ** as the table to be indexed.  pParse->pNewTable is a table that is
60942 ** currently being constructed by a CREATE TABLE statement.
60943 **
60944 ** pList is a list of columns to be indexed.  pList will be NULL if this
60945 ** is a primary key or unique-constraint on the most recent column added
60946 ** to the table currently under construction.  
60947 */
60948 SQLITE_PRIVATE void sqlite3CreateIndex(
60949   Parse *pParse,     /* All information about this parse */
60950   Token *pName1,     /* First part of index name. May be NULL */
60951   Token *pName2,     /* Second part of index name. May be NULL */
60952   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
60953   ExprList *pList,   /* A list of columns to be indexed */
60954   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
60955   Token *pStart,     /* The CREATE token that begins this statement */
60956   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
60957   int sortOrder,     /* Sort order of primary key when pList==NULL */
60958   int ifNotExist     /* Omit error if index already exists */
60959 ){
60960   Table *pTab = 0;     /* Table to be indexed */
60961   Index *pIndex = 0;   /* The index to be created */
60962   char *zName = 0;     /* Name of the index */
60963   int nName;           /* Number of characters in zName */
60964   int i, j;
60965   Token nullId;        /* Fake token for an empty ID list */
60966   DbFixer sFix;        /* For assigning database names to pTable */
60967   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
60968   sqlite3 *db = pParse->db;
60969   Db *pDb;             /* The specific table containing the indexed database */
60970   int iDb;             /* Index of the database that is being written */
60971   Token *pName = 0;    /* Unqualified name of the index to create */
60972   struct ExprList_item *pListItem; /* For looping over pList */
60973   int nCol;
60974   int nExtra = 0;
60975   char *zExtra;
60976
60977   if( pParse->nErr || db->mallocFailed || IN_DECLARE_VTAB ){
60978     goto exit_create_index;
60979   }
60980
60981   /*
60982   ** Find the table that is to be indexed.  Return early if not found.
60983   */
60984   if( pTblName!=0 ){
60985
60986     /* Use the two-part index name to determine the database 
60987     ** to search for the table. 'Fix' the table name to this db
60988     ** before looking up the table.
60989     */
60990     assert( pName1 && pName2 );
60991     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
60992     if( iDb<0 ) goto exit_create_index;
60993
60994 #ifndef SQLITE_OMIT_TEMPDB
60995     /* If the index name was unqualified, check if the the table
60996     ** is a temp table. If so, set the database to 1. Do not do this
60997     ** if initialising a database schema.
60998     */
60999     if( !db->init.busy ){
61000       pTab = sqlite3SrcListLookup(pParse, pTblName);
61001       if( pName2 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
61002         iDb = 1;
61003       }
61004     }
61005 #endif
61006
61007     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
61008         sqlite3FixSrcList(&sFix, pTblName)
61009     ){
61010       /* Because the parser constructs pTblName from a single identifier,
61011       ** sqlite3FixSrcList can never fail. */
61012       assert(0);
61013     }
61014     pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName, 
61015         pTblName->a[0].zDatabase);
61016     if( !pTab || db->mallocFailed ) goto exit_create_index;
61017     assert( db->aDb[iDb].pSchema==pTab->pSchema );
61018   }else{
61019     assert( pName==0 );
61020     pTab = pParse->pNewTable;
61021     if( !pTab ) goto exit_create_index;
61022     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
61023   }
61024   pDb = &db->aDb[iDb];
61025
61026   if( pTab==0 || pParse->nErr ) goto exit_create_index;
61027   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
61028     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
61029     goto exit_create_index;
61030   }
61031 #ifndef SQLITE_OMIT_VIEW
61032   if( pTab->pSelect ){
61033     sqlite3ErrorMsg(pParse, "views may not be indexed");
61034     goto exit_create_index;
61035   }
61036 #endif
61037 #ifndef SQLITE_OMIT_VIRTUALTABLE
61038   if( IsVirtual(pTab) ){
61039     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
61040     goto exit_create_index;
61041   }
61042 #endif
61043
61044   /*
61045   ** Find the name of the index.  Make sure there is not already another
61046   ** index or table with the same name.  
61047   **
61048   ** Exception:  If we are reading the names of permanent indices from the
61049   ** sqlite_master table (because some other process changed the schema) and
61050   ** one of the index names collides with the name of a temporary table or
61051   ** index, then we will continue to process this index.
61052   **
61053   ** If pName==0 it means that we are
61054   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
61055   ** own name.
61056   */
61057   if( pName ){
61058     zName = sqlite3NameFromToken(db, pName);
61059     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
61060     if( zName==0 ) goto exit_create_index;
61061     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
61062       goto exit_create_index;
61063     }
61064     if( !db->init.busy ){
61065       if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
61066       if( sqlite3FindTable(db, zName, 0)!=0 ){
61067         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
61068         goto exit_create_index;
61069       }
61070     }
61071     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
61072       if( !ifNotExist ){
61073         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
61074       }
61075       goto exit_create_index;
61076     }
61077   }else{
61078     int n;
61079     Index *pLoop;
61080     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
61081     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
61082     if( zName==0 ){
61083       goto exit_create_index;
61084     }
61085   }
61086
61087   /* Check for authorization to create an index.
61088   */
61089 #ifndef SQLITE_OMIT_AUTHORIZATION
61090   {
61091     const char *zDb = pDb->zName;
61092     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
61093       goto exit_create_index;
61094     }
61095     i = SQLITE_CREATE_INDEX;
61096     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
61097     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
61098       goto exit_create_index;
61099     }
61100   }
61101 #endif
61102
61103   /* If pList==0, it means this routine was called to make a primary
61104   ** key out of the last column added to the table under construction.
61105   ** So create a fake list to simulate this.
61106   */
61107   if( pList==0 ){
61108     nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName;
61109     nullId.n = strlen((char*)nullId.z);
61110     pList = sqlite3ExprListAppend(pParse, 0, 0, &nullId);
61111     if( pList==0 ) goto exit_create_index;
61112     pList->a[0].sortOrder = sortOrder;
61113   }
61114
61115   /* Figure out how many bytes of space are required to store explicitly
61116   ** specified collation sequence names.
61117   */
61118   for(i=0; i<pList->nExpr; i++){
61119     Expr *pExpr;
61120     CollSeq *pColl;
61121     if( (pExpr = pList->a[i].pExpr)!=0 && (pColl = pExpr->pColl)!=0 ){
61122       nExtra += (1 + strlen(pColl->zName));
61123     }
61124   }
61125
61126   /* 
61127   ** Allocate the index structure. 
61128   */
61129   nName = strlen(zName);
61130   nCol = pList->nExpr;
61131   pIndex = sqlite3DbMallocZero(db, 
61132       sizeof(Index) +              /* Index structure  */
61133       sizeof(int)*nCol +           /* Index.aiColumn   */
61134       sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
61135       sizeof(char *)*nCol +        /* Index.azColl     */
61136       sizeof(u8)*nCol +            /* Index.aSortOrder */
61137       nName + 1 +                  /* Index.zName      */
61138       nExtra                       /* Collation sequence names */
61139   );
61140   if( db->mallocFailed ){
61141     goto exit_create_index;
61142   }
61143   pIndex->azColl = (char**)(&pIndex[1]);
61144   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
61145   pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
61146   pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
61147   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
61148   zExtra = (char *)(&pIndex->zName[nName+1]);
61149   memcpy(pIndex->zName, zName, nName+1);
61150   pIndex->pTable = pTab;
61151   pIndex->nColumn = pList->nExpr;
61152   pIndex->onError = onError;
61153   pIndex->autoIndex = pName==0;
61154   pIndex->pSchema = db->aDb[iDb].pSchema;
61155
61156   /* Check to see if we should honor DESC requests on index columns
61157   */
61158   if( pDb->pSchema->file_format>=4 ){
61159     sortOrderMask = -1;   /* Honor DESC */
61160   }else{
61161     sortOrderMask = 0;    /* Ignore DESC */
61162   }
61163
61164   /* Scan the names of the columns of the table to be indexed and
61165   ** load the column indices into the Index structure.  Report an error
61166   ** if any column is not found.
61167   */
61168   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
61169     const char *zColName = pListItem->zName;
61170     Column *pTabCol;
61171     int requestedSortOrder;
61172     char *zColl;                   /* Collation sequence name */
61173
61174     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
61175       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
61176     }
61177     if( j>=pTab->nCol ){
61178       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
61179         pTab->zName, zColName);
61180       goto exit_create_index;
61181     }
61182     /* TODO:  Add a test to make sure that the same column is not named
61183     ** more than once within the same index.  Only the first instance of
61184     ** the column will ever be used by the optimizer.  Note that using the
61185     ** same column more than once cannot be an error because that would 
61186     ** break backwards compatibility - it needs to be a warning.
61187     */
61188     pIndex->aiColumn[i] = j;
61189     if( pListItem->pExpr && pListItem->pExpr->pColl ){
61190       assert( pListItem->pExpr->pColl );
61191       zColl = zExtra;
61192       sqlite3_snprintf(nExtra, zExtra, "%s", pListItem->pExpr->pColl->zName);
61193       zExtra += (strlen(zColl) + 1);
61194     }else{
61195       zColl = pTab->aCol[j].zColl;
61196       if( !zColl ){
61197         zColl = db->pDfltColl->zName;
61198       }
61199     }
61200     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl, -1) ){
61201       goto exit_create_index;
61202     }
61203     pIndex->azColl[i] = zColl;
61204     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
61205     pIndex->aSortOrder[i] = requestedSortOrder;
61206   }
61207   sqlite3DefaultRowEst(pIndex);
61208
61209   if( pTab==pParse->pNewTable ){
61210     /* This routine has been called to create an automatic index as a
61211     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
61212     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
61213     ** i.e. one of:
61214     **
61215     ** CREATE TABLE t(x PRIMARY KEY, y);
61216     ** CREATE TABLE t(x, y, UNIQUE(x, y));
61217     **
61218     ** Either way, check to see if the table already has such an index. If
61219     ** so, don't bother creating this one. This only applies to
61220     ** automatically created indices. Users can do as they wish with
61221     ** explicit indices.
61222     */
61223     Index *pIdx;
61224     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
61225       int k;
61226       assert( pIdx->onError!=OE_None );
61227       assert( pIdx->autoIndex );
61228       assert( pIndex->onError!=OE_None );
61229
61230       if( pIdx->nColumn!=pIndex->nColumn ) continue;
61231       for(k=0; k<pIdx->nColumn; k++){
61232         const char *z1 = pIdx->azColl[k];
61233         const char *z2 = pIndex->azColl[k];
61234         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
61235         if( pIdx->aSortOrder[k]!=pIndex->aSortOrder[k] ) break;
61236         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
61237       }
61238       if( k==pIdx->nColumn ){
61239         if( pIdx->onError!=pIndex->onError ){
61240           /* This constraint creates the same index as a previous
61241           ** constraint specified somewhere in the CREATE TABLE statement.
61242           ** However the ON CONFLICT clauses are different. If both this 
61243           ** constraint and the previous equivalent constraint have explicit
61244           ** ON CONFLICT clauses this is an error. Otherwise, use the
61245           ** explicitly specified behaviour for the index.
61246           */
61247           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
61248             sqlite3ErrorMsg(pParse, 
61249                 "conflicting ON CONFLICT clauses specified", 0);
61250           }
61251           if( pIdx->onError==OE_Default ){
61252             pIdx->onError = pIndex->onError;
61253           }
61254         }
61255         goto exit_create_index;
61256       }
61257     }
61258   }
61259
61260   /* Link the new Index structure to its table and to the other
61261   ** in-memory database structures. 
61262   */
61263   if( db->init.busy ){
61264     Index *p;
61265     p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
61266                          pIndex->zName, strlen(pIndex->zName)+1, pIndex);
61267     if( p ){
61268       assert( p==pIndex );  /* Malloc must have failed */
61269       db->mallocFailed = 1;
61270       goto exit_create_index;
61271     }
61272     db->flags |= SQLITE_InternChanges;
61273     if( pTblName!=0 ){
61274       pIndex->tnum = db->init.newTnum;
61275     }
61276   }
61277
61278   /* If the db->init.busy is 0 then create the index on disk.  This
61279   ** involves writing the index into the master table and filling in the
61280   ** index with the current table contents.
61281   **
61282   ** The db->init.busy is 0 when the user first enters a CREATE INDEX 
61283   ** command.  db->init.busy is 1 when a database is opened and 
61284   ** CREATE INDEX statements are read out of the master table.  In
61285   ** the latter case the index already exists on disk, which is why
61286   ** we don't want to recreate it.
61287   **
61288   ** If pTblName==0 it means this index is generated as a primary key
61289   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
61290   ** has just been created, it contains no data and the index initialization
61291   ** step can be skipped.
61292   */
61293   else if( db->init.busy==0 ){
61294     Vdbe *v;
61295     char *zStmt;
61296     int iMem = ++pParse->nMem;
61297
61298     v = sqlite3GetVdbe(pParse);
61299     if( v==0 ) goto exit_create_index;
61300
61301
61302     /* Create the rootpage for the index
61303     */
61304     sqlite3BeginWriteOperation(pParse, 1, iDb);
61305     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
61306
61307     /* Gather the complete text of the CREATE INDEX statement into
61308     ** the zStmt variable
61309     */
61310     if( pStart && pEnd ){
61311       /* A named index with an explicit CREATE INDEX statement */
61312       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
61313         onError==OE_None ? "" : " UNIQUE",
61314         pEnd->z - pName->z + 1,
61315         pName->z);
61316     }else{
61317       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
61318       /* zStmt = sqlite3MPrintf(""); */
61319       zStmt = 0;
61320     }
61321
61322     /* Add an entry in sqlite_master for this index
61323     */
61324     sqlite3NestedParse(pParse, 
61325         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
61326         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
61327         pIndex->zName,
61328         pTab->zName,
61329         iMem,
61330         zStmt
61331     );
61332     sqlite3DbFree(db, zStmt);
61333
61334     /* Fill the index with data and reparse the schema. Code an OP_Expire
61335     ** to invalidate all pre-compiled statements.
61336     */
61337     if( pTblName ){
61338       sqlite3RefillIndex(pParse, pIndex, iMem);
61339       sqlite3ChangeCookie(pParse, iDb);
61340       sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
61341          sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
61342       sqlite3VdbeAddOp1(v, OP_Expire, 0);
61343     }
61344   }
61345
61346   /* When adding an index to the list of indices for a table, make
61347   ** sure all indices labeled OE_Replace come after all those labeled
61348   ** OE_Ignore.  This is necessary for the correct operation of UPDATE
61349   ** and INSERT.
61350   */
61351   if( db->init.busy || pTblName==0 ){
61352     if( onError!=OE_Replace || pTab->pIndex==0
61353          || pTab->pIndex->onError==OE_Replace){
61354       pIndex->pNext = pTab->pIndex;
61355       pTab->pIndex = pIndex;
61356     }else{
61357       Index *pOther = pTab->pIndex;
61358       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
61359         pOther = pOther->pNext;
61360       }
61361       pIndex->pNext = pOther->pNext;
61362       pOther->pNext = pIndex;
61363     }
61364     pIndex = 0;
61365   }
61366
61367   /* Clean up before exiting */
61368 exit_create_index:
61369   if( pIndex ){
61370     freeIndex(pIndex);
61371   }
61372   sqlite3ExprListDelete(db, pList);
61373   sqlite3SrcListDelete(db, pTblName);
61374   sqlite3DbFree(db, zName);
61375   return;
61376 }
61377
61378 /*
61379 ** Generate code to make sure the file format number is at least minFormat.
61380 ** The generated code will increase the file format number if necessary.
61381 */
61382 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
61383   Vdbe *v;
61384   v = sqlite3GetVdbe(pParse);
61385   if( v ){
61386     int r1 = sqlite3GetTempReg(pParse);
61387     int r2 = sqlite3GetTempReg(pParse);
61388     int j1;
61389     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, 1);
61390     sqlite3VdbeUsesBtree(v, iDb);
61391     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
61392     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
61393     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, r2);
61394     sqlite3VdbeJumpHere(v, j1);
61395     sqlite3ReleaseTempReg(pParse, r1);
61396     sqlite3ReleaseTempReg(pParse, r2);
61397   }
61398 }
61399
61400 /*
61401 ** Fill the Index.aiRowEst[] array with default information - information
61402 ** to be used when we have not run the ANALYZE command.
61403 **
61404 ** aiRowEst[0] is suppose to contain the number of elements in the index.
61405 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
61406 ** number of rows in the table that match any particular value of the
61407 ** first column of the index.  aiRowEst[2] is an estimate of the number
61408 ** of rows that match any particular combiniation of the first 2 columns
61409 ** of the index.  And so forth.  It must always be the case that
61410 *
61411 **           aiRowEst[N]<=aiRowEst[N-1]
61412 **           aiRowEst[N]>=1
61413 **
61414 ** Apart from that, we have little to go on besides intuition as to
61415 ** how aiRowEst[] should be initialized.  The numbers generated here
61416 ** are based on typical values found in actual indices.
61417 */
61418 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
61419   unsigned *a = pIdx->aiRowEst;
61420   int i;
61421   assert( a!=0 );
61422   a[0] = 1000000;
61423   for(i=pIdx->nColumn; i>=5; i--){
61424     a[i] = 5;
61425   }
61426   while( i>=1 ){
61427     a[i] = 11 - i;
61428     i--;
61429   }
61430   if( pIdx->onError!=OE_None ){
61431     a[pIdx->nColumn] = 1;
61432   }
61433 }
61434
61435 /*
61436 ** This routine will drop an existing named index.  This routine
61437 ** implements the DROP INDEX statement.
61438 */
61439 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
61440   Index *pIndex;
61441   Vdbe *v;
61442   sqlite3 *db = pParse->db;
61443   int iDb;
61444
61445   if( pParse->nErr || db->mallocFailed ){
61446     goto exit_drop_index;
61447   }
61448   assert( pName->nSrc==1 );
61449   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
61450     goto exit_drop_index;
61451   }
61452   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
61453   if( pIndex==0 ){
61454     if( !ifExists ){
61455       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
61456     }
61457     pParse->checkSchema = 1;
61458     goto exit_drop_index;
61459   }
61460   if( pIndex->autoIndex ){
61461     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
61462       "or PRIMARY KEY constraint cannot be dropped", 0);
61463     goto exit_drop_index;
61464   }
61465   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
61466 #ifndef SQLITE_OMIT_AUTHORIZATION
61467   {
61468     int code = SQLITE_DROP_INDEX;
61469     Table *pTab = pIndex->pTable;
61470     const char *zDb = db->aDb[iDb].zName;
61471     const char *zTab = SCHEMA_TABLE(iDb);
61472     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
61473       goto exit_drop_index;
61474     }
61475     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
61476     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
61477       goto exit_drop_index;
61478     }
61479   }
61480 #endif
61481
61482   /* Generate code to remove the index and from the master table */
61483   v = sqlite3GetVdbe(pParse);
61484   if( v ){
61485     sqlite3BeginWriteOperation(pParse, 1, iDb);
61486     sqlite3NestedParse(pParse,
61487        "DELETE FROM %Q.%s WHERE name=%Q",
61488        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
61489        pIndex->zName
61490     );
61491     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
61492       sqlite3NestedParse(pParse,
61493         "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
61494         db->aDb[iDb].zName, pIndex->zName
61495       );
61496     }
61497     sqlite3ChangeCookie(pParse, iDb);
61498     destroyRootPage(pParse, pIndex->tnum, iDb);
61499     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
61500   }
61501
61502 exit_drop_index:
61503   sqlite3SrcListDelete(db, pName);
61504 }
61505
61506 /*
61507 ** pArray is a pointer to an array of objects.  Each object in the
61508 ** array is szEntry bytes in size.  This routine allocates a new
61509 ** object on the end of the array.
61510 **
61511 ** *pnEntry is the number of entries already in use.  *pnAlloc is
61512 ** the previously allocated size of the array.  initSize is the
61513 ** suggested initial array size allocation.
61514 **
61515 ** The index of the new entry is returned in *pIdx.
61516 **
61517 ** This routine returns a pointer to the array of objects.  This
61518 ** might be the same as the pArray parameter or it might be a different
61519 ** pointer if the array was resized.
61520 */
61521 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
61522   sqlite3 *db,      /* Connection to notify of malloc failures */
61523   void *pArray,     /* Array of objects.  Might be reallocated */
61524   int szEntry,      /* Size of each object in the array */
61525   int initSize,     /* Suggested initial allocation, in elements */
61526   int *pnEntry,     /* Number of objects currently in use */
61527   int *pnAlloc,     /* Current size of the allocation, in elements */
61528   int *pIdx         /* Write the index of a new slot here */
61529 ){
61530   char *z;
61531   if( *pnEntry >= *pnAlloc ){
61532     void *pNew;
61533     int newSize;
61534     newSize = (*pnAlloc)*2 + initSize;
61535     pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
61536     if( pNew==0 ){
61537       *pIdx = -1;
61538       return pArray;
61539     }
61540     *pnAlloc = newSize;
61541     pArray = pNew;
61542   }
61543   z = (char*)pArray;
61544   memset(&z[*pnEntry * szEntry], 0, szEntry);
61545   *pIdx = *pnEntry;
61546   ++*pnEntry;
61547   return pArray;
61548 }
61549
61550 /*
61551 ** Append a new element to the given IdList.  Create a new IdList if
61552 ** need be.
61553 **
61554 ** A new IdList is returned, or NULL if malloc() fails.
61555 */
61556 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
61557   int i;
61558   if( pList==0 ){
61559     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
61560     if( pList==0 ) return 0;
61561     pList->nAlloc = 0;
61562   }
61563   pList->a = sqlite3ArrayAllocate(
61564       db,
61565       pList->a,
61566       sizeof(pList->a[0]),
61567       5,
61568       &pList->nId,
61569       &pList->nAlloc,
61570       &i
61571   );
61572   if( i<0 ){
61573     sqlite3IdListDelete(db, pList);
61574     return 0;
61575   }
61576   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
61577   return pList;
61578 }
61579
61580 /*
61581 ** Delete an IdList.
61582 */
61583 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
61584   int i;
61585   if( pList==0 ) return;
61586   for(i=0; i<pList->nId; i++){
61587     sqlite3DbFree(db, pList->a[i].zName);
61588   }
61589   sqlite3DbFree(db, pList->a);
61590   sqlite3DbFree(db, pList);
61591 }
61592
61593 /*
61594 ** Return the index in pList of the identifier named zId.  Return -1
61595 ** if not found.
61596 */
61597 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
61598   int i;
61599   if( pList==0 ) return -1;
61600   for(i=0; i<pList->nId; i++){
61601     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
61602   }
61603   return -1;
61604 }
61605
61606 /*
61607 ** Expand the space allocated for the given SrcList object by
61608 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
61609 ** New slots are zeroed.
61610 **
61611 ** For example, suppose a SrcList initially contains two entries: A,B.
61612 ** To append 3 new entries onto the end, do this:
61613 **
61614 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
61615 **
61616 ** After the call above it would contain:  A, B, nil, nil, nil.
61617 ** If the iStart argument had been 1 instead of 2, then the result
61618 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
61619 ** the iStart value would be 0.  The result then would
61620 ** be: nil, nil, nil, A, B.
61621 **
61622 ** If a memory allocation fails the SrcList is unchanged.  The
61623 ** db->mallocFailed flag will be set to true.
61624 */
61625 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
61626   sqlite3 *db,       /* Database connection to notify of OOM errors */
61627   SrcList *pSrc,     /* The SrcList to be enlarged */
61628   int nExtra,        /* Number of new slots to add to pSrc->a[] */
61629   int iStart         /* Index in pSrc->a[] of first new slot */
61630 ){
61631   int i;
61632
61633   /* Sanity checking on calling parameters */
61634   assert( iStart>=0 );
61635   assert( nExtra>=1 );
61636   if( pSrc==0 || iStart>pSrc->nSrc ){
61637     assert( db->mallocFailed );
61638     return pSrc;
61639   }
61640
61641   /* Allocate additional space if needed */
61642   if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
61643     SrcList *pNew;
61644     int nAlloc = pSrc->nSrc+nExtra;
61645     pNew = sqlite3DbRealloc(db, pSrc,
61646                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
61647     if( pNew==0 ){
61648       assert( db->mallocFailed );
61649       return pSrc;
61650     }
61651     pSrc = pNew;
61652     pSrc->nAlloc = nAlloc;
61653   }
61654
61655   /* Move existing slots that come after the newly inserted slots
61656   ** out of the way */
61657   for(i=pSrc->nSrc-1; i>=iStart; i--){
61658     pSrc->a[i+nExtra] = pSrc->a[i];
61659   }
61660   pSrc->nSrc += nExtra;
61661
61662   /* Zero the newly allocated slots */
61663   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
61664   for(i=iStart; i<iStart+nExtra; i++){
61665     pSrc->a[i].iCursor = -1;
61666   }
61667
61668   /* Return a pointer to the enlarged SrcList */
61669   return pSrc;
61670 }
61671
61672
61673 /*
61674 ** Append a new table name to the given SrcList.  Create a new SrcList if
61675 ** need be.  A new entry is created in the SrcList even if pToken is NULL.
61676 **
61677 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
61678 ** SrcList might be the same as the SrcList that was input or it might be
61679 ** a new one.  If an OOM error does occurs, then the prior value of pList
61680 ** that is input to this routine is automatically freed.
61681 **
61682 ** If pDatabase is not null, it means that the table has an optional
61683 ** database name prefix.  Like this:  "database.table".  The pDatabase
61684 ** points to the table name and the pTable points to the database name.
61685 ** The SrcList.a[].zName field is filled with the table name which might
61686 ** come from pTable (if pDatabase is NULL) or from pDatabase.  
61687 ** SrcList.a[].zDatabase is filled with the database name from pTable,
61688 ** or with NULL if no database is specified.
61689 **
61690 ** In other words, if call like this:
61691 **
61692 **         sqlite3SrcListAppend(D,A,B,0);
61693 **
61694 ** Then B is a table name and the database name is unspecified.  If called
61695 ** like this:
61696 **
61697 **         sqlite3SrcListAppend(D,A,B,C);
61698 **
61699 ** Then C is the table name and B is the database name.
61700 */
61701 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
61702   sqlite3 *db,        /* Connection to notify of malloc failures */
61703   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
61704   Token *pTable,      /* Table to append */
61705   Token *pDatabase    /* Database of the table */
61706 ){
61707   struct SrcList_item *pItem;
61708   if( pList==0 ){
61709     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
61710     if( pList==0 ) return 0;
61711     pList->nAlloc = 1;
61712   }
61713   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
61714   if( db->mallocFailed ){
61715     sqlite3SrcListDelete(db, pList);
61716     return 0;
61717   }
61718   pItem = &pList->a[pList->nSrc-1];
61719   if( pDatabase && pDatabase->z==0 ){
61720     pDatabase = 0;
61721   }
61722   if( pDatabase && pTable ){
61723     Token *pTemp = pDatabase;
61724     pDatabase = pTable;
61725     pTable = pTemp;
61726   }
61727   pItem->zName = sqlite3NameFromToken(db, pTable);
61728   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
61729   return pList;
61730 }
61731
61732 /*
61733 ** Assign VdbeCursor index numbers to all tables in a SrcList
61734 */
61735 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
61736   int i;
61737   struct SrcList_item *pItem;
61738   assert(pList || pParse->db->mallocFailed );
61739   if( pList ){
61740     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
61741       if( pItem->iCursor>=0 ) break;
61742       pItem->iCursor = pParse->nTab++;
61743       if( pItem->pSelect ){
61744         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
61745       }
61746     }
61747   }
61748 }
61749
61750 /*
61751 ** Delete an entire SrcList including all its substructure.
61752 */
61753 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
61754   int i;
61755   struct SrcList_item *pItem;
61756   if( pList==0 ) return;
61757   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
61758     sqlite3DbFree(db, pItem->zDatabase);
61759     sqlite3DbFree(db, pItem->zName);
61760     sqlite3DbFree(db, pItem->zAlias);
61761     sqlite3DbFree(db, pItem->zIndex);
61762     sqlite3DeleteTable(pItem->pTab);
61763     sqlite3SelectDelete(db, pItem->pSelect);
61764     sqlite3ExprDelete(db, pItem->pOn);
61765     sqlite3IdListDelete(db, pItem->pUsing);
61766   }
61767   sqlite3DbFree(db, pList);
61768 }
61769
61770 /*
61771 ** This routine is called by the parser to add a new term to the
61772 ** end of a growing FROM clause.  The "p" parameter is the part of
61773 ** the FROM clause that has already been constructed.  "p" is NULL
61774 ** if this is the first term of the FROM clause.  pTable and pDatabase
61775 ** are the name of the table and database named in the FROM clause term.
61776 ** pDatabase is NULL if the database name qualifier is missing - the
61777 ** usual case.  If the term has a alias, then pAlias points to the
61778 ** alias token.  If the term is a subquery, then pSubquery is the
61779 ** SELECT statement that the subquery encodes.  The pTable and
61780 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
61781 ** parameters are the content of the ON and USING clauses.
61782 **
61783 ** Return a new SrcList which encodes is the FROM with the new
61784 ** term added.
61785 */
61786 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
61787   Parse *pParse,          /* Parsing context */
61788   SrcList *p,             /* The left part of the FROM clause already seen */
61789   Token *pTable,          /* Name of the table to add to the FROM clause */
61790   Token *pDatabase,       /* Name of the database containing pTable */
61791   Token *pAlias,          /* The right-hand side of the AS subexpression */
61792   Select *pSubquery,      /* A subquery used in place of a table name */
61793   Expr *pOn,              /* The ON clause of a join */
61794   IdList *pUsing          /* The USING clause of a join */
61795 ){
61796   struct SrcList_item *pItem;
61797   sqlite3 *db = pParse->db;
61798   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
61799   if( p==0 || p->nSrc==0 ){
61800     sqlite3ExprDelete(db, pOn);
61801     sqlite3IdListDelete(db, pUsing);
61802     sqlite3SelectDelete(db, pSubquery);
61803     return p;
61804   }
61805   pItem = &p->a[p->nSrc-1];
61806   if( pAlias && pAlias->n ){
61807     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
61808   }
61809   pItem->pSelect = pSubquery;
61810   pItem->pOn = pOn;
61811   pItem->pUsing = pUsing;
61812   return p;
61813 }
61814
61815 /*
61816 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 
61817 ** element of the source-list passed as the second argument.
61818 */
61819 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
61820   if( pIndexedBy && p && p->nSrc>0 ){
61821     struct SrcList_item *pItem = &p->a[p->nSrc-1];
61822     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
61823     if( pIndexedBy->n==1 && !pIndexedBy->z ){
61824       /* A "NOT INDEXED" clause was supplied. See parse.y 
61825       ** construct "indexed_opt" for details. */
61826       pItem->notIndexed = 1;
61827     }else{
61828       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
61829     }
61830   }
61831 }
61832
61833 /*
61834 ** When building up a FROM clause in the parser, the join operator
61835 ** is initially attached to the left operand.  But the code generator
61836 ** expects the join operator to be on the right operand.  This routine
61837 ** Shifts all join operators from left to right for an entire FROM
61838 ** clause.
61839 **
61840 ** Example: Suppose the join is like this:
61841 **
61842 **           A natural cross join B
61843 **
61844 ** The operator is "natural cross join".  The A and B operands are stored
61845 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
61846 ** operator with A.  This routine shifts that operator over to B.
61847 */
61848 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
61849   if( p && p->a ){
61850     int i;
61851     for(i=p->nSrc-1; i>0; i--){
61852       p->a[i].jointype = p->a[i-1].jointype;
61853     }
61854     p->a[0].jointype = 0;
61855   }
61856 }
61857
61858 /*
61859 ** Begin a transaction
61860 */
61861 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
61862   sqlite3 *db;
61863   Vdbe *v;
61864   int i;
61865
61866   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
61867   if( pParse->nErr || db->mallocFailed ) return;
61868   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
61869
61870   v = sqlite3GetVdbe(pParse);
61871   if( !v ) return;
61872   if( type!=TK_DEFERRED ){
61873     for(i=0; i<db->nDb; i++){
61874       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
61875       sqlite3VdbeUsesBtree(v, i);
61876     }
61877   }
61878   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
61879 }
61880
61881 /*
61882 ** Commit a transaction
61883 */
61884 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
61885   sqlite3 *db;
61886   Vdbe *v;
61887
61888   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
61889   if( pParse->nErr || db->mallocFailed ) return;
61890   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
61891
61892   v = sqlite3GetVdbe(pParse);
61893   if( v ){
61894     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
61895   }
61896 }
61897
61898 /*
61899 ** Rollback a transaction
61900 */
61901 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
61902   sqlite3 *db;
61903   Vdbe *v;
61904
61905   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
61906   if( pParse->nErr || db->mallocFailed ) return;
61907   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
61908
61909   v = sqlite3GetVdbe(pParse);
61910   if( v ){
61911     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
61912   }
61913 }
61914
61915 /*
61916 ** Make sure the TEMP database is open and available for use.  Return
61917 ** the number of errors.  Leave any error messages in the pParse structure.
61918 */
61919 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
61920   sqlite3 *db = pParse->db;
61921   if( db->aDb[1].pBt==0 && !pParse->explain ){
61922     int rc;
61923     static const int flags = 
61924           SQLITE_OPEN_READWRITE |
61925           SQLITE_OPEN_CREATE |
61926           SQLITE_OPEN_EXCLUSIVE |
61927           SQLITE_OPEN_DELETEONCLOSE |
61928           SQLITE_OPEN_TEMP_DB;
61929
61930     rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags,
61931                                  &db->aDb[1].pBt);
61932     if( rc!=SQLITE_OK ){
61933       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
61934         "file for storing temporary tables");
61935       pParse->rc = rc;
61936       return 1;
61937     }
61938     assert( (db->flags & SQLITE_InTrans)==0 || db->autoCommit );
61939     assert( db->aDb[1].pSchema );
61940     sqlite3PagerJournalMode(sqlite3BtreePager(db->aDb[1].pBt),
61941                             db->dfltJournalMode);
61942   }
61943   return 0;
61944 }
61945
61946 /*
61947 ** Generate VDBE code that will verify the schema cookie and start
61948 ** a read-transaction for all named database files.
61949 **
61950 ** It is important that all schema cookies be verified and all
61951 ** read transactions be started before anything else happens in
61952 ** the VDBE program.  But this routine can be called after much other
61953 ** code has been generated.  So here is what we do:
61954 **
61955 ** The first time this routine is called, we code an OP_Goto that
61956 ** will jump to a subroutine at the end of the program.  Then we
61957 ** record every database that needs its schema verified in the
61958 ** pParse->cookieMask field.  Later, after all other code has been
61959 ** generated, the subroutine that does the cookie verifications and
61960 ** starts the transactions will be coded and the OP_Goto P2 value
61961 ** will be made to point to that subroutine.  The generation of the
61962 ** cookie verification subroutine code happens in sqlite3FinishCoding().
61963 **
61964 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
61965 ** schema on any databases.  This can be used to position the OP_Goto
61966 ** early in the code, before we know if any database tables will be used.
61967 */
61968 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
61969   sqlite3 *db;
61970   Vdbe *v;
61971   int mask;
61972
61973   v = sqlite3GetVdbe(pParse);
61974   if( v==0 ) return;  /* This only happens if there was a prior error */
61975   db = pParse->db;
61976   if( pParse->cookieGoto==0 ){
61977     pParse->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
61978   }
61979   if( iDb>=0 ){
61980     assert( iDb<db->nDb );
61981     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
61982     assert( iDb<SQLITE_MAX_ATTACHED+2 );
61983     mask = 1<<iDb;
61984     if( (pParse->cookieMask & mask)==0 ){
61985       pParse->cookieMask |= mask;
61986       pParse->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
61987       if( !OMIT_TEMPDB && iDb==1 ){
61988         sqlite3OpenTempDatabase(pParse);
61989       }
61990     }
61991   }
61992 }
61993
61994 /*
61995 ** Generate VDBE code that prepares for doing an operation that
61996 ** might change the database.
61997 **
61998 ** This routine starts a new transaction if we are not already within
61999 ** a transaction.  If we are already within a transaction, then a checkpoint
62000 ** is set if the setStatement parameter is true.  A checkpoint should
62001 ** be set for operations that might fail (due to a constraint) part of
62002 ** the way through and which will need to undo some writes without having to
62003 ** rollback the whole transaction.  For operations where all constraints
62004 ** can be checked before any changes are made to the database, it is never
62005 ** necessary to undo a write and the checkpoint should not be set.
62006 **
62007 ** Only database iDb and the temp database are made writable by this call.
62008 ** If iDb==0, then the main and temp databases are made writable.   If
62009 ** iDb==1 then only the temp database is made writable.  If iDb>1 then the
62010 ** specified auxiliary database and the temp database are made writable.
62011 */
62012 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
62013   Vdbe *v = sqlite3GetVdbe(pParse);
62014   if( v==0 ) return;
62015   sqlite3CodeVerifySchema(pParse, iDb);
62016   pParse->writeMask |= 1<<iDb;
62017   if( setStatement && pParse->nested==0 ){
62018     sqlite3VdbeAddOp1(v, OP_Statement, iDb);
62019   }
62020   if( (OMIT_TEMPDB || iDb!=1) && pParse->db->aDb[1].pBt!=0 ){
62021     sqlite3BeginWriteOperation(pParse, setStatement, 1);
62022   }
62023 }
62024
62025 /*
62026 ** Check to see if pIndex uses the collating sequence pColl.  Return
62027 ** true if it does and false if it does not.
62028 */
62029 #ifndef SQLITE_OMIT_REINDEX
62030 static int collationMatch(const char *zColl, Index *pIndex){
62031   int i;
62032   for(i=0; i<pIndex->nColumn; i++){
62033     const char *z = pIndex->azColl[i];
62034     if( z==zColl || (z && zColl && 0==sqlite3StrICmp(z, zColl)) ){
62035       return 1;
62036     }
62037   }
62038   return 0;
62039 }
62040 #endif
62041
62042 /*
62043 ** Recompute all indices of pTab that use the collating sequence pColl.
62044 ** If pColl==0 then recompute all indices of pTab.
62045 */
62046 #ifndef SQLITE_OMIT_REINDEX
62047 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
62048   Index *pIndex;              /* An index associated with pTab */
62049
62050   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
62051     if( zColl==0 || collationMatch(zColl, pIndex) ){
62052       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
62053       sqlite3BeginWriteOperation(pParse, 0, iDb);
62054       sqlite3RefillIndex(pParse, pIndex, -1);
62055     }
62056   }
62057 }
62058 #endif
62059
62060 /*
62061 ** Recompute all indices of all tables in all databases where the
62062 ** indices use the collating sequence pColl.  If pColl==0 then recompute
62063 ** all indices everywhere.
62064 */
62065 #ifndef SQLITE_OMIT_REINDEX
62066 static void reindexDatabases(Parse *pParse, char const *zColl){
62067   Db *pDb;                    /* A single database */
62068   int iDb;                    /* The database index number */
62069   sqlite3 *db = pParse->db;   /* The database connection */
62070   HashElem *k;                /* For looping over tables in pDb */
62071   Table *pTab;                /* A table in the database */
62072
62073   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
62074     assert( pDb!=0 );
62075     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
62076       pTab = (Table*)sqliteHashData(k);
62077       reindexTable(pParse, pTab, zColl);
62078     }
62079   }
62080 }
62081 #endif
62082
62083 /*
62084 ** Generate code for the REINDEX command.
62085 **
62086 **        REINDEX                            -- 1
62087 **        REINDEX  <collation>               -- 2
62088 **        REINDEX  ?<database>.?<tablename>  -- 3
62089 **        REINDEX  ?<database>.?<indexname>  -- 4
62090 **
62091 ** Form 1 causes all indices in all attached databases to be rebuilt.
62092 ** Form 2 rebuilds all indices in all databases that use the named
62093 ** collating function.  Forms 3 and 4 rebuild the named index or all
62094 ** indices associated with the named table.
62095 */
62096 #ifndef SQLITE_OMIT_REINDEX
62097 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
62098   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
62099   char *z;                    /* Name of a table or index */
62100   const char *zDb;            /* Name of the database */
62101   Table *pTab;                /* A table in the database */
62102   Index *pIndex;              /* An index associated with pTab */
62103   int iDb;                    /* The database index number */
62104   sqlite3 *db = pParse->db;   /* The database connection */
62105   Token *pObjName;            /* Name of the table or index to be reindexed */
62106
62107   /* Read the database schema. If an error occurs, leave an error message
62108   ** and code in pParse and return NULL. */
62109   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
62110     return;
62111   }
62112
62113   if( pName1==0 || pName1->z==0 ){
62114     reindexDatabases(pParse, 0);
62115     return;
62116   }else if( pName2==0 || pName2->z==0 ){
62117     char *zColl;
62118     assert( pName1->z );
62119     zColl = sqlite3NameFromToken(pParse->db, pName1);
62120     if( !zColl ) return;
62121     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, -1, 0);
62122     if( pColl ){
62123       if( zColl ){
62124         reindexDatabases(pParse, zColl);
62125         sqlite3DbFree(db, zColl);
62126       }
62127       return;
62128     }
62129     sqlite3DbFree(db, zColl);
62130   }
62131   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
62132   if( iDb<0 ) return;
62133   z = sqlite3NameFromToken(db, pObjName);
62134   if( z==0 ) return;
62135   zDb = db->aDb[iDb].zName;
62136   pTab = sqlite3FindTable(db, z, zDb);
62137   if( pTab ){
62138     reindexTable(pParse, pTab, 0);
62139     sqlite3DbFree(db, z);
62140     return;
62141   }
62142   pIndex = sqlite3FindIndex(db, z, zDb);
62143   sqlite3DbFree(db, z);
62144   if( pIndex ){
62145     sqlite3BeginWriteOperation(pParse, 0, iDb);
62146     sqlite3RefillIndex(pParse, pIndex, -1);
62147     return;
62148   }
62149   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
62150 }
62151 #endif
62152
62153 /*
62154 ** Return a dynamicly allocated KeyInfo structure that can be used
62155 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
62156 **
62157 ** If successful, a pointer to the new structure is returned. In this case
62158 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned 
62159 ** pointer. If an error occurs (out of memory or missing collation 
62160 ** sequence), NULL is returned and the state of pParse updated to reflect
62161 ** the error.
62162 */
62163 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
62164   int i;
62165   int nCol = pIdx->nColumn;
62166   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
62167   sqlite3 *db = pParse->db;
62168   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
62169
62170   if( pKey ){
62171     pKey->db = pParse->db;
62172     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
62173     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
62174     for(i=0; i<nCol; i++){
62175       char *zColl = pIdx->azColl[i];
62176       assert( zColl );
62177       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl, -1);
62178       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
62179     }
62180     pKey->nField = nCol;
62181   }
62182
62183   if( pParse->nErr ){
62184     sqlite3DbFree(db, pKey);
62185     pKey = 0;
62186   }
62187   return pKey;
62188 }
62189
62190 /************** End of build.c ***********************************************/
62191 /************** Begin file callback.c ****************************************/
62192 /*
62193 ** 2005 May 23 
62194 **
62195 ** The author disclaims copyright to this source code.  In place of
62196 ** a legal notice, here is a blessing:
62197 **
62198 **    May you do good and not evil.
62199 **    May you find forgiveness for yourself and forgive others.
62200 **    May you share freely, never taking more than you give.
62201 **
62202 *************************************************************************
62203 **
62204 ** This file contains functions used to access the internal hash tables
62205 ** of user defined functions and collation sequences.
62206 **
62207 ** $Id: callback.c,v 1.32 2008/10/10 17:41:29 drh Exp $
62208 */
62209
62210
62211 /*
62212 ** Invoke the 'collation needed' callback to request a collation sequence
62213 ** in the database text encoding of name zName, length nName.
62214 ** If the collation sequence
62215 */
62216 static void callCollNeeded(sqlite3 *db, const char *zName, int nName){
62217   assert( !db->xCollNeeded || !db->xCollNeeded16 );
62218   if( nName<0 ) nName = sqlite3Strlen(db, zName);
62219   if( db->xCollNeeded ){
62220     char *zExternal = sqlite3DbStrNDup(db, zName, nName);
62221     if( !zExternal ) return;
62222     db->xCollNeeded(db->pCollNeededArg, db, (int)ENC(db), zExternal);
62223     sqlite3DbFree(db, zExternal);
62224   }
62225 #ifndef SQLITE_OMIT_UTF16
62226   if( db->xCollNeeded16 ){
62227     char const *zExternal;
62228     sqlite3_value *pTmp = sqlite3ValueNew(db);
62229     sqlite3ValueSetStr(pTmp, nName, zName, SQLITE_UTF8, SQLITE_STATIC);
62230     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
62231     if( zExternal ){
62232       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
62233     }
62234     sqlite3ValueFree(pTmp);
62235   }
62236 #endif
62237 }
62238
62239 /*
62240 ** This routine is called if the collation factory fails to deliver a
62241 ** collation function in the best encoding but there may be other versions
62242 ** of this collation function (for other text encodings) available. Use one
62243 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
62244 ** possible.
62245 */
62246 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
62247   CollSeq *pColl2;
62248   char *z = pColl->zName;
62249   int n = strlen(z);
62250   int i;
62251   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
62252   for(i=0; i<3; i++){
62253     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, n, 0);
62254     if( pColl2->xCmp!=0 ){
62255       memcpy(pColl, pColl2, sizeof(CollSeq));
62256       pColl->xDel = 0;         /* Do not copy the destructor */
62257       return SQLITE_OK;
62258     }
62259   }
62260   return SQLITE_ERROR;
62261 }
62262
62263 /*
62264 ** This function is responsible for invoking the collation factory callback
62265 ** or substituting a collation sequence of a different encoding when the
62266 ** requested collation sequence is not available in the database native
62267 ** encoding.
62268 ** 
62269 ** If it is not NULL, then pColl must point to the database native encoding 
62270 ** collation sequence with name zName, length nName.
62271 **
62272 ** The return value is either the collation sequence to be used in database
62273 ** db for collation type name zName, length nName, or NULL, if no collation
62274 ** sequence can be found.
62275 */
62276 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
62277   sqlite3* db, 
62278   CollSeq *pColl, 
62279   const char *zName, 
62280   int nName
62281 ){
62282   CollSeq *p;
62283
62284   p = pColl;
62285   if( !p ){
62286     p = sqlite3FindCollSeq(db, ENC(db), zName, nName, 0);
62287   }
62288   if( !p || !p->xCmp ){
62289     /* No collation sequence of this type for this encoding is registered.
62290     ** Call the collation factory to see if it can supply us with one.
62291     */
62292     callCollNeeded(db, zName, nName);
62293     p = sqlite3FindCollSeq(db, ENC(db), zName, nName, 0);
62294   }
62295   if( p && !p->xCmp && synthCollSeq(db, p) ){
62296     p = 0;
62297   }
62298   assert( !p || p->xCmp );
62299   return p;
62300 }
62301
62302 /*
62303 ** This routine is called on a collation sequence before it is used to
62304 ** check that it is defined. An undefined collation sequence exists when
62305 ** a database is loaded that contains references to collation sequences
62306 ** that have not been defined by sqlite3_create_collation() etc.
62307 **
62308 ** If required, this routine calls the 'collation needed' callback to
62309 ** request a definition of the collating sequence. If this doesn't work, 
62310 ** an equivalent collating sequence that uses a text encoding different
62311 ** from the main database is substituted, if one is available.
62312 */
62313 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
62314   if( pColl ){
62315     const char *zName = pColl->zName;
62316     CollSeq *p = sqlite3GetCollSeq(pParse->db, pColl, zName, -1);
62317     if( !p ){
62318       if( pParse->nErr==0 ){
62319         sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
62320       }
62321       pParse->nErr++;
62322       return SQLITE_ERROR;
62323     }
62324     assert( p==pColl );
62325   }
62326   return SQLITE_OK;
62327 }
62328
62329
62330
62331 /*
62332 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
62333 ** specified by zName and nName is not found and parameter 'create' is
62334 ** true, then create a new entry. Otherwise return NULL.
62335 **
62336 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
62337 ** array of three CollSeq structures. The first is the collation sequence
62338 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
62339 **
62340 ** Stored immediately after the three collation sequences is a copy of
62341 ** the collation sequence name. A pointer to this string is stored in
62342 ** each collation sequence structure.
62343 */
62344 static CollSeq *findCollSeqEntry(
62345   sqlite3 *db,
62346   const char *zName,
62347   int nName,
62348   int create
62349 ){
62350   CollSeq *pColl;
62351   if( nName<0 ) nName = sqlite3Strlen(db, zName);
62352   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
62353
62354   if( 0==pColl && create ){
62355     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
62356     if( pColl ){
62357       CollSeq *pDel = 0;
62358       pColl[0].zName = (char*)&pColl[3];
62359       pColl[0].enc = SQLITE_UTF8;
62360       pColl[1].zName = (char*)&pColl[3];
62361       pColl[1].enc = SQLITE_UTF16LE;
62362       pColl[2].zName = (char*)&pColl[3];
62363       pColl[2].enc = SQLITE_UTF16BE;
62364       memcpy(pColl[0].zName, zName, nName);
62365       pColl[0].zName[nName] = 0;
62366       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
62367
62368       /* If a malloc() failure occured in sqlite3HashInsert(), it will 
62369       ** return the pColl pointer to be deleted (because it wasn't added
62370       ** to the hash table).
62371       */
62372       assert( pDel==0 || pDel==pColl );
62373       if( pDel!=0 ){
62374         db->mallocFailed = 1;
62375         sqlite3DbFree(db, pDel);
62376         pColl = 0;
62377       }
62378     }
62379   }
62380   return pColl;
62381 }
62382
62383 /*
62384 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
62385 ** Return the CollSeq* pointer for the collation sequence named zName
62386 ** for the encoding 'enc' from the database 'db'.
62387 **
62388 ** If the entry specified is not found and 'create' is true, then create a
62389 ** new entry.  Otherwise return NULL.
62390 **
62391 ** A separate function sqlite3LocateCollSeq() is a wrapper around
62392 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
62393 ** if necessary and generates an error message if the collating sequence
62394 ** cannot be found.
62395 */
62396 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
62397   sqlite3 *db,
62398   u8 enc,
62399   const char *zName,
62400   int nName,
62401   int create
62402 ){
62403   CollSeq *pColl;
62404   if( zName ){
62405     pColl = findCollSeqEntry(db, zName, nName, create);
62406   }else{
62407     pColl = db->pDfltColl;
62408   }
62409   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
62410   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
62411   if( pColl ) pColl += enc-1;
62412   return pColl;
62413 }
62414
62415 /* During the search for the best function definition, this procedure
62416 ** is called to test how well the function passed as the first argument
62417 ** matches the request for a function with nArg arguments in a system
62418 ** that uses encoding enc. The value returned indicates how well the
62419 ** request is matched. A higher value indicates a better match.
62420 **
62421 ** The returned value is always between 1 and 6, as follows:
62422 **
62423 ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
62424 **    encoding is requested, or vice versa.
62425 ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
62426 **    requested, or vice versa.
62427 ** 3: A variable arguments function using the same text encoding.
62428 ** 4: A function with the exact number of arguments requested that
62429 **    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
62430 ** 5: A function with the exact number of arguments requested that
62431 **    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
62432 ** 6: An exact match.
62433 **
62434 */
62435 static int matchQuality(FuncDef *p, int nArg, u8 enc){
62436   int match = 0;
62437   if( p->nArg==-1 || p->nArg==nArg || nArg==-1 ){
62438     match = 1;
62439     if( p->nArg==nArg || nArg==-1 ){
62440       match = 4;
62441     }
62442     if( enc==p->iPrefEnc ){
62443       match += 2;
62444     }
62445     else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
62446              (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
62447       match += 1;
62448     }
62449   }
62450   return match;
62451 }
62452
62453 /*
62454 ** Search a FuncDefHash for a function with the given name.  Return
62455 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
62456 */
62457 static FuncDef *functionSearch(
62458   FuncDefHash *pHash,  /* Hash table to search */
62459   int h,               /* Hash of the name */
62460   const char *zFunc,   /* Name of function */
62461   int nFunc            /* Number of bytes in zFunc */
62462 ){
62463   FuncDef *p;
62464   for(p=pHash->a[h]; p; p=p->pHash){
62465     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
62466       return p;
62467     }
62468   }
62469   return 0;
62470 }
62471
62472 /*
62473 ** Insert a new FuncDef into a FuncDefHash hash table.
62474 */
62475 SQLITE_PRIVATE void sqlite3FuncDefInsert(
62476   FuncDefHash *pHash,  /* The hash table into which to insert */
62477   FuncDef *pDef        /* The function definition to insert */
62478 ){
62479   FuncDef *pOther;
62480   int nName = strlen(pDef->zName);
62481   u8 c1 = (u8)pDef->zName[0];
62482   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
62483   pOther = functionSearch(pHash, h, pDef->zName, nName);
62484   if( pOther ){
62485     pDef->pNext = pOther->pNext;
62486     pOther->pNext = pDef;
62487   }else{
62488     pDef->pNext = 0;
62489     pDef->pHash = pHash->a[h];
62490     pHash->a[h] = pDef;
62491   }
62492 }
62493   
62494   
62495
62496 /*
62497 ** Locate a user function given a name, a number of arguments and a flag
62498 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
62499 ** pointer to the FuncDef structure that defines that function, or return
62500 ** NULL if the function does not exist.
62501 **
62502 ** If the createFlag argument is true, then a new (blank) FuncDef
62503 ** structure is created and liked into the "db" structure if a
62504 ** no matching function previously existed.  When createFlag is true
62505 ** and the nArg parameter is -1, then only a function that accepts
62506 ** any number of arguments will be returned.
62507 **
62508 ** If createFlag is false and nArg is -1, then the first valid
62509 ** function found is returned.  A function is valid if either xFunc
62510 ** or xStep is non-zero.
62511 **
62512 ** If createFlag is false, then a function with the required name and
62513 ** number of arguments may be returned even if the eTextRep flag does not
62514 ** match that requested.
62515 */
62516 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
62517   sqlite3 *db,       /* An open database */
62518   const char *zName, /* Name of the function.  Not null-terminated */
62519   int nName,         /* Number of characters in the name */
62520   int nArg,          /* Number of arguments.  -1 means any number */
62521   u8 enc,            /* Preferred text encoding */
62522   int createFlag     /* Create new entry if true and does not otherwise exist */
62523 ){
62524   FuncDef *p;         /* Iterator variable */
62525   FuncDef *pBest = 0; /* Best match found so far */
62526   int bestScore = 0;  /* Score of best match */
62527   int h;              /* Hash value */
62528
62529
62530   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
62531   if( nArg<-1 ) nArg = -1;
62532   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
62533
62534   /* First search for a match amongst the application-defined functions.
62535   */
62536   p = functionSearch(&db->aFunc, h, zName, nName);
62537   while( p ){
62538     int score = matchQuality(p, nArg, enc);
62539     if( score>bestScore ){
62540       pBest = p;
62541       bestScore = score;
62542     }
62543     p = p->pNext;
62544   }
62545
62546   /* If no match is found, search the built-in functions.
62547   **
62548   ** Except, if createFlag is true, that means that we are trying to
62549   ** install a new function.  Whatever FuncDef structure is returned will
62550   ** have fields overwritten with new information appropriate for the
62551   ** new function.  But the FuncDefs for built-in functions are read-only.
62552   ** So we must not search for built-ins when creating a new function.
62553   */ 
62554   if( !createFlag && !pBest ){
62555     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
62556     p = functionSearch(pHash, h, zName, nName);
62557     while( p ){
62558       int score = matchQuality(p, nArg, enc);
62559       if( score>bestScore ){
62560         pBest = p;
62561         bestScore = score;
62562       }
62563       p = p->pNext;
62564     }
62565   }
62566
62567   /* If the createFlag parameter is true and the search did not reveal an
62568   ** exact match for the name, number of arguments and encoding, then add a
62569   ** new entry to the hash table and return it.
62570   */
62571   if( createFlag && (bestScore<6 || pBest->nArg!=nArg) && 
62572       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
62573     pBest->zName = (char *)&pBest[1];
62574     pBest->nArg = nArg;
62575     pBest->iPrefEnc = enc;
62576     memcpy(pBest->zName, zName, nName);
62577     pBest->zName[nName] = 0;
62578     sqlite3FuncDefInsert(&db->aFunc, pBest);
62579   }
62580
62581   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
62582     return pBest;
62583   }
62584   return 0;
62585 }
62586
62587 /*
62588 ** Free all resources held by the schema structure. The void* argument points
62589 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the 
62590 ** pointer itself, it just cleans up subsiduary resources (i.e. the contents
62591 ** of the schema hash tables).
62592 **
62593 ** The Schema.cache_size variable is not cleared.
62594 */
62595 SQLITE_PRIVATE void sqlite3SchemaFree(void *p){
62596   Hash temp1;
62597   Hash temp2;
62598   HashElem *pElem;
62599   Schema *pSchema = (Schema *)p;
62600
62601   temp1 = pSchema->tblHash;
62602   temp2 = pSchema->trigHash;
62603   sqlite3HashInit(&pSchema->trigHash, 0);
62604   sqlite3HashClear(&pSchema->aFKey);
62605   sqlite3HashClear(&pSchema->idxHash);
62606   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
62607     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
62608   }
62609   sqlite3HashClear(&temp2);
62610   sqlite3HashInit(&pSchema->tblHash, 0);
62611   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
62612     Table *pTab = sqliteHashData(pElem);
62613     sqlite3DeleteTable(pTab);
62614   }
62615   sqlite3HashClear(&temp1);
62616   pSchema->pSeqTab = 0;
62617   pSchema->flags &= ~DB_SchemaLoaded;
62618 }
62619
62620 /*
62621 ** Find and return the schema associated with a BTree.  Create
62622 ** a new one if necessary.
62623 */
62624 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
62625   Schema * p;
62626   if( pBt ){
62627     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaFree);
62628   }else{
62629     p = (Schema *)sqlite3MallocZero(sizeof(Schema));
62630   }
62631   if( !p ){
62632     db->mallocFailed = 1;
62633   }else if ( 0==p->file_format ){
62634     sqlite3HashInit(&p->tblHash, 0);
62635     sqlite3HashInit(&p->idxHash, 0);
62636     sqlite3HashInit(&p->trigHash, 0);
62637     sqlite3HashInit(&p->aFKey, 1);
62638     p->enc = SQLITE_UTF8;
62639   }
62640   return p;
62641 }
62642
62643 /************** End of callback.c ********************************************/
62644 /************** Begin file delete.c ******************************************/
62645 /*
62646 ** 2001 September 15
62647 **
62648 ** The author disclaims copyright to this source code.  In place of
62649 ** a legal notice, here is a blessing:
62650 **
62651 **    May you do good and not evil.
62652 **    May you find forgiveness for yourself and forgive others.
62653 **    May you share freely, never taking more than you give.
62654 **
62655 *************************************************************************
62656 ** This file contains C code routines that are called by the parser
62657 ** in order to generate code for DELETE FROM statements.
62658 **
62659 ** $Id: delete.c,v 1.187 2008/11/19 09:05:27 danielk1977 Exp $
62660 */
62661
62662 /*
62663 ** Look up every table that is named in pSrc.  If any table is not found,
62664 ** add an error message to pParse->zErrMsg and return NULL.  If all tables
62665 ** are found, return a pointer to the last table.
62666 */
62667 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
62668   struct SrcList_item *pItem = pSrc->a;
62669   Table *pTab;
62670   assert( pItem && pSrc->nSrc==1 );
62671   pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
62672   sqlite3DeleteTable(pItem->pTab);
62673   pItem->pTab = pTab;
62674   if( pTab ){
62675     pTab->nRef++;
62676   }
62677   if( sqlite3IndexedByLookup(pParse, pItem) ){
62678     pTab = 0;
62679   }
62680   return pTab;
62681 }
62682
62683 /*
62684 ** Check to make sure the given table is writable.  If it is not
62685 ** writable, generate an error message and return 1.  If it is
62686 ** writable return 0;
62687 */
62688 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
62689   if( ((pTab->tabFlags & TF_Readonly)!=0
62690         && (pParse->db->flags & SQLITE_WriteSchema)==0
62691         && pParse->nested==0) 
62692 #ifndef SQLITE_OMIT_VIRTUALTABLE
62693       || (pTab->pMod && pTab->pMod->pModule->xUpdate==0)
62694 #endif
62695   ){
62696     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
62697     return 1;
62698   }
62699 #ifndef SQLITE_OMIT_VIEW
62700   if( !viewOk && pTab->pSelect ){
62701     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
62702     return 1;
62703   }
62704 #endif
62705   return 0;
62706 }
62707
62708 /*
62709 ** Generate code that will open a table for reading.
62710 */
62711 SQLITE_PRIVATE void sqlite3OpenTable(
62712   Parse *p,       /* Generate code into this VDBE */
62713   int iCur,       /* The cursor number of the table */
62714   int iDb,        /* The database index in sqlite3.aDb[] */
62715   Table *pTab,    /* The table to be opened */
62716   int opcode      /* OP_OpenRead or OP_OpenWrite */
62717 ){
62718   Vdbe *v;
62719   if( IsVirtual(pTab) ) return;
62720   v = sqlite3GetVdbe(p);
62721   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
62722   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite), pTab->zName);
62723   sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
62724   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
62725   VdbeComment((v, "%s", pTab->zName));
62726 }
62727
62728
62729 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
62730 /*
62731 ** Evaluate a view and store its result in an ephemeral table.  The
62732 ** pWhere argument is an optional WHERE clause that restricts the
62733 ** set of rows in the view that are to be added to the ephemeral table.
62734 */
62735 SQLITE_PRIVATE void sqlite3MaterializeView(
62736   Parse *pParse,       /* Parsing context */
62737   Table *pView,        /* View definition */
62738   Expr *pWhere,        /* Optional WHERE clause to be added */
62739   int iCur             /* Cursor number for ephemerial table */
62740 ){
62741   SelectDest dest;
62742   Select *pDup;
62743   sqlite3 *db = pParse->db;
62744
62745   pDup = sqlite3SelectDup(db, pView->pSelect);
62746   if( pWhere ){
62747     SrcList *pFrom;
62748     Token viewName;
62749     
62750     pWhere = sqlite3ExprDup(db, pWhere);
62751     viewName.z = (u8*)pView->zName;
62752     viewName.n = (unsigned int)strlen((const char*)viewName.z);
62753     pFrom = sqlite3SrcListAppendFromTerm(pParse, 0, 0, 0, &viewName, pDup, 0,0);
62754     pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
62755   }
62756   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
62757   sqlite3Select(pParse, pDup, &dest);
62758   sqlite3SelectDelete(db, pDup);
62759 }
62760 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
62761
62762 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
62763 /*
62764 ** Generate an expression tree to implement the WHERE, ORDER BY,
62765 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
62766 **
62767 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
62768 **                            \__________________________/
62769 **                               pLimitWhere (pInClause)
62770 */
62771 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
62772   Parse *pParse,               /* The parser context */
62773   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
62774   Expr *pWhere,                /* The WHERE clause.  May be null */
62775   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
62776   Expr *pLimit,                /* The LIMIT clause.  May be null */
62777   Expr *pOffset,               /* The OFFSET clause.  May be null */
62778   char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
62779 ){
62780   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
62781   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
62782   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
62783   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
62784   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
62785   Select *pSelect = NULL;      /* Complete SELECT tree */
62786
62787   /* Check that there isn't an ORDER BY without a LIMIT clause.
62788   */
62789   if( pOrderBy && (pLimit == 0) ) {
62790     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
62791     pParse->parseError = 1;
62792     goto limit_where_cleanup_2;
62793   }
62794
62795   /* We only need to generate a select expression if there
62796   ** is a limit/offset term to enforce.
62797   */
62798   if( pLimit == 0 ) {
62799     /* if pLimit is null, pOffset will always be null as well. */
62800     assert( pOffset == 0 );
62801     return pWhere;
62802   }
62803
62804   /* Generate a select expression tree to enforce the limit/offset 
62805   ** term for the DELETE or UPDATE statement.  For example:
62806   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
62807   ** becomes:
62808   **   DELETE FROM table_a WHERE rowid IN ( 
62809   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
62810   **   );
62811   */
62812
62813   pSelectRowid = sqlite3Expr(pParse->db, TK_ROW, 0, 0, 0);
62814   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
62815   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid, 0);
62816   if( pEList == 0 ) goto limit_where_cleanup_2;
62817
62818   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
62819   ** and the SELECT subtree. */
62820   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc);
62821   if( pSelectSrc == 0 ) {
62822     sqlite3ExprListDelete(pParse->db, pEList);
62823     goto limit_where_cleanup_2;
62824   }
62825
62826   /* generate the SELECT expression tree. */
62827   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,pOrderBy,0,pLimit,pOffset);
62828   if( pSelect == 0 ) return 0;
62829
62830   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
62831   pWhereRowid = sqlite3Expr(pParse->db, TK_ROW, 0, 0, 0);
62832   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
62833   pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
62834   if( pInClause == 0 ) goto limit_where_cleanup_1;
62835
62836   pInClause->pSelect = pSelect;
62837   sqlite3ExprSetHeight(pParse, pInClause);
62838   return pInClause;
62839
62840   /* something went wrong. clean up anything allocated. */
62841 limit_where_cleanup_1:
62842   sqlite3SelectDelete(pParse->db, pSelect);
62843   return 0;
62844
62845 limit_where_cleanup_2:
62846   sqlite3ExprDelete(pParse->db, pWhere);
62847   sqlite3ExprListDelete(pParse->db, pOrderBy);
62848   sqlite3ExprDelete(pParse->db, pLimit);
62849   sqlite3ExprDelete(pParse->db, pOffset);
62850   return 0;
62851 }
62852 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
62853
62854 /*
62855 ** Generate code for a DELETE FROM statement.
62856 **
62857 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
62858 **                 \________/       \________________/
62859 **                  pTabList              pWhere
62860 */
62861 SQLITE_PRIVATE void sqlite3DeleteFrom(
62862   Parse *pParse,         /* The parser context */
62863   SrcList *pTabList,     /* The table from which we should delete things */
62864   Expr *pWhere           /* The WHERE clause.  May be null */
62865 ){
62866   Vdbe *v;               /* The virtual database engine */
62867   Table *pTab;           /* The table from which records will be deleted */
62868   const char *zDb;       /* Name of database holding pTab */
62869   int end, addr = 0;     /* A couple addresses of generated code */
62870   int i;                 /* Loop counter */
62871   WhereInfo *pWInfo;     /* Information about the WHERE clause */
62872   Index *pIdx;           /* For looping over indices of the table */
62873   int iCur;              /* VDBE Cursor number for pTab */
62874   sqlite3 *db;           /* Main database structure */
62875   AuthContext sContext;  /* Authorization context */
62876   int oldIdx = -1;       /* Cursor for the OLD table of AFTER triggers */
62877   NameContext sNC;       /* Name context to resolve expressions in */
62878   int iDb;               /* Database number */
62879   int memCnt = -1;       /* Memory cell used for change counting */
62880   int rcauth;            /* Value returned by authorization callback */
62881
62882 #ifndef SQLITE_OMIT_TRIGGER
62883   int isView;                  /* True if attempting to delete from a view */
62884   int triggers_exist = 0;      /* True if any triggers exist */
62885 #endif
62886   int iBeginAfterTrigger;      /* Address of after trigger program */
62887   int iEndAfterTrigger;        /* Exit of after trigger program */
62888   int iBeginBeforeTrigger;     /* Address of before trigger program */
62889   int iEndBeforeTrigger;       /* Exit of before trigger program */
62890   u32 old_col_mask = 0;        /* Mask of OLD.* columns in use */
62891
62892   sContext.pParse = 0;
62893   db = pParse->db;
62894   if( pParse->nErr || db->mallocFailed ){
62895     goto delete_from_cleanup;
62896   }
62897   assert( pTabList->nSrc==1 );
62898
62899   /* Locate the table which we want to delete.  This table has to be
62900   ** put in an SrcList structure because some of the subroutines we
62901   ** will be calling are designed to work with multiple tables and expect
62902   ** an SrcList* parameter instead of just a Table* parameter.
62903   */
62904   pTab = sqlite3SrcListLookup(pParse, pTabList);
62905   if( pTab==0 )  goto delete_from_cleanup;
62906
62907   /* Figure out if we have any triggers and if the table being
62908   ** deleted from is a view
62909   */
62910 #ifndef SQLITE_OMIT_TRIGGER
62911   triggers_exist = sqlite3TriggersExist(pTab, TK_DELETE, 0);
62912   isView = pTab->pSelect!=0;
62913 #else
62914 # define triggers_exist 0
62915 # define isView 0
62916 #endif
62917 #ifdef SQLITE_OMIT_VIEW
62918 # undef isView
62919 # define isView 0
62920 #endif
62921
62922   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
62923     goto delete_from_cleanup;
62924   }
62925   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
62926   assert( iDb<db->nDb );
62927   zDb = db->aDb[iDb].zName;
62928   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
62929   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
62930   if( rcauth==SQLITE_DENY ){
62931     goto delete_from_cleanup;
62932   }
62933   assert(!isView || triggers_exist);
62934
62935   /* If pTab is really a view, make sure it has been initialized.
62936   */
62937   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
62938     goto delete_from_cleanup;
62939   }
62940
62941   /* Allocate a cursor used to store the old.* data for a trigger.
62942   */
62943   if( triggers_exist ){ 
62944     oldIdx = pParse->nTab++;
62945   }
62946
62947   /* Assign  cursor number to the table and all its indices.
62948   */
62949   assert( pTabList->nSrc==1 );
62950   iCur = pTabList->a[0].iCursor = pParse->nTab++;
62951   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
62952     pParse->nTab++;
62953   }
62954
62955   /* Start the view context
62956   */
62957   if( isView ){
62958     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
62959   }
62960
62961   /* Begin generating code.
62962   */
62963   v = sqlite3GetVdbe(pParse);
62964   if( v==0 ){
62965     goto delete_from_cleanup;
62966   }
62967   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
62968   sqlite3BeginWriteOperation(pParse, triggers_exist, iDb);
62969
62970   if( triggers_exist ){
62971     int orconf = ((pParse->trigStack)?pParse->trigStack->orconf:OE_Default);
62972     int iGoto = sqlite3VdbeAddOp0(v, OP_Goto);
62973     addr = sqlite3VdbeMakeLabel(v);
62974
62975     iBeginBeforeTrigger = sqlite3VdbeCurrentAddr(v);
62976     (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_BEFORE, pTab,
62977         -1, oldIdx, orconf, addr, &old_col_mask, 0);
62978     iEndBeforeTrigger = sqlite3VdbeAddOp0(v, OP_Goto);
62979
62980     iBeginAfterTrigger = sqlite3VdbeCurrentAddr(v);
62981     (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_AFTER, pTab, -1,
62982         oldIdx, orconf, addr, &old_col_mask, 0);
62983     iEndAfterTrigger = sqlite3VdbeAddOp0(v, OP_Goto);
62984
62985     sqlite3VdbeJumpHere(v, iGoto);
62986   }
62987
62988   /* If we are trying to delete from a view, realize that view into
62989   ** a ephemeral table.
62990   */
62991 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
62992   if( isView ){
62993     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
62994   }
62995 #endif
62996
62997   /* Resolve the column names in the WHERE clause.
62998   */
62999   memset(&sNC, 0, sizeof(sNC));
63000   sNC.pParse = pParse;
63001   sNC.pSrcList = pTabList;
63002   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
63003     goto delete_from_cleanup;
63004   }
63005
63006   /* Initialize the counter of the number of rows deleted, if
63007   ** we are counting rows.
63008   */
63009   if( db->flags & SQLITE_CountRows ){
63010     memCnt = ++pParse->nMem;
63011     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
63012   }
63013
63014 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
63015   /* Special case: A DELETE without a WHERE clause deletes everything.
63016   ** It is easier just to erase the whole table.  Note, however, that
63017   ** this means that the row change count will be incorrect.
63018   */
63019   if( rcauth==SQLITE_OK && pWhere==0 && !triggers_exist && !IsVirtual(pTab) ){
63020     assert( !isView );
63021     sqlite3VdbeAddOp3(v, OP_Clear, pTab->tnum, iDb, memCnt);
63022     if( !pParse->nested ){
63023       sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
63024     }
63025     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
63026       assert( pIdx->pSchema==pTab->pSchema );
63027       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
63028     }
63029   }else
63030 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
63031   /* The usual case: There is a WHERE clause so we have to scan through
63032   ** the table and pick which records to delete.
63033   */
63034   {
63035     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
63036
63037     /* Begin the database scan
63038     */
63039     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0);
63040     if( pWInfo==0 ) goto delete_from_cleanup;
63041
63042     /* Remember the rowid of every item to be deleted.
63043     */
63044     sqlite3VdbeAddOp2(v, IsVirtual(pTab) ? OP_VRowid : OP_Rowid, iCur, iRowid);
63045     sqlite3VdbeAddOp1(v, OP_FifoWrite, iRowid);
63046     if( db->flags & SQLITE_CountRows ){
63047       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
63048     }
63049
63050     /* End the database scan loop.
63051     */
63052     sqlite3WhereEnd(pWInfo);
63053
63054     /* Open the pseudo-table used to store OLD if there are triggers.
63055     */
63056     if( triggers_exist ){
63057       sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
63058       sqlite3VdbeAddOp1(v, OP_OpenPseudo, oldIdx);
63059     }
63060
63061     /* Delete every item whose key was written to the list during the
63062     ** database scan.  We have to delete items after the scan is complete
63063     ** because deleting an item can change the scan order.
63064     */
63065     end = sqlite3VdbeMakeLabel(v);
63066
63067     if( !isView ){
63068       /* Open cursors for the table we are deleting from and 
63069       ** all its indices.
63070       */
63071       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
63072     }
63073
63074     /* This is the beginning of the delete loop. If a trigger encounters
63075     ** an IGNORE constraint, it jumps back to here.
63076     */
63077     if( triggers_exist ){
63078       sqlite3VdbeResolveLabel(v, addr);
63079     }
63080     addr = sqlite3VdbeAddOp2(v, OP_FifoRead, iRowid, end);
63081
63082     if( triggers_exist ){
63083       int iData = ++pParse->nMem;   /* For storing row data of OLD table */
63084
63085       /* If the record is no longer present in the table, jump to the
63086       ** next iteration of the loop through the contents of the fifo.
63087       */
63088       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, iRowid);
63089
63090       /* Populate the OLD.* pseudo-table */
63091       if( old_col_mask ){
63092         sqlite3VdbeAddOp2(v, OP_RowData, iCur, iData);
63093       }else{
63094         sqlite3VdbeAddOp2(v, OP_Null, 0, iData);
63095       }
63096       sqlite3VdbeAddOp3(v, OP_Insert, oldIdx, iData, iRowid);
63097
63098       /* Jump back and run the BEFORE triggers */
63099       sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginBeforeTrigger);
63100       sqlite3VdbeJumpHere(v, iEndBeforeTrigger);
63101     }
63102
63103     if( !isView ){
63104       /* Delete the row */
63105 #ifndef SQLITE_OMIT_VIRTUALTABLE
63106       if( IsVirtual(pTab) ){
63107         const char *pVtab = (const char *)pTab->pVtab;
63108         sqlite3VtabMakeWritable(pParse, pTab);
63109         sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVtab, P4_VTAB);
63110       }else
63111 #endif
63112       {
63113         sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, pParse->nested==0);
63114       }
63115     }
63116
63117     /* If there are row triggers, close all cursors then invoke
63118     ** the AFTER triggers
63119     */
63120     if( triggers_exist ){
63121       /* Jump back and run the AFTER triggers */
63122       sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginAfterTrigger);
63123       sqlite3VdbeJumpHere(v, iEndAfterTrigger);
63124     }
63125
63126     /* End of the delete loop */
63127     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
63128     sqlite3VdbeResolveLabel(v, end);
63129
63130     /* Close the cursors after the loop if there are no row triggers */
63131     if( !isView  && !IsVirtual(pTab) ){
63132       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
63133         sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
63134       }
63135       sqlite3VdbeAddOp1(v, OP_Close, iCur);
63136     }
63137   }
63138
63139   /*
63140   ** Return the number of rows that were deleted. If this routine is 
63141   ** generating code because of a call to sqlite3NestedParse(), do not
63142   ** invoke the callback function.
63143   */
63144   if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
63145     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
63146     sqlite3VdbeSetNumCols(v, 1);
63147     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
63148   }
63149
63150 delete_from_cleanup:
63151   sqlite3AuthContextPop(&sContext);
63152   sqlite3SrcListDelete(db, pTabList);
63153   sqlite3ExprDelete(db, pWhere);
63154   return;
63155 }
63156
63157 /*
63158 ** This routine generates VDBE code that causes a single row of a
63159 ** single table to be deleted.
63160 **
63161 ** The VDBE must be in a particular state when this routine is called.
63162 ** These are the requirements:
63163 **
63164 **   1.  A read/write cursor pointing to pTab, the table containing the row
63165 **       to be deleted, must be opened as cursor number "base".
63166 **
63167 **   2.  Read/write cursors for all indices of pTab must be open as
63168 **       cursor number base+i for the i-th index.
63169 **
63170 **   3.  The record number of the row to be deleted must be stored in
63171 **       memory cell iRowid.
63172 **
63173 ** This routine pops the top of the stack to remove the record number
63174 ** and then generates code to remove both the table record and all index
63175 ** entries that point to that record.
63176 */
63177 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
63178   Parse *pParse,     /* Parsing context */
63179   Table *pTab,       /* Table containing the row to be deleted */
63180   int iCur,          /* Cursor number for the table */
63181   int iRowid,        /* Memory cell that contains the rowid to delete */
63182   int count          /* Increment the row change counter */
63183 ){
63184   int addr;
63185   Vdbe *v;
63186
63187   v = pParse->pVdbe;
63188   addr = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowid);
63189   sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
63190   sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
63191   if( count ){
63192     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
63193   }
63194   sqlite3VdbeJumpHere(v, addr);
63195 }
63196
63197 /*
63198 ** This routine generates VDBE code that causes the deletion of all
63199 ** index entries associated with a single row of a single table.
63200 **
63201 ** The VDBE must be in a particular state when this routine is called.
63202 ** These are the requirements:
63203 **
63204 **   1.  A read/write cursor pointing to pTab, the table containing the row
63205 **       to be deleted, must be opened as cursor number "iCur".
63206 **
63207 **   2.  Read/write cursors for all indices of pTab must be open as
63208 **       cursor number iCur+i for the i-th index.
63209 **
63210 **   3.  The "iCur" cursor must be pointing to the row that is to be
63211 **       deleted.
63212 */
63213 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
63214   Parse *pParse,     /* Parsing and code generating context */
63215   Table *pTab,       /* Table containing the row to be deleted */
63216   int iCur,          /* Cursor number for the table */
63217   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
63218 ){
63219   int i;
63220   Index *pIdx;
63221   int r1;
63222
63223   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
63224     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
63225     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
63226     sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
63227   }
63228 }
63229
63230 /*
63231 ** Generate code that will assemble an index key and put it in register
63232 ** regOut.  The key with be for index pIdx which is an index on pTab.
63233 ** iCur is the index of a cursor open on the pTab table and pointing to
63234 ** the entry that needs indexing.
63235 **
63236 ** Return a register number which is the first in a block of
63237 ** registers that holds the elements of the index key.  The
63238 ** block of registers has already been deallocated by the time
63239 ** this routine returns.
63240 */
63241 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
63242   Parse *pParse,     /* Parsing context */
63243   Index *pIdx,       /* The index for which to generate a key */
63244   int iCur,          /* Cursor number for the pIdx->pTable table */
63245   int regOut,        /* Write the new index key to this register */
63246   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
63247 ){
63248   Vdbe *v = pParse->pVdbe;
63249   int j;
63250   Table *pTab = pIdx->pTable;
63251   int regBase;
63252   int nCol;
63253
63254   nCol = pIdx->nColumn;
63255   regBase = sqlite3GetTempRange(pParse, nCol+1);
63256   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
63257   for(j=0; j<nCol; j++){
63258     int idx = pIdx->aiColumn[j];
63259     if( idx==pTab->iPKey ){
63260       sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
63261     }else{
63262       sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
63263       sqlite3ColumnDefault(v, pTab, idx);
63264     }
63265   }
63266   if( doMakeRec ){
63267     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
63268     sqlite3IndexAffinityStr(v, pIdx);
63269     sqlite3ExprCacheAffinityChange(pParse, regBase, nCol+1);
63270   }
63271   sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
63272   return regBase;
63273 }
63274
63275 /* Make sure "isView" gets undefined in case this file becomes part of
63276 ** the amalgamation - so that subsequent files do not see isView as a
63277 ** macro. */
63278 #undef isView
63279
63280 /************** End of delete.c **********************************************/
63281 /************** Begin file func.c ********************************************/
63282 /*
63283 ** 2002 February 23
63284 **
63285 ** The author disclaims copyright to this source code.  In place of
63286 ** a legal notice, here is a blessing:
63287 **
63288 **    May you do good and not evil.
63289 **    May you find forgiveness for yourself and forgive others.
63290 **    May you share freely, never taking more than you give.
63291 **
63292 *************************************************************************
63293 ** This file contains the C functions that implement various SQL
63294 ** functions of SQLite.  
63295 **
63296 ** There is only one exported symbol in this file - the function
63297 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
63298 ** All other code has file scope.
63299 **
63300 ** $Id: func.c,v 1.206 2008/11/19 16:52:44 danielk1977 Exp $
63301 */
63302
63303 /*
63304 ** Return the collating function associated with a function.
63305 */
63306 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
63307   return context->pColl;
63308 }
63309
63310 /*
63311 ** Implementation of the non-aggregate min() and max() functions
63312 */
63313 static void minmaxFunc(
63314   sqlite3_context *context,
63315   int argc,
63316   sqlite3_value **argv
63317 ){
63318   int i;
63319   int mask;    /* 0 for min() or 0xffffffff for max() */
63320   int iBest;
63321   CollSeq *pColl;
63322
63323   if( argc==0 ) return;
63324   mask = sqlite3_user_data(context)==0 ? 0 : -1;
63325   pColl = sqlite3GetFuncCollSeq(context);
63326   assert( pColl );
63327   assert( mask==-1 || mask==0 );
63328   iBest = 0;
63329   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
63330   for(i=1; i<argc; i++){
63331     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
63332     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
63333       iBest = i;
63334     }
63335   }
63336   sqlite3_result_value(context, argv[iBest]);
63337 }
63338
63339 /*
63340 ** Return the type of the argument.
63341 */
63342 static void typeofFunc(
63343   sqlite3_context *context,
63344   int NotUsed,
63345   sqlite3_value **argv
63346 ){
63347   const char *z = 0;
63348   UNUSED_PARAMETER(NotUsed);
63349   switch( sqlite3_value_type(argv[0]) ){
63350     case SQLITE_NULL:    z = "null";    break;
63351     case SQLITE_INTEGER: z = "integer"; break;
63352     case SQLITE_TEXT:    z = "text";    break;
63353     case SQLITE_FLOAT:   z = "real";    break;
63354     case SQLITE_BLOB:    z = "blob";    break;
63355   }
63356   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
63357 }
63358
63359
63360 /*
63361 ** Implementation of the length() function
63362 */
63363 static void lengthFunc(
63364   sqlite3_context *context,
63365   int argc,
63366   sqlite3_value **argv
63367 ){
63368   int len;
63369
63370   assert( argc==1 );
63371   UNUSED_PARAMETER(argc);
63372   switch( sqlite3_value_type(argv[0]) ){
63373     case SQLITE_BLOB:
63374     case SQLITE_INTEGER:
63375     case SQLITE_FLOAT: {
63376       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
63377       break;
63378     }
63379     case SQLITE_TEXT: {
63380       const unsigned char *z = sqlite3_value_text(argv[0]);
63381       if( z==0 ) return;
63382       len = 0;
63383       while( *z ){
63384         len++;
63385         SQLITE_SKIP_UTF8(z);
63386       }
63387       sqlite3_result_int(context, len);
63388       break;
63389     }
63390     default: {
63391       sqlite3_result_null(context);
63392       break;
63393     }
63394   }
63395 }
63396
63397 /*
63398 ** Implementation of the abs() function
63399 */
63400 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
63401   assert( argc==1 );
63402   UNUSED_PARAMETER(argc);
63403   switch( sqlite3_value_type(argv[0]) ){
63404     case SQLITE_INTEGER: {
63405       i64 iVal = sqlite3_value_int64(argv[0]);
63406       if( iVal<0 ){
63407         if( (iVal<<1)==0 ){
63408           sqlite3_result_error(context, "integer overflow", -1);
63409           return;
63410         }
63411         iVal = -iVal;
63412       } 
63413       sqlite3_result_int64(context, iVal);
63414       break;
63415     }
63416     case SQLITE_NULL: {
63417       sqlite3_result_null(context);
63418       break;
63419     }
63420     default: {
63421       double rVal = sqlite3_value_double(argv[0]);
63422       if( rVal<0 ) rVal = -rVal;
63423       sqlite3_result_double(context, rVal);
63424       break;
63425     }
63426   }
63427 }
63428
63429 /*
63430 ** Implementation of the substr() function.
63431 **
63432 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
63433 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
63434 ** of x.  If x is text, then we actually count UTF-8 characters.
63435 ** If x is a blob, then we count bytes.
63436 **
63437 ** If p1 is negative, then we begin abs(p1) from the end of x[].
63438 */
63439 static void substrFunc(
63440   sqlite3_context *context,
63441   int argc,
63442   sqlite3_value **argv
63443 ){
63444   const unsigned char *z;
63445   const unsigned char *z2;
63446   int len;
63447   int p0type;
63448   i64 p1, p2;
63449
63450   assert( argc==3 || argc==2 );
63451   p0type = sqlite3_value_type(argv[0]);
63452   if( p0type==SQLITE_BLOB ){
63453     len = sqlite3_value_bytes(argv[0]);
63454     z = sqlite3_value_blob(argv[0]);
63455     if( z==0 ) return;
63456     assert( len==sqlite3_value_bytes(argv[0]) );
63457   }else{
63458     z = sqlite3_value_text(argv[0]);
63459     if( z==0 ) return;
63460     len = 0;
63461     for(z2=z; *z2; len++){
63462       SQLITE_SKIP_UTF8(z2);
63463     }
63464   }
63465   p1 = sqlite3_value_int(argv[1]);
63466   if( argc==3 ){
63467     p2 = sqlite3_value_int(argv[2]);
63468   }else{
63469     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
63470   }
63471   if( p1<0 ){
63472     p1 += len;
63473     if( p1<0 ){
63474       p2 += p1;
63475       p1 = 0;
63476     }
63477   }else if( p1>0 ){
63478     p1--;
63479   }
63480   if( p1+p2>len ){
63481     p2 = len-p1;
63482   }
63483   if( p0type!=SQLITE_BLOB ){
63484     while( *z && p1 ){
63485       SQLITE_SKIP_UTF8(z);
63486       p1--;
63487     }
63488     for(z2=z; *z2 && p2; p2--){
63489       SQLITE_SKIP_UTF8(z2);
63490     }
63491     sqlite3_result_text(context, (char*)z, z2-z, SQLITE_TRANSIENT);
63492   }else{
63493     if( p2<0 ) p2 = 0;
63494     sqlite3_result_blob(context, (char*)&z[p1], p2, SQLITE_TRANSIENT);
63495   }
63496 }
63497
63498 /*
63499 ** Implementation of the round() function
63500 */
63501 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
63502   int n = 0;
63503   double r;
63504   char zBuf[500];  /* larger than the %f representation of the largest double */
63505   assert( argc==1 || argc==2 );
63506   if( argc==2 ){
63507     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
63508     n = sqlite3_value_int(argv[1]);
63509     if( n>30 ) n = 30;
63510     if( n<0 ) n = 0;
63511   }
63512   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
63513   r = sqlite3_value_double(argv[0]);
63514   sqlite3_snprintf(sizeof(zBuf),zBuf,"%.*f",n,r);
63515   sqlite3AtoF(zBuf, &r);
63516   sqlite3_result_double(context, r);
63517 }
63518
63519 /*
63520 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
63521 ** allocation fails, call sqlite3_result_error_nomem() to notify
63522 ** the database handle that malloc() has failed.
63523 */
63524 static void *contextMalloc(sqlite3_context *context, i64 nByte){
63525   char *z;
63526   if( nByte>sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH] ){
63527     sqlite3_result_error_toobig(context);
63528     z = 0;
63529   }else{
63530     z = sqlite3Malloc(nByte);
63531     if( !z && nByte>0 ){
63532       sqlite3_result_error_nomem(context);
63533     }
63534   }
63535   return z;
63536 }
63537
63538 /*
63539 ** Implementation of the upper() and lower() SQL functions.
63540 */
63541 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
63542   char *z1;
63543   const char *z2;
63544   int i, n;
63545   if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
63546   z2 = (char*)sqlite3_value_text(argv[0]);
63547   n = sqlite3_value_bytes(argv[0]);
63548   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
63549   assert( z2==(char*)sqlite3_value_text(argv[0]) );
63550   if( z2 ){
63551     z1 = contextMalloc(context, ((i64)n)+1);
63552     if( z1 ){
63553       memcpy(z1, z2, n+1);
63554       for(i=0; z1[i]; i++){
63555         z1[i] = toupper(z1[i]);
63556       }
63557       sqlite3_result_text(context, z1, -1, sqlite3_free);
63558     }
63559   }
63560 }
63561 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
63562   char *z1;
63563   const char *z2;
63564   int i, n;
63565   if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
63566   z2 = (char*)sqlite3_value_text(argv[0]);
63567   n = sqlite3_value_bytes(argv[0]);
63568   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
63569   assert( z2==(char*)sqlite3_value_text(argv[0]) );
63570   if( z2 ){
63571     z1 = contextMalloc(context, ((i64)n)+1);
63572     if( z1 ){
63573       memcpy(z1, z2, n+1);
63574       for(i=0; z1[i]; i++){
63575         z1[i] = tolower(z1[i]);
63576       }
63577       sqlite3_result_text(context, z1, -1, sqlite3_free);
63578     }
63579   }
63580 }
63581
63582 /*
63583 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  
63584 ** All three do the same thing.  They return the first non-NULL
63585 ** argument.
63586 */
63587 static void ifnullFunc(
63588   sqlite3_context *context,
63589   int argc,
63590   sqlite3_value **argv
63591 ){
63592   int i;
63593   for(i=0; i<argc; i++){
63594     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
63595       sqlite3_result_value(context, argv[i]);
63596       break;
63597     }
63598   }
63599 }
63600
63601 /*
63602 ** Implementation of random().  Return a random integer.  
63603 */
63604 static void randomFunc(
63605   sqlite3_context *context,
63606   int NotUsed,
63607   sqlite3_value **NotUsed2
63608 ){
63609   sqlite_int64 r;
63610   UNUSED_PARAMETER2(NotUsed, NotUsed2);
63611   sqlite3_randomness(sizeof(r), &r);
63612   if( (r<<1)==0 ) r = 0;  /* Prevent 0x8000.... as the result so that we */
63613                           /* can always do abs() of the result */
63614   sqlite3_result_int64(context, r);
63615 }
63616
63617 /*
63618 ** Implementation of randomblob(N).  Return a random blob
63619 ** that is N bytes long.
63620 */
63621 static void randomBlob(
63622   sqlite3_context *context,
63623   int argc,
63624   sqlite3_value **argv
63625 ){
63626   int n;
63627   unsigned char *p;
63628   assert( argc==1 );
63629   UNUSED_PARAMETER(argc);
63630   n = sqlite3_value_int(argv[0]);
63631   if( n<1 ){
63632     n = 1;
63633   }
63634   p = contextMalloc(context, n);
63635   if( p ){
63636     sqlite3_randomness(n, p);
63637     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
63638   }
63639 }
63640
63641 /*
63642 ** Implementation of the last_insert_rowid() SQL function.  The return
63643 ** value is the same as the sqlite3_last_insert_rowid() API function.
63644 */
63645 static void last_insert_rowid(
63646   sqlite3_context *context, 
63647   int NotUsed, 
63648   sqlite3_value **NotUsed2
63649 ){
63650   sqlite3 *db = sqlite3_context_db_handle(context);
63651   UNUSED_PARAMETER2(NotUsed, NotUsed2);
63652   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
63653 }
63654
63655 /*
63656 ** Implementation of the changes() SQL function.  The return value is the
63657 ** same as the sqlite3_changes() API function.
63658 */
63659 static void changes(
63660   sqlite3_context *context,
63661   int NotUsed,
63662   sqlite3_value **NotUsed2
63663 ){
63664   sqlite3 *db = sqlite3_context_db_handle(context);
63665   UNUSED_PARAMETER2(NotUsed, NotUsed2);
63666   sqlite3_result_int(context, sqlite3_changes(db));
63667 }
63668
63669 /*
63670 ** Implementation of the total_changes() SQL function.  The return value is
63671 ** the same as the sqlite3_total_changes() API function.
63672 */
63673 static void total_changes(
63674   sqlite3_context *context,
63675   int NotUsed,
63676   sqlite3_value **NotUsed2
63677 ){
63678   sqlite3 *db = sqlite3_context_db_handle(context);
63679   UNUSED_PARAMETER2(NotUsed, NotUsed2);
63680   sqlite3_result_int(context, sqlite3_total_changes(db));
63681 }
63682
63683 /*
63684 ** A structure defining how to do GLOB-style comparisons.
63685 */
63686 struct compareInfo {
63687   u8 matchAll;
63688   u8 matchOne;
63689   u8 matchSet;
63690   u8 noCase;
63691 };
63692
63693 /*
63694 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
63695 ** character is exactly one byte in size.  Also, all characters are
63696 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
63697 ** whereas only characters less than 0x80 do in ASCII.
63698 */
63699 #if defined(SQLITE_EBCDIC)
63700 # define sqlite3Utf8Read(A,B,C)  (*(A++))
63701 # define GlogUpperToLower(A)     A = sqlite3UpperToLower[A]
63702 #else
63703 # define GlogUpperToLower(A)     if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
63704 #endif
63705
63706 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
63707 /* The correct SQL-92 behavior is for the LIKE operator to ignore
63708 ** case.  Thus  'a' LIKE 'A' would be true. */
63709 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
63710 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
63711 ** is case sensitive causing 'a' LIKE 'A' to be false */
63712 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
63713
63714 /*
63715 ** Compare two UTF-8 strings for equality where the first string can
63716 ** potentially be a "glob" expression.  Return true (1) if they
63717 ** are the same and false (0) if they are different.
63718 **
63719 ** Globbing rules:
63720 **
63721 **      '*'       Matches any sequence of zero or more characters.
63722 **
63723 **      '?'       Matches exactly one character.
63724 **
63725 **     [...]      Matches one character from the enclosed list of
63726 **                characters.
63727 **
63728 **     [^...]     Matches one character not in the enclosed list.
63729 **
63730 ** With the [...] and [^...] matching, a ']' character can be included
63731 ** in the list by making it the first character after '[' or '^'.  A
63732 ** range of characters can be specified using '-'.  Example:
63733 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
63734 ** it the last character in the list.
63735 **
63736 ** This routine is usually quick, but can be N**2 in the worst case.
63737 **
63738 ** Hints: to match '*' or '?', put them in "[]".  Like this:
63739 **
63740 **         abc[*]xyz        Matches "abc*xyz" only
63741 */
63742 static int patternCompare(
63743   const u8 *zPattern,              /* The glob pattern */
63744   const u8 *zString,               /* The string to compare against the glob */
63745   const struct compareInfo *pInfo, /* Information about how to do the compare */
63746   const int esc                    /* The escape character */
63747 ){
63748   int c, c2;
63749   int invert;
63750   int seen;
63751   u8 matchOne = pInfo->matchOne;
63752   u8 matchAll = pInfo->matchAll;
63753   u8 matchSet = pInfo->matchSet;
63754   u8 noCase = pInfo->noCase; 
63755   int prevEscape = 0;     /* True if the previous character was 'escape' */
63756
63757   while( (c = sqlite3Utf8Read(zPattern,0,&zPattern))!=0 ){
63758     if( !prevEscape && c==matchAll ){
63759       while( (c=sqlite3Utf8Read(zPattern,0,&zPattern)) == matchAll
63760                || c == matchOne ){
63761         if( c==matchOne && sqlite3Utf8Read(zString, 0, &zString)==0 ){
63762           return 0;
63763         }
63764       }
63765       if( c==0 ){
63766         return 1;
63767       }else if( c==esc ){
63768         c = sqlite3Utf8Read(zPattern, 0, &zPattern);
63769         if( c==0 ){
63770           return 0;
63771         }
63772       }else if( c==matchSet ){
63773         assert( esc==0 );         /* This is GLOB, not LIKE */
63774         assert( matchSet<0x80 );  /* '[' is a single-byte character */
63775         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
63776           SQLITE_SKIP_UTF8(zString);
63777         }
63778         return *zString!=0;
63779       }
63780       while( (c2 = sqlite3Utf8Read(zString,0,&zString))!=0 ){
63781         if( noCase ){
63782           GlogUpperToLower(c2);
63783           GlogUpperToLower(c);
63784           while( c2 != 0 && c2 != c ){
63785             c2 = sqlite3Utf8Read(zString, 0, &zString);
63786             GlogUpperToLower(c2);
63787           }
63788         }else{
63789           while( c2 != 0 && c2 != c ){
63790             c2 = sqlite3Utf8Read(zString, 0, &zString);
63791           }
63792         }
63793         if( c2==0 ) return 0;
63794         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
63795       }
63796       return 0;
63797     }else if( !prevEscape && c==matchOne ){
63798       if( sqlite3Utf8Read(zString, 0, &zString)==0 ){
63799         return 0;
63800       }
63801     }else if( c==matchSet ){
63802       int prior_c = 0;
63803       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
63804       seen = 0;
63805       invert = 0;
63806       c = sqlite3Utf8Read(zString, 0, &zString);
63807       if( c==0 ) return 0;
63808       c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
63809       if( c2=='^' ){
63810         invert = 1;
63811         c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
63812       }
63813       if( c2==']' ){
63814         if( c==']' ) seen = 1;
63815         c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
63816       }
63817       while( c2 && c2!=']' ){
63818         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
63819           c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
63820           if( c>=prior_c && c<=c2 ) seen = 1;
63821           prior_c = 0;
63822         }else{
63823           if( c==c2 ){
63824             seen = 1;
63825           }
63826           prior_c = c2;
63827         }
63828         c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
63829       }
63830       if( c2==0 || (seen ^ invert)==0 ){
63831         return 0;
63832       }
63833     }else if( esc==c && !prevEscape ){
63834       prevEscape = 1;
63835     }else{
63836       c2 = sqlite3Utf8Read(zString, 0, &zString);
63837       if( noCase ){
63838         GlogUpperToLower(c);
63839         GlogUpperToLower(c2);
63840       }
63841       if( c!=c2 ){
63842         return 0;
63843       }
63844       prevEscape = 0;
63845     }
63846   }
63847   return *zString==0;
63848 }
63849
63850 /*
63851 ** Count the number of times that the LIKE operator (or GLOB which is
63852 ** just a variation of LIKE) gets called.  This is used for testing
63853 ** only.
63854 */
63855 #ifdef SQLITE_TEST
63856 SQLITE_API int sqlite3_like_count = 0;
63857 #endif
63858
63859
63860 /*
63861 ** Implementation of the like() SQL function.  This function implements
63862 ** the build-in LIKE operator.  The first argument to the function is the
63863 ** pattern and the second argument is the string.  So, the SQL statements:
63864 **
63865 **       A LIKE B
63866 **
63867 ** is implemented as like(B,A).
63868 **
63869 ** This same function (with a different compareInfo structure) computes
63870 ** the GLOB operator.
63871 */
63872 static void likeFunc(
63873   sqlite3_context *context, 
63874   int argc, 
63875   sqlite3_value **argv
63876 ){
63877   const unsigned char *zA, *zB;
63878   int escape = 0;
63879   sqlite3 *db = sqlite3_context_db_handle(context);
63880
63881   zB = sqlite3_value_text(argv[0]);
63882   zA = sqlite3_value_text(argv[1]);
63883
63884   /* Limit the length of the LIKE or GLOB pattern to avoid problems
63885   ** of deep recursion and N*N behavior in patternCompare().
63886   */
63887   if( sqlite3_value_bytes(argv[0]) >
63888         db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
63889     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
63890     return;
63891   }
63892   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
63893
63894   if( argc==3 ){
63895     /* The escape character string must consist of a single UTF-8 character.
63896     ** Otherwise, return an error.
63897     */
63898     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
63899     if( zEsc==0 ) return;
63900     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
63901       sqlite3_result_error(context, 
63902           "ESCAPE expression must be a single character", -1);
63903       return;
63904     }
63905     escape = sqlite3Utf8Read(zEsc, 0, &zEsc);
63906   }
63907   if( zA && zB ){
63908     struct compareInfo *pInfo = sqlite3_user_data(context);
63909 #ifdef SQLITE_TEST
63910     sqlite3_like_count++;
63911 #endif
63912     
63913     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
63914   }
63915 }
63916
63917 /*
63918 ** Implementation of the NULLIF(x,y) function.  The result is the first
63919 ** argument if the arguments are different.  The result is NULL if the
63920 ** arguments are equal to each other.
63921 */
63922 static void nullifFunc(
63923   sqlite3_context *context,
63924   int NotUsed,
63925   sqlite3_value **argv
63926 ){
63927   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
63928   UNUSED_PARAMETER(NotUsed);
63929   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
63930     sqlite3_result_value(context, argv[0]);
63931   }
63932 }
63933
63934 /*
63935 ** Implementation of the VERSION(*) function.  The result is the version
63936 ** of the SQLite library that is running.
63937 */
63938 static void versionFunc(
63939   sqlite3_context *context,
63940   int NotUsed,
63941   sqlite3_value **NotUsed2
63942 ){
63943   UNUSED_PARAMETER2(NotUsed, NotUsed2);
63944   sqlite3_result_text(context, sqlite3_version, -1, SQLITE_STATIC);
63945 }
63946
63947 /* Array for converting from half-bytes (nybbles) into ASCII hex
63948 ** digits. */
63949 static const char hexdigits[] = {
63950   '0', '1', '2', '3', '4', '5', '6', '7',
63951   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
63952 };
63953
63954 /*
63955 ** EXPERIMENTAL - This is not an official function.  The interface may
63956 ** change.  This function may disappear.  Do not write code that depends
63957 ** on this function.
63958 **
63959 ** Implementation of the QUOTE() function.  This function takes a single
63960 ** argument.  If the argument is numeric, the return value is the same as
63961 ** the argument.  If the argument is NULL, the return value is the string
63962 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
63963 ** single-quote escapes.
63964 */
63965 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
63966   if( argc<1 ) return;
63967   switch( sqlite3_value_type(argv[0]) ){
63968     case SQLITE_NULL: {
63969       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
63970       break;
63971     }
63972     case SQLITE_INTEGER:
63973     case SQLITE_FLOAT: {
63974       sqlite3_result_value(context, argv[0]);
63975       break;
63976     }
63977     case SQLITE_BLOB: {
63978       char *zText = 0;
63979       char const *zBlob = sqlite3_value_blob(argv[0]);
63980       int nBlob = sqlite3_value_bytes(argv[0]);
63981       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
63982       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 
63983       if( zText ){
63984         int i;
63985         for(i=0; i<nBlob; i++){
63986           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
63987           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
63988         }
63989         zText[(nBlob*2)+2] = '\'';
63990         zText[(nBlob*2)+3] = '\0';
63991         zText[0] = 'X';
63992         zText[1] = '\'';
63993         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
63994         sqlite3_free(zText);
63995       }
63996       break;
63997     }
63998     case SQLITE_TEXT: {
63999       int i,j;
64000       u64 n;
64001       const unsigned char *zArg = sqlite3_value_text(argv[0]);
64002       char *z;
64003
64004       if( zArg==0 ) return;
64005       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
64006       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
64007       if( z ){
64008         z[0] = '\'';
64009         for(i=0, j=1; zArg[i]; i++){
64010           z[j++] = zArg[i];
64011           if( zArg[i]=='\'' ){
64012             z[j++] = '\'';
64013           }
64014         }
64015         z[j++] = '\'';
64016         z[j] = 0;
64017         sqlite3_result_text(context, z, j, sqlite3_free);
64018       }
64019     }
64020   }
64021 }
64022
64023 /*
64024 ** The hex() function.  Interpret the argument as a blob.  Return
64025 ** a hexadecimal rendering as text.
64026 */
64027 static void hexFunc(
64028   sqlite3_context *context,
64029   int argc,
64030   sqlite3_value **argv
64031 ){
64032   int i, n;
64033   const unsigned char *pBlob;
64034   char *zHex, *z;
64035   assert( argc==1 );
64036   UNUSED_PARAMETER(argc);
64037   pBlob = sqlite3_value_blob(argv[0]);
64038   n = sqlite3_value_bytes(argv[0]);
64039   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
64040   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
64041   if( zHex ){
64042     for(i=0; i<n; i++, pBlob++){
64043       unsigned char c = *pBlob;
64044       *(z++) = hexdigits[(c>>4)&0xf];
64045       *(z++) = hexdigits[c&0xf];
64046     }
64047     *z = 0;
64048     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
64049   }
64050 }
64051
64052 /*
64053 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
64054 */
64055 static void zeroblobFunc(
64056   sqlite3_context *context,
64057   int argc,
64058   sqlite3_value **argv
64059 ){
64060   i64 n;
64061   assert( argc==1 );
64062   UNUSED_PARAMETER(argc);
64063   n = sqlite3_value_int64(argv[0]);
64064   if( n>SQLITE_MAX_LENGTH ){
64065     sqlite3_result_error_toobig(context);
64066   }else{
64067     sqlite3_result_zeroblob(context, n);
64068   }
64069 }
64070
64071 /*
64072 ** The replace() function.  Three arguments are all strings: call
64073 ** them A, B, and C. The result is also a string which is derived
64074 ** from A by replacing every occurance of B with C.  The match
64075 ** must be exact.  Collating sequences are not used.
64076 */
64077 static void replaceFunc(
64078   sqlite3_context *context,
64079   int argc,
64080   sqlite3_value **argv
64081 ){
64082   const unsigned char *zStr;        /* The input string A */
64083   const unsigned char *zPattern;    /* The pattern string B */
64084   const unsigned char *zRep;        /* The replacement string C */
64085   unsigned char *zOut;              /* The output */
64086   int nStr;                /* Size of zStr */
64087   int nPattern;            /* Size of zPattern */
64088   int nRep;                /* Size of zRep */
64089   i64 nOut;                /* Maximum size of zOut */
64090   int loopLimit;           /* Last zStr[] that might match zPattern[] */
64091   int i, j;                /* Loop counters */
64092
64093   assert( argc==3 );
64094   UNUSED_PARAMETER(argc);
64095   zStr = sqlite3_value_text(argv[0]);
64096   if( zStr==0 ) return;
64097   nStr = sqlite3_value_bytes(argv[0]);
64098   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
64099   zPattern = sqlite3_value_text(argv[1]);
64100   if( zPattern==0 || zPattern[0]==0 ) return;
64101   nPattern = sqlite3_value_bytes(argv[1]);
64102   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
64103   zRep = sqlite3_value_text(argv[2]);
64104   if( zRep==0 ) return;
64105   nRep = sqlite3_value_bytes(argv[2]);
64106   assert( zRep==sqlite3_value_text(argv[2]) );
64107   nOut = nStr + 1;
64108   assert( nOut<SQLITE_MAX_LENGTH );
64109   zOut = contextMalloc(context, (i64)nOut);
64110   if( zOut==0 ){
64111     return;
64112   }
64113   loopLimit = nStr - nPattern;  
64114   for(i=j=0; i<=loopLimit; i++){
64115     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
64116       zOut[j++] = zStr[i];
64117     }else{
64118       u8 *zOld;
64119       sqlite3 *db = sqlite3_context_db_handle(context);
64120       nOut += nRep - nPattern;
64121       if( nOut>=db->aLimit[SQLITE_LIMIT_LENGTH] ){
64122         sqlite3_result_error_toobig(context);
64123         sqlite3DbFree(db, zOut);
64124         return;
64125       }
64126       zOld = zOut;
64127       zOut = sqlite3_realloc(zOut, (int)nOut);
64128       if( zOut==0 ){
64129         sqlite3_result_error_nomem(context);
64130         sqlite3DbFree(db, zOld);
64131         return;
64132       }
64133       memcpy(&zOut[j], zRep, nRep);
64134       j += nRep;
64135       i += nPattern-1;
64136     }
64137   }
64138   assert( j+nStr-i+1==nOut );
64139   memcpy(&zOut[j], &zStr[i], nStr-i);
64140   j += nStr - i;
64141   assert( j<=nOut );
64142   zOut[j] = 0;
64143   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
64144 }
64145
64146 /*
64147 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
64148 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
64149 */
64150 static void trimFunc(
64151   sqlite3_context *context,
64152   int argc,
64153   sqlite3_value **argv
64154 ){
64155   const unsigned char *zIn;         /* Input string */
64156   const unsigned char *zCharSet;    /* Set of characters to trim */
64157   int nIn;                          /* Number of bytes in input */
64158   int flags;                        /* 1: trimleft  2: trimright  3: trim */
64159   int i;                            /* Loop counter */
64160   unsigned char *aLen;              /* Length of each character in zCharSet */
64161   unsigned char **azChar;           /* Individual characters in zCharSet */
64162   int nChar;                        /* Number of characters in zCharSet */
64163
64164   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
64165     return;
64166   }
64167   zIn = sqlite3_value_text(argv[0]);
64168   if( zIn==0 ) return;
64169   nIn = sqlite3_value_bytes(argv[0]);
64170   assert( zIn==sqlite3_value_text(argv[0]) );
64171   if( argc==1 ){
64172     static const unsigned char lenOne[] = { 1 };
64173     static unsigned char * const azOne[] = { (u8*)" " };
64174     nChar = 1;
64175     aLen = (u8*)lenOne;
64176     azChar = (unsigned char **)azOne;
64177     zCharSet = 0;
64178   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
64179     return;
64180   }else{
64181     const unsigned char *z;
64182     for(z=zCharSet, nChar=0; *z; nChar++){
64183       SQLITE_SKIP_UTF8(z);
64184     }
64185     if( nChar>0 ){
64186       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
64187       if( azChar==0 ){
64188         return;
64189       }
64190       aLen = (unsigned char*)&azChar[nChar];
64191       for(z=zCharSet, nChar=0; *z; nChar++){
64192         azChar[nChar] = (unsigned char *)z;
64193         SQLITE_SKIP_UTF8(z);
64194         aLen[nChar] = z - azChar[nChar];
64195       }
64196     }
64197   }
64198   if( nChar>0 ){
64199     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
64200     if( flags & 1 ){
64201       while( nIn>0 ){
64202         int len;
64203         for(i=0; i<nChar; i++){
64204           len = aLen[i];
64205           if( memcmp(zIn, azChar[i], len)==0 ) break;
64206         }
64207         if( i>=nChar ) break;
64208         zIn += len;
64209         nIn -= len;
64210       }
64211     }
64212     if( flags & 2 ){
64213       while( nIn>0 ){
64214         int len;
64215         for(i=0; i<nChar; i++){
64216           len = aLen[i];
64217           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
64218         }
64219         if( i>=nChar ) break;
64220         nIn -= len;
64221       }
64222     }
64223     if( zCharSet ){
64224       sqlite3_free(azChar);
64225     }
64226   }
64227   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
64228 }
64229
64230
64231 #ifdef SQLITE_SOUNDEX
64232 /*
64233 ** Compute the soundex encoding of a word.
64234 */
64235 static void soundexFunc(
64236   sqlite3_context *context,
64237   int argc,
64238   sqlite3_value **argv
64239 ){
64240   char zResult[8];
64241   const u8 *zIn;
64242   int i, j;
64243   static const unsigned char iCode[] = {
64244     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
64245     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
64246     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
64247     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
64248     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
64249     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
64250     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
64251     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
64252   };
64253   assert( argc==1 );
64254   zIn = (u8*)sqlite3_value_text(argv[0]);
64255   if( zIn==0 ) zIn = (u8*)"";
64256   for(i=0; zIn[i] && !isalpha(zIn[i]); i++){}
64257   if( zIn[i] ){
64258     u8 prevcode = iCode[zIn[i]&0x7f];
64259     zResult[0] = toupper(zIn[i]);
64260     for(j=1; j<4 && zIn[i]; i++){
64261       int code = iCode[zIn[i]&0x7f];
64262       if( code>0 ){
64263         if( code!=prevcode ){
64264           prevcode = code;
64265           zResult[j++] = code + '0';
64266         }
64267       }else{
64268         prevcode = 0;
64269       }
64270     }
64271     while( j<4 ){
64272       zResult[j++] = '0';
64273     }
64274     zResult[j] = 0;
64275     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
64276   }else{
64277     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
64278   }
64279 }
64280 #endif
64281
64282 #ifndef SQLITE_OMIT_LOAD_EXTENSION
64283 /*
64284 ** A function that loads a shared-library extension then returns NULL.
64285 */
64286 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
64287   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
64288   const char *zProc;
64289   sqlite3 *db = sqlite3_context_db_handle(context);
64290   char *zErrMsg = 0;
64291
64292   if( argc==2 ){
64293     zProc = (const char *)sqlite3_value_text(argv[1]);
64294   }else{
64295     zProc = 0;
64296   }
64297   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
64298     sqlite3_result_error(context, zErrMsg, -1);
64299     sqlite3_free(zErrMsg);
64300   }
64301 }
64302 #endif
64303
64304
64305 /*
64306 ** An instance of the following structure holds the context of a
64307 ** sum() or avg() aggregate computation.
64308 */
64309 typedef struct SumCtx SumCtx;
64310 struct SumCtx {
64311   double rSum;      /* Floating point sum */
64312   i64 iSum;         /* Integer sum */   
64313   i64 cnt;          /* Number of elements summed */
64314   u8 overflow;      /* True if integer overflow seen */
64315   u8 approx;        /* True if non-integer value was input to the sum */
64316 };
64317
64318 /*
64319 ** Routines used to compute the sum, average, and total.
64320 **
64321 ** The SUM() function follows the (broken) SQL standard which means
64322 ** that it returns NULL if it sums over no inputs.  TOTAL returns
64323 ** 0.0 in that case.  In addition, TOTAL always returns a float where
64324 ** SUM might return an integer if it never encounters a floating point
64325 ** value.  TOTAL never fails, but SUM might through an exception if
64326 ** it overflows an integer.
64327 */
64328 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
64329   SumCtx *p;
64330   int type;
64331   assert( argc==1 );
64332   UNUSED_PARAMETER(argc);
64333   p = sqlite3_aggregate_context(context, sizeof(*p));
64334   type = sqlite3_value_numeric_type(argv[0]);
64335   if( p && type!=SQLITE_NULL ){
64336     p->cnt++;
64337     if( type==SQLITE_INTEGER ){
64338       i64 v = sqlite3_value_int64(argv[0]);
64339       p->rSum += v;
64340       if( (p->approx|p->overflow)==0 ){
64341         i64 iNewSum = p->iSum + v;
64342         int s1 = p->iSum >> (sizeof(i64)*8-1);
64343         int s2 = v       >> (sizeof(i64)*8-1);
64344         int s3 = iNewSum >> (sizeof(i64)*8-1);
64345         p->overflow = (s1&s2&~s3) | (~s1&~s2&s3);
64346         p->iSum = iNewSum;
64347       }
64348     }else{
64349       p->rSum += sqlite3_value_double(argv[0]);
64350       p->approx = 1;
64351     }
64352   }
64353 }
64354 static void sumFinalize(sqlite3_context *context){
64355   SumCtx *p;
64356   p = sqlite3_aggregate_context(context, 0);
64357   if( p && p->cnt>0 ){
64358     if( p->overflow ){
64359       sqlite3_result_error(context,"integer overflow",-1);
64360     }else if( p->approx ){
64361       sqlite3_result_double(context, p->rSum);
64362     }else{
64363       sqlite3_result_int64(context, p->iSum);
64364     }
64365   }
64366 }
64367 static void avgFinalize(sqlite3_context *context){
64368   SumCtx *p;
64369   p = sqlite3_aggregate_context(context, 0);
64370   if( p && p->cnt>0 ){
64371     sqlite3_result_double(context, p->rSum/(double)p->cnt);
64372   }
64373 }
64374 static void totalFinalize(sqlite3_context *context){
64375   SumCtx *p;
64376   p = sqlite3_aggregate_context(context, 0);
64377   sqlite3_result_double(context, p ? p->rSum : 0.0);
64378 }
64379
64380 /*
64381 ** The following structure keeps track of state information for the
64382 ** count() aggregate function.
64383 */
64384 typedef struct CountCtx CountCtx;
64385 struct CountCtx {
64386   i64 n;
64387 };
64388
64389 /*
64390 ** Routines to implement the count() aggregate function.
64391 */
64392 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
64393   CountCtx *p;
64394   p = sqlite3_aggregate_context(context, sizeof(*p));
64395   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
64396     p->n++;
64397   }
64398 }   
64399 static void countFinalize(sqlite3_context *context){
64400   CountCtx *p;
64401   p = sqlite3_aggregate_context(context, 0);
64402   sqlite3_result_int64(context, p ? p->n : 0);
64403 }
64404
64405 /*
64406 ** Routines to implement min() and max() aggregate functions.
64407 */
64408 static void minmaxStep(
64409   sqlite3_context *context, 
64410   int NotUsed, 
64411   sqlite3_value **argv
64412 ){
64413   Mem *pArg  = (Mem *)argv[0];
64414   Mem *pBest;
64415   UNUSED_PARAMETER(NotUsed);
64416
64417   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
64418   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
64419   if( !pBest ) return;
64420
64421   if( pBest->flags ){
64422     int max;
64423     int cmp;
64424     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
64425     /* This step function is used for both the min() and max() aggregates,
64426     ** the only difference between the two being that the sense of the
64427     ** comparison is inverted. For the max() aggregate, the
64428     ** sqlite3_user_data() function returns (void *)-1. For min() it
64429     ** returns (void *)db, where db is the sqlite3* database pointer.
64430     ** Therefore the next statement sets variable 'max' to 1 for the max()
64431     ** aggregate, or 0 for min().
64432     */
64433     max = sqlite3_user_data(context)!=0;
64434     cmp = sqlite3MemCompare(pBest, pArg, pColl);
64435     if( (max && cmp<0) || (!max && cmp>0) ){
64436       sqlite3VdbeMemCopy(pBest, pArg);
64437     }
64438   }else{
64439     sqlite3VdbeMemCopy(pBest, pArg);
64440   }
64441 }
64442 static void minMaxFinalize(sqlite3_context *context){
64443   sqlite3_value *pRes;
64444   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
64445   if( pRes ){
64446     if( pRes->flags ){
64447       sqlite3_result_value(context, pRes);
64448     }
64449     sqlite3VdbeMemRelease(pRes);
64450   }
64451 }
64452
64453 /*
64454 ** group_concat(EXPR, ?SEPARATOR?)
64455 */
64456 static void groupConcatStep(
64457   sqlite3_context *context,
64458   int argc,
64459   sqlite3_value **argv
64460 ){
64461   const char *zVal;
64462   StrAccum *pAccum;
64463   const char *zSep;
64464   int nVal, nSep, i;
64465   if( argc==0 || sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
64466   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
64467
64468   if( pAccum ){
64469     sqlite3 *db = sqlite3_context_db_handle(context);
64470     pAccum->useMalloc = 1;
64471     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
64472     if( pAccum->nChar ){
64473       if( argc>1 ){
64474         zSep = (char*)sqlite3_value_text(argv[argc-1]);
64475         nSep = sqlite3_value_bytes(argv[argc-1]);
64476       }else{
64477         zSep = ",";
64478         nSep = 1;
64479       }
64480       sqlite3StrAccumAppend(pAccum, zSep, nSep);
64481     }
64482     i = 0;
64483     do{
64484       zVal = (char*)sqlite3_value_text(argv[i]);
64485       nVal = sqlite3_value_bytes(argv[i]);
64486       sqlite3StrAccumAppend(pAccum, zVal, nVal);
64487       i++;
64488     }while( i<argc-1 );
64489   }
64490 }
64491 static void groupConcatFinalize(sqlite3_context *context){
64492   StrAccum *pAccum;
64493   pAccum = sqlite3_aggregate_context(context, 0);
64494   if( pAccum ){
64495     if( pAccum->tooBig ){
64496       sqlite3_result_error_toobig(context);
64497     }else if( pAccum->mallocFailed ){
64498       sqlite3_result_error_nomem(context);
64499     }else{    
64500       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
64501                           sqlite3_free);
64502     }
64503   }
64504 }
64505
64506 /*
64507 ** This function registered all of the above C functions as SQL
64508 ** functions.  This should be the only routine in this file with
64509 ** external linkage.
64510 */
64511 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
64512 #ifndef SQLITE_OMIT_ALTERTABLE
64513   sqlite3AlterFunctions(db);
64514 #endif
64515   if( !db->mallocFailed ){
64516     int rc = sqlite3_overload_function(db, "MATCH", 2);
64517     assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
64518     if( rc==SQLITE_NOMEM ){
64519       db->mallocFailed = 1;
64520     }
64521   }
64522 #ifdef SQLITE_SSE
64523   (void)sqlite3SseFunctions(db);
64524 #endif
64525 }
64526
64527 /*
64528 ** Set the LIKEOPT flag on the 2-argument function with the given name.
64529 */
64530 static void setLikeOptFlag(sqlite3 *db, const char *zName, int flagVal){
64531   FuncDef *pDef;
64532   pDef = sqlite3FindFunction(db, zName, strlen(zName), 2, SQLITE_UTF8, 0);
64533   if( pDef ){
64534     pDef->flags = flagVal;
64535   }
64536 }
64537
64538 /*
64539 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
64540 ** parameter determines whether or not the LIKE operator is case
64541 ** sensitive.  GLOB is always case sensitive.
64542 */
64543 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
64544   struct compareInfo *pInfo;
64545   if( caseSensitive ){
64546     pInfo = (struct compareInfo*)&likeInfoAlt;
64547   }else{
64548     pInfo = (struct compareInfo*)&likeInfoNorm;
64549   }
64550   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
64551   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
64552   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8, 
64553       (struct compareInfo*)&globInfo, likeFunc, 0,0);
64554   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
64555   setLikeOptFlag(db, "like", 
64556       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
64557 }
64558
64559 /*
64560 ** pExpr points to an expression which implements a function.  If
64561 ** it is appropriate to apply the LIKE optimization to that function
64562 ** then set aWc[0] through aWc[2] to the wildcard characters and
64563 ** return TRUE.  If the function is not a LIKE-style function then
64564 ** return FALSE.
64565 */
64566 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
64567   FuncDef *pDef;
64568   if( pExpr->op!=TK_FUNCTION || !pExpr->pList ){
64569     return 0;
64570   }
64571   if( pExpr->pList->nExpr!=2 ){
64572     return 0;
64573   }
64574   pDef = sqlite3FindFunction(db, (char*)pExpr->token.z, pExpr->token.n, 2,
64575                              SQLITE_UTF8, 0);
64576   if( pDef==0 || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
64577     return 0;
64578   }
64579
64580   /* The memcpy() statement assumes that the wildcard characters are
64581   ** the first three statements in the compareInfo structure.  The
64582   ** asserts() that follow verify that assumption
64583   */
64584   memcpy(aWc, pDef->pUserData, 3);
64585   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
64586   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
64587   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
64588   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
64589   return 1;
64590 }
64591
64592 /*
64593 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
64594 ** to the global function hash table.  This occurs at start-time (as
64595 ** a consequence of calling sqlite3_initialize()).
64596 **
64597 ** After this routine runs
64598 */
64599 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
64600   /*
64601   ** The following array holds FuncDef structures for all of the functions
64602   ** defined in this file.
64603   **
64604   ** The array cannot be constant since changes are made to the
64605   ** FuncDef.pHash elements at start-time.  The elements of this array
64606   ** are read-only after initialization is complete.
64607   */
64608   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
64609     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
64610     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
64611     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
64612     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
64613     FUNCTION(trim,               1, 3, 0, trimFunc         ),
64614     FUNCTION(trim,               2, 3, 0, trimFunc         ),
64615     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
64616     FUNCTION(min,                0, 0, 1, 0                ),
64617     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
64618     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
64619     FUNCTION(max,                0, 1, 1, 0                ),
64620     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
64621     FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
64622     FUNCTION(length,             1, 0, 0, lengthFunc       ),
64623     FUNCTION(substr,             2, 0, 0, substrFunc       ),
64624     FUNCTION(substr,             3, 0, 0, substrFunc       ),
64625     FUNCTION(abs,                1, 0, 0, absFunc          ),
64626     FUNCTION(round,              1, 0, 0, roundFunc        ),
64627     FUNCTION(round,              2, 0, 0, roundFunc        ),
64628     FUNCTION(upper,              1, 0, 0, upperFunc        ),
64629     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
64630     FUNCTION(coalesce,           1, 0, 0, 0                ),
64631     FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ),
64632     FUNCTION(coalesce,           0, 0, 0, 0                ),
64633     FUNCTION(hex,                1, 0, 0, hexFunc          ),
64634     FUNCTION(ifnull,             2, 0, 1, ifnullFunc       ),
64635     FUNCTION(random,            -1, 0, 0, randomFunc       ),
64636     FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
64637     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
64638     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
64639     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
64640     FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
64641     FUNCTION(changes,            0, 0, 0, changes          ),
64642     FUNCTION(total_changes,      0, 0, 0, total_changes    ),
64643     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
64644     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
64645   #ifdef SQLITE_SOUNDEX
64646     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
64647   #endif
64648   #ifndef SQLITE_OMIT_LOAD_EXTENSION
64649     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
64650     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
64651   #endif
64652     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
64653     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
64654     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
64655     AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ),
64656     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
64657     AGGREGATE(group_concat,     -1, 0, 0, groupConcatStep, groupConcatFinalize),
64658   
64659     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
64660   #ifdef SQLITE_CASE_SENSITIVE_LIKE
64661     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
64662     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
64663   #else
64664     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
64665     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
64666   #endif
64667   };
64668
64669   int i;
64670   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
64671   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
64672
64673   for(i=0; i<ArraySize(aBuiltinFunc); i++){
64674     sqlite3FuncDefInsert(pHash, &aFunc[i]);
64675   }
64676   sqlite3RegisterDateTimeFunctions();
64677 }
64678
64679 /************** End of func.c ************************************************/
64680 /************** Begin file insert.c ******************************************/
64681 /*
64682 ** 2001 September 15
64683 **
64684 ** The author disclaims copyright to this source code.  In place of
64685 ** a legal notice, here is a blessing:
64686 **
64687 **    May you do good and not evil.
64688 **    May you find forgiveness for yourself and forgive others.
64689 **    May you share freely, never taking more than you give.
64690 **
64691 *************************************************************************
64692 ** This file contains C code routines that are called by the parser
64693 ** to handle INSERT statements in SQLite.
64694 **
64695 ** $Id: insert.c,v 1.253 2008/11/19 09:05:27 danielk1977 Exp $
64696 */
64697
64698 /*
64699 ** Set P4 of the most recently inserted opcode to a column affinity
64700 ** string for index pIdx. A column affinity string has one character
64701 ** for each column in the table, according to the affinity of the column:
64702 **
64703 **  Character      Column affinity
64704 **  ------------------------------
64705 **  'a'            TEXT
64706 **  'b'            NONE
64707 **  'c'            NUMERIC
64708 **  'd'            INTEGER
64709 **  'e'            REAL
64710 **
64711 ** An extra 'b' is appended to the end of the string to cover the
64712 ** rowid that appears as the last column in every index.
64713 */
64714 SQLITE_PRIVATE void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
64715   if( !pIdx->zColAff ){
64716     /* The first time a column affinity string for a particular index is
64717     ** required, it is allocated and populated here. It is then stored as
64718     ** a member of the Index structure for subsequent use.
64719     **
64720     ** The column affinity string will eventually be deleted by
64721     ** sqliteDeleteIndex() when the Index structure itself is cleaned
64722     ** up.
64723     */
64724     int n;
64725     Table *pTab = pIdx->pTable;
64726     sqlite3 *db = sqlite3VdbeDb(v);
64727     pIdx->zColAff = (char *)sqlite3Malloc(pIdx->nColumn+2);
64728     if( !pIdx->zColAff ){
64729       db->mallocFailed = 1;
64730       return;
64731     }
64732     for(n=0; n<pIdx->nColumn; n++){
64733       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
64734     }
64735     pIdx->zColAff[n++] = SQLITE_AFF_NONE;
64736     pIdx->zColAff[n] = 0;
64737   }
64738  
64739   sqlite3VdbeChangeP4(v, -1, pIdx->zColAff, 0);
64740 }
64741
64742 /*
64743 ** Set P4 of the most recently inserted opcode to a column affinity
64744 ** string for table pTab. A column affinity string has one character
64745 ** for each column indexed by the index, according to the affinity of the
64746 ** column:
64747 **
64748 **  Character      Column affinity
64749 **  ------------------------------
64750 **  'a'            TEXT
64751 **  'b'            NONE
64752 **  'c'            NUMERIC
64753 **  'd'            INTEGER
64754 **  'e'            REAL
64755 */
64756 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
64757   /* The first time a column affinity string for a particular table
64758   ** is required, it is allocated and populated here. It is then 
64759   ** stored as a member of the Table structure for subsequent use.
64760   **
64761   ** The column affinity string will eventually be deleted by
64762   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
64763   */
64764   if( !pTab->zColAff ){
64765     char *zColAff;
64766     int i;
64767     sqlite3 *db = sqlite3VdbeDb(v);
64768
64769     zColAff = (char *)sqlite3Malloc(pTab->nCol+1);
64770     if( !zColAff ){
64771       db->mallocFailed = 1;
64772       return;
64773     }
64774
64775     for(i=0; i<pTab->nCol; i++){
64776       zColAff[i] = pTab->aCol[i].affinity;
64777     }
64778     zColAff[pTab->nCol] = '\0';
64779
64780     pTab->zColAff = zColAff;
64781   }
64782
64783   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
64784 }
64785
64786 /*
64787 ** Return non-zero if the table pTab in database iDb or any of its indices
64788 ** have been opened at any point in the VDBE program beginning at location
64789 ** iStartAddr throught the end of the program.  This is used to see if 
64790 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
64791 ** run without using temporary table for the results of the SELECT. 
64792 */
64793 static int readsTable(Vdbe *v, int iStartAddr, int iDb, Table *pTab){
64794   int i;
64795   int iEnd = sqlite3VdbeCurrentAddr(v);
64796   for(i=iStartAddr; i<iEnd; i++){
64797     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
64798     assert( pOp!=0 );
64799     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
64800       Index *pIndex;
64801       int tnum = pOp->p2;
64802       if( tnum==pTab->tnum ){
64803         return 1;
64804       }
64805       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
64806         if( tnum==pIndex->tnum ){
64807           return 1;
64808         }
64809       }
64810     }
64811 #ifndef SQLITE_OMIT_VIRTUALTABLE
64812     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pTab->pVtab ){
64813       assert( pOp->p4.pVtab!=0 );
64814       assert( pOp->p4type==P4_VTAB );
64815       return 1;
64816     }
64817 #endif
64818   }
64819   return 0;
64820 }
64821
64822 #ifndef SQLITE_OMIT_AUTOINCREMENT
64823 /*
64824 ** Write out code to initialize the autoincrement logic.  This code
64825 ** looks up the current autoincrement value in the sqlite_sequence
64826 ** table and stores that value in a register.  Code generated by
64827 ** autoIncStep() will keep that register holding the largest
64828 ** rowid value.  Code generated by autoIncEnd() will write the new
64829 ** largest value of the counter back into the sqlite_sequence table.
64830 **
64831 ** This routine returns the index of the mem[] cell that contains
64832 ** the maximum rowid counter.
64833 **
64834 ** Three consecutive registers are allocated by this routine.  The
64835 ** first two hold the name of the target table and the maximum rowid 
64836 ** inserted into the target table, respectively.
64837 ** The third holds the rowid in sqlite_sequence where we will
64838 ** write back the revised maximum rowid.  This routine returns the
64839 ** index of the second of these three registers.
64840 */
64841 static int autoIncBegin(
64842   Parse *pParse,      /* Parsing context */
64843   int iDb,            /* Index of the database holding pTab */
64844   Table *pTab         /* The table we are writing to */
64845 ){
64846   int memId = 0;      /* Register holding maximum rowid */
64847   if( pTab->tabFlags & TF_Autoincrement ){
64848     Vdbe *v = pParse->pVdbe;
64849     Db *pDb = &pParse->db->aDb[iDb];
64850     int iCur = pParse->nTab;
64851     int addr;               /* Address of the top of the loop */
64852     assert( v );
64853     pParse->nMem++;         /* Holds name of table */
64854     memId = ++pParse->nMem;
64855     pParse->nMem++;
64856     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
64857     addr = sqlite3VdbeCurrentAddr(v);
64858     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, pTab->zName, 0);
64859     sqlite3VdbeAddOp2(v, OP_Rewind, iCur, addr+9);
64860     sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, memId);
64861     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
64862     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
64863     sqlite3VdbeAddOp2(v, OP_Rowid, iCur, memId+1);
64864     sqlite3VdbeAddOp3(v, OP_Column, iCur, 1, memId);
64865     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
64866     sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+2);
64867     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
64868     sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
64869   }
64870   return memId;
64871 }
64872
64873 /*
64874 ** Update the maximum rowid for an autoincrement calculation.
64875 **
64876 ** This routine should be called when the top of the stack holds a
64877 ** new rowid that is about to be inserted.  If that new rowid is
64878 ** larger than the maximum rowid in the memId memory cell, then the
64879 ** memory cell is updated.  The stack is unchanged.
64880 */
64881 static void autoIncStep(Parse *pParse, int memId, int regRowid){
64882   if( memId>0 ){
64883     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
64884   }
64885 }
64886
64887 /*
64888 ** After doing one or more inserts, the maximum rowid is stored
64889 ** in reg[memId].  Generate code to write this value back into the
64890 ** the sqlite_sequence table.
64891 */
64892 static void autoIncEnd(
64893   Parse *pParse,     /* The parsing context */
64894   int iDb,           /* Index of the database holding pTab */
64895   Table *pTab,       /* Table we are inserting into */
64896   int memId          /* Memory cell holding the maximum rowid */
64897 ){
64898   if( pTab->tabFlags & TF_Autoincrement ){
64899     int iCur = pParse->nTab;
64900     Vdbe *v = pParse->pVdbe;
64901     Db *pDb = &pParse->db->aDb[iDb];
64902     int j1;
64903     int iRec = ++pParse->nMem;    /* Memory cell used for record */
64904
64905     assert( v );
64906     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
64907     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
64908     sqlite3VdbeAddOp2(v, OP_NewRowid, iCur, memId+1);
64909     sqlite3VdbeJumpHere(v, j1);
64910     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
64911     sqlite3VdbeAddOp3(v, OP_Insert, iCur, iRec, memId+1);
64912     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
64913     sqlite3VdbeAddOp1(v, OP_Close, iCur);
64914   }
64915 }
64916 #else
64917 /*
64918 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
64919 ** above are all no-ops
64920 */
64921 # define autoIncBegin(A,B,C) (0)
64922 # define autoIncStep(A,B,C)
64923 # define autoIncEnd(A,B,C,D)
64924 #endif /* SQLITE_OMIT_AUTOINCREMENT */
64925
64926
64927 /* Forward declaration */
64928 static int xferOptimization(
64929   Parse *pParse,        /* Parser context */
64930   Table *pDest,         /* The table we are inserting into */
64931   Select *pSelect,      /* A SELECT statement to use as the data source */
64932   int onError,          /* How to handle constraint errors */
64933   int iDbDest           /* The database of pDest */
64934 );
64935
64936 /*
64937 ** This routine is call to handle SQL of the following forms:
64938 **
64939 **    insert into TABLE (IDLIST) values(EXPRLIST)
64940 **    insert into TABLE (IDLIST) select
64941 **
64942 ** The IDLIST following the table name is always optional.  If omitted,
64943 ** then a list of all columns for the table is substituted.  The IDLIST
64944 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
64945 **
64946 ** The pList parameter holds EXPRLIST in the first form of the INSERT
64947 ** statement above, and pSelect is NULL.  For the second form, pList is
64948 ** NULL and pSelect is a pointer to the select statement used to generate
64949 ** data for the insert.
64950 **
64951 ** The code generated follows one of four templates.  For a simple
64952 ** select with data coming from a VALUES clause, the code executes
64953 ** once straight down through.  Pseudo-code follows (we call this
64954 ** the "1st template"):
64955 **
64956 **         open write cursor to <table> and its indices
64957 **         puts VALUES clause expressions onto the stack
64958 **         write the resulting record into <table>
64959 **         cleanup
64960 **
64961 ** The three remaining templates assume the statement is of the form
64962 **
64963 **   INSERT INTO <table> SELECT ...
64964 **
64965 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
64966 ** in other words if the SELECT pulls all columns from a single table
64967 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
64968 ** if <table2> and <table1> are distinct tables but have identical
64969 ** schemas, including all the same indices, then a special optimization
64970 ** is invoked that copies raw records from <table2> over to <table1>.
64971 ** See the xferOptimization() function for the implementation of this
64972 ** template.  This is the 2nd template.
64973 **
64974 **         open a write cursor to <table>
64975 **         open read cursor on <table2>
64976 **         transfer all records in <table2> over to <table>
64977 **         close cursors
64978 **         foreach index on <table>
64979 **           open a write cursor on the <table> index
64980 **           open a read cursor on the corresponding <table2> index
64981 **           transfer all records from the read to the write cursors
64982 **           close cursors
64983 **         end foreach
64984 **
64985 ** The 3rd template is for when the second template does not apply
64986 ** and the SELECT clause does not read from <table> at any time.
64987 ** The generated code follows this template:
64988 **
64989 **         EOF <- 0
64990 **         X <- A
64991 **         goto B
64992 **      A: setup for the SELECT
64993 **         loop over the rows in the SELECT
64994 **           load values into registers R..R+n
64995 **           yield X
64996 **         end loop
64997 **         cleanup after the SELECT
64998 **         EOF <- 1
64999 **         yield X
65000 **         goto A
65001 **      B: open write cursor to <table> and its indices
65002 **      C: yield X
65003 **         if EOF goto D
65004 **         insert the select result into <table> from R..R+n
65005 **         goto C
65006 **      D: cleanup
65007 **
65008 ** The 4th template is used if the insert statement takes its
65009 ** values from a SELECT but the data is being inserted into a table
65010 ** that is also read as part of the SELECT.  In the third form,
65011 ** we have to use a intermediate table to store the results of
65012 ** the select.  The template is like this:
65013 **
65014 **         EOF <- 0
65015 **         X <- A
65016 **         goto B
65017 **      A: setup for the SELECT
65018 **         loop over the tables in the SELECT
65019 **           load value into register R..R+n
65020 **           yield X
65021 **         end loop
65022 **         cleanup after the SELECT
65023 **         EOF <- 1
65024 **         yield X
65025 **         halt-error
65026 **      B: open temp table
65027 **      L: yield X
65028 **         if EOF goto M
65029 **         insert row from R..R+n into temp table
65030 **         goto L
65031 **      M: open write cursor to <table> and its indices
65032 **         rewind temp table
65033 **      C: loop over rows of intermediate table
65034 **           transfer values form intermediate table into <table>
65035 **         end loop
65036 **      D: cleanup
65037 */
65038 SQLITE_PRIVATE void sqlite3Insert(
65039   Parse *pParse,        /* Parser context */
65040   SrcList *pTabList,    /* Name of table into which we are inserting */
65041   ExprList *pList,      /* List of values to be inserted */
65042   Select *pSelect,      /* A SELECT statement to use as the data source */
65043   IdList *pColumn,      /* Column names corresponding to IDLIST. */
65044   int onError           /* How to handle constraint errors */
65045 ){
65046   sqlite3 *db;          /* The main database structure */
65047   Table *pTab;          /* The table to insert into.  aka TABLE */
65048   char *zTab;           /* Name of the table into which we are inserting */
65049   const char *zDb;      /* Name of the database holding this table */
65050   int i, j, idx;        /* Loop counters */
65051   Vdbe *v;              /* Generate code into this virtual machine */
65052   Index *pIdx;          /* For looping over indices of the table */
65053   int nColumn;          /* Number of columns in the data */
65054   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
65055   int baseCur = 0;      /* VDBE Cursor number for pTab */
65056   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
65057   int endOfLoop;        /* Label for the end of the insertion loop */
65058   int useTempTable = 0; /* Store SELECT results in intermediate table */
65059   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
65060   int addrInsTop = 0;   /* Jump to label "D" */
65061   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
65062   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
65063   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
65064   int newIdx = -1;      /* Cursor for the NEW pseudo-table */
65065   int iDb;              /* Index of database holding TABLE */
65066   Db *pDb;              /* The database containing table being inserted into */
65067   int appendFlag = 0;   /* True if the insert is likely to be an append */
65068
65069   /* Register allocations */
65070   int regFromSelect;    /* Base register for data coming from SELECT */
65071   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
65072   int regRowCount = 0;  /* Memory cell used for the row counter */
65073   int regIns;           /* Block of regs holding rowid+data being inserted */
65074   int regRowid;         /* registers holding insert rowid */
65075   int regData;          /* register holding first column to insert */
65076   int regRecord;        /* Holds the assemblied row record */
65077   int regEof;           /* Register recording end of SELECT data */
65078   int *aRegIdx = 0;     /* One register allocated to each index */
65079
65080
65081 #ifndef SQLITE_OMIT_TRIGGER
65082   int isView;                 /* True if attempting to insert into a view */
65083   int triggers_exist = 0;     /* True if there are FOR EACH ROW triggers */
65084 #endif
65085
65086   db = pParse->db;
65087   if( pParse->nErr || db->mallocFailed ){
65088     goto insert_cleanup;
65089   }
65090
65091   /* Locate the table into which we will be inserting new information.
65092   */
65093   assert( pTabList->nSrc==1 );
65094   zTab = pTabList->a[0].zName;
65095   if( zTab==0 ) goto insert_cleanup;
65096   pTab = sqlite3SrcListLookup(pParse, pTabList);
65097   if( pTab==0 ){
65098     goto insert_cleanup;
65099   }
65100   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
65101   assert( iDb<db->nDb );
65102   pDb = &db->aDb[iDb];
65103   zDb = pDb->zName;
65104   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
65105     goto insert_cleanup;
65106   }
65107
65108   /* Figure out if we have any triggers and if the table being
65109   ** inserted into is a view
65110   */
65111 #ifndef SQLITE_OMIT_TRIGGER
65112   triggers_exist = sqlite3TriggersExist(pTab, TK_INSERT, 0);
65113   isView = pTab->pSelect!=0;
65114 #else
65115 # define triggers_exist 0
65116 # define isView 0
65117 #endif
65118 #ifdef SQLITE_OMIT_VIEW
65119 # undef isView
65120 # define isView 0
65121 #endif
65122
65123   /* Ensure that:
65124   *  (a) the table is not read-only, 
65125   *  (b) that if it is a view then ON INSERT triggers exist
65126   */
65127   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
65128     goto insert_cleanup;
65129   }
65130   assert( pTab!=0 );
65131
65132   /* If pTab is really a view, make sure it has been initialized.
65133   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 
65134   ** module table).
65135   */
65136   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
65137     goto insert_cleanup;
65138   }
65139
65140   /* Allocate a VDBE
65141   */
65142   v = sqlite3GetVdbe(pParse);
65143   if( v==0 ) goto insert_cleanup;
65144   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
65145   sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
65146
65147   /* if there are row triggers, allocate a temp table for new.* references. */
65148   if( triggers_exist ){
65149     newIdx = pParse->nTab++;
65150   }
65151
65152 #ifndef SQLITE_OMIT_XFER_OPT
65153   /* If the statement is of the form
65154   **
65155   **       INSERT INTO <table1> SELECT * FROM <table2>;
65156   **
65157   ** Then special optimizations can be applied that make the transfer
65158   ** very fast and which reduce fragmentation of indices.
65159   **
65160   ** This is the 2nd template.
65161   */
65162   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
65163     assert( !triggers_exist );
65164     assert( pList==0 );
65165     goto insert_cleanup;
65166   }
65167 #endif /* SQLITE_OMIT_XFER_OPT */
65168
65169   /* If this is an AUTOINCREMENT table, look up the sequence number in the
65170   ** sqlite_sequence table and store it in memory cell regAutoinc.
65171   */
65172   regAutoinc = autoIncBegin(pParse, iDb, pTab);
65173
65174   /* Figure out how many columns of data are supplied.  If the data
65175   ** is coming from a SELECT statement, then generate a co-routine that
65176   ** produces a single row of the SELECT on each invocation.  The
65177   ** co-routine is the common header to the 3rd and 4th templates.
65178   */
65179   if( pSelect ){
65180     /* Data is coming from a SELECT.  Generate code to implement that SELECT
65181     ** as a co-routine.  The code is common to both the 3rd and 4th
65182     ** templates:
65183     **
65184     **         EOF <- 0
65185     **         X <- A
65186     **         goto B
65187     **      A: setup for the SELECT
65188     **         loop over the tables in the SELECT
65189     **           load value into register R..R+n
65190     **           yield X
65191     **         end loop
65192     **         cleanup after the SELECT
65193     **         EOF <- 1
65194     **         yield X
65195     **         halt-error
65196     **
65197     ** On each invocation of the co-routine, it puts a single row of the
65198     ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
65199     ** (These output registers are allocated by sqlite3Select().)  When
65200     ** the SELECT completes, it sets the EOF flag stored in regEof.
65201     */
65202     int rc, j1;
65203
65204     regEof = ++pParse->nMem;
65205     sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
65206     VdbeComment((v, "SELECT eof flag"));
65207     sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
65208     addrSelect = sqlite3VdbeCurrentAddr(v)+2;
65209     sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
65210     j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
65211     VdbeComment((v, "Jump over SELECT coroutine"));
65212
65213     /* Resolve the expressions in the SELECT statement and execute it. */
65214     rc = sqlite3Select(pParse, pSelect, &dest);
65215     if( rc || pParse->nErr || db->mallocFailed ){
65216       goto insert_cleanup;
65217     }
65218     sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
65219     sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
65220     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
65221     VdbeComment((v, "End of SELECT coroutine"));
65222     sqlite3VdbeJumpHere(v, j1);                          /* label B: */
65223
65224     regFromSelect = dest.iMem;
65225     assert( pSelect->pEList );
65226     nColumn = pSelect->pEList->nExpr;
65227     assert( dest.nMem==nColumn );
65228
65229     /* Set useTempTable to TRUE if the result of the SELECT statement
65230     ** should be written into a temporary table (template 4).  Set to
65231     ** FALSE if each* row of the SELECT can be written directly into
65232     ** the destination table (template 3).
65233     **
65234     ** A temp table must be used if the table being updated is also one
65235     ** of the tables being read by the SELECT statement.  Also use a 
65236     ** temp table in the case of row triggers.
65237     */
65238     if( triggers_exist || readsTable(v, addrSelect, iDb, pTab) ){
65239       useTempTable = 1;
65240     }
65241
65242     if( useTempTable ){
65243       /* Invoke the coroutine to extract information from the SELECT
65244       ** and add it to a transient table srcTab.  The code generated
65245       ** here is from the 4th template:
65246       **
65247       **      B: open temp table
65248       **      L: yield X
65249       **         if EOF goto M
65250       **         insert row from R..R+n into temp table
65251       **         goto L
65252       **      M: ...
65253       */
65254       int regRec;      /* Register to hold packed record */
65255       int regRowid;    /* Register to hold temp table ROWID */
65256       int addrTop;     /* Label "L" */
65257       int addrIf;      /* Address of jump to M */
65258
65259       srcTab = pParse->nTab++;
65260       regRec = sqlite3GetTempReg(pParse);
65261       regRowid = sqlite3GetTempReg(pParse);
65262       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
65263       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
65264       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
65265       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
65266       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regRowid);
65267       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regRowid);
65268       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
65269       sqlite3VdbeJumpHere(v, addrIf);
65270       sqlite3ReleaseTempReg(pParse, regRec);
65271       sqlite3ReleaseTempReg(pParse, regRowid);
65272     }
65273   }else{
65274     /* This is the case if the data for the INSERT is coming from a VALUES
65275     ** clause
65276     */
65277     NameContext sNC;
65278     memset(&sNC, 0, sizeof(sNC));
65279     sNC.pParse = pParse;
65280     srcTab = -1;
65281     assert( useTempTable==0 );
65282     nColumn = pList ? pList->nExpr : 0;
65283     for(i=0; i<nColumn; i++){
65284       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
65285         goto insert_cleanup;
65286       }
65287     }
65288   }
65289
65290   /* Make sure the number of columns in the source data matches the number
65291   ** of columns to be inserted into the table.
65292   */
65293   if( IsVirtual(pTab) ){
65294     for(i=0; i<pTab->nCol; i++){
65295       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
65296     }
65297   }
65298   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
65299     sqlite3ErrorMsg(pParse, 
65300        "table %S has %d columns but %d values were supplied",
65301        pTabList, 0, pTab->nCol, nColumn);
65302     goto insert_cleanup;
65303   }
65304   if( pColumn!=0 && nColumn!=pColumn->nId ){
65305     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
65306     goto insert_cleanup;
65307   }
65308
65309   /* If the INSERT statement included an IDLIST term, then make sure
65310   ** all elements of the IDLIST really are columns of the table and 
65311   ** remember the column indices.
65312   **
65313   ** If the table has an INTEGER PRIMARY KEY column and that column
65314   ** is named in the IDLIST, then record in the keyColumn variable
65315   ** the index into IDLIST of the primary key column.  keyColumn is
65316   ** the index of the primary key as it appears in IDLIST, not as
65317   ** is appears in the original table.  (The index of the primary
65318   ** key in the original table is pTab->iPKey.)
65319   */
65320   if( pColumn ){
65321     for(i=0; i<pColumn->nId; i++){
65322       pColumn->a[i].idx = -1;
65323     }
65324     for(i=0; i<pColumn->nId; i++){
65325       for(j=0; j<pTab->nCol; j++){
65326         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
65327           pColumn->a[i].idx = j;
65328           if( j==pTab->iPKey ){
65329             keyColumn = i;
65330           }
65331           break;
65332         }
65333       }
65334       if( j>=pTab->nCol ){
65335         if( sqlite3IsRowid(pColumn->a[i].zName) ){
65336           keyColumn = i;
65337         }else{
65338           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
65339               pTabList, 0, pColumn->a[i].zName);
65340           pParse->nErr++;
65341           goto insert_cleanup;
65342         }
65343       }
65344     }
65345   }
65346
65347   /* If there is no IDLIST term but the table has an integer primary
65348   ** key, the set the keyColumn variable to the primary key column index
65349   ** in the original table definition.
65350   */
65351   if( pColumn==0 && nColumn>0 ){
65352     keyColumn = pTab->iPKey;
65353   }
65354
65355   /* Open the temp table for FOR EACH ROW triggers
65356   */
65357   if( triggers_exist ){
65358     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
65359     sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0);
65360   }
65361     
65362   /* Initialize the count of rows to be inserted
65363   */
65364   if( db->flags & SQLITE_CountRows ){
65365     regRowCount = ++pParse->nMem;
65366     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
65367   }
65368
65369   /* If this is not a view, open the table and and all indices */
65370   if( !isView ){
65371     int nIdx;
65372     int i;
65373
65374     baseCur = pParse->nTab;
65375     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
65376     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
65377     if( aRegIdx==0 ){
65378       goto insert_cleanup;
65379     }
65380     for(i=0; i<nIdx; i++){
65381       aRegIdx[i] = ++pParse->nMem;
65382     }
65383   }
65384
65385   /* This is the top of the main insertion loop */
65386   if( useTempTable ){
65387     /* This block codes the top of loop only.  The complete loop is the
65388     ** following pseudocode (template 4):
65389     **
65390     **         rewind temp table
65391     **      C: loop over rows of intermediate table
65392     **           transfer values form intermediate table into <table>
65393     **         end loop
65394     **      D: ...
65395     */
65396     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
65397     addrCont = sqlite3VdbeCurrentAddr(v);
65398   }else if( pSelect ){
65399     /* This block codes the top of loop only.  The complete loop is the
65400     ** following pseudocode (template 3):
65401     **
65402     **      C: yield X
65403     **         if EOF goto D
65404     **         insert the select result into <table> from R..R+n
65405     **         goto C
65406     **      D: ...
65407     */
65408     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
65409     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
65410   }
65411
65412   /* Allocate registers for holding the rowid of the new row,
65413   ** the content of the new row, and the assemblied row record.
65414   */
65415   regRecord = ++pParse->nMem;
65416   regRowid = regIns = pParse->nMem+1;
65417   pParse->nMem += pTab->nCol + 1;
65418   if( IsVirtual(pTab) ){
65419     regRowid++;
65420     pParse->nMem++;
65421   }
65422   regData = regRowid+1;
65423
65424   /* Run the BEFORE and INSTEAD OF triggers, if there are any
65425   */
65426   endOfLoop = sqlite3VdbeMakeLabel(v);
65427   if( triggers_exist & TRIGGER_BEFORE ){
65428     int regRowid;
65429     int regCols;
65430     int regRec;
65431
65432     /* build the NEW.* reference row.  Note that if there is an INTEGER
65433     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
65434     ** translated into a unique ID for the row.  But on a BEFORE trigger,
65435     ** we do not know what the unique ID will be (because the insert has
65436     ** not happened yet) so we substitute a rowid of -1
65437     */
65438     regRowid = sqlite3GetTempReg(pParse);
65439     if( keyColumn<0 ){
65440       sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
65441     }else if( useTempTable ){
65442       sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
65443     }else{
65444       int j1;
65445       assert( pSelect==0 );  /* Otherwise useTempTable is true */
65446       sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
65447       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
65448       sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
65449       sqlite3VdbeJumpHere(v, j1);
65450       sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
65451     }
65452
65453     /* Cannot have triggers on a virtual table. If it were possible,
65454     ** this block would have to account for hidden column.
65455     */
65456     assert(!IsVirtual(pTab));
65457
65458     /* Create the new column data
65459     */
65460     regCols = sqlite3GetTempRange(pParse, pTab->nCol);
65461     for(i=0; i<pTab->nCol; i++){
65462       if( pColumn==0 ){
65463         j = i;
65464       }else{
65465         for(j=0; j<pColumn->nId; j++){
65466           if( pColumn->a[j].idx==i ) break;
65467         }
65468       }
65469       if( pColumn && j>=pColumn->nId ){
65470         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i);
65471       }else if( useTempTable ){
65472         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i); 
65473       }else{
65474         assert( pSelect==0 ); /* Otherwise useTempTable is true */
65475         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i);
65476       }
65477     }
65478     regRec = sqlite3GetTempReg(pParse);
65479     sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRec);
65480
65481     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
65482     ** do not attempt any conversions before assembling the record.
65483     ** If this is a real table, attempt conversions as required by the
65484     ** table column affinities.
65485     */
65486     if( !isView ){
65487       sqlite3TableAffinityStr(v, pTab);
65488     }
65489     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid);
65490     sqlite3ReleaseTempReg(pParse, regRec);
65491     sqlite3ReleaseTempReg(pParse, regRowid);
65492     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol);
65493
65494     /* Fire BEFORE or INSTEAD OF triggers */
65495     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab, 
65496         newIdx, -1, onError, endOfLoop, 0, 0) ){
65497       goto insert_cleanup;
65498     }
65499   }
65500
65501   /* Push the record number for the new entry onto the stack.  The
65502   ** record number is a randomly generate integer created by NewRowid
65503   ** except when the table has an INTEGER PRIMARY KEY column, in which
65504   ** case the record number is the same as that column. 
65505   */
65506   if( !isView ){
65507     if( IsVirtual(pTab) ){
65508       /* The row that the VUpdate opcode will delete: none */
65509       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
65510     }
65511     if( keyColumn>=0 ){
65512       if( useTempTable ){
65513         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
65514       }else if( pSelect ){
65515         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
65516       }else{
65517         VdbeOp *pOp;
65518         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
65519         pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
65520         if( pOp && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
65521           appendFlag = 1;
65522           pOp->opcode = OP_NewRowid;
65523           pOp->p1 = baseCur;
65524           pOp->p2 = regRowid;
65525           pOp->p3 = regAutoinc;
65526         }
65527       }
65528       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
65529       ** to generate a unique primary key value.
65530       */
65531       if( !appendFlag ){
65532         int j1;
65533         if( !IsVirtual(pTab) ){
65534           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
65535           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
65536           sqlite3VdbeJumpHere(v, j1);
65537         }else{
65538           j1 = sqlite3VdbeCurrentAddr(v);
65539           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
65540         }
65541         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
65542       }
65543     }else if( IsVirtual(pTab) ){
65544       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
65545     }else{
65546       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
65547       appendFlag = 1;
65548     }
65549     autoIncStep(pParse, regAutoinc, regRowid);
65550
65551     /* Push onto the stack, data for all columns of the new entry, beginning
65552     ** with the first column.
65553     */
65554     nHidden = 0;
65555     for(i=0; i<pTab->nCol; i++){
65556       int iRegStore = regRowid+1+i;
65557       if( i==pTab->iPKey ){
65558         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
65559         ** Whenever this column is read, the record number will be substituted
65560         ** in its place.  So will fill this column with a NULL to avoid
65561         ** taking up data space with information that will never be used. */
65562         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
65563         continue;
65564       }
65565       if( pColumn==0 ){
65566         if( IsHiddenColumn(&pTab->aCol[i]) ){
65567           assert( IsVirtual(pTab) );
65568           j = -1;
65569           nHidden++;
65570         }else{
65571           j = i - nHidden;
65572         }
65573       }else{
65574         for(j=0; j<pColumn->nId; j++){
65575           if( pColumn->a[j].idx==i ) break;
65576         }
65577       }
65578       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
65579         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
65580       }else if( useTempTable ){
65581         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
65582       }else if( pSelect ){
65583         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
65584       }else{
65585         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
65586       }
65587     }
65588
65589     /* Generate code to check constraints and generate index keys and
65590     ** do the insertion.
65591     */
65592 #ifndef SQLITE_OMIT_VIRTUALTABLE
65593     if( IsVirtual(pTab) ){
65594       sqlite3VtabMakeWritable(pParse, pTab);
65595       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns,
65596                      (const char*)pTab->pVtab, P4_VTAB);
65597     }else
65598 #endif
65599     {
65600       sqlite3GenerateConstraintChecks(
65601           pParse,
65602           pTab,
65603           baseCur,
65604           regIns,
65605           aRegIdx,
65606           keyColumn>=0,
65607           0,
65608           onError,
65609           endOfLoop
65610       );
65611       sqlite3CompleteInsertion(
65612           pParse,
65613           pTab,
65614           baseCur,
65615           regIns,
65616           aRegIdx,
65617           0,
65618           (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
65619           appendFlag
65620        );
65621     }
65622   }
65623
65624   /* Update the count of rows that are inserted
65625   */
65626   if( (db->flags & SQLITE_CountRows)!=0 ){
65627     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
65628   }
65629
65630   if( triggers_exist ){
65631     /* Code AFTER triggers */
65632     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
65633           newIdx, -1, onError, endOfLoop, 0, 0) ){
65634       goto insert_cleanup;
65635     }
65636   }
65637
65638   /* The bottom of the main insertion loop, if the data source
65639   ** is a SELECT statement.
65640   */
65641   sqlite3VdbeResolveLabel(v, endOfLoop);
65642   if( useTempTable ){
65643     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
65644     sqlite3VdbeJumpHere(v, addrInsTop);
65645     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
65646   }else if( pSelect ){
65647     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
65648     sqlite3VdbeJumpHere(v, addrInsTop);
65649   }
65650
65651   if( !IsVirtual(pTab) && !isView ){
65652     /* Close all tables opened */
65653     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
65654     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
65655       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
65656     }
65657   }
65658
65659   /* Update the sqlite_sequence table by storing the content of the
65660   ** counter value in memory regAutoinc back into the sqlite_sequence
65661   ** table.
65662   */
65663   autoIncEnd(pParse, iDb, pTab, regAutoinc);
65664
65665   /*
65666   ** Return the number of rows inserted. If this routine is 
65667   ** generating code because of a call to sqlite3NestedParse(), do not
65668   ** invoke the callback function.
65669   */
65670   if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
65671     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
65672     sqlite3VdbeSetNumCols(v, 1);
65673     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
65674   }
65675
65676 insert_cleanup:
65677   sqlite3SrcListDelete(db, pTabList);
65678   sqlite3ExprListDelete(db, pList);
65679   sqlite3SelectDelete(db, pSelect);
65680   sqlite3IdListDelete(db, pColumn);
65681   sqlite3DbFree(db, aRegIdx);
65682 }
65683
65684 /*
65685 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
65686 **
65687 ** The input is a range of consecutive registers as follows:
65688 **
65689 **    1.  The rowid of the row to be updated before the update.  This
65690 **        value is omitted unless we are doing an UPDATE that involves a
65691 **        change to the record number or writing to a virtual table.
65692 **
65693 **    2.  The rowid of the row after the update.
65694 **
65695 **    3.  The data in the first column of the entry after the update.
65696 **
65697 **    i.  Data from middle columns...
65698 **
65699 **    N.  The data in the last column of the entry after the update.
65700 **
65701 ** The regRowid parameter is the index of the register containing (2).
65702 **
65703 ** The old rowid shown as entry (1) above is omitted unless both isUpdate
65704 ** and rowidChng are 1.  isUpdate is true for UPDATEs and false for
65705 ** INSERTs.  RowidChng means that the new rowid is explicitly specified by
65706 ** the update or insert statement.  If rowidChng is false, it means that
65707 ** the rowid is computed automatically in an insert or that the rowid value
65708 ** is not modified by the update.
65709 **
65710 ** The code generated by this routine store new index entries into
65711 ** registers identified by aRegIdx[].  No index entry is created for
65712 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
65713 ** the same as the order of indices on the linked list of indices
65714 ** attached to the table.
65715 **
65716 ** This routine also generates code to check constraints.  NOT NULL,
65717 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
65718 ** then the appropriate action is performed.  There are five possible
65719 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
65720 **
65721 **  Constraint type  Action       What Happens
65722 **  ---------------  ----------   ----------------------------------------
65723 **  any              ROLLBACK     The current transaction is rolled back and
65724 **                                sqlite3_exec() returns immediately with a
65725 **                                return code of SQLITE_CONSTRAINT.
65726 **
65727 **  any              ABORT        Back out changes from the current command
65728 **                                only (do not do a complete rollback) then
65729 **                                cause sqlite3_exec() to return immediately
65730 **                                with SQLITE_CONSTRAINT.
65731 **
65732 **  any              FAIL         Sqlite_exec() returns immediately with a
65733 **                                return code of SQLITE_CONSTRAINT.  The
65734 **                                transaction is not rolled back and any
65735 **                                prior changes are retained.
65736 **
65737 **  any              IGNORE       The record number and data is popped from
65738 **                                the stack and there is an immediate jump
65739 **                                to label ignoreDest.
65740 **
65741 **  NOT NULL         REPLACE      The NULL value is replace by the default
65742 **                                value for that column.  If the default value
65743 **                                is NULL, the action is the same as ABORT.
65744 **
65745 **  UNIQUE           REPLACE      The other row that conflicts with the row
65746 **                                being inserted is removed.
65747 **
65748 **  CHECK            REPLACE      Illegal.  The results in an exception.
65749 **
65750 ** Which action to take is determined by the overrideError parameter.
65751 ** Or if overrideError==OE_Default, then the pParse->onError parameter
65752 ** is used.  Or if pParse->onError==OE_Default then the onError value
65753 ** for the constraint is used.
65754 **
65755 ** The calling routine must open a read/write cursor for pTab with
65756 ** cursor number "baseCur".  All indices of pTab must also have open
65757 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
65758 ** Except, if there is no possibility of a REPLACE action then
65759 ** cursors do not need to be open for indices where aRegIdx[i]==0.
65760 */
65761 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
65762   Parse *pParse,      /* The parser context */
65763   Table *pTab,        /* the table into which we are inserting */
65764   int baseCur,        /* Index of a read/write cursor pointing at pTab */
65765   int regRowid,       /* Index of the range of input registers */
65766   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
65767   int rowidChng,      /* True if the rowid might collide with existing entry */
65768   int isUpdate,       /* True for UPDATE, False for INSERT */
65769   int overrideError,  /* Override onError to this if not OE_Default */
65770   int ignoreDest      /* Jump to this label on an OE_Ignore resolution */
65771 ){
65772   int i;
65773   Vdbe *v;
65774   int nCol;
65775   int onError;
65776   int j1, j2, j3;     /* Addresses of jump instructions */
65777   int regData;        /* Register containing first data column */
65778   int iCur;
65779   Index *pIdx;
65780   int seenReplace = 0;
65781   int hasTwoRowids = (isUpdate && rowidChng);
65782
65783   v = sqlite3GetVdbe(pParse);
65784   assert( v!=0 );
65785   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
65786   nCol = pTab->nCol;
65787   regData = regRowid + 1;
65788
65789
65790   /* Test all NOT NULL constraints.
65791   */
65792   for(i=0; i<nCol; i++){
65793     if( i==pTab->iPKey ){
65794       continue;
65795     }
65796     onError = pTab->aCol[i].notNull;
65797     if( onError==OE_None ) continue;
65798     if( overrideError!=OE_Default ){
65799       onError = overrideError;
65800     }else if( onError==OE_Default ){
65801       onError = OE_Abort;
65802     }
65803     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
65804       onError = OE_Abort;
65805     }
65806     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
65807     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
65808         || onError==OE_Ignore || onError==OE_Replace );
65809     switch( onError ){
65810       case OE_Rollback:
65811       case OE_Abort:
65812       case OE_Fail: {
65813         char *zMsg;
65814         sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
65815         zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
65816                               pTab->zName, pTab->aCol[i].zName);
65817         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
65818         break;
65819       }
65820       case OE_Ignore: {
65821         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
65822         break;
65823       }
65824       case OE_Replace: {
65825         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
65826         break;
65827       }
65828     }
65829     sqlite3VdbeJumpHere(v, j1);
65830   }
65831
65832   /* Test all CHECK constraints
65833   */
65834 #ifndef SQLITE_OMIT_CHECK
65835   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
65836     int allOk = sqlite3VdbeMakeLabel(v);
65837     pParse->ckBase = regData;
65838     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
65839     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
65840     if( onError==OE_Ignore ){
65841       sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
65842     }else{
65843       sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
65844     }
65845     sqlite3VdbeResolveLabel(v, allOk);
65846   }
65847 #endif /* !defined(SQLITE_OMIT_CHECK) */
65848
65849   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
65850   ** of the new record does not previously exist.  Except, if this
65851   ** is an UPDATE and the primary key is not changing, that is OK.
65852   */
65853   if( rowidChng ){
65854     onError = pTab->keyConf;
65855     if( overrideError!=OE_Default ){
65856       onError = overrideError;
65857     }else if( onError==OE_Default ){
65858       onError = OE_Abort;
65859     }
65860     
65861     if( onError!=OE_Replace || pTab->pIndex ){
65862       if( isUpdate ){
65863         j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, regRowid-1);
65864       }
65865       j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
65866       switch( onError ){
65867         default: {
65868           onError = OE_Abort;
65869           /* Fall thru into the next case */
65870         }
65871         case OE_Rollback:
65872         case OE_Abort:
65873         case OE_Fail: {
65874           sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
65875                            "PRIMARY KEY must be unique", P4_STATIC);
65876           break;
65877         }
65878         case OE_Replace: {
65879           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
65880           seenReplace = 1;
65881           break;
65882         }
65883         case OE_Ignore: {
65884           assert( seenReplace==0 );
65885           sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
65886           break;
65887         }
65888       }
65889       sqlite3VdbeJumpHere(v, j3);
65890       if( isUpdate ){
65891         sqlite3VdbeJumpHere(v, j2);
65892       }
65893     }
65894   }
65895
65896   /* Test all UNIQUE constraints by creating entries for each UNIQUE
65897   ** index and making sure that duplicate entries do not already exist.
65898   ** Add the new records to the indices as we go.
65899   */
65900   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
65901     int regIdx;
65902     int regR;
65903
65904     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
65905
65906     /* Create a key for accessing the index entry */
65907     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
65908     for(i=0; i<pIdx->nColumn; i++){
65909       int idx = pIdx->aiColumn[i];
65910       if( idx==pTab->iPKey ){
65911         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
65912       }else{
65913         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
65914       }
65915     }
65916     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
65917     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
65918     sqlite3IndexAffinityStr(v, pIdx);
65919     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
65920     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
65921
65922     /* Find out what action to take in case there is an indexing conflict */
65923     onError = pIdx->onError;
65924     if( onError==OE_None ) continue;  /* pIdx is not a UNIQUE index */
65925     if( overrideError!=OE_Default ){
65926       onError = overrideError;
65927     }else if( onError==OE_Default ){
65928       onError = OE_Abort;
65929     }
65930     if( seenReplace ){
65931       if( onError==OE_Ignore ) onError = OE_Replace;
65932       else if( onError==OE_Fail ) onError = OE_Abort;
65933     }
65934     
65935
65936     /* Check to see if the new index entry will be unique */
65937     j2 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdx, 0, pIdx->nColumn);
65938     regR = sqlite3GetTempReg(pParse);
65939     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid-hasTwoRowids, regR);
65940     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
65941                            regR, SQLITE_INT_TO_PTR(aRegIdx[iCur]),
65942                            P4_INT32);
65943
65944     /* Generate code that executes if the new index entry is not unique */
65945     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
65946         || onError==OE_Ignore || onError==OE_Replace );
65947     switch( onError ){
65948       case OE_Rollback:
65949       case OE_Abort:
65950       case OE_Fail: {
65951         int j, n1, n2;
65952         char zErrMsg[200];
65953         sqlite3_snprintf(ArraySize(zErrMsg), zErrMsg,
65954                          pIdx->nColumn>1 ? "columns " : "column ");
65955         n1 = strlen(zErrMsg);
65956         for(j=0; j<pIdx->nColumn && n1<ArraySize(zErrMsg)-30; j++){
65957           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
65958           n2 = strlen(zCol);
65959           if( j>0 ){
65960             sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], ", ");
65961             n1 += 2;
65962           }
65963           if( n1+n2>ArraySize(zErrMsg)-30 ){
65964             sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], "...");
65965             n1 += 3;
65966             break;
65967           }else{
65968             sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
65969             n1 += n2;
65970           }
65971         }
65972         sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], 
65973             pIdx->nColumn>1 ? " are not unique" : " is not unique");
65974         sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErrMsg,0);
65975         break;
65976       }
65977       case OE_Ignore: {
65978         assert( seenReplace==0 );
65979         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
65980         break;
65981       }
65982       case OE_Replace: {
65983         sqlite3GenerateRowDelete(pParse, pTab, baseCur, regR, 0);
65984         seenReplace = 1;
65985         break;
65986       }
65987     }
65988     sqlite3VdbeJumpHere(v, j2);
65989     sqlite3VdbeJumpHere(v, j3);
65990     sqlite3ReleaseTempReg(pParse, regR);
65991   }
65992 }
65993
65994 /*
65995 ** This routine generates code to finish the INSERT or UPDATE operation
65996 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
65997 ** A consecutive range of registers starting at regRowid contains the
65998 ** rowid and the content to be inserted.
65999 **
66000 ** The arguments to this routine should be the same as the first six
66001 ** arguments to sqlite3GenerateConstraintChecks.
66002 */
66003 SQLITE_PRIVATE void sqlite3CompleteInsertion(
66004   Parse *pParse,      /* The parser context */
66005   Table *pTab,        /* the table into which we are inserting */
66006   int baseCur,        /* Index of a read/write cursor pointing at pTab */
66007   int regRowid,       /* Range of content */
66008   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
66009   int isUpdate,       /* True for UPDATE, False for INSERT */
66010   int newIdx,         /* Index of NEW table for triggers.  -1 if none */
66011   int appendBias      /* True if this is likely to be an append */
66012 ){
66013   int i;
66014   Vdbe *v;
66015   int nIdx;
66016   Index *pIdx;
66017   int pik_flags;
66018   int regData;
66019   int regRec;
66020
66021   v = sqlite3GetVdbe(pParse);
66022   assert( v!=0 );
66023   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
66024   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
66025   for(i=nIdx-1; i>=0; i--){
66026     if( aRegIdx[i]==0 ) continue;
66027     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
66028   }
66029   regData = regRowid + 1;
66030   regRec = sqlite3GetTempReg(pParse);
66031   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
66032   sqlite3TableAffinityStr(v, pTab);
66033   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
66034 #ifndef SQLITE_OMIT_TRIGGER
66035   if( newIdx>=0 ){
66036     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid);
66037   }
66038 #endif
66039   if( pParse->nested ){
66040     pik_flags = 0;
66041   }else{
66042     pik_flags = OPFLAG_NCHANGE;
66043     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
66044   }
66045   if( appendBias ){
66046     pik_flags |= OPFLAG_APPEND;
66047   }
66048   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
66049   if( !pParse->nested ){
66050     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
66051   }
66052   sqlite3VdbeChangeP5(v, pik_flags);
66053 }
66054
66055 /*
66056 ** Generate code that will open cursors for a table and for all
66057 ** indices of that table.  The "baseCur" parameter is the cursor number used
66058 ** for the table.  Indices are opened on subsequent cursors.
66059 **
66060 ** Return the number of indices on the table.
66061 */
66062 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
66063   Parse *pParse,   /* Parsing context */
66064   Table *pTab,     /* Table to be opened */
66065   int baseCur,     /* Cursor number assigned to the table */
66066   int op           /* OP_OpenRead or OP_OpenWrite */
66067 ){
66068   int i;
66069   int iDb;
66070   Index *pIdx;
66071   Vdbe *v;
66072
66073   if( IsVirtual(pTab) ) return 0;
66074   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
66075   v = sqlite3GetVdbe(pParse);
66076   assert( v!=0 );
66077   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
66078   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
66079     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
66080     assert( pIdx->pSchema==pTab->pSchema );
66081     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
66082                       (char*)pKey, P4_KEYINFO_HANDOFF);
66083     VdbeComment((v, "%s", pIdx->zName));
66084   }
66085   if( pParse->nTab<=baseCur+i ){
66086     pParse->nTab = baseCur+i;
66087   }
66088   return i-1;
66089 }
66090
66091
66092 #ifdef SQLITE_TEST
66093 /*
66094 ** The following global variable is incremented whenever the
66095 ** transfer optimization is used.  This is used for testing
66096 ** purposes only - to make sure the transfer optimization really
66097 ** is happening when it is suppose to.
66098 */
66099 SQLITE_API int sqlite3_xferopt_count;
66100 #endif /* SQLITE_TEST */
66101
66102
66103 #ifndef SQLITE_OMIT_XFER_OPT
66104 /*
66105 ** Check to collation names to see if they are compatible.
66106 */
66107 static int xferCompatibleCollation(const char *z1, const char *z2){
66108   if( z1==0 ){
66109     return z2==0;
66110   }
66111   if( z2==0 ){
66112     return 0;
66113   }
66114   return sqlite3StrICmp(z1, z2)==0;
66115 }
66116
66117
66118 /*
66119 ** Check to see if index pSrc is compatible as a source of data
66120 ** for index pDest in an insert transfer optimization.  The rules
66121 ** for a compatible index:
66122 **
66123 **    *   The index is over the same set of columns
66124 **    *   The same DESC and ASC markings occurs on all columns
66125 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
66126 **    *   The same collating sequence on each column
66127 */
66128 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
66129   int i;
66130   assert( pDest && pSrc );
66131   assert( pDest->pTable!=pSrc->pTable );
66132   if( pDest->nColumn!=pSrc->nColumn ){
66133     return 0;   /* Different number of columns */
66134   }
66135   if( pDest->onError!=pSrc->onError ){
66136     return 0;   /* Different conflict resolution strategies */
66137   }
66138   for(i=0; i<pSrc->nColumn; i++){
66139     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
66140       return 0;   /* Different columns indexed */
66141     }
66142     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
66143       return 0;   /* Different sort orders */
66144     }
66145     if( pSrc->azColl[i]!=pDest->azColl[i] ){
66146       return 0;   /* Different collating sequences */
66147     }
66148   }
66149
66150   /* If no test above fails then the indices must be compatible */
66151   return 1;
66152 }
66153
66154 /*
66155 ** Attempt the transfer optimization on INSERTs of the form
66156 **
66157 **     INSERT INTO tab1 SELECT * FROM tab2;
66158 **
66159 ** This optimization is only attempted if
66160 **
66161 **    (1)  tab1 and tab2 have identical schemas including all the
66162 **         same indices and constraints
66163 **
66164 **    (2)  tab1 and tab2 are different tables
66165 **
66166 **    (3)  There must be no triggers on tab1
66167 **
66168 **    (4)  The result set of the SELECT statement is "*"
66169 **
66170 **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
66171 **         or LIMIT clause.
66172 **
66173 **    (6)  The SELECT statement is a simple (not a compound) select that
66174 **         contains only tab2 in its FROM clause
66175 **
66176 ** This method for implementing the INSERT transfers raw records from
66177 ** tab2 over to tab1.  The columns are not decoded.  Raw records from
66178 ** the indices of tab2 are transfered to tab1 as well.  In so doing,
66179 ** the resulting tab1 has much less fragmentation.
66180 **
66181 ** This routine returns TRUE if the optimization is attempted.  If any
66182 ** of the conditions above fail so that the optimization should not
66183 ** be attempted, then this routine returns FALSE.
66184 */
66185 static int xferOptimization(
66186   Parse *pParse,        /* Parser context */
66187   Table *pDest,         /* The table we are inserting into */
66188   Select *pSelect,      /* A SELECT statement to use as the data source */
66189   int onError,          /* How to handle constraint errors */
66190   int iDbDest           /* The database of pDest */
66191 ){
66192   ExprList *pEList;                /* The result set of the SELECT */
66193   Table *pSrc;                     /* The table in the FROM clause of SELECT */
66194   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
66195   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
66196   int i;                           /* Loop counter */
66197   int iDbSrc;                      /* The database of pSrc */
66198   int iSrc, iDest;                 /* Cursors from source and destination */
66199   int addr1, addr2;                /* Loop addresses */
66200   int emptyDestTest;               /* Address of test for empty pDest */
66201   int emptySrcTest;                /* Address of test for empty pSrc */
66202   Vdbe *v;                         /* The VDBE we are building */
66203   KeyInfo *pKey;                   /* Key information for an index */
66204   int regAutoinc;                  /* Memory register used by AUTOINC */
66205   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
66206   int regData, regRowid;           /* Registers holding data and rowid */
66207
66208   if( pSelect==0 ){
66209     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
66210   }
66211   if( pDest->pTrigger ){
66212     return 0;   /* tab1 must not have triggers */
66213   }
66214 #ifndef SQLITE_OMIT_VIRTUALTABLE
66215   if( pDest->tabFlags & TF_Virtual ){
66216     return 0;   /* tab1 must not be a virtual table */
66217   }
66218 #endif
66219   if( onError==OE_Default ){
66220     onError = OE_Abort;
66221   }
66222   if( onError!=OE_Abort && onError!=OE_Rollback ){
66223     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
66224   }
66225   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
66226   if( pSelect->pSrc->nSrc!=1 ){
66227     return 0;   /* FROM clause must have exactly one term */
66228   }
66229   if( pSelect->pSrc->a[0].pSelect ){
66230     return 0;   /* FROM clause cannot contain a subquery */
66231   }
66232   if( pSelect->pWhere ){
66233     return 0;   /* SELECT may not have a WHERE clause */
66234   }
66235   if( pSelect->pOrderBy ){
66236     return 0;   /* SELECT may not have an ORDER BY clause */
66237   }
66238   /* Do not need to test for a HAVING clause.  If HAVING is present but
66239   ** there is no ORDER BY, we will get an error. */
66240   if( pSelect->pGroupBy ){
66241     return 0;   /* SELECT may not have a GROUP BY clause */
66242   }
66243   if( pSelect->pLimit ){
66244     return 0;   /* SELECT may not have a LIMIT clause */
66245   }
66246   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
66247   if( pSelect->pPrior ){
66248     return 0;   /* SELECT may not be a compound query */
66249   }
66250   if( pSelect->selFlags & SF_Distinct ){
66251     return 0;   /* SELECT may not be DISTINCT */
66252   }
66253   pEList = pSelect->pEList;
66254   assert( pEList!=0 );
66255   if( pEList->nExpr!=1 ){
66256     return 0;   /* The result set must have exactly one column */
66257   }
66258   assert( pEList->a[0].pExpr );
66259   if( pEList->a[0].pExpr->op!=TK_ALL ){
66260     return 0;   /* The result set must be the special operator "*" */
66261   }
66262
66263   /* At this point we have established that the statement is of the
66264   ** correct syntactic form to participate in this optimization.  Now
66265   ** we have to check the semantics.
66266   */
66267   pItem = pSelect->pSrc->a;
66268   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
66269   if( pSrc==0 ){
66270     return 0;   /* FROM clause does not contain a real table */
66271   }
66272   if( pSrc==pDest ){
66273     return 0;   /* tab1 and tab2 may not be the same table */
66274   }
66275 #ifndef SQLITE_OMIT_VIRTUALTABLE
66276   if( pSrc->tabFlags & TF_Virtual ){
66277     return 0;   /* tab2 must not be a virtual table */
66278   }
66279 #endif
66280   if( pSrc->pSelect ){
66281     return 0;   /* tab2 may not be a view */
66282   }
66283   if( pDest->nCol!=pSrc->nCol ){
66284     return 0;   /* Number of columns must be the same in tab1 and tab2 */
66285   }
66286   if( pDest->iPKey!=pSrc->iPKey ){
66287     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
66288   }
66289   for(i=0; i<pDest->nCol; i++){
66290     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
66291       return 0;    /* Affinity must be the same on all columns */
66292     }
66293     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
66294       return 0;    /* Collating sequence must be the same on all columns */
66295     }
66296     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
66297       return 0;    /* tab2 must be NOT NULL if tab1 is */
66298     }
66299   }
66300   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
66301     if( pDestIdx->onError!=OE_None ){
66302       destHasUniqueIdx = 1;
66303     }
66304     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
66305       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
66306     }
66307     if( pSrcIdx==0 ){
66308       return 0;    /* pDestIdx has no corresponding index in pSrc */
66309     }
66310   }
66311 #ifndef SQLITE_OMIT_CHECK
66312   if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
66313     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
66314   }
66315 #endif
66316
66317   /* If we get this far, it means either:
66318   **
66319   **    *   We can always do the transfer if the table contains an
66320   **        an integer primary key
66321   **
66322   **    *   We can conditionally do the transfer if the destination
66323   **        table is empty.
66324   */
66325 #ifdef SQLITE_TEST
66326   sqlite3_xferopt_count++;
66327 #endif
66328   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
66329   v = sqlite3GetVdbe(pParse);
66330   sqlite3CodeVerifySchema(pParse, iDbSrc);
66331   iSrc = pParse->nTab++;
66332   iDest = pParse->nTab++;
66333   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
66334   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
66335   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
66336     /* If tables do not have an INTEGER PRIMARY KEY and there
66337     ** are indices to be copied and the destination is not empty,
66338     ** we have to disallow the transfer optimization because the
66339     ** the rowids might change which will mess up indexing.
66340     **
66341     ** Or if the destination has a UNIQUE index and is not empty,
66342     ** we also disallow the transfer optimization because we cannot
66343     ** insure that all entries in the union of DEST and SRC will be
66344     ** unique.
66345     */
66346     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
66347     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
66348     sqlite3VdbeJumpHere(v, addr1);
66349   }else{
66350     emptyDestTest = 0;
66351   }
66352   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
66353   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
66354   regData = sqlite3GetTempReg(pParse);
66355   regRowid = sqlite3GetTempReg(pParse);
66356   if( pDest->iPKey>=0 ){
66357     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
66358     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
66359     sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
66360                       "PRIMARY KEY must be unique", P4_STATIC);
66361     sqlite3VdbeJumpHere(v, addr2);
66362     autoIncStep(pParse, regAutoinc, regRowid);
66363   }else if( pDest->pIndex==0 ){
66364     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
66365   }else{
66366     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
66367     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
66368   }
66369   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
66370   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
66371   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
66372   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
66373   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
66374   autoIncEnd(pParse, iDbDest, pDest, regAutoinc);
66375   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
66376     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
66377       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
66378     }
66379     assert( pSrcIdx );
66380     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
66381     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
66382     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
66383     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
66384                       (char*)pKey, P4_KEYINFO_HANDOFF);
66385     VdbeComment((v, "%s", pSrcIdx->zName));
66386     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
66387     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
66388                       (char*)pKey, P4_KEYINFO_HANDOFF);
66389     VdbeComment((v, "%s", pDestIdx->zName));
66390     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
66391     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
66392     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
66393     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
66394     sqlite3VdbeJumpHere(v, addr1);
66395   }
66396   sqlite3VdbeJumpHere(v, emptySrcTest);
66397   sqlite3ReleaseTempReg(pParse, regRowid);
66398   sqlite3ReleaseTempReg(pParse, regData);
66399   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
66400   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
66401   if( emptyDestTest ){
66402     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
66403     sqlite3VdbeJumpHere(v, emptyDestTest);
66404     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
66405     return 0;
66406   }else{
66407     return 1;
66408   }
66409 }
66410 #endif /* SQLITE_OMIT_XFER_OPT */
66411
66412 /* Make sure "isView" gets undefined in case this file becomes part of
66413 ** the amalgamation - so that subsequent files do not see isView as a
66414 ** macro. */
66415 #undef isView
66416
66417 /************** End of insert.c **********************************************/
66418 /************** Begin file legacy.c ******************************************/
66419 /*
66420 ** 2001 September 15
66421 **
66422 ** The author disclaims copyright to this source code.  In place of
66423 ** a legal notice, here is a blessing:
66424 **
66425 **    May you do good and not evil.
66426 **    May you find forgiveness for yourself and forgive others.
66427 **    May you share freely, never taking more than you give.
66428 **
66429 *************************************************************************
66430 ** Main file for the SQLite library.  The routines in this file
66431 ** implement the programmer interface to the library.  Routines in
66432 ** other files are for internal use by SQLite and should not be
66433 ** accessed by users of the library.
66434 **
66435 ** $Id: legacy.c,v 1.29 2008/08/02 03:50:39 drh Exp $
66436 */
66437
66438
66439 /*
66440 ** Execute SQL code.  Return one of the SQLITE_ success/failure
66441 ** codes.  Also write an error message into memory obtained from
66442 ** malloc() and make *pzErrMsg point to that message.
66443 **
66444 ** If the SQL is a query, then for each row in the query result
66445 ** the xCallback() function is called.  pArg becomes the first
66446 ** argument to xCallback().  If xCallback=NULL then no callback
66447 ** is invoked, even for queries.
66448 */
66449 SQLITE_API int sqlite3_exec(
66450   sqlite3 *db,                /* The database on which the SQL executes */
66451   const char *zSql,           /* The SQL to be executed */
66452   sqlite3_callback xCallback, /* Invoke this callback routine */
66453   void *pArg,                 /* First argument to xCallback() */
66454   char **pzErrMsg             /* Write error messages here */
66455 ){
66456   int rc = SQLITE_OK;
66457   const char *zLeftover;
66458   sqlite3_stmt *pStmt = 0;
66459   char **azCols = 0;
66460
66461   int nRetry = 0;
66462   int nCallback;
66463
66464   if( zSql==0 ) zSql = "";
66465
66466   sqlite3_mutex_enter(db->mutex);
66467   sqlite3Error(db, SQLITE_OK, 0);
66468   while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
66469     int nCol;
66470     char **azVals = 0;
66471
66472     pStmt = 0;
66473     rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
66474     assert( rc==SQLITE_OK || pStmt==0 );
66475     if( rc!=SQLITE_OK ){
66476       continue;
66477     }
66478     if( !pStmt ){
66479       /* this happens for a comment or white-space */
66480       zSql = zLeftover;
66481       continue;
66482     }
66483
66484     nCallback = 0;
66485     nCol = sqlite3_column_count(pStmt);
66486
66487     while( 1 ){
66488       int i;
66489       rc = sqlite3_step(pStmt);
66490
66491       /* Invoke the callback function if required */
66492       if( xCallback && (SQLITE_ROW==rc || 
66493           (SQLITE_DONE==rc && !nCallback && db->flags&SQLITE_NullCallback)) ){
66494         if( 0==nCallback ){
66495           if( azCols==0 ){
66496             azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
66497             if( azCols==0 ){
66498               goto exec_out;
66499             }
66500           }
66501           for(i=0; i<nCol; i++){
66502             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
66503             /* sqlite3VdbeSetColName() installs column names as UTF8
66504             ** strings so there is no way for sqlite3_column_name() to fail. */
66505             assert( azCols[i]!=0 );
66506           }
66507           nCallback++;
66508         }
66509         if( rc==SQLITE_ROW ){
66510           azVals = &azCols[nCol];
66511           for(i=0; i<nCol; i++){
66512             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
66513             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
66514               db->mallocFailed = 1;
66515               goto exec_out;
66516             }
66517           }
66518         }
66519         if( xCallback(pArg, nCol, azVals, azCols) ){
66520           rc = SQLITE_ABORT;
66521           sqlite3_finalize(pStmt);
66522           pStmt = 0;
66523           sqlite3Error(db, SQLITE_ABORT, 0);
66524           goto exec_out;
66525         }
66526       }
66527
66528       if( rc!=SQLITE_ROW ){
66529         rc = sqlite3_finalize(pStmt);
66530         pStmt = 0;
66531         if( rc!=SQLITE_SCHEMA ){
66532           nRetry = 0;
66533           zSql = zLeftover;
66534           while( isspace((unsigned char)zSql[0]) ) zSql++;
66535         }
66536         break;
66537       }
66538     }
66539
66540     sqlite3DbFree(db, azCols);
66541     azCols = 0;
66542   }
66543
66544 exec_out:
66545   if( pStmt ) sqlite3_finalize(pStmt);
66546   sqlite3DbFree(db, azCols);
66547
66548   rc = sqlite3ApiExit(db, rc);
66549   if( rc!=SQLITE_OK && rc==sqlite3_errcode(db) && pzErrMsg ){
66550     int nErrMsg = 1 + strlen(sqlite3_errmsg(db));
66551     *pzErrMsg = sqlite3Malloc(nErrMsg);
66552     if( *pzErrMsg ){
66553       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
66554     }
66555   }else if( pzErrMsg ){
66556     *pzErrMsg = 0;
66557   }
66558
66559   assert( (rc&db->errMask)==rc );
66560   sqlite3_mutex_leave(db->mutex);
66561   return rc;
66562 }
66563
66564 /************** End of legacy.c **********************************************/
66565 /************** Begin file loadext.c *****************************************/
66566 /*
66567 ** 2006 June 7
66568 **
66569 ** The author disclaims copyright to this source code.  In place of
66570 ** a legal notice, here is a blessing:
66571 **
66572 **    May you do good and not evil.
66573 **    May you find forgiveness for yourself and forgive others.
66574 **    May you share freely, never taking more than you give.
66575 **
66576 *************************************************************************
66577 ** This file contains code used to dynamically load extensions into
66578 ** the SQLite library.
66579 **
66580 ** $Id: loadext.c,v 1.56 2008/10/12 00:27:53 shane Exp $
66581 */
66582
66583 #ifndef SQLITE_CORE
66584   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
66585 #endif
66586 /************** Include sqlite3ext.h in the middle of loadext.c **************/
66587 /************** Begin file sqlite3ext.h **************************************/
66588 /*
66589 ** 2006 June 7
66590 **
66591 ** The author disclaims copyright to this source code.  In place of
66592 ** a legal notice, here is a blessing:
66593 **
66594 **    May you do good and not evil.
66595 **    May you find forgiveness for yourself and forgive others.
66596 **    May you share freely, never taking more than you give.
66597 **
66598 *************************************************************************
66599 ** This header file defines the SQLite interface for use by
66600 ** shared libraries that want to be imported as extensions into
66601 ** an SQLite instance.  Shared libraries that intend to be loaded
66602 ** as extensions by SQLite should #include this file instead of 
66603 ** sqlite3.h.
66604 **
66605 ** @(#) $Id: sqlite3ext.h,v 1.25 2008/10/12 00:27:54 shane Exp $
66606 */
66607 #ifndef _SQLITE3EXT_H_
66608 #define _SQLITE3EXT_H_
66609
66610 typedef struct sqlite3_api_routines sqlite3_api_routines;
66611
66612 /*
66613 ** The following structure holds pointers to all of the SQLite API
66614 ** routines.
66615 **
66616 ** WARNING:  In order to maintain backwards compatibility, add new
66617 ** interfaces to the end of this structure only.  If you insert new
66618 ** interfaces in the middle of this structure, then older different
66619 ** versions of SQLite will not be able to load each others' shared
66620 ** libraries!
66621 */
66622 struct sqlite3_api_routines {
66623   void * (*aggregate_context)(sqlite3_context*,int nBytes);
66624   int  (*aggregate_count)(sqlite3_context*);
66625   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
66626   int  (*bind_double)(sqlite3_stmt*,int,double);
66627   int  (*bind_int)(sqlite3_stmt*,int,int);
66628   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
66629   int  (*bind_null)(sqlite3_stmt*,int);
66630   int  (*bind_parameter_count)(sqlite3_stmt*);
66631   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
66632   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
66633   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
66634   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
66635   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
66636   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
66637   int  (*busy_timeout)(sqlite3*,int ms);
66638   int  (*changes)(sqlite3*);
66639   int  (*close)(sqlite3*);
66640   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
66641   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
66642   const void * (*column_blob)(sqlite3_stmt*,int iCol);
66643   int  (*column_bytes)(sqlite3_stmt*,int iCol);
66644   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
66645   int  (*column_count)(sqlite3_stmt*pStmt);
66646   const char * (*column_database_name)(sqlite3_stmt*,int);
66647   const void * (*column_database_name16)(sqlite3_stmt*,int);
66648   const char * (*column_decltype)(sqlite3_stmt*,int i);
66649   const void * (*column_decltype16)(sqlite3_stmt*,int);
66650   double  (*column_double)(sqlite3_stmt*,int iCol);
66651   int  (*column_int)(sqlite3_stmt*,int iCol);
66652   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
66653   const char * (*column_name)(sqlite3_stmt*,int);
66654   const void * (*column_name16)(sqlite3_stmt*,int);
66655   const char * (*column_origin_name)(sqlite3_stmt*,int);
66656   const void * (*column_origin_name16)(sqlite3_stmt*,int);
66657   const char * (*column_table_name)(sqlite3_stmt*,int);
66658   const void * (*column_table_name16)(sqlite3_stmt*,int);
66659   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
66660   const void * (*column_text16)(sqlite3_stmt*,int iCol);
66661   int  (*column_type)(sqlite3_stmt*,int iCol);
66662   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
66663   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
66664   int  (*complete)(const char*sql);
66665   int  (*complete16)(const void*sql);
66666   int  (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
66667   int  (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*));
66668   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*));
66669   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*));
66670   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
66671   int  (*data_count)(sqlite3_stmt*pStmt);
66672   sqlite3 * (*db_handle)(sqlite3_stmt*);
66673   int (*declare_vtab)(sqlite3*,const char*);
66674   int  (*enable_shared_cache)(int);
66675   int  (*errcode)(sqlite3*db);
66676   const char * (*errmsg)(sqlite3*);
66677   const void * (*errmsg16)(sqlite3*);
66678   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
66679   int  (*expired)(sqlite3_stmt*);
66680   int  (*finalize)(sqlite3_stmt*pStmt);
66681   void  (*free)(void*);
66682   void  (*free_table)(char**result);
66683   int  (*get_autocommit)(sqlite3*);
66684   void * (*get_auxdata)(sqlite3_context*,int);
66685   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
66686   int  (*global_recover)(void);
66687   void  (*interruptx)(sqlite3*);
66688   sqlite_int64  (*last_insert_rowid)(sqlite3*);
66689   const char * (*libversion)(void);
66690   int  (*libversion_number)(void);
66691   void *(*malloc)(int);
66692   char * (*mprintf)(const char*,...);
66693   int  (*open)(const char*,sqlite3**);
66694   int  (*open16)(const void*,sqlite3**);
66695   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
66696   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
66697   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
66698   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
66699   void *(*realloc)(void*,int);
66700   int  (*reset)(sqlite3_stmt*pStmt);
66701   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
66702   void  (*result_double)(sqlite3_context*,double);
66703   void  (*result_error)(sqlite3_context*,const char*,int);
66704   void  (*result_error16)(sqlite3_context*,const void*,int);
66705   void  (*result_int)(sqlite3_context*,int);
66706   void  (*result_int64)(sqlite3_context*,sqlite_int64);
66707   void  (*result_null)(sqlite3_context*);
66708   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
66709   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
66710   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
66711   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
66712   void  (*result_value)(sqlite3_context*,sqlite3_value*);
66713   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
66714   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
66715   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
66716   char * (*snprintf)(int,char*,const char*,...);
66717   int  (*step)(sqlite3_stmt*);
66718   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
66719   void  (*thread_cleanup)(void);
66720   int  (*total_changes)(sqlite3*);
66721   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
66722   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
66723   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
66724   void * (*user_data)(sqlite3_context*);
66725   const void * (*value_blob)(sqlite3_value*);
66726   int  (*value_bytes)(sqlite3_value*);
66727   int  (*value_bytes16)(sqlite3_value*);
66728   double  (*value_double)(sqlite3_value*);
66729   int  (*value_int)(sqlite3_value*);
66730   sqlite_int64  (*value_int64)(sqlite3_value*);
66731   int  (*value_numeric_type)(sqlite3_value*);
66732   const unsigned char * (*value_text)(sqlite3_value*);
66733   const void * (*value_text16)(sqlite3_value*);
66734   const void * (*value_text16be)(sqlite3_value*);
66735   const void * (*value_text16le)(sqlite3_value*);
66736   int  (*value_type)(sqlite3_value*);
66737   char *(*vmprintf)(const char*,va_list);
66738   /* Added ??? */
66739   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
66740   /* Added by 3.3.13 */
66741   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
66742   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
66743   int (*clear_bindings)(sqlite3_stmt*);
66744   /* Added by 3.4.1 */
66745   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
66746   /* Added by 3.5.0 */
66747   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
66748   int (*blob_bytes)(sqlite3_blob*);
66749   int (*blob_close)(sqlite3_blob*);
66750   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
66751   int (*blob_read)(sqlite3_blob*,void*,int,int);
66752   int (*blob_write)(sqlite3_blob*,const void*,int,int);
66753   int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
66754   int (*file_control)(sqlite3*,const char*,int,void*);
66755   sqlite3_int64 (*memory_highwater)(int);
66756   sqlite3_int64 (*memory_used)(void);
66757   sqlite3_mutex *(*mutex_alloc)(int);
66758   void (*mutex_enter)(sqlite3_mutex*);
66759   void (*mutex_free)(sqlite3_mutex*);
66760   void (*mutex_leave)(sqlite3_mutex*);
66761   int (*mutex_try)(sqlite3_mutex*);
66762   int (*open_v2)(const char*,sqlite3**,int,const char*);
66763   int (*release_memory)(int);
66764   void (*result_error_nomem)(sqlite3_context*);
66765   void (*result_error_toobig)(sqlite3_context*);
66766   int (*sleep)(int);
66767   void (*soft_heap_limit)(int);
66768   sqlite3_vfs *(*vfs_find)(const char*);
66769   int (*vfs_register)(sqlite3_vfs*,int);
66770   int (*vfs_unregister)(sqlite3_vfs*);
66771   int (*xthreadsafe)(void);
66772   void (*result_zeroblob)(sqlite3_context*,int);
66773   void (*result_error_code)(sqlite3_context*,int);
66774   int (*test_control)(int, ...);
66775   void (*randomness)(int,void*);
66776   sqlite3 *(*context_db_handle)(sqlite3_context*);
66777   int (*extended_result_codes)(sqlite3*,int);
66778   int (*limit)(sqlite3*,int,int);
66779   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
66780   const char *(*sql)(sqlite3_stmt*);
66781   int (*status)(int,int*,int*,int);
66782 };
66783
66784 /*
66785 ** The following macros redefine the API routines so that they are
66786 ** redirected throught the global sqlite3_api structure.
66787 **
66788 ** This header file is also used by the loadext.c source file
66789 ** (part of the main SQLite library - not an extension) so that
66790 ** it can get access to the sqlite3_api_routines structure
66791 ** definition.  But the main library does not want to redefine
66792 ** the API.  So the redefinition macros are only valid if the
66793 ** SQLITE_CORE macros is undefined.
66794 */
66795 #ifndef SQLITE_CORE
66796 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
66797 #ifndef SQLITE_OMIT_DEPRECATED
66798 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
66799 #endif
66800 #define sqlite3_bind_blob              sqlite3_api->bind_blob
66801 #define sqlite3_bind_double            sqlite3_api->bind_double
66802 #define sqlite3_bind_int               sqlite3_api->bind_int
66803 #define sqlite3_bind_int64             sqlite3_api->bind_int64
66804 #define sqlite3_bind_null              sqlite3_api->bind_null
66805 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
66806 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
66807 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
66808 #define sqlite3_bind_text              sqlite3_api->bind_text
66809 #define sqlite3_bind_text16            sqlite3_api->bind_text16
66810 #define sqlite3_bind_value             sqlite3_api->bind_value
66811 #define sqlite3_busy_handler           sqlite3_api->busy_handler
66812 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
66813 #define sqlite3_changes                sqlite3_api->changes
66814 #define sqlite3_close                  sqlite3_api->close
66815 #define sqlite3_collation_needed       sqlite3_api->collation_needed
66816 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
66817 #define sqlite3_column_blob            sqlite3_api->column_blob
66818 #define sqlite3_column_bytes           sqlite3_api->column_bytes
66819 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
66820 #define sqlite3_column_count           sqlite3_api->column_count
66821 #define sqlite3_column_database_name   sqlite3_api->column_database_name
66822 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
66823 #define sqlite3_column_decltype        sqlite3_api->column_decltype
66824 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
66825 #define sqlite3_column_double          sqlite3_api->column_double
66826 #define sqlite3_column_int             sqlite3_api->column_int
66827 #define sqlite3_column_int64           sqlite3_api->column_int64
66828 #define sqlite3_column_name            sqlite3_api->column_name
66829 #define sqlite3_column_name16          sqlite3_api->column_name16
66830 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
66831 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
66832 #define sqlite3_column_table_name      sqlite3_api->column_table_name
66833 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
66834 #define sqlite3_column_text            sqlite3_api->column_text
66835 #define sqlite3_column_text16          sqlite3_api->column_text16
66836 #define sqlite3_column_type            sqlite3_api->column_type
66837 #define sqlite3_column_value           sqlite3_api->column_value
66838 #define sqlite3_commit_hook            sqlite3_api->commit_hook
66839 #define sqlite3_complete               sqlite3_api->complete
66840 #define sqlite3_complete16             sqlite3_api->complete16
66841 #define sqlite3_create_collation       sqlite3_api->create_collation
66842 #define sqlite3_create_collation16     sqlite3_api->create_collation16
66843 #define sqlite3_create_function        sqlite3_api->create_function
66844 #define sqlite3_create_function16      sqlite3_api->create_function16
66845 #define sqlite3_create_module          sqlite3_api->create_module
66846 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
66847 #define sqlite3_data_count             sqlite3_api->data_count
66848 #define sqlite3_db_handle              sqlite3_api->db_handle
66849 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
66850 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
66851 #define sqlite3_errcode                sqlite3_api->errcode
66852 #define sqlite3_errmsg                 sqlite3_api->errmsg
66853 #define sqlite3_errmsg16               sqlite3_api->errmsg16
66854 #define sqlite3_exec                   sqlite3_api->exec
66855 #ifndef SQLITE_OMIT_DEPRECATED
66856 #define sqlite3_expired                sqlite3_api->expired
66857 #endif
66858 #define sqlite3_finalize               sqlite3_api->finalize
66859 #define sqlite3_free                   sqlite3_api->free
66860 #define sqlite3_free_table             sqlite3_api->free_table
66861 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
66862 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
66863 #define sqlite3_get_table              sqlite3_api->get_table
66864 #ifndef SQLITE_OMIT_DEPRECATED
66865 #define sqlite3_global_recover         sqlite3_api->global_recover
66866 #endif
66867 #define sqlite3_interrupt              sqlite3_api->interruptx
66868 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
66869 #define sqlite3_libversion             sqlite3_api->libversion
66870 #define sqlite3_libversion_number      sqlite3_api->libversion_number
66871 #define sqlite3_malloc                 sqlite3_api->malloc
66872 #define sqlite3_mprintf                sqlite3_api->mprintf
66873 #define sqlite3_open                   sqlite3_api->open
66874 #define sqlite3_open16                 sqlite3_api->open16
66875 #define sqlite3_prepare                sqlite3_api->prepare
66876 #define sqlite3_prepare16              sqlite3_api->prepare16
66877 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
66878 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
66879 #define sqlite3_profile                sqlite3_api->profile
66880 #define sqlite3_progress_handler       sqlite3_api->progress_handler
66881 #define sqlite3_realloc                sqlite3_api->realloc
66882 #define sqlite3_reset                  sqlite3_api->reset
66883 #define sqlite3_result_blob            sqlite3_api->result_blob
66884 #define sqlite3_result_double          sqlite3_api->result_double
66885 #define sqlite3_result_error           sqlite3_api->result_error
66886 #define sqlite3_result_error16         sqlite3_api->result_error16
66887 #define sqlite3_result_int             sqlite3_api->result_int
66888 #define sqlite3_result_int64           sqlite3_api->result_int64
66889 #define sqlite3_result_null            sqlite3_api->result_null
66890 #define sqlite3_result_text            sqlite3_api->result_text
66891 #define sqlite3_result_text16          sqlite3_api->result_text16
66892 #define sqlite3_result_text16be        sqlite3_api->result_text16be
66893 #define sqlite3_result_text16le        sqlite3_api->result_text16le
66894 #define sqlite3_result_value           sqlite3_api->result_value
66895 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
66896 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
66897 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
66898 #define sqlite3_snprintf               sqlite3_api->snprintf
66899 #define sqlite3_step                   sqlite3_api->step
66900 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
66901 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
66902 #define sqlite3_total_changes          sqlite3_api->total_changes
66903 #define sqlite3_trace                  sqlite3_api->trace
66904 #ifndef SQLITE_OMIT_DEPRECATED
66905 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
66906 #endif
66907 #define sqlite3_update_hook            sqlite3_api->update_hook
66908 #define sqlite3_user_data              sqlite3_api->user_data
66909 #define sqlite3_value_blob             sqlite3_api->value_blob
66910 #define sqlite3_value_bytes            sqlite3_api->value_bytes
66911 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
66912 #define sqlite3_value_double           sqlite3_api->value_double
66913 #define sqlite3_value_int              sqlite3_api->value_int
66914 #define sqlite3_value_int64            sqlite3_api->value_int64
66915 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
66916 #define sqlite3_value_text             sqlite3_api->value_text
66917 #define sqlite3_value_text16           sqlite3_api->value_text16
66918 #define sqlite3_value_text16be         sqlite3_api->value_text16be
66919 #define sqlite3_value_text16le         sqlite3_api->value_text16le
66920 #define sqlite3_value_type             sqlite3_api->value_type
66921 #define sqlite3_vmprintf               sqlite3_api->vmprintf
66922 #define sqlite3_overload_function      sqlite3_api->overload_function
66923 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
66924 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
66925 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
66926 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
66927 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
66928 #define sqlite3_blob_close             sqlite3_api->blob_close
66929 #define sqlite3_blob_open              sqlite3_api->blob_open
66930 #define sqlite3_blob_read              sqlite3_api->blob_read
66931 #define sqlite3_blob_write             sqlite3_api->blob_write
66932 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
66933 #define sqlite3_file_control           sqlite3_api->file_control
66934 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
66935 #define sqlite3_memory_used            sqlite3_api->memory_used
66936 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
66937 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
66938 #define sqlite3_mutex_free             sqlite3_api->mutex_free
66939 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
66940 #define sqlite3_mutex_try              sqlite3_api->mutex_try
66941 #define sqlite3_open_v2                sqlite3_api->open_v2
66942 #define sqlite3_release_memory         sqlite3_api->release_memory
66943 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
66944 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
66945 #define sqlite3_sleep                  sqlite3_api->sleep
66946 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
66947 #define sqlite3_vfs_find               sqlite3_api->vfs_find
66948 #define sqlite3_vfs_register           sqlite3_api->vfs_register
66949 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
66950 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
66951 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
66952 #define sqlite3_result_error_code      sqlite3_api->result_error_code
66953 #define sqlite3_test_control           sqlite3_api->test_control
66954 #define sqlite3_randomness             sqlite3_api->randomness
66955 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
66956 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
66957 #define sqlite3_limit                  sqlite3_api->limit
66958 #define sqlite3_next_stmt              sqlite3_api->next_stmt
66959 #define sqlite3_sql                    sqlite3_api->sql
66960 #define sqlite3_status                 sqlite3_api->status
66961 #endif /* SQLITE_CORE */
66962
66963 #define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
66964 #define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
66965
66966 #endif /* _SQLITE3EXT_H_ */
66967
66968 /************** End of sqlite3ext.h ******************************************/
66969 /************** Continuing where we left off in loadext.c ********************/
66970
66971 #ifndef SQLITE_OMIT_LOAD_EXTENSION
66972
66973 /*
66974 ** Some API routines are omitted when various features are
66975 ** excluded from a build of SQLite.  Substitute a NULL pointer
66976 ** for any missing APIs.
66977 */
66978 #ifndef SQLITE_ENABLE_COLUMN_METADATA
66979 # define sqlite3_column_database_name   0
66980 # define sqlite3_column_database_name16 0
66981 # define sqlite3_column_table_name      0
66982 # define sqlite3_column_table_name16    0
66983 # define sqlite3_column_origin_name     0
66984 # define sqlite3_column_origin_name16   0
66985 # define sqlite3_table_column_metadata  0
66986 #endif
66987
66988 #ifdef SQLITE_OMIT_AUTHORIZATION
66989 # define sqlite3_set_authorizer         0
66990 #endif
66991
66992 #ifdef SQLITE_OMIT_UTF16
66993 # define sqlite3_bind_text16            0
66994 # define sqlite3_collation_needed16     0
66995 # define sqlite3_column_decltype16      0
66996 # define sqlite3_column_name16          0
66997 # define sqlite3_column_text16          0
66998 # define sqlite3_complete16             0
66999 # define sqlite3_create_collation16     0
67000 # define sqlite3_create_function16      0
67001 # define sqlite3_errmsg16               0
67002 # define sqlite3_open16                 0
67003 # define sqlite3_prepare16              0
67004 # define sqlite3_prepare16_v2           0
67005 # define sqlite3_result_error16         0
67006 # define sqlite3_result_text16          0
67007 # define sqlite3_result_text16be        0
67008 # define sqlite3_result_text16le        0
67009 # define sqlite3_value_text16           0
67010 # define sqlite3_value_text16be         0
67011 # define sqlite3_value_text16le         0
67012 # define sqlite3_column_database_name16 0
67013 # define sqlite3_column_table_name16    0
67014 # define sqlite3_column_origin_name16   0
67015 #endif
67016
67017 #ifdef SQLITE_OMIT_COMPLETE
67018 # define sqlite3_complete 0
67019 # define sqlite3_complete16 0
67020 #endif
67021
67022 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
67023 # define sqlite3_progress_handler 0
67024 #endif
67025
67026 #ifdef SQLITE_OMIT_VIRTUALTABLE
67027 # define sqlite3_create_module 0
67028 # define sqlite3_create_module_v2 0
67029 # define sqlite3_declare_vtab 0
67030 #endif
67031
67032 #ifdef SQLITE_OMIT_SHARED_CACHE
67033 # define sqlite3_enable_shared_cache 0
67034 #endif
67035
67036 #ifdef SQLITE_OMIT_TRACE
67037 # define sqlite3_profile       0
67038 # define sqlite3_trace         0
67039 #endif
67040
67041 #ifdef SQLITE_OMIT_GET_TABLE
67042 # define sqlite3_free_table    0
67043 # define sqlite3_get_table     0
67044 #endif
67045
67046 #ifdef SQLITE_OMIT_INCRBLOB
67047 #define sqlite3_bind_zeroblob  0
67048 #define sqlite3_blob_bytes     0
67049 #define sqlite3_blob_close     0
67050 #define sqlite3_blob_open      0
67051 #define sqlite3_blob_read      0
67052 #define sqlite3_blob_write     0
67053 #endif
67054
67055 /*
67056 ** The following structure contains pointers to all SQLite API routines.
67057 ** A pointer to this structure is passed into extensions when they are
67058 ** loaded so that the extension can make calls back into the SQLite
67059 ** library.
67060 **
67061 ** When adding new APIs, add them to the bottom of this structure
67062 ** in order to preserve backwards compatibility.
67063 **
67064 ** Extensions that use newer APIs should first call the
67065 ** sqlite3_libversion_number() to make sure that the API they
67066 ** intend to use is supported by the library.  Extensions should
67067 ** also check to make sure that the pointer to the function is
67068 ** not NULL before calling it.
67069 */
67070 static const sqlite3_api_routines sqlite3Apis = {
67071   sqlite3_aggregate_context,
67072 #ifndef SQLITE_OMIT_DEPRECATED
67073   sqlite3_aggregate_count,
67074 #else
67075   0,
67076 #endif
67077   sqlite3_bind_blob,
67078   sqlite3_bind_double,
67079   sqlite3_bind_int,
67080   sqlite3_bind_int64,
67081   sqlite3_bind_null,
67082   sqlite3_bind_parameter_count,
67083   sqlite3_bind_parameter_index,
67084   sqlite3_bind_parameter_name,
67085   sqlite3_bind_text,
67086   sqlite3_bind_text16,
67087   sqlite3_bind_value,
67088   sqlite3_busy_handler,
67089   sqlite3_busy_timeout,
67090   sqlite3_changes,
67091   sqlite3_close,
67092   sqlite3_collation_needed,
67093   sqlite3_collation_needed16,
67094   sqlite3_column_blob,
67095   sqlite3_column_bytes,
67096   sqlite3_column_bytes16,
67097   sqlite3_column_count,
67098   sqlite3_column_database_name,
67099   sqlite3_column_database_name16,
67100   sqlite3_column_decltype,
67101   sqlite3_column_decltype16,
67102   sqlite3_column_double,
67103   sqlite3_column_int,
67104   sqlite3_column_int64,
67105   sqlite3_column_name,
67106   sqlite3_column_name16,
67107   sqlite3_column_origin_name,
67108   sqlite3_column_origin_name16,
67109   sqlite3_column_table_name,
67110   sqlite3_column_table_name16,
67111   sqlite3_column_text,
67112   sqlite3_column_text16,
67113   sqlite3_column_type,
67114   sqlite3_column_value,
67115   sqlite3_commit_hook,
67116   sqlite3_complete,
67117   sqlite3_complete16,
67118   sqlite3_create_collation,
67119   sqlite3_create_collation16,
67120   sqlite3_create_function,
67121   sqlite3_create_function16,
67122   sqlite3_create_module,
67123   sqlite3_data_count,
67124   sqlite3_db_handle,
67125   sqlite3_declare_vtab,
67126   sqlite3_enable_shared_cache,
67127   sqlite3_errcode,
67128   sqlite3_errmsg,
67129   sqlite3_errmsg16,
67130   sqlite3_exec,
67131 #ifndef SQLITE_OMIT_DEPRECATED
67132   sqlite3_expired,
67133 #else
67134   0,
67135 #endif
67136   sqlite3_finalize,
67137   sqlite3_free,
67138   sqlite3_free_table,
67139   sqlite3_get_autocommit,
67140   sqlite3_get_auxdata,
67141   sqlite3_get_table,
67142   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
67143   sqlite3_interrupt,
67144   sqlite3_last_insert_rowid,
67145   sqlite3_libversion,
67146   sqlite3_libversion_number,
67147   sqlite3_malloc,
67148   sqlite3_mprintf,
67149   sqlite3_open,
67150   sqlite3_open16,
67151   sqlite3_prepare,
67152   sqlite3_prepare16,
67153   sqlite3_profile,
67154   sqlite3_progress_handler,
67155   sqlite3_realloc,
67156   sqlite3_reset,
67157   sqlite3_result_blob,
67158   sqlite3_result_double,
67159   sqlite3_result_error,
67160   sqlite3_result_error16,
67161   sqlite3_result_int,
67162   sqlite3_result_int64,
67163   sqlite3_result_null,
67164   sqlite3_result_text,
67165   sqlite3_result_text16,
67166   sqlite3_result_text16be,
67167   sqlite3_result_text16le,
67168   sqlite3_result_value,
67169   sqlite3_rollback_hook,
67170   sqlite3_set_authorizer,
67171   sqlite3_set_auxdata,
67172   sqlite3_snprintf,
67173   sqlite3_step,
67174   sqlite3_table_column_metadata,
67175 #ifndef SQLITE_OMIT_DEPRECATED
67176   sqlite3_thread_cleanup,
67177 #else
67178   0,
67179 #endif
67180   sqlite3_total_changes,
67181   sqlite3_trace,
67182 #ifndef SQLITE_OMIT_DEPRECATED
67183   sqlite3_transfer_bindings,
67184 #else
67185   0,
67186 #endif
67187   sqlite3_update_hook,
67188   sqlite3_user_data,
67189   sqlite3_value_blob,
67190   sqlite3_value_bytes,
67191   sqlite3_value_bytes16,
67192   sqlite3_value_double,
67193   sqlite3_value_int,
67194   sqlite3_value_int64,
67195   sqlite3_value_numeric_type,
67196   sqlite3_value_text,
67197   sqlite3_value_text16,
67198   sqlite3_value_text16be,
67199   sqlite3_value_text16le,
67200   sqlite3_value_type,
67201   sqlite3_vmprintf,
67202   /*
67203   ** The original API set ends here.  All extensions can call any
67204   ** of the APIs above provided that the pointer is not NULL.  But
67205   ** before calling APIs that follow, extension should check the
67206   ** sqlite3_libversion_number() to make sure they are dealing with
67207   ** a library that is new enough to support that API.
67208   *************************************************************************
67209   */
67210   sqlite3_overload_function,
67211
67212   /*
67213   ** Added after 3.3.13
67214   */
67215   sqlite3_prepare_v2,
67216   sqlite3_prepare16_v2,
67217   sqlite3_clear_bindings,
67218
67219   /*
67220   ** Added for 3.4.1
67221   */
67222   sqlite3_create_module_v2,
67223
67224   /*
67225   ** Added for 3.5.0
67226   */
67227   sqlite3_bind_zeroblob,
67228   sqlite3_blob_bytes,
67229   sqlite3_blob_close,
67230   sqlite3_blob_open,
67231   sqlite3_blob_read,
67232   sqlite3_blob_write,
67233   sqlite3_create_collation_v2,
67234   sqlite3_file_control,
67235   sqlite3_memory_highwater,
67236   sqlite3_memory_used,
67237 #ifdef SQLITE_MUTEX_OMIT
67238   0, 
67239   0, 
67240   0,
67241   0,
67242   0,
67243 #else
67244   sqlite3_mutex_alloc,
67245   sqlite3_mutex_enter,
67246   sqlite3_mutex_free,
67247   sqlite3_mutex_leave,
67248   sqlite3_mutex_try,
67249 #endif
67250   sqlite3_open_v2,
67251   sqlite3_release_memory,
67252   sqlite3_result_error_nomem,
67253   sqlite3_result_error_toobig,
67254   sqlite3_sleep,
67255   sqlite3_soft_heap_limit,
67256   sqlite3_vfs_find,
67257   sqlite3_vfs_register,
67258   sqlite3_vfs_unregister,
67259
67260   /*
67261   ** Added for 3.5.8
67262   */
67263   sqlite3_threadsafe,
67264   sqlite3_result_zeroblob,
67265   sqlite3_result_error_code,
67266   sqlite3_test_control,
67267   sqlite3_randomness,
67268   sqlite3_context_db_handle,
67269
67270   /*
67271   ** Added for 3.6.0
67272   */
67273   sqlite3_extended_result_codes,
67274   sqlite3_limit,
67275   sqlite3_next_stmt,
67276   sqlite3_sql,
67277   sqlite3_status,
67278 };
67279
67280 /*
67281 ** Attempt to load an SQLite extension library contained in the file
67282 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
67283 ** default entry point name (sqlite3_extension_init) is used.  Use
67284 ** of the default name is recommended.
67285 **
67286 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
67287 **
67288 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
67289 ** error message text.  The calling function should free this memory
67290 ** by calling sqlite3DbFree(db, ).
67291 */
67292 static int sqlite3LoadExtension(
67293   sqlite3 *db,          /* Load the extension into this database connection */
67294   const char *zFile,    /* Name of the shared library containing extension */
67295   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
67296   char **pzErrMsg       /* Put error message here if not 0 */
67297 ){
67298   sqlite3_vfs *pVfs = db->pVfs;
67299   void *handle;
67300   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
67301   char *zErrmsg = 0;
67302   void **aHandle;
67303
67304   /* Ticket #1863.  To avoid a creating security problems for older
67305   ** applications that relink against newer versions of SQLite, the
67306   ** ability to run load_extension is turned off by default.  One
67307   ** must call sqlite3_enable_load_extension() to turn on extension
67308   ** loading.  Otherwise you get the following error.
67309   */
67310   if( (db->flags & SQLITE_LoadExtension)==0 ){
67311     if( pzErrMsg ){
67312       *pzErrMsg = sqlite3_mprintf("not authorized");
67313     }
67314     return SQLITE_ERROR;
67315   }
67316
67317   if( zProc==0 ){
67318     zProc = "sqlite3_extension_init";
67319   }
67320
67321   handle = sqlite3OsDlOpen(pVfs, zFile);
67322   if( handle==0 ){
67323     if( pzErrMsg ){
67324       char zErr[256];
67325       zErr[sizeof(zErr)-1] = '\0';
67326       sqlite3_snprintf(sizeof(zErr)-1, zErr, 
67327           "unable to open shared library [%s]", zFile);
67328       sqlite3OsDlError(pVfs, sizeof(zErr)-1, zErr);
67329       *pzErrMsg = sqlite3DbStrDup(0, zErr);
67330     }
67331     return SQLITE_ERROR;
67332   }
67333   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
67334                    sqlite3OsDlSym(pVfs, handle, zProc);
67335   if( xInit==0 ){
67336     if( pzErrMsg ){
67337       char zErr[256];
67338       zErr[sizeof(zErr)-1] = '\0';
67339       sqlite3_snprintf(sizeof(zErr)-1, zErr,
67340           "no entry point [%s] in shared library [%s]", zProc,zFile);
67341       sqlite3OsDlError(pVfs, sizeof(zErr)-1, zErr);
67342       *pzErrMsg = sqlite3DbStrDup(0, zErr);
67343       sqlite3OsDlClose(pVfs, handle);
67344     }
67345     return SQLITE_ERROR;
67346   }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
67347     if( pzErrMsg ){
67348       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
67349     }
67350     sqlite3_free(zErrmsg);
67351     sqlite3OsDlClose(pVfs, handle);
67352     return SQLITE_ERROR;
67353   }
67354
67355   /* Append the new shared library handle to the db->aExtension array. */
67356   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
67357   if( aHandle==0 ){
67358     return SQLITE_NOMEM;
67359   }
67360   if( db->nExtension>0 ){
67361     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
67362   }
67363   sqlite3DbFree(db, db->aExtension);
67364   db->aExtension = aHandle;
67365
67366   db->aExtension[db->nExtension++] = handle;
67367   return SQLITE_OK;
67368 }
67369 SQLITE_API int sqlite3_load_extension(
67370   sqlite3 *db,          /* Load the extension into this database connection */
67371   const char *zFile,    /* Name of the shared library containing extension */
67372   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
67373   char **pzErrMsg       /* Put error message here if not 0 */
67374 ){
67375   int rc;
67376   sqlite3_mutex_enter(db->mutex);
67377   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
67378   sqlite3_mutex_leave(db->mutex);
67379   return rc;
67380 }
67381
67382 /*
67383 ** Call this routine when the database connection is closing in order
67384 ** to clean up loaded extensions
67385 */
67386 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
67387   int i;
67388   assert( sqlite3_mutex_held(db->mutex) );
67389   for(i=0; i<db->nExtension; i++){
67390     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
67391   }
67392   sqlite3DbFree(db, db->aExtension);
67393 }
67394
67395 /*
67396 ** Enable or disable extension loading.  Extension loading is disabled by
67397 ** default so as not to open security holes in older applications.
67398 */
67399 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
67400   sqlite3_mutex_enter(db->mutex);
67401   if( onoff ){
67402     db->flags |= SQLITE_LoadExtension;
67403   }else{
67404     db->flags &= ~SQLITE_LoadExtension;
67405   }
67406   sqlite3_mutex_leave(db->mutex);
67407   return SQLITE_OK;
67408 }
67409
67410 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
67411
67412 /*
67413 ** The auto-extension code added regardless of whether or not extension
67414 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
67415 ** code if regular extension loading is not available.  This is that
67416 ** dummy pointer.
67417 */
67418 #ifdef SQLITE_OMIT_LOAD_EXTENSION
67419 static const sqlite3_api_routines sqlite3Apis = { 0 };
67420 #endif
67421
67422
67423 /*
67424 ** The following object holds the list of automatically loaded
67425 ** extensions.
67426 **
67427 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
67428 ** mutex must be held while accessing this list.
67429 */
67430 typedef struct sqlite3ExtType sqlite3ExtType;
67431 static SQLITE_WSD struct sqlite3ExtType {
67432   int nExt;        /* Number of entries in aExt[] */          
67433   void **aExt;     /* Pointers to the extension init functions */
67434 } sqlite3Autoext = { 0, 0 };
67435
67436 /* The "wsdAutoext" macro will resolve to the autoextension
67437 ** state vector.  If writable static data is unsupported on the target,
67438 ** we have to locate the state vector at run-time.  In the more common
67439 ** case where writable static data is supported, wsdStat can refer directly
67440 ** to the "sqlite3Autoext" state vector declared above.
67441 */
67442 #ifdef SQLITE_OMIT_WSD
67443 # define wsdAutoextInit \
67444   sqlite3ExtType *x = &GLOBAL(sqlite3ExtType,sqlite3Autoext)
67445 # define wsdAutoext x[0]
67446 #else
67447 # define wsdAutoextInit
67448 # define wsdAutoext sqlite3Autoext
67449 #endif
67450
67451
67452 /*
67453 ** Register a statically linked extension that is automatically
67454 ** loaded by every new database connection.
67455 */
67456 SQLITE_API int sqlite3_auto_extension(void *xInit){
67457   int rc = SQLITE_OK;
67458 #ifndef SQLITE_OMIT_AUTOINIT
67459   rc = sqlite3_initialize();
67460   if( rc ){
67461     return rc;
67462   }else
67463 #endif
67464   {
67465     int i;
67466 #if SQLITE_THREADSAFE
67467     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
67468 #endif
67469     wsdAutoextInit;
67470     sqlite3_mutex_enter(mutex);
67471     for(i=0; i<wsdAutoext.nExt; i++){
67472       if( wsdAutoext.aExt[i]==xInit ) break;
67473     }
67474     if( i==wsdAutoext.nExt ){
67475       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
67476       void **aNew;
67477       aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
67478       if( aNew==0 ){
67479         rc = SQLITE_NOMEM;
67480       }else{
67481         wsdAutoext.aExt = aNew;
67482         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
67483         wsdAutoext.nExt++;
67484       }
67485     }
67486     sqlite3_mutex_leave(mutex);
67487     assert( (rc&0xff)==rc );
67488     return rc;
67489   }
67490 }
67491
67492 /*
67493 ** Reset the automatic extension loading mechanism.
67494 */
67495 SQLITE_API void sqlite3_reset_auto_extension(void){
67496 #ifndef SQLITE_OMIT_AUTOINIT
67497   if( sqlite3_initialize()==SQLITE_OK )
67498 #endif
67499   {
67500 #if SQLITE_THREADSAFE
67501     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
67502 #endif
67503     wsdAutoextInit;
67504     sqlite3_mutex_enter(mutex);
67505     sqlite3_free(wsdAutoext.aExt);
67506     wsdAutoext.aExt = 0;
67507     wsdAutoext.nExt = 0;
67508     sqlite3_mutex_leave(mutex);
67509   }
67510 }
67511
67512 /*
67513 ** Load all automatic extensions.
67514 */
67515 SQLITE_PRIVATE int sqlite3AutoLoadExtensions(sqlite3 *db){
67516   int i;
67517   int go = 1;
67518   int rc = SQLITE_OK;
67519   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
67520
67521   wsdAutoextInit;
67522   if( wsdAutoext.nExt==0 ){
67523     /* Common case: early out without every having to acquire a mutex */
67524     return SQLITE_OK;
67525   }
67526   for(i=0; go; i++){
67527     char *zErrmsg = 0;
67528 #if SQLITE_THREADSAFE
67529     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
67530 #endif
67531     sqlite3_mutex_enter(mutex);
67532     if( i>=wsdAutoext.nExt ){
67533       xInit = 0;
67534       go = 0;
67535     }else{
67536       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
67537               wsdAutoext.aExt[i];
67538     }
67539     sqlite3_mutex_leave(mutex);
67540     if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
67541       sqlite3Error(db, SQLITE_ERROR,
67542             "automatic extension loading failed: %s", zErrmsg);
67543       go = 0;
67544       rc = SQLITE_ERROR;
67545       sqlite3_free(zErrmsg);
67546     }
67547   }
67548   return rc;
67549 }
67550
67551 /************** End of loadext.c *********************************************/
67552 /************** Begin file pragma.c ******************************************/
67553 /*
67554 ** 2003 April 6
67555 **
67556 ** The author disclaims copyright to this source code.  In place of
67557 ** a legal notice, here is a blessing:
67558 **
67559 **    May you do good and not evil.
67560 **    May you find forgiveness for yourself and forgive others.
67561 **    May you share freely, never taking more than you give.
67562 **
67563 *************************************************************************
67564 ** This file contains code used to implement the PRAGMA command.
67565 **
67566 ** $Id: pragma.c,v 1.194 2008/11/17 19:18:55 danielk1977 Exp $
67567 */
67568
67569 /* Ignore this whole file if pragmas are disabled
67570 */
67571 #if !defined(SQLITE_OMIT_PRAGMA) && !defined(SQLITE_OMIT_PARSER)
67572
67573 /*
67574 ** Interpret the given string as a safety level.  Return 0 for OFF,
67575 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or 
67576 ** unrecognized string argument.
67577 **
67578 ** Note that the values returned are one less that the values that
67579 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
67580 ** to support legacy SQL code.  The safety level used to be boolean
67581 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
67582 */
67583 static int getSafetyLevel(const char *z){
67584                              /* 123456789 123456789 */
67585   static const char zText[] = "onoffalseyestruefull";
67586   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
67587   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
67588   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
67589   int i, n;
67590   if( isdigit(*z) ){
67591     return atoi(z);
67592   }
67593   n = strlen(z);
67594   for(i=0; i<ArraySize(iLength); i++){
67595     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
67596       return iValue[i];
67597     }
67598   }
67599   return 1;
67600 }
67601
67602 /*
67603 ** Interpret the given string as a boolean value.
67604 */
67605 static int getBoolean(const char *z){
67606   return getSafetyLevel(z)&1;
67607 }
67608
67609 /*
67610 ** Interpret the given string as a locking mode value.
67611 */
67612 static int getLockingMode(const char *z){
67613   if( z ){
67614     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
67615     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
67616   }
67617   return PAGER_LOCKINGMODE_QUERY;
67618 }
67619
67620 #ifndef SQLITE_OMIT_AUTOVACUUM
67621 /*
67622 ** Interpret the given string as an auto-vacuum mode value.
67623 **
67624 ** The following strings, "none", "full" and "incremental" are 
67625 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
67626 */
67627 static int getAutoVacuum(const char *z){
67628   int i;
67629   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
67630   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
67631   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
67632   i = atoi(z);
67633   return ((i>=0&&i<=2)?i:0);
67634 }
67635 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
67636
67637 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
67638 /*
67639 ** Interpret the given string as a temp db location. Return 1 for file
67640 ** backed temporary databases, 2 for the Red-Black tree in memory database
67641 ** and 0 to use the compile-time default.
67642 */
67643 static int getTempStore(const char *z){
67644   if( z[0]>='0' && z[0]<='2' ){
67645     return z[0] - '0';
67646   }else if( sqlite3StrICmp(z, "file")==0 ){
67647     return 1;
67648   }else if( sqlite3StrICmp(z, "memory")==0 ){
67649     return 2;
67650   }else{
67651     return 0;
67652   }
67653 }
67654 #endif /* SQLITE_PAGER_PRAGMAS */
67655
67656 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
67657 /*
67658 ** Invalidate temp storage, either when the temp storage is changed
67659 ** from default, or when 'file' and the temp_store_directory has changed
67660 */
67661 static int invalidateTempStorage(Parse *pParse){
67662   sqlite3 *db = pParse->db;
67663   if( db->aDb[1].pBt!=0 ){
67664     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
67665       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
67666         "from within a transaction");
67667       return SQLITE_ERROR;
67668     }
67669     sqlite3BtreeClose(db->aDb[1].pBt);
67670     db->aDb[1].pBt = 0;
67671     sqlite3ResetInternalSchema(db, 0);
67672   }
67673   return SQLITE_OK;
67674 }
67675 #endif /* SQLITE_PAGER_PRAGMAS */
67676
67677 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
67678 /*
67679 ** If the TEMP database is open, close it and mark the database schema
67680 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
67681 ** or DEFAULT_TEMP_STORE pragmas.
67682 */
67683 static int changeTempStorage(Parse *pParse, const char *zStorageType){
67684   int ts = getTempStore(zStorageType);
67685   sqlite3 *db = pParse->db;
67686   if( db->temp_store==ts ) return SQLITE_OK;
67687   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
67688     return SQLITE_ERROR;
67689   }
67690   db->temp_store = ts;
67691   return SQLITE_OK;
67692 }
67693 #endif /* SQLITE_PAGER_PRAGMAS */
67694
67695 /*
67696 ** Generate code to return a single integer value.
67697 */
67698 static void returnSingleInt(Parse *pParse, const char *zLabel, int value){
67699   Vdbe *v = sqlite3GetVdbe(pParse);
67700   int mem = ++pParse->nMem;
67701   sqlite3VdbeAddOp2(v, OP_Integer, value, mem);
67702   if( pParse->explain==0 ){
67703     sqlite3VdbeSetNumCols(v, 1);
67704     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
67705   }
67706   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
67707 }
67708
67709 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
67710 /*
67711 ** Check to see if zRight and zLeft refer to a pragma that queries
67712 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
67713 ** Also, implement the pragma.
67714 */
67715 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
67716   static const struct sPragmaType {
67717     const char *zName;  /* Name of the pragma */
67718     int mask;           /* Mask for the db->flags value */
67719   } aPragma[] = {
67720     { "full_column_names",        SQLITE_FullColNames  },
67721     { "short_column_names",       SQLITE_ShortColNames },
67722     { "count_changes",            SQLITE_CountRows     },
67723     { "empty_result_callbacks",   SQLITE_NullCallback  },
67724     { "legacy_file_format",       SQLITE_LegacyFileFmt },
67725     { "fullfsync",                SQLITE_FullFSync     },
67726 #ifdef SQLITE_DEBUG
67727     { "sql_trace",                SQLITE_SqlTrace      },
67728     { "vdbe_listing",             SQLITE_VdbeListing   },
67729     { "vdbe_trace",               SQLITE_VdbeTrace     },
67730 #endif
67731 #ifndef SQLITE_OMIT_CHECK
67732     { "ignore_check_constraints", SQLITE_IgnoreChecks  },
67733 #endif
67734     /* The following is VERY experimental */
67735     { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
67736     { "omit_readlock",            SQLITE_NoReadlock    },
67737
67738     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
67739     ** flag if there are any active statements. */
67740     { "read_uncommitted",         SQLITE_ReadUncommitted },
67741   };
67742   int i;
67743   const struct sPragmaType *p;
67744   for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
67745     if( sqlite3StrICmp(zLeft, p->zName)==0 ){
67746       sqlite3 *db = pParse->db;
67747       Vdbe *v;
67748       v = sqlite3GetVdbe(pParse);
67749       if( v ){
67750         if( zRight==0 ){
67751           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
67752         }else{
67753           if( getBoolean(zRight) ){
67754             db->flags |= p->mask;
67755           }else{
67756             db->flags &= ~p->mask;
67757           }
67758
67759           /* Many of the flag-pragmas modify the code generated by the SQL 
67760           ** compiler (eg. count_changes). So add an opcode to expire all
67761           ** compiled SQL statements after modifying a pragma value.
67762           */
67763           sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
67764         }
67765       }
67766
67767       return 1;
67768     }
67769   }
67770   return 0;
67771 }
67772 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
67773
67774 static const char *actionName(u8 action){
67775   switch( action ){
67776     case OE_SetNull:  return "SET NULL";
67777     case OE_SetDflt:  return "SET DEFAULT";
67778     case OE_Restrict: return "RESTRICT";
67779     case OE_Cascade:  return "CASCADE";
67780   }
67781   return "";
67782 }
67783
67784 /*
67785 ** Process a pragma statement.  
67786 **
67787 ** Pragmas are of this form:
67788 **
67789 **      PRAGMA [database.]id [= value]
67790 **
67791 ** The identifier might also be a string.  The value is a string, and
67792 ** identifier, or a number.  If minusFlag is true, then the value is
67793 ** a number that was preceded by a minus sign.
67794 **
67795 ** If the left side is "database.id" then pId1 is the database name
67796 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
67797 ** id and pId2 is any empty string.
67798 */
67799 SQLITE_PRIVATE void sqlite3Pragma(
67800   Parse *pParse, 
67801   Token *pId1,        /* First part of [database.]id field */
67802   Token *pId2,        /* Second part of [database.]id field, or NULL */
67803   Token *pValue,      /* Token for <value>, or NULL */
67804   int minusFlag       /* True if a '-' sign preceded <value> */
67805 ){
67806   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
67807   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
67808   const char *zDb = 0;   /* The database name */
67809   Token *pId;            /* Pointer to <id> token */
67810   int iDb;               /* Database index for <database> */
67811   sqlite3 *db = pParse->db;
67812   Db *pDb;
67813   Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
67814   if( v==0 ) return;
67815   pParse->nMem = 2;
67816
67817   /* Interpret the [database.] part of the pragma statement. iDb is the
67818   ** index of the database this pragma is being applied to in db.aDb[]. */
67819   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
67820   if( iDb<0 ) return;
67821   pDb = &db->aDb[iDb];
67822
67823   /* If the temp database has been explicitly named as part of the 
67824   ** pragma, make sure it is open. 
67825   */
67826   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
67827     return;
67828   }
67829
67830   zLeft = sqlite3NameFromToken(db, pId);
67831   if( !zLeft ) return;
67832   if( minusFlag ){
67833     zRight = sqlite3MPrintf(db, "-%T", pValue);
67834   }else{
67835     zRight = sqlite3NameFromToken(db, pValue);
67836   }
67837
67838   zDb = ((pId2 && pId2->n>0)?pDb->zName:0);
67839   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
67840     goto pragma_out;
67841   }
67842  
67843 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
67844   /*
67845   **  PRAGMA [database.]default_cache_size
67846   **  PRAGMA [database.]default_cache_size=N
67847   **
67848   ** The first form reports the current persistent setting for the
67849   ** page cache size.  The value returned is the maximum number of
67850   ** pages in the page cache.  The second form sets both the current
67851   ** page cache size value and the persistent page cache size value
67852   ** stored in the database file.
67853   **
67854   ** The default cache size is stored in meta-value 2 of page 1 of the
67855   ** database file.  The cache size is actually the absolute value of
67856   ** this memory location.  The sign of meta-value 2 determines the
67857   ** synchronous setting.  A negative value means synchronous is off
67858   ** and a positive value means synchronous is on.
67859   */
67860   if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
67861     static const VdbeOpList getCacheSize[] = {
67862       { OP_ReadCookie,  0, 1,        2},  /* 0 */
67863       { OP_IfPos,       1, 6,        0},
67864       { OP_Integer,     0, 2,        0},
67865       { OP_Subtract,    1, 2,        1},
67866       { OP_IfPos,       1, 6,        0},
67867       { OP_Integer,     0, 1,        0},  /* 5 */
67868       { OP_ResultRow,   1, 1,        0},
67869     };
67870     int addr;
67871     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
67872     sqlite3VdbeUsesBtree(v, iDb);
67873     if( !zRight ){
67874       sqlite3VdbeSetNumCols(v, 1);
67875       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
67876       pParse->nMem += 2;
67877       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
67878       sqlite3VdbeChangeP1(v, addr, iDb);
67879       sqlite3VdbeChangeP1(v, addr+5, SQLITE_DEFAULT_CACHE_SIZE);
67880     }else{
67881       int size = atoi(zRight);
67882       if( size<0 ) size = -size;
67883       sqlite3BeginWriteOperation(pParse, 0, iDb);
67884       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
67885       sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, 2, 2);
67886       addr = sqlite3VdbeAddOp2(v, OP_IfPos, 2, 0);
67887       sqlite3VdbeAddOp2(v, OP_Integer, -size, 1);
67888       sqlite3VdbeJumpHere(v, addr);
67889       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 2, 1);
67890       pDb->pSchema->cache_size = size;
67891       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
67892     }
67893   }else
67894
67895   /*
67896   **  PRAGMA [database.]page_size
67897   **  PRAGMA [database.]page_size=N
67898   **
67899   ** The first form reports the current setting for the
67900   ** database page size in bytes.  The second form sets the
67901   ** database page size value.  The value can only be set if
67902   ** the database has not yet been created.
67903   */
67904   if( sqlite3StrICmp(zLeft,"page_size")==0 ){
67905     Btree *pBt = pDb->pBt;
67906     if( !zRight ){
67907       int size = pBt ? sqlite3BtreeGetPageSize(pBt) : 0;
67908       returnSingleInt(pParse, "page_size", size);
67909     }else{
67910       /* Malloc may fail when setting the page-size, as there is an internal
67911       ** buffer that the pager module resizes using sqlite3_realloc().
67912       */
67913       db->nextPagesize = atoi(zRight);
67914       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1) ){
67915         db->mallocFailed = 1;
67916       }
67917     }
67918   }else
67919
67920   /*
67921   **  PRAGMA [database.]max_page_count
67922   **  PRAGMA [database.]max_page_count=N
67923   **
67924   ** The first form reports the current setting for the
67925   ** maximum number of pages in the database file.  The 
67926   ** second form attempts to change this setting.  Both
67927   ** forms return the current setting.
67928   */
67929   if( sqlite3StrICmp(zLeft,"max_page_count")==0 ){
67930     Btree *pBt = pDb->pBt;
67931     int newMax = 0;
67932     if( zRight ){
67933       newMax = atoi(zRight);
67934     }
67935     if( pBt ){
67936       newMax = sqlite3BtreeMaxPageCount(pBt, newMax);
67937     }
67938     returnSingleInt(pParse, "max_page_count", newMax);
67939   }else
67940
67941   /*
67942   **  PRAGMA [database.]page_count
67943   **
67944   ** Return the number of pages in the specified database.
67945   */
67946   if( sqlite3StrICmp(zLeft,"page_count")==0 ){
67947     Vdbe *v;
67948     int iReg;
67949     v = sqlite3GetVdbe(pParse);
67950     if( !v || sqlite3ReadSchema(pParse) ) goto pragma_out;
67951     sqlite3CodeVerifySchema(pParse, iDb);
67952     iReg = ++pParse->nMem;
67953     sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
67954     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
67955     sqlite3VdbeSetNumCols(v, 1);
67956     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "page_count", SQLITE_STATIC);
67957   }else
67958
67959   /*
67960   **  PRAGMA [database.]locking_mode
67961   **  PRAGMA [database.]locking_mode = (normal|exclusive)
67962   */
67963   if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
67964     const char *zRet = "normal";
67965     int eMode = getLockingMode(zRight);
67966
67967     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
67968       /* Simple "PRAGMA locking_mode;" statement. This is a query for
67969       ** the current default locking mode (which may be different to
67970       ** the locking-mode of the main database).
67971       */
67972       eMode = db->dfltLockMode;
67973     }else{
67974       Pager *pPager;
67975       if( pId2->n==0 ){
67976         /* This indicates that no database name was specified as part
67977         ** of the PRAGMA command. In this case the locking-mode must be
67978         ** set on all attached databases, as well as the main db file.
67979         **
67980         ** Also, the sqlite3.dfltLockMode variable is set so that
67981         ** any subsequently attached databases also use the specified
67982         ** locking mode.
67983         */
67984         int ii;
67985         assert(pDb==&db->aDb[0]);
67986         for(ii=2; ii<db->nDb; ii++){
67987           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
67988           sqlite3PagerLockingMode(pPager, eMode);
67989         }
67990         db->dfltLockMode = eMode;
67991       }
67992       pPager = sqlite3BtreePager(pDb->pBt);
67993       eMode = sqlite3PagerLockingMode(pPager, eMode);
67994     }
67995
67996     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
67997     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
67998       zRet = "exclusive";
67999     }
68000     sqlite3VdbeSetNumCols(v, 1);
68001     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
68002     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
68003     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
68004   }else
68005
68006   /*
68007   **  PRAGMA [database.]journal_mode
68008   **  PRAGMA [database.]journal_mode = (delete|persist|off|truncate|memory)
68009   */
68010   if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
68011     int eMode;
68012     static char * const azModeName[] = {
68013       "delete", "persist", "off", "truncate", "memory"
68014     };
68015
68016     if( zRight==0 ){
68017       eMode = PAGER_JOURNALMODE_QUERY;
68018     }else{
68019       int n = strlen(zRight);
68020       eMode = sizeof(azModeName)/sizeof(azModeName[0]) - 1;
68021       while( eMode>=0 && sqlite3StrNICmp(zRight, azModeName[eMode], n)!=0 ){
68022         eMode--;
68023       }
68024     }
68025     if( pId2->n==0 && eMode==PAGER_JOURNALMODE_QUERY ){
68026       /* Simple "PRAGMA journal_mode;" statement. This is a query for
68027       ** the current default journal mode (which may be different to
68028       ** the journal-mode of the main database).
68029       */
68030       eMode = db->dfltJournalMode;
68031     }else{
68032       Pager *pPager;
68033       if( pId2->n==0 ){
68034         /* This indicates that no database name was specified as part
68035         ** of the PRAGMA command. In this case the journal-mode must be
68036         ** set on all attached databases, as well as the main db file.
68037         **
68038         ** Also, the sqlite3.dfltJournalMode variable is set so that
68039         ** any subsequently attached databases also use the specified
68040         ** journal mode.
68041         */
68042         int ii;
68043         assert(pDb==&db->aDb[0]);
68044         for(ii=1; ii<db->nDb; ii++){
68045           if( db->aDb[ii].pBt ){
68046             pPager = sqlite3BtreePager(db->aDb[ii].pBt);
68047             sqlite3PagerJournalMode(pPager, eMode);
68048           }
68049         }
68050         db->dfltJournalMode = eMode;
68051       }
68052       pPager = sqlite3BtreePager(pDb->pBt);
68053       eMode = sqlite3PagerJournalMode(pPager, eMode);
68054     }
68055     assert( eMode==PAGER_JOURNALMODE_DELETE
68056               || eMode==PAGER_JOURNALMODE_TRUNCATE
68057               || eMode==PAGER_JOURNALMODE_PERSIST
68058               || eMode==PAGER_JOURNALMODE_OFF
68059               || eMode==PAGER_JOURNALMODE_MEMORY );
68060     sqlite3VdbeSetNumCols(v, 1);
68061     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
68062     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, 
68063            azModeName[eMode], P4_STATIC);
68064     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
68065   }else
68066
68067   /*
68068   **  PRAGMA [database.]journal_size_limit
68069   **  PRAGMA [database.]journal_size_limit=N
68070   **
68071   ** Get or set the (boolean) value of the database 'auto-vacuum' parameter.
68072   */
68073   if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
68074     Pager *pPager = sqlite3BtreePager(pDb->pBt);
68075     i64 iLimit = -2;
68076     if( zRight ){
68077       int iLimit32 = atoi(zRight);
68078       if( iLimit32<-1 ){
68079         iLimit32 = -1;
68080       }
68081       iLimit = iLimit32;
68082     }
68083     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
68084     returnSingleInt(pParse, "journal_size_limit", (int)iLimit);
68085   }else
68086
68087 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
68088
68089   /*
68090   **  PRAGMA [database.]auto_vacuum
68091   **  PRAGMA [database.]auto_vacuum=N
68092   **
68093   ** Get or set the (boolean) value of the database 'auto-vacuum' parameter.
68094   */
68095 #ifndef SQLITE_OMIT_AUTOVACUUM
68096   if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
68097     Btree *pBt = pDb->pBt;
68098     if( sqlite3ReadSchema(pParse) ){
68099       goto pragma_out;
68100     }
68101     if( !zRight ){
68102       int auto_vacuum = 
68103           pBt ? sqlite3BtreeGetAutoVacuum(pBt) : SQLITE_DEFAULT_AUTOVACUUM;
68104       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
68105     }else{
68106       int eAuto = getAutoVacuum(zRight);
68107       db->nextAutovac = eAuto;
68108       if( eAuto>=0 ){
68109         /* Call SetAutoVacuum() to set initialize the internal auto and
68110         ** incr-vacuum flags. This is required in case this connection
68111         ** creates the database file. It is important that it is created
68112         ** as an auto-vacuum capable db.
68113         */
68114         int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
68115         if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
68116           /* When setting the auto_vacuum mode to either "full" or 
68117           ** "incremental", write the value of meta[6] in the database
68118           ** file. Before writing to meta[6], check that meta[3] indicates
68119           ** that this really is an auto-vacuum capable database.
68120           */
68121           static const VdbeOpList setMeta6[] = {
68122             { OP_Transaction,    0,               1,        0},    /* 0 */
68123             { OP_ReadCookie,     0,               1,        3},    /* 1 */
68124             { OP_If,             1,               0,        0},    /* 2 */
68125             { OP_Halt,           SQLITE_OK,       OE_Abort, 0},    /* 3 */
68126             { OP_Integer,        0,               1,        0},    /* 4 */
68127             { OP_SetCookie,      0,               6,        1},    /* 5 */
68128           };
68129           int iAddr;
68130           iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
68131           sqlite3VdbeChangeP1(v, iAddr, iDb);
68132           sqlite3VdbeChangeP1(v, iAddr+1, iDb);
68133           sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
68134           sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
68135           sqlite3VdbeChangeP1(v, iAddr+5, iDb);
68136           sqlite3VdbeUsesBtree(v, iDb);
68137         }
68138       }
68139     }
68140   }else
68141 #endif
68142
68143   /*
68144   **  PRAGMA [database.]incremental_vacuum(N)
68145   **
68146   ** Do N steps of incremental vacuuming on a database.
68147   */
68148 #ifndef SQLITE_OMIT_AUTOVACUUM
68149   if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
68150     int iLimit, addr;
68151     if( sqlite3ReadSchema(pParse) ){
68152       goto pragma_out;
68153     }
68154     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
68155       iLimit = 0x7fffffff;
68156     }
68157     sqlite3BeginWriteOperation(pParse, 0, iDb);
68158     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
68159     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
68160     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
68161     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
68162     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
68163     sqlite3VdbeJumpHere(v, addr);
68164   }else
68165 #endif
68166
68167 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
68168   /*
68169   **  PRAGMA [database.]cache_size
68170   **  PRAGMA [database.]cache_size=N
68171   **
68172   ** The first form reports the current local setting for the
68173   ** page cache size.  The local setting can be different from
68174   ** the persistent cache size value that is stored in the database
68175   ** file itself.  The value returned is the maximum number of
68176   ** pages in the page cache.  The second form sets the local
68177   ** page cache size value.  It does not change the persistent
68178   ** cache size stored on the disk so the cache size will revert
68179   ** to its default value when the database is closed and reopened.
68180   ** N should be a positive integer.
68181   */
68182   if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
68183     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
68184     if( !zRight ){
68185       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
68186     }else{
68187       int size = atoi(zRight);
68188       if( size<0 ) size = -size;
68189       pDb->pSchema->cache_size = size;
68190       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
68191     }
68192   }else
68193
68194   /*
68195   **   PRAGMA temp_store
68196   **   PRAGMA temp_store = "default"|"memory"|"file"
68197   **
68198   ** Return or set the local value of the temp_store flag.  Changing
68199   ** the local value does not make changes to the disk file and the default
68200   ** value will be restored the next time the database is opened.
68201   **
68202   ** Note that it is possible for the library compile-time options to
68203   ** override this setting
68204   */
68205   if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
68206     if( !zRight ){
68207       returnSingleInt(pParse, "temp_store", db->temp_store);
68208     }else{
68209       changeTempStorage(pParse, zRight);
68210     }
68211   }else
68212
68213   /*
68214   **   PRAGMA temp_store_directory
68215   **   PRAGMA temp_store_directory = ""|"directory_name"
68216   **
68217   ** Return or set the local value of the temp_store_directory flag.  Changing
68218   ** the value sets a specific directory to be used for temporary files.
68219   ** Setting to a null string reverts to the default temporary directory search.
68220   ** If temporary directory is changed, then invalidateTempStorage.
68221   **
68222   */
68223   if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
68224     if( !zRight ){
68225       if( sqlite3_temp_directory ){
68226         sqlite3VdbeSetNumCols(v, 1);
68227         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
68228             "temp_store_directory", SQLITE_STATIC);
68229         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
68230         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
68231       }
68232     }else{
68233 #ifndef SQLITE_OMIT_WSD
68234       if( zRight[0] ){
68235         int rc;
68236         int res;
68237         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
68238         if( rc!=SQLITE_OK || res==0 ){
68239           sqlite3ErrorMsg(pParse, "not a writable directory");
68240           goto pragma_out;
68241         }
68242       }
68243       if( SQLITE_TEMP_STORE==0
68244        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
68245        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
68246       ){
68247         invalidateTempStorage(pParse);
68248       }
68249       sqlite3_free(sqlite3_temp_directory);
68250       if( zRight[0] ){
68251         sqlite3_temp_directory = sqlite3DbStrDup(0, zRight);
68252       }else{
68253         sqlite3_temp_directory = 0;
68254       }
68255 #endif /* SQLITE_OMIT_WSD */
68256     }
68257   }else
68258
68259   /*
68260   **   PRAGMA [database.]synchronous
68261   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
68262   **
68263   ** Return or set the local value of the synchronous flag.  Changing
68264   ** the local value does not make changes to the disk file and the
68265   ** default value will be restored the next time the database is
68266   ** opened.
68267   */
68268   if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
68269     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
68270     if( !zRight ){
68271       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
68272     }else{
68273       if( !db->autoCommit ){
68274         sqlite3ErrorMsg(pParse, 
68275             "Safety level may not be changed inside a transaction");
68276       }else{
68277         pDb->safety_level = getSafetyLevel(zRight)+1;
68278       }
68279     }
68280   }else
68281 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
68282
68283 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
68284   if( flagPragma(pParse, zLeft, zRight) ){
68285     /* The flagPragma() subroutine also generates any necessary code
68286     ** there is nothing more to do here */
68287   }else
68288 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
68289
68290 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
68291   /*
68292   **   PRAGMA table_info(<table>)
68293   **
68294   ** Return a single row for each column of the named table. The columns of
68295   ** the returned data set are:
68296   **
68297   ** cid:        Column id (numbered from left to right, starting at 0)
68298   ** name:       Column name
68299   ** type:       Column declaration type.
68300   ** notnull:    True if 'NOT NULL' is part of column declaration
68301   ** dflt_value: The default value for the column, if any.
68302   */
68303   if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
68304     Table *pTab;
68305     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
68306     pTab = sqlite3FindTable(db, zRight, zDb);
68307     if( pTab ){
68308       int i;
68309       int nHidden = 0;
68310       Column *pCol;
68311       sqlite3VdbeSetNumCols(v, 6);
68312       pParse->nMem = 6;
68313       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
68314       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
68315       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
68316       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
68317       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
68318       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
68319       sqlite3ViewGetColumnNames(pParse, pTab);
68320       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
68321         const Token *pDflt;
68322         if( IsHiddenColumn(pCol) ){
68323           nHidden++;
68324           continue;
68325         }
68326         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
68327         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
68328         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
68329            pCol->zType ? pCol->zType : "", 0);
68330         sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
68331         if( pCol->pDflt && (pDflt = &pCol->pDflt->span)->z ){
68332           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pDflt->z, pDflt->n);
68333         }else{
68334           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
68335         }
68336         sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
68337         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
68338       }
68339     }
68340   }else
68341
68342   if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
68343     Index *pIdx;
68344     Table *pTab;
68345     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
68346     pIdx = sqlite3FindIndex(db, zRight, zDb);
68347     if( pIdx ){
68348       int i;
68349       pTab = pIdx->pTable;
68350       sqlite3VdbeSetNumCols(v, 3);
68351       pParse->nMem = 3;
68352       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
68353       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
68354       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
68355       for(i=0; i<pIdx->nColumn; i++){
68356         int cnum = pIdx->aiColumn[i];
68357         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
68358         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
68359         assert( pTab->nCol>cnum );
68360         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
68361         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
68362       }
68363     }
68364   }else
68365
68366   if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
68367     Index *pIdx;
68368     Table *pTab;
68369     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
68370     pTab = sqlite3FindTable(db, zRight, zDb);
68371     if( pTab ){
68372       v = sqlite3GetVdbe(pParse);
68373       pIdx = pTab->pIndex;
68374       if( pIdx ){
68375         int i = 0; 
68376         sqlite3VdbeSetNumCols(v, 3);
68377         pParse->nMem = 3;
68378         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
68379         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
68380         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
68381         while(pIdx){
68382           sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
68383           sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
68384           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
68385           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
68386           ++i;
68387           pIdx = pIdx->pNext;
68388         }
68389       }
68390     }
68391   }else
68392
68393   if( sqlite3StrICmp(zLeft, "database_list")==0 ){
68394     int i;
68395     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
68396     sqlite3VdbeSetNumCols(v, 3);
68397     pParse->nMem = 3;
68398     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
68399     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
68400     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
68401     for(i=0; i<db->nDb; i++){
68402       if( db->aDb[i].pBt==0 ) continue;
68403       assert( db->aDb[i].zName!=0 );
68404       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
68405       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
68406       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
68407            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
68408       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
68409     }
68410   }else
68411
68412   if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
68413     int i = 0;
68414     HashElem *p;
68415     sqlite3VdbeSetNumCols(v, 2);
68416     pParse->nMem = 2;
68417     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
68418     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
68419     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
68420       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
68421       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
68422       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
68423       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
68424     }
68425   }else
68426 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
68427
68428 #ifndef SQLITE_OMIT_FOREIGN_KEY
68429   if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
68430     FKey *pFK;
68431     Table *pTab;
68432     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
68433     pTab = sqlite3FindTable(db, zRight, zDb);
68434     if( pTab ){
68435       v = sqlite3GetVdbe(pParse);
68436       pFK = pTab->pFKey;
68437       if( pFK ){
68438         int i = 0; 
68439         sqlite3VdbeSetNumCols(v, 8);
68440         pParse->nMem = 8;
68441         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
68442         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
68443         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
68444         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
68445         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
68446         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
68447         sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
68448         sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
68449         while(pFK){
68450           int j;
68451           for(j=0; j<pFK->nCol; j++){
68452             char *zCol = pFK->aCol[j].zCol;
68453             char *zOnUpdate = (char *)actionName(pFK->updateConf);
68454             char *zOnDelete = (char *)actionName(pFK->deleteConf);
68455             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
68456             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
68457             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
68458             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
68459                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
68460             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
68461             sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
68462             sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
68463             sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
68464             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
68465           }
68466           ++i;
68467           pFK = pFK->pNextFrom;
68468         }
68469       }
68470     }
68471   }else
68472 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
68473
68474 #ifndef NDEBUG
68475   if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
68476     if( zRight ){
68477       if( getBoolean(zRight) ){
68478         sqlite3ParserTrace(stderr, "parser: ");
68479       }else{
68480         sqlite3ParserTrace(0, 0);
68481       }
68482     }
68483   }else
68484 #endif
68485
68486   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
68487   ** used will be case sensitive or not depending on the RHS.
68488   */
68489   if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
68490     if( zRight ){
68491       sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
68492     }
68493   }else
68494
68495 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
68496 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
68497 #endif
68498
68499 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
68500   /* Pragma "quick_check" is an experimental reduced version of 
68501   ** integrity_check designed to detect most database corruption
68502   ** without most of the overhead of a full integrity-check.
68503   */
68504   if( sqlite3StrICmp(zLeft, "integrity_check")==0
68505    || sqlite3StrICmp(zLeft, "quick_check")==0 
68506   ){
68507     int i, j, addr, mxErr;
68508
68509     /* Code that appears at the end of the integrity check.  If no error
68510     ** messages have been generated, output OK.  Otherwise output the
68511     ** error message
68512     */
68513     static const VdbeOpList endCode[] = {
68514       { OP_AddImm,      1, 0,        0},    /* 0 */
68515       { OP_IfNeg,       1, 0,        0},    /* 1 */
68516       { OP_String8,     0, 3,        0},    /* 2 */
68517       { OP_ResultRow,   3, 1,        0},
68518     };
68519
68520     int isQuick = (zLeft[0]=='q');
68521
68522     /* Initialize the VDBE program */
68523     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
68524     pParse->nMem = 6;
68525     sqlite3VdbeSetNumCols(v, 1);
68526     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
68527
68528     /* Set the maximum error count */
68529     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
68530     if( zRight ){
68531       mxErr = atoi(zRight);
68532       if( mxErr<=0 ){
68533         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
68534       }
68535     }
68536     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
68537
68538     /* Do an integrity check on each database file */
68539     for(i=0; i<db->nDb; i++){
68540       HashElem *x;
68541       Hash *pTbls;
68542       int cnt = 0;
68543
68544       if( OMIT_TEMPDB && i==1 ) continue;
68545
68546       sqlite3CodeVerifySchema(pParse, i);
68547       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
68548       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
68549       sqlite3VdbeJumpHere(v, addr);
68550
68551       /* Do an integrity check of the B-Tree
68552       **
68553       ** Begin by filling registers 2, 3, ... with the root pages numbers
68554       ** for all tables and indices in the database.
68555       */
68556       pTbls = &db->aDb[i].pSchema->tblHash;
68557       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
68558         Table *pTab = sqliteHashData(x);
68559         Index *pIdx;
68560         sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
68561         cnt++;
68562         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
68563           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
68564           cnt++;
68565         }
68566       }
68567       if( cnt==0 ) continue;
68568
68569       /* Make sure sufficient number of registers have been allocated */
68570       if( pParse->nMem < cnt+4 ){
68571         pParse->nMem = cnt+4;
68572       }
68573
68574       /* Do the b-tree integrity checks */
68575       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
68576       sqlite3VdbeChangeP5(v, i);
68577       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
68578       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
68579          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
68580          P4_DYNAMIC);
68581       sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
68582       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
68583       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
68584       sqlite3VdbeJumpHere(v, addr);
68585
68586       /* Make sure all the indices are constructed correctly.
68587       */
68588       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
68589         Table *pTab = sqliteHashData(x);
68590         Index *pIdx;
68591         int loopTop;
68592
68593         if( pTab->pIndex==0 ) continue;
68594         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
68595         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
68596         sqlite3VdbeJumpHere(v, addr);
68597         sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
68598         sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
68599         loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
68600         sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
68601         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
68602           int jmp2;
68603           static const VdbeOpList idxErr[] = {
68604             { OP_AddImm,      1, -1,  0},
68605             { OP_String8,     0,  3,  0},    /* 1 */
68606             { OP_Rowid,       1,  4,  0},
68607             { OP_String8,     0,  5,  0},    /* 3 */
68608             { OP_String8,     0,  6,  0},    /* 4 */
68609             { OP_Concat,      4,  3,  3},
68610             { OP_Concat,      5,  3,  3},
68611             { OP_Concat,      6,  3,  3},
68612             { OP_ResultRow,   3,  1,  0},
68613             { OP_IfPos,       1,  0,  0},    /* 9 */
68614             { OP_Halt,        0,  0,  0},
68615           };
68616           sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 1);
68617           jmp2 = sqlite3VdbeAddOp3(v, OP_Found, j+2, 0, 3);
68618           addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
68619           sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
68620           sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
68621           sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_STATIC);
68622           sqlite3VdbeJumpHere(v, addr+9);
68623           sqlite3VdbeJumpHere(v, jmp2);
68624         }
68625         sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
68626         sqlite3VdbeJumpHere(v, loopTop);
68627         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
68628           static const VdbeOpList cntIdx[] = {
68629              { OP_Integer,      0,  3,  0},
68630              { OP_Rewind,       0,  0,  0},  /* 1 */
68631              { OP_AddImm,       3,  1,  0},
68632              { OP_Next,         0,  0,  0},  /* 3 */
68633              { OP_Eq,           2,  0,  3},  /* 4 */
68634              { OP_AddImm,       1, -1,  0},
68635              { OP_String8,      0,  2,  0},  /* 6 */
68636              { OP_String8,      0,  3,  0},  /* 7 */
68637              { OP_Concat,       3,  2,  2},
68638              { OP_ResultRow,    2,  1,  0},
68639           };
68640           if( pIdx->tnum==0 ) continue;
68641           addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
68642           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
68643           sqlite3VdbeJumpHere(v, addr);
68644           addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
68645           sqlite3VdbeChangeP1(v, addr+1, j+2);
68646           sqlite3VdbeChangeP2(v, addr+1, addr+4);
68647           sqlite3VdbeChangeP1(v, addr+3, j+2);
68648           sqlite3VdbeChangeP2(v, addr+3, addr+2);
68649           sqlite3VdbeJumpHere(v, addr+4);
68650           sqlite3VdbeChangeP4(v, addr+6, 
68651                      "wrong # of entries in index ", P4_STATIC);
68652           sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_STATIC);
68653         }
68654       } 
68655     }
68656     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
68657     sqlite3VdbeChangeP2(v, addr, -mxErr);
68658     sqlite3VdbeJumpHere(v, addr+1);
68659     sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
68660   }else
68661 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
68662
68663 #ifndef SQLITE_OMIT_UTF16
68664   /*
68665   **   PRAGMA encoding
68666   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
68667   **
68668   ** In its first form, this pragma returns the encoding of the main
68669   ** database. If the database is not initialized, it is initialized now.
68670   **
68671   ** The second form of this pragma is a no-op if the main database file
68672   ** has not already been initialized. In this case it sets the default
68673   ** encoding that will be used for the main database file if a new file
68674   ** is created. If an existing main database file is opened, then the
68675   ** default text encoding for the existing database is used.
68676   ** 
68677   ** In all cases new databases created using the ATTACH command are
68678   ** created to use the same default text encoding as the main database. If
68679   ** the main database has not been initialized and/or created when ATTACH
68680   ** is executed, this is done before the ATTACH operation.
68681   **
68682   ** In the second form this pragma sets the text encoding to be used in
68683   ** new database files created using this database handle. It is only
68684   ** useful if invoked immediately after the main database i
68685   */
68686   if( sqlite3StrICmp(zLeft, "encoding")==0 ){
68687     static const struct EncName {
68688       char *zName;
68689       u8 enc;
68690     } encnames[] = {
68691       { "UTF-8",    SQLITE_UTF8        },
68692       { "UTF8",     SQLITE_UTF8        },
68693       { "UTF-16le", SQLITE_UTF16LE     },
68694       { "UTF16le",  SQLITE_UTF16LE     },
68695       { "UTF-16be", SQLITE_UTF16BE     },
68696       { "UTF16be",  SQLITE_UTF16BE     },
68697       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
68698       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
68699       { 0, 0 }
68700     };
68701     const struct EncName *pEnc;
68702     if( !zRight ){    /* "PRAGMA encoding" */
68703       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
68704       sqlite3VdbeSetNumCols(v, 1);
68705       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
68706       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
68707       for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
68708         if( pEnc->enc==ENC(pParse->db) ){
68709           sqlite3VdbeChangeP4(v, -1, pEnc->zName, P4_STATIC);
68710           break;
68711         }
68712       }
68713       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
68714     }else{                        /* "PRAGMA encoding = XXX" */
68715       /* Only change the value of sqlite.enc if the database handle is not
68716       ** initialized. If the main database exists, the new sqlite.enc value
68717       ** will be overwritten when the schema is next loaded. If it does not
68718       ** already exists, it will be created to use the new encoding value.
68719       */
68720       if( 
68721         !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
68722         DbHasProperty(db, 0, DB_Empty) 
68723       ){
68724         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
68725           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
68726             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
68727             break;
68728           }
68729         }
68730         if( !pEnc->zName ){
68731           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
68732         }
68733       }
68734     }
68735   }else
68736 #endif /* SQLITE_OMIT_UTF16 */
68737
68738 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
68739   /*
68740   **   PRAGMA [database.]schema_version
68741   **   PRAGMA [database.]schema_version = <integer>
68742   **
68743   **   PRAGMA [database.]user_version
68744   **   PRAGMA [database.]user_version = <integer>
68745   **
68746   ** The pragma's schema_version and user_version are used to set or get
68747   ** the value of the schema-version and user-version, respectively. Both
68748   ** the schema-version and the user-version are 32-bit signed integers
68749   ** stored in the database header.
68750   **
68751   ** The schema-cookie is usually only manipulated internally by SQLite. It
68752   ** is incremented by SQLite whenever the database schema is modified (by
68753   ** creating or dropping a table or index). The schema version is used by
68754   ** SQLite each time a query is executed to ensure that the internal cache
68755   ** of the schema used when compiling the SQL query matches the schema of
68756   ** the database against which the compiled query is actually executed.
68757   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
68758   ** the schema-version is potentially dangerous and may lead to program
68759   ** crashes or database corruption. Use with caution!
68760   **
68761   ** The user-version is not used internally by SQLite. It may be used by
68762   ** applications for any purpose.
68763   */
68764   if( sqlite3StrICmp(zLeft, "schema_version")==0 
68765    || sqlite3StrICmp(zLeft, "user_version")==0 
68766    || sqlite3StrICmp(zLeft, "freelist_count")==0 
68767   ){
68768     int iCookie;   /* Cookie index. 0 for schema-cookie, 6 for user-cookie. */
68769     sqlite3VdbeUsesBtree(v, iDb);
68770     switch( zLeft[0] ){
68771       case 's': case 'S':
68772         iCookie = 0;
68773         break;
68774       case 'f': case 'F':
68775         iCookie = 1;
68776         iDb = (-1*(iDb+1));
68777         assert(iDb<=0);
68778         break;
68779       default:
68780         iCookie = 5;
68781         break;
68782     }
68783
68784     if( zRight && iDb>=0 ){
68785       /* Write the specified cookie value */
68786       static const VdbeOpList setCookie[] = {
68787         { OP_Transaction,    0,  1,  0},    /* 0 */
68788         { OP_Integer,        0,  1,  0},    /* 1 */
68789         { OP_SetCookie,      0,  0,  1},    /* 2 */
68790       };
68791       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
68792       sqlite3VdbeChangeP1(v, addr, iDb);
68793       sqlite3VdbeChangeP1(v, addr+1, atoi(zRight));
68794       sqlite3VdbeChangeP1(v, addr+2, iDb);
68795       sqlite3VdbeChangeP2(v, addr+2, iCookie);
68796     }else{
68797       /* Read the specified cookie value */
68798       static const VdbeOpList readCookie[] = {
68799         { OP_ReadCookie,      0,  1,  0},    /* 0 */
68800         { OP_ResultRow,       1,  1,  0}
68801       };
68802       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
68803       sqlite3VdbeChangeP1(v, addr, iDb);
68804       sqlite3VdbeChangeP3(v, addr, iCookie);
68805       sqlite3VdbeSetNumCols(v, 1);
68806       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
68807     }
68808   }else
68809 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
68810
68811 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
68812   /*
68813   ** Report the current state of file logs for all databases
68814   */
68815   if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
68816     static const char *const azLockName[] = {
68817       "unlocked", "shared", "reserved", "pending", "exclusive"
68818     };
68819     int i;
68820     Vdbe *v = sqlite3GetVdbe(pParse);
68821     sqlite3VdbeSetNumCols(v, 2);
68822     pParse->nMem = 2;
68823     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
68824     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
68825     for(i=0; i<db->nDb; i++){
68826       Btree *pBt;
68827       Pager *pPager;
68828       const char *zState = "unknown";
68829       int j;
68830       if( db->aDb[i].zName==0 ) continue;
68831       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
68832       pBt = db->aDb[i].pBt;
68833       if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
68834         zState = "closed";
68835       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, 
68836                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
68837          zState = azLockName[j];
68838       }
68839       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
68840       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
68841     }
68842
68843   }else
68844 #endif
68845
68846 #ifdef SQLITE_SSE
68847   /*
68848   ** Check to see if the sqlite_statements table exists.  Create it
68849   ** if it does not.
68850   */
68851   if( sqlite3StrICmp(zLeft, "create_sqlite_statement_table")==0 ){
68852     extern int sqlite3CreateStatementsTable(Parse*);
68853     sqlite3CreateStatementsTable(pParse);
68854   }else
68855 #endif
68856
68857 #if SQLITE_HAS_CODEC
68858   if( sqlite3StrICmp(zLeft, "key")==0 ){
68859     sqlite3_key(db, zRight, strlen(zRight));
68860   }else
68861 #endif
68862 #if SQLITE_HAS_CODEC || defined(SQLITE_ENABLE_CEROD)
68863   if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
68864 #if SQLITE_HAS_CODEC
68865     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
68866       extern void sqlite3_activate_see(const char*);
68867       sqlite3_activate_see(&zRight[4]);
68868     }
68869 #endif
68870 #ifdef SQLITE_ENABLE_CEROD
68871     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
68872       extern void sqlite3_activate_cerod(const char*);
68873       sqlite3_activate_cerod(&zRight[6]);
68874     }
68875 #endif
68876   }
68877 #endif
68878
68879   {}
68880
68881   if( v ){
68882     /* Code an OP_Expire at the end of each PRAGMA program to cause
68883     ** the VDBE implementing the pragma to expire. Most (all?) pragmas
68884     ** are only valid for a single execution.
68885     */
68886     sqlite3VdbeAddOp2(v, OP_Expire, 1, 0);
68887
68888     /*
68889     ** Reset the safety level, in case the fullfsync flag or synchronous
68890     ** setting changed.
68891     */
68892 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
68893     if( db->autoCommit ){
68894       sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
68895                  (db->flags&SQLITE_FullFSync)!=0);
68896     }
68897 #endif
68898   }
68899 pragma_out:
68900   sqlite3DbFree(db, zLeft);
68901   sqlite3DbFree(db, zRight);
68902 }
68903
68904 #endif /* SQLITE_OMIT_PRAGMA || SQLITE_OMIT_PARSER */
68905
68906 /************** End of pragma.c **********************************************/
68907 /************** Begin file prepare.c *****************************************/
68908 /*
68909 ** 2005 May 25
68910 **
68911 ** The author disclaims copyright to this source code.  In place of
68912 ** a legal notice, here is a blessing:
68913 **
68914 **    May you do good and not evil.
68915 **    May you find forgiveness for yourself and forgive others.
68916 **    May you share freely, never taking more than you give.
68917 **
68918 *************************************************************************
68919 ** This file contains the implementation of the sqlite3_prepare()
68920 ** interface, and routines that contribute to loading the database schema
68921 ** from disk.
68922 **
68923 ** $Id: prepare.c,v 1.101 2008/11/19 16:52:44 danielk1977 Exp $
68924 */
68925
68926 /*
68927 ** Fill the InitData structure with an error message that indicates
68928 ** that the database is corrupt.
68929 */
68930 static void corruptSchema(
68931   InitData *pData,     /* Initialization context */
68932   const char *zObj,    /* Object being parsed at the point of error */
68933   const char *zExtra   /* Error information */
68934 ){
68935   sqlite3 *db = pData->db;
68936   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
68937     if( zObj==0 ) zObj = "?";
68938     sqlite3SetString(pData->pzErrMsg, pData->db,
68939        "malformed database schema (%s)", zObj);
68940     if( zExtra && zExtra[0] ){
68941       *pData->pzErrMsg = sqlite3MAppendf(pData->db, *pData->pzErrMsg, "%s - %s",
68942                                   *pData->pzErrMsg, zExtra);
68943     }
68944   }
68945   pData->rc = SQLITE_CORRUPT;
68946 }
68947
68948 /*
68949 ** This is the callback routine for the code that initializes the
68950 ** database.  See sqlite3Init() below for additional information.
68951 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
68952 **
68953 ** Each callback contains the following information:
68954 **
68955 **     argv[0] = name of thing being created
68956 **     argv[1] = root page number for table or index. 0 for trigger or view.
68957 **     argv[2] = SQL text for the CREATE statement.
68958 **
68959 */
68960 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
68961   InitData *pData = (InitData*)pInit;
68962   sqlite3 *db = pData->db;
68963   int iDb = pData->iDb;
68964
68965   assert( argc==3 );
68966   UNUSED_PARAMETER2(NotUsed, argc);
68967   assert( sqlite3_mutex_held(db->mutex) );
68968   DbClearProperty(db, iDb, DB_Empty);
68969   if( db->mallocFailed ){
68970     corruptSchema(pData, argv[0], 0);
68971     return SQLITE_NOMEM;
68972   }
68973
68974   assert( iDb>=0 && iDb<db->nDb );
68975   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
68976   if( argv[1]==0 ){
68977     corruptSchema(pData, argv[0], 0);
68978   }else if( argv[2] && argv[2][0] ){
68979     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
68980     ** But because db->init.busy is set to 1, no VDBE code is generated
68981     ** or executed.  All the parser does is build the internal data
68982     ** structures that describe the table, index, or view.
68983     */
68984     char *zErr;
68985     int rc;
68986     u8 lookasideEnabled;
68987     assert( db->init.busy );
68988     db->init.iDb = iDb;
68989     db->init.newTnum = atoi(argv[1]);
68990     lookasideEnabled = db->lookaside.bEnabled;
68991     db->lookaside.bEnabled = 0;
68992     rc = sqlite3_exec(db, argv[2], 0, 0, &zErr);
68993     db->init.iDb = 0;
68994     db->lookaside.bEnabled = lookasideEnabled;
68995     assert( rc!=SQLITE_OK || zErr==0 );
68996     if( SQLITE_OK!=rc ){
68997       pData->rc = rc;
68998       if( rc==SQLITE_NOMEM ){
68999         db->mallocFailed = 1;
69000       }else if( rc!=SQLITE_INTERRUPT ){
69001         corruptSchema(pData, argv[0], zErr);
69002       }
69003       sqlite3DbFree(db, zErr);
69004     }
69005   }else if( argv[0]==0 ){
69006     corruptSchema(pData, 0, 0);
69007   }else{
69008     /* If the SQL column is blank it means this is an index that
69009     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
69010     ** constraint for a CREATE TABLE.  The index should have already
69011     ** been created when we processed the CREATE TABLE.  All we have
69012     ** to do here is record the root page number for that index.
69013     */
69014     Index *pIndex;
69015     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
69016     if( pIndex==0 || pIndex->tnum!=0 ){
69017       /* This can occur if there exists an index on a TEMP table which
69018       ** has the same name as another index on a permanent index.  Since
69019       ** the permanent table is hidden by the TEMP table, we can also
69020       ** safely ignore the index on the permanent table.
69021       */
69022       /* Do Nothing */;
69023     }else{
69024       pIndex->tnum = atoi(argv[1]);
69025     }
69026   }
69027   return 0;
69028 }
69029
69030 /*
69031 ** Attempt to read the database schema and initialize internal
69032 ** data structures for a single database file.  The index of the
69033 ** database file is given by iDb.  iDb==0 is used for the main
69034 ** database.  iDb==1 should never be used.  iDb>=2 is used for
69035 ** auxiliary databases.  Return one of the SQLITE_ error codes to
69036 ** indicate success or failure.
69037 */
69038 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
69039   int rc;
69040   BtCursor *curMain;
69041   int size;
69042   Table *pTab;
69043   Db *pDb;
69044   char const *azArg[4];
69045   int meta[10];
69046   InitData initData;
69047   char const *zMasterSchema;
69048   char const *zMasterName = SCHEMA_TABLE(iDb);
69049
69050   /*
69051   ** The master database table has a structure like this
69052   */
69053   static const char master_schema[] = 
69054      "CREATE TABLE sqlite_master(\n"
69055      "  type text,\n"
69056      "  name text,\n"
69057      "  tbl_name text,\n"
69058      "  rootpage integer,\n"
69059      "  sql text\n"
69060      ")"
69061   ;
69062 #ifndef SQLITE_OMIT_TEMPDB
69063   static const char temp_master_schema[] = 
69064      "CREATE TEMP TABLE sqlite_temp_master(\n"
69065      "  type text,\n"
69066      "  name text,\n"
69067      "  tbl_name text,\n"
69068      "  rootpage integer,\n"
69069      "  sql text\n"
69070      ")"
69071   ;
69072 #else
69073   #define temp_master_schema 0
69074 #endif
69075
69076   assert( iDb>=0 && iDb<db->nDb );
69077   assert( db->aDb[iDb].pSchema );
69078   assert( sqlite3_mutex_held(db->mutex) );
69079   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
69080
69081   /* zMasterSchema and zInitScript are set to point at the master schema
69082   ** and initialisation script appropriate for the database being
69083   ** initialised. zMasterName is the name of the master table.
69084   */
69085   if( !OMIT_TEMPDB && iDb==1 ){
69086     zMasterSchema = temp_master_schema;
69087   }else{
69088     zMasterSchema = master_schema;
69089   }
69090   zMasterName = SCHEMA_TABLE(iDb);
69091
69092   /* Construct the schema tables.  */
69093   azArg[0] = zMasterName;
69094   azArg[1] = "1";
69095   azArg[2] = zMasterSchema;
69096   azArg[3] = 0;
69097   initData.db = db;
69098   initData.iDb = iDb;
69099   initData.rc = SQLITE_OK;
69100   initData.pzErrMsg = pzErrMsg;
69101   (void)sqlite3SafetyOff(db);
69102   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
69103   (void)sqlite3SafetyOn(db);
69104   if( initData.rc ){
69105     rc = initData.rc;
69106     goto error_out;
69107   }
69108   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
69109   if( pTab ){
69110     pTab->tabFlags |= TF_Readonly;
69111   }
69112
69113   /* Create a cursor to hold the database open
69114   */
69115   pDb = &db->aDb[iDb];
69116   if( pDb->pBt==0 ){
69117     if( !OMIT_TEMPDB && iDb==1 ){
69118       DbSetProperty(db, 1, DB_SchemaLoaded);
69119     }
69120     return SQLITE_OK;
69121   }
69122   curMain = sqlite3MallocZero(sqlite3BtreeCursorSize());
69123   if( !curMain ){
69124     rc = SQLITE_NOMEM;
69125     goto error_out;
69126   }
69127   sqlite3BtreeEnter(pDb->pBt);
69128   rc = sqlite3BtreeCursor(pDb->pBt, MASTER_ROOT, 0, 0, curMain);
69129   if( rc!=SQLITE_OK && rc!=SQLITE_EMPTY ){
69130     sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
69131     goto initone_error_out;
69132   }
69133
69134   /* Get the database meta information.
69135   **
69136   ** Meta values are as follows:
69137   **    meta[0]   Schema cookie.  Changes with each schema change.
69138   **    meta[1]   File format of schema layer.
69139   **    meta[2]   Size of the page cache.
69140   **    meta[3]   Use freelist if 0.  Autovacuum if greater than zero.
69141   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
69142   **    meta[5]   The user cookie. Used by the application.
69143   **    meta[6]   Incremental-vacuum flag.
69144   **    meta[7]
69145   **    meta[8]
69146   **    meta[9]
69147   **
69148   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
69149   ** the possible values of meta[4].
69150   */
69151   if( rc==SQLITE_OK ){
69152     int i;
69153     for(i=0; i<ArraySize(meta); i++){
69154       rc = sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
69155       if( rc ){
69156         sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
69157         goto initone_error_out;
69158       }
69159     }
69160   }else{
69161     memset(meta, 0, sizeof(meta));
69162   }
69163   pDb->pSchema->schema_cookie = meta[0];
69164
69165   /* If opening a non-empty database, check the text encoding. For the
69166   ** main database, set sqlite3.enc to the encoding of the main database.
69167   ** For an attached db, it is an error if the encoding is not the same
69168   ** as sqlite3.enc.
69169   */
69170   if( meta[4] ){  /* text encoding */
69171     if( iDb==0 ){
69172       /* If opening the main database, set ENC(db). */
69173       ENC(db) = (u8)meta[4];
69174       db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0);
69175     }else{
69176       /* If opening an attached database, the encoding much match ENC(db) */
69177       if( meta[4]!=ENC(db) ){
69178         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
69179             " text encoding as main database");
69180         rc = SQLITE_ERROR;
69181         goto initone_error_out;
69182       }
69183     }
69184   }else{
69185     DbSetProperty(db, iDb, DB_Empty);
69186   }
69187   pDb->pSchema->enc = ENC(db);
69188
69189   if( pDb->pSchema->cache_size==0 ){
69190     size = meta[2];
69191     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
69192     if( size<0 ) size = -size;
69193     pDb->pSchema->cache_size = size;
69194     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
69195   }
69196
69197   /*
69198   ** file_format==1    Version 3.0.0.
69199   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
69200   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
69201   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
69202   */
69203   pDb->pSchema->file_format = meta[1];
69204   if( pDb->pSchema->file_format==0 ){
69205     pDb->pSchema->file_format = 1;
69206   }
69207   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
69208     sqlite3SetString(pzErrMsg, db, "unsupported file format");
69209     rc = SQLITE_ERROR;
69210     goto initone_error_out;
69211   }
69212
69213   /* Ticket #2804:  When we open a database in the newer file format,
69214   ** clear the legacy_file_format pragma flag so that a VACUUM will
69215   ** not downgrade the database and thus invalidate any descending
69216   ** indices that the user might have created.
69217   */
69218   if( iDb==0 && meta[1]>=4 ){
69219     db->flags &= ~SQLITE_LegacyFileFmt;
69220   }
69221
69222   /* Read the schema information out of the schema tables
69223   */
69224   assert( db->init.busy );
69225   if( rc==SQLITE_EMPTY ){
69226     /* For an empty database, there is nothing to read */
69227     rc = SQLITE_OK;
69228   }else{
69229     char *zSql;
69230     zSql = sqlite3MPrintf(db, 
69231         "SELECT name, rootpage, sql FROM '%q'.%s",
69232         db->aDb[iDb].zName, zMasterName);
69233     (void)sqlite3SafetyOff(db);
69234 #ifndef SQLITE_OMIT_AUTHORIZATION
69235     {
69236       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
69237       xAuth = db->xAuth;
69238       db->xAuth = 0;
69239 #endif
69240       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
69241 #ifndef SQLITE_OMIT_AUTHORIZATION
69242       db->xAuth = xAuth;
69243     }
69244 #endif
69245     if( rc==SQLITE_OK ) rc = initData.rc;
69246     (void)sqlite3SafetyOn(db);
69247     sqlite3DbFree(db, zSql);
69248 #ifndef SQLITE_OMIT_ANALYZE
69249     if( rc==SQLITE_OK ){
69250       sqlite3AnalysisLoad(db, iDb);
69251     }
69252 #endif
69253   }
69254   if( db->mallocFailed ){
69255     rc = SQLITE_NOMEM;
69256     sqlite3ResetInternalSchema(db, 0);
69257   }
69258   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
69259     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
69260     ** the schema loaded, even if errors occured. In this situation the 
69261     ** current sqlite3_prepare() operation will fail, but the following one
69262     ** will attempt to compile the supplied statement against whatever subset
69263     ** of the schema was loaded before the error occured. The primary
69264     ** purpose of this is to allow access to the sqlite_master table
69265     ** even when its contents have been corrupted.
69266     */
69267     DbSetProperty(db, iDb, DB_SchemaLoaded);
69268     rc = SQLITE_OK;
69269   }
69270
69271   /* Jump here for an error that occurs after successfully allocating
69272   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
69273   ** before that point, jump to error_out.
69274   */
69275 initone_error_out:
69276   sqlite3BtreeCloseCursor(curMain);
69277   sqlite3_free(curMain);
69278   sqlite3BtreeLeave(pDb->pBt);
69279
69280 error_out:
69281   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
69282     db->mallocFailed = 1;
69283   }
69284   return rc;
69285 }
69286
69287 /*
69288 ** Initialize all database files - the main database file, the file
69289 ** used to store temporary tables, and any additional database files
69290 ** created using ATTACH statements.  Return a success code.  If an
69291 ** error occurs, write an error message into *pzErrMsg.
69292 **
69293 ** After a database is initialized, the DB_SchemaLoaded bit is set
69294 ** bit is set in the flags field of the Db structure. If the database
69295 ** file was of zero-length, then the DB_Empty flag is also set.
69296 */
69297 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
69298   int i, rc;
69299   int commit_internal = !(db->flags&SQLITE_InternChanges);
69300   
69301   assert( sqlite3_mutex_held(db->mutex) );
69302   if( db->init.busy ) return SQLITE_OK;
69303   rc = SQLITE_OK;
69304   db->init.busy = 1;
69305   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
69306     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
69307     rc = sqlite3InitOne(db, i, pzErrMsg);
69308     if( rc ){
69309       sqlite3ResetInternalSchema(db, i);
69310     }
69311   }
69312
69313   /* Once all the other databases have been initialised, load the schema
69314   ** for the TEMP database. This is loaded last, as the TEMP database
69315   ** schema may contain references to objects in other databases.
69316   */
69317 #ifndef SQLITE_OMIT_TEMPDB
69318   if( rc==SQLITE_OK && db->nDb>1 && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
69319     rc = sqlite3InitOne(db, 1, pzErrMsg);
69320     if( rc ){
69321       sqlite3ResetInternalSchema(db, 1);
69322     }
69323   }
69324 #endif
69325
69326   db->init.busy = 0;
69327   if( rc==SQLITE_OK && commit_internal ){
69328     sqlite3CommitInternalChanges(db);
69329   }
69330
69331   return rc; 
69332 }
69333
69334 /*
69335 ** This routine is a no-op if the database schema is already initialised.
69336 ** Otherwise, the schema is loaded. An error code is returned.
69337 */
69338 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
69339   int rc = SQLITE_OK;
69340   sqlite3 *db = pParse->db;
69341   assert( sqlite3_mutex_held(db->mutex) );
69342   if( !db->init.busy ){
69343     rc = sqlite3Init(db, &pParse->zErrMsg);
69344   }
69345   if( rc!=SQLITE_OK ){
69346     pParse->rc = rc;
69347     pParse->nErr++;
69348   }
69349   return rc;
69350 }
69351
69352
69353 /*
69354 ** Check schema cookies in all databases.  If any cookie is out
69355 ** of date, return 0.  If all schema cookies are current, return 1.
69356 */
69357 static int schemaIsValid(sqlite3 *db){
69358   int iDb;
69359   int rc;
69360   BtCursor *curTemp;
69361   int cookie;
69362   int allOk = 1;
69363
69364   curTemp = (BtCursor *)sqlite3Malloc(sqlite3BtreeCursorSize());
69365   if( curTemp ){
69366     assert( sqlite3_mutex_held(db->mutex) );
69367     for(iDb=0; allOk && iDb<db->nDb; iDb++){
69368       Btree *pBt;
69369       pBt = db->aDb[iDb].pBt;
69370       if( pBt==0 ) continue;
69371       memset(curTemp, 0, sqlite3BtreeCursorSize());
69372       rc = sqlite3BtreeCursor(pBt, MASTER_ROOT, 0, 0, curTemp);
69373       if( rc==SQLITE_OK ){
69374         rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&cookie);
69375         if( rc==SQLITE_OK && cookie!=db->aDb[iDb].pSchema->schema_cookie ){
69376           allOk = 0;
69377         }
69378         sqlite3BtreeCloseCursor(curTemp);
69379       }
69380       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
69381         db->mallocFailed = 1;
69382       }
69383     }
69384     sqlite3_free(curTemp);
69385   }else{
69386     allOk = 0;
69387     db->mallocFailed = 1;
69388   }
69389
69390   return allOk;
69391 }
69392
69393 /*
69394 ** Convert a schema pointer into the iDb index that indicates
69395 ** which database file in db->aDb[] the schema refers to.
69396 **
69397 ** If the same database is attached more than once, the first
69398 ** attached database is returned.
69399 */
69400 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
69401   int i = -1000000;
69402
69403   /* If pSchema is NULL, then return -1000000. This happens when code in 
69404   ** expr.c is trying to resolve a reference to a transient table (i.e. one
69405   ** created by a sub-select). In this case the return value of this 
69406   ** function should never be used.
69407   **
69408   ** We return -1000000 instead of the more usual -1 simply because using
69409   ** -1000000 as incorrectly using -1000000 index into db->aDb[] is much 
69410   ** more likely to cause a segfault than -1 (of course there are assert()
69411   ** statements too, but it never hurts to play the odds).
69412   */
69413   assert( sqlite3_mutex_held(db->mutex) );
69414   if( pSchema ){
69415     for(i=0; i<db->nDb; i++){
69416       if( db->aDb[i].pSchema==pSchema ){
69417         break;
69418       }
69419     }
69420     assert( i>=0 &&i>=0 &&  i<db->nDb );
69421   }
69422   return i;
69423 }
69424
69425 /*
69426 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
69427 */
69428 static int sqlite3Prepare(
69429   sqlite3 *db,              /* Database handle. */
69430   const char *zSql,         /* UTF-8 encoded SQL statement. */
69431   int nBytes,               /* Length of zSql in bytes. */
69432   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
69433   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
69434   const char **pzTail       /* OUT: End of parsed string */
69435 ){
69436   Parse sParse;
69437   char *zErrMsg = 0;
69438   int rc = SQLITE_OK;
69439   int i;
69440
69441   assert( ppStmt );
69442   *ppStmt = 0;
69443   if( sqlite3SafetyOn(db) ){
69444     return SQLITE_MISUSE;
69445   }
69446   assert( !db->mallocFailed );
69447   assert( sqlite3_mutex_held(db->mutex) );
69448
69449   /* If any attached database schemas are locked, do not proceed with
69450   ** compilation. Instead return SQLITE_LOCKED immediately.
69451   */
69452   for(i=0; i<db->nDb; i++) {
69453     Btree *pBt = db->aDb[i].pBt;
69454     if( pBt ){
69455       int rc;
69456       rc = sqlite3BtreeSchemaLocked(pBt);
69457       if( rc ){
69458         const char *zDb = db->aDb[i].zName;
69459         sqlite3Error(db, SQLITE_LOCKED, "database schema is locked: %s", zDb);
69460         (void)sqlite3SafetyOff(db);
69461         return sqlite3ApiExit(db, SQLITE_LOCKED);
69462       }
69463     }
69464   }
69465   
69466   memset(&sParse, 0, sizeof(sParse));
69467   sParse.db = db;
69468   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
69469     char *zSqlCopy;
69470     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
69471     if( nBytes>mxLen ){
69472       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
69473       (void)sqlite3SafetyOff(db);
69474       return sqlite3ApiExit(db, SQLITE_TOOBIG);
69475     }
69476     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
69477     if( zSqlCopy ){
69478       sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
69479       sqlite3DbFree(db, zSqlCopy);
69480       sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
69481     }else{
69482       sParse.zTail = &zSql[nBytes];
69483     }
69484   }else{
69485     sqlite3RunParser(&sParse, zSql, &zErrMsg);
69486   }
69487
69488   if( db->mallocFailed ){
69489     sParse.rc = SQLITE_NOMEM;
69490   }
69491   if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
69492   if( sParse.checkSchema && !schemaIsValid(db) ){
69493     sParse.rc = SQLITE_SCHEMA;
69494   }
69495   if( sParse.rc==SQLITE_SCHEMA ){
69496     sqlite3ResetInternalSchema(db, 0);
69497   }
69498   if( db->mallocFailed ){
69499     sParse.rc = SQLITE_NOMEM;
69500   }
69501   if( pzTail ){
69502     *pzTail = sParse.zTail;
69503   }
69504   rc = sParse.rc;
69505
69506 #ifndef SQLITE_OMIT_EXPLAIN
69507   if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
69508     if( sParse.explain==2 ){
69509       sqlite3VdbeSetNumCols(sParse.pVdbe, 3);
69510       sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "order", SQLITE_STATIC);
69511       sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "from", SQLITE_STATIC);
69512       sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "detail", SQLITE_STATIC);
69513     }else{
69514       sqlite3VdbeSetNumCols(sParse.pVdbe, 8);
69515       sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "addr", SQLITE_STATIC);
69516       sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "opcode", SQLITE_STATIC);
69517       sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "p1", SQLITE_STATIC);
69518       sqlite3VdbeSetColName(sParse.pVdbe, 3, COLNAME_NAME, "p2", SQLITE_STATIC);
69519       sqlite3VdbeSetColName(sParse.pVdbe, 4, COLNAME_NAME, "p3", SQLITE_STATIC);
69520       sqlite3VdbeSetColName(sParse.pVdbe, 5, COLNAME_NAME, "p4", SQLITE_STATIC);
69521       sqlite3VdbeSetColName(sParse.pVdbe, 6, COLNAME_NAME, "p5", SQLITE_STATIC);
69522       sqlite3VdbeSetColName(sParse.pVdbe, 7, COLNAME_NAME, "comment", SQLITE_STATIC);
69523     }
69524   }
69525 #endif
69526
69527   if( sqlite3SafetyOff(db) ){
69528     rc = SQLITE_MISUSE;
69529   }
69530
69531   if( saveSqlFlag ){
69532     sqlite3VdbeSetSql(sParse.pVdbe, zSql, sParse.zTail - zSql);
69533   }
69534   if( rc!=SQLITE_OK || db->mallocFailed ){
69535     sqlite3_finalize((sqlite3_stmt*)sParse.pVdbe);
69536     assert(!(*ppStmt));
69537   }else{
69538     *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
69539   }
69540
69541   if( zErrMsg ){
69542     sqlite3Error(db, rc, "%s", zErrMsg);
69543     sqlite3DbFree(db, zErrMsg);
69544   }else{
69545     sqlite3Error(db, rc, 0);
69546   }
69547
69548   rc = sqlite3ApiExit(db, rc);
69549   assert( (rc&db->errMask)==rc );
69550   return rc;
69551 }
69552 static int sqlite3LockAndPrepare(
69553   sqlite3 *db,              /* Database handle. */
69554   const char *zSql,         /* UTF-8 encoded SQL statement. */
69555   int nBytes,               /* Length of zSql in bytes. */
69556   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
69557   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
69558   const char **pzTail       /* OUT: End of parsed string */
69559 ){
69560   int rc;
69561   if( !sqlite3SafetyCheckOk(db) ){
69562     return SQLITE_MISUSE;
69563   }
69564   sqlite3_mutex_enter(db->mutex);
69565   sqlite3BtreeEnterAll(db);
69566   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, ppStmt, pzTail);
69567   sqlite3BtreeLeaveAll(db);
69568   sqlite3_mutex_leave(db->mutex);
69569   return rc;
69570 }
69571
69572 /*
69573 ** Rerun the compilation of a statement after a schema change.
69574 ** Return true if the statement was recompiled successfully.
69575 ** Return false if there is an error of some kind.
69576 */
69577 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
69578   int rc;
69579   sqlite3_stmt *pNew;
69580   const char *zSql;
69581   sqlite3 *db;
69582
69583   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
69584   zSql = sqlite3_sql((sqlite3_stmt *)p);
69585   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
69586   db = sqlite3VdbeDb(p);
69587   assert( sqlite3_mutex_held(db->mutex) );
69588   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, &pNew, 0);
69589   if( rc ){
69590     if( rc==SQLITE_NOMEM ){
69591       db->mallocFailed = 1;
69592     }
69593     assert( pNew==0 );
69594     return 0;
69595   }else{
69596     assert( pNew!=0 );
69597   }
69598   sqlite3VdbeSwap((Vdbe*)pNew, p);
69599   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
69600   sqlite3VdbeResetStepResult((Vdbe*)pNew);
69601   sqlite3VdbeFinalize((Vdbe*)pNew);
69602   return 1;
69603 }
69604
69605
69606 /*
69607 ** Two versions of the official API.  Legacy and new use.  In the legacy
69608 ** version, the original SQL text is not saved in the prepared statement
69609 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
69610 ** sqlite3_step().  In the new version, the original SQL text is retained
69611 ** and the statement is automatically recompiled if an schema change
69612 ** occurs.
69613 */
69614 SQLITE_API int sqlite3_prepare(
69615   sqlite3 *db,              /* Database handle. */
69616   const char *zSql,         /* UTF-8 encoded SQL statement. */
69617   int nBytes,               /* Length of zSql in bytes. */
69618   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
69619   const char **pzTail       /* OUT: End of parsed string */
69620 ){
69621   int rc;
69622   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,ppStmt,pzTail);
69623   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
69624   return rc;
69625 }
69626 SQLITE_API int sqlite3_prepare_v2(
69627   sqlite3 *db,              /* Database handle. */
69628   const char *zSql,         /* UTF-8 encoded SQL statement. */
69629   int nBytes,               /* Length of zSql in bytes. */
69630   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
69631   const char **pzTail       /* OUT: End of parsed string */
69632 ){
69633   int rc;
69634   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,ppStmt,pzTail);
69635   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
69636   return rc;
69637 }
69638
69639
69640 #ifndef SQLITE_OMIT_UTF16
69641 /*
69642 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
69643 */
69644 static int sqlite3Prepare16(
69645   sqlite3 *db,              /* Database handle. */ 
69646   const void *zSql,         /* UTF-8 encoded SQL statement. */
69647   int nBytes,               /* Length of zSql in bytes. */
69648   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
69649   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
69650   const void **pzTail       /* OUT: End of parsed string */
69651 ){
69652   /* This function currently works by first transforming the UTF-16
69653   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
69654   ** tricky bit is figuring out the pointer to return in *pzTail.
69655   */
69656   char *zSql8;
69657   const char *zTail8 = 0;
69658   int rc = SQLITE_OK;
69659
69660   if( !sqlite3SafetyCheckOk(db) ){
69661     return SQLITE_MISUSE;
69662   }
69663   sqlite3_mutex_enter(db->mutex);
69664   zSql8 = sqlite3Utf16to8(db, zSql, nBytes);
69665   if( zSql8 ){
69666     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, ppStmt, &zTail8);
69667   }
69668
69669   if( zTail8 && pzTail ){
69670     /* If sqlite3_prepare returns a tail pointer, we calculate the
69671     ** equivalent pointer into the UTF-16 string by counting the unicode
69672     ** characters between zSql8 and zTail8, and then returning a pointer
69673     ** the same number of characters into the UTF-16 string.
69674     */
69675     int chars_parsed = sqlite3Utf8CharLen(zSql8, zTail8-zSql8);
69676     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
69677   }
69678   sqlite3DbFree(db, zSql8); 
69679   rc = sqlite3ApiExit(db, rc);
69680   sqlite3_mutex_leave(db->mutex);
69681   return rc;
69682 }
69683
69684 /*
69685 ** Two versions of the official API.  Legacy and new use.  In the legacy
69686 ** version, the original SQL text is not saved in the prepared statement
69687 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
69688 ** sqlite3_step().  In the new version, the original SQL text is retained
69689 ** and the statement is automatically recompiled if an schema change
69690 ** occurs.
69691 */
69692 SQLITE_API int sqlite3_prepare16(
69693   sqlite3 *db,              /* Database handle. */ 
69694   const void *zSql,         /* UTF-8 encoded SQL statement. */
69695   int nBytes,               /* Length of zSql in bytes. */
69696   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
69697   const void **pzTail       /* OUT: End of parsed string */
69698 ){
69699   int rc;
69700   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
69701   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
69702   return rc;
69703 }
69704 SQLITE_API int sqlite3_prepare16_v2(
69705   sqlite3 *db,              /* Database handle. */ 
69706   const void *zSql,         /* UTF-8 encoded SQL statement. */
69707   int nBytes,               /* Length of zSql in bytes. */
69708   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
69709   const void **pzTail       /* OUT: End of parsed string */
69710 ){
69711   int rc;
69712   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
69713   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
69714   return rc;
69715 }
69716
69717 #endif /* SQLITE_OMIT_UTF16 */
69718
69719 /************** End of prepare.c *********************************************/
69720 /************** Begin file select.c ******************************************/
69721 /*
69722 ** 2001 September 15
69723 **
69724 ** The author disclaims copyright to this source code.  In place of
69725 ** a legal notice, here is a blessing:
69726 **
69727 **    May you do good and not evil.
69728 **    May you find forgiveness for yourself and forgive others.
69729 **    May you share freely, never taking more than you give.
69730 **
69731 *************************************************************************
69732 ** This file contains C code routines that are called by the parser
69733 ** to handle SELECT statements in SQLite.
69734 **
69735 ** $Id: select.c,v 1.486 2008/11/19 09:05:27 danielk1977 Exp $
69736 */
69737
69738
69739 /*
69740 ** Delete all the content of a Select structure but do not deallocate
69741 ** the select structure itself.
69742 */
69743 static void clearSelect(sqlite3 *db, Select *p){
69744   sqlite3ExprListDelete(db, p->pEList);
69745   sqlite3SrcListDelete(db, p->pSrc);
69746   sqlite3ExprDelete(db, p->pWhere);
69747   sqlite3ExprListDelete(db, p->pGroupBy);
69748   sqlite3ExprDelete(db, p->pHaving);
69749   sqlite3ExprListDelete(db, p->pOrderBy);
69750   sqlite3SelectDelete(db, p->pPrior);
69751   sqlite3ExprDelete(db, p->pLimit);
69752   sqlite3ExprDelete(db, p->pOffset);
69753 }
69754
69755 /*
69756 ** Initialize a SelectDest structure.
69757 */
69758 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
69759   pDest->eDest = eDest;
69760   pDest->iParm = iParm;
69761   pDest->affinity = 0;
69762   pDest->iMem = 0;
69763   pDest->nMem = 0;
69764 }
69765
69766
69767 /*
69768 ** Allocate a new Select structure and return a pointer to that
69769 ** structure.
69770 */
69771 SQLITE_PRIVATE Select *sqlite3SelectNew(
69772   Parse *pParse,        /* Parsing context */
69773   ExprList *pEList,     /* which columns to include in the result */
69774   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
69775   Expr *pWhere,         /* the WHERE clause */
69776   ExprList *pGroupBy,   /* the GROUP BY clause */
69777   Expr *pHaving,        /* the HAVING clause */
69778   ExprList *pOrderBy,   /* the ORDER BY clause */
69779   int isDistinct,       /* true if the DISTINCT keyword is present */
69780   Expr *pLimit,         /* LIMIT value.  NULL means not used */
69781   Expr *pOffset         /* OFFSET value.  NULL means no offset */
69782 ){
69783   Select *pNew;
69784   Select standin;
69785   sqlite3 *db = pParse->db;
69786   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
69787   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
69788   if( pNew==0 ){
69789     pNew = &standin;
69790     memset(pNew, 0, sizeof(*pNew));
69791   }
69792   if( pEList==0 ){
69793     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0,0,0), 0);
69794   }
69795   pNew->pEList = pEList;
69796   pNew->pSrc = pSrc;
69797   pNew->pWhere = pWhere;
69798   pNew->pGroupBy = pGroupBy;
69799   pNew->pHaving = pHaving;
69800   pNew->pOrderBy = pOrderBy;
69801   pNew->selFlags = isDistinct ? SF_Distinct : 0;
69802   pNew->op = TK_SELECT;
69803   pNew->pLimit = pLimit;
69804   pNew->pOffset = pOffset;
69805   pNew->addrOpenEphm[0] = -1;
69806   pNew->addrOpenEphm[1] = -1;
69807   pNew->addrOpenEphm[2] = -1;
69808   if( db->mallocFailed ) {
69809     clearSelect(db, pNew);
69810     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
69811     pNew = 0;
69812   }
69813   return pNew;
69814 }
69815
69816 /*
69817 ** Delete the given Select structure and all of its substructures.
69818 */
69819 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
69820   if( p ){
69821     clearSelect(db, p);
69822     sqlite3DbFree(db, p);
69823   }
69824 }
69825
69826 /*
69827 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
69828 ** type of join.  Return an integer constant that expresses that type
69829 ** in terms of the following bit values:
69830 **
69831 **     JT_INNER
69832 **     JT_CROSS
69833 **     JT_OUTER
69834 **     JT_NATURAL
69835 **     JT_LEFT
69836 **     JT_RIGHT
69837 **
69838 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
69839 **
69840 ** If an illegal or unsupported join type is seen, then still return
69841 ** a join type, but put an error in the pParse structure.
69842 */
69843 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
69844   int jointype = 0;
69845   Token *apAll[3];
69846   Token *p;
69847   static const struct {
69848     const char zKeyword[8];
69849     u8 nChar;
69850     u8 code;
69851   } keywords[] = {
69852     { "natural", 7, JT_NATURAL },
69853     { "left",    4, JT_LEFT|JT_OUTER },
69854     { "right",   5, JT_RIGHT|JT_OUTER },
69855     { "full",    4, JT_LEFT|JT_RIGHT|JT_OUTER },
69856     { "outer",   5, JT_OUTER },
69857     { "inner",   5, JT_INNER },
69858     { "cross",   5, JT_INNER|JT_CROSS },
69859   };
69860   int i, j;
69861   apAll[0] = pA;
69862   apAll[1] = pB;
69863   apAll[2] = pC;
69864   for(i=0; i<3 && apAll[i]; i++){
69865     p = apAll[i];
69866     for(j=0; j<ArraySize(keywords); j++){
69867       if( p->n==keywords[j].nChar 
69868           && sqlite3StrNICmp((char*)p->z, keywords[j].zKeyword, p->n)==0 ){
69869         jointype |= keywords[j].code;
69870         break;
69871       }
69872     }
69873     if( j>=ArraySize(keywords) ){
69874       jointype |= JT_ERROR;
69875       break;
69876     }
69877   }
69878   if(
69879      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
69880      (jointype & JT_ERROR)!=0
69881   ){
69882     const char *zSp = " ";
69883     assert( pB!=0 );
69884     if( pC==0 ){ zSp++; }
69885     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
69886        "%T %T%s%T", pA, pB, zSp, pC);
69887     jointype = JT_INNER;
69888   }else if( jointype & JT_RIGHT ){
69889     sqlite3ErrorMsg(pParse, 
69890       "RIGHT and FULL OUTER JOINs are not currently supported");
69891     jointype = JT_INNER;
69892   }
69893   return jointype;
69894 }
69895
69896 /*
69897 ** Return the index of a column in a table.  Return -1 if the column
69898 ** is not contained in the table.
69899 */
69900 static int columnIndex(Table *pTab, const char *zCol){
69901   int i;
69902   for(i=0; i<pTab->nCol; i++){
69903     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
69904   }
69905   return -1;
69906 }
69907
69908 /*
69909 ** Set the value of a token to a '\000'-terminated string.
69910 */
69911 static void setToken(Token *p, const char *z){
69912   p->z = (u8*)z;
69913   p->n = z ? strlen(z) : 0;
69914   p->dyn = 0;
69915 }
69916
69917 /*
69918 ** Set the token to the double-quoted and escaped version of the string pointed
69919 ** to by z. For example;
69920 **
69921 **    {a"bc}  ->  {"a""bc"}
69922 */
69923 static void setQuotedToken(Parse *pParse, Token *p, const char *z){
69924
69925   /* Check if the string appears to be quoted using "..." or `...`
69926   ** or [...] or '...' or if the string contains any " characters.  
69927   ** If it does, then record a version of the string with the special
69928   ** characters escaped.
69929   */
69930   const char *z2 = z;
69931   if( *z2!='[' && *z2!='`' && *z2!='\'' ){
69932     while( *z2 ){
69933       if( *z2=='"' ) break;
69934       z2++;
69935     }
69936   }
69937
69938   if( *z2 ){
69939     /* String contains " characters - copy and quote the string. */
69940     p->z = (u8 *)sqlite3MPrintf(pParse->db, "\"%w\"", z);
69941     if( p->z ){
69942       p->n = strlen((char *)p->z);
69943       p->dyn = 1;
69944     }
69945   }else{
69946     /* String contains no " characters - copy the pointer. */
69947     p->z = (u8*)z;
69948     p->n = (z2 - z);
69949     p->dyn = 0;
69950   }
69951 }
69952
69953 /*
69954 ** Create an expression node for an identifier with the name of zName
69955 */
69956 SQLITE_PRIVATE Expr *sqlite3CreateIdExpr(Parse *pParse, const char *zName){
69957   Token dummy;
69958   setToken(&dummy, zName);
69959   return sqlite3PExpr(pParse, TK_ID, 0, 0, &dummy);
69960 }
69961
69962 /*
69963 ** Add a term to the WHERE expression in *ppExpr that requires the
69964 ** zCol column to be equal in the two tables pTab1 and pTab2.
69965 */
69966 static void addWhereTerm(
69967   Parse *pParse,           /* Parsing context */
69968   const char *zCol,        /* Name of the column */
69969   const Table *pTab1,      /* First table */
69970   const char *zAlias1,     /* Alias for first table.  May be NULL */
69971   const Table *pTab2,      /* Second table */
69972   const char *zAlias2,     /* Alias for second table.  May be NULL */
69973   int iRightJoinTable,     /* VDBE cursor for the right table */
69974   Expr **ppExpr,           /* Add the equality term to this expression */
69975   int isOuterJoin          /* True if dealing with an OUTER join */
69976 ){
69977   Expr *pE1a, *pE1b, *pE1c;
69978   Expr *pE2a, *pE2b, *pE2c;
69979   Expr *pE;
69980
69981   pE1a = sqlite3CreateIdExpr(pParse, zCol);
69982   pE2a = sqlite3CreateIdExpr(pParse, zCol);
69983   if( zAlias1==0 ){
69984     zAlias1 = pTab1->zName;
69985   }
69986   pE1b = sqlite3CreateIdExpr(pParse, zAlias1);
69987   if( zAlias2==0 ){
69988     zAlias2 = pTab2->zName;
69989   }
69990   pE2b = sqlite3CreateIdExpr(pParse, zAlias2);
69991   pE1c = sqlite3PExpr(pParse, TK_DOT, pE1b, pE1a, 0);
69992   pE2c = sqlite3PExpr(pParse, TK_DOT, pE2b, pE2a, 0);
69993   pE = sqlite3PExpr(pParse, TK_EQ, pE1c, pE2c, 0);
69994   if( pE && isOuterJoin ){
69995     ExprSetProperty(pE, EP_FromJoin);
69996     pE->iRightJoinTable = iRightJoinTable;
69997   }
69998   *ppExpr = sqlite3ExprAnd(pParse->db,*ppExpr, pE);
69999 }
70000
70001 /*
70002 ** Set the EP_FromJoin property on all terms of the given expression.
70003 ** And set the Expr.iRightJoinTable to iTable for every term in the
70004 ** expression.
70005 **
70006 ** The EP_FromJoin property is used on terms of an expression to tell
70007 ** the LEFT OUTER JOIN processing logic that this term is part of the
70008 ** join restriction specified in the ON or USING clause and not a part
70009 ** of the more general WHERE clause.  These terms are moved over to the
70010 ** WHERE clause during join processing but we need to remember that they
70011 ** originated in the ON or USING clause.
70012 **
70013 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
70014 ** expression depends on table iRightJoinTable even if that table is not
70015 ** explicitly mentioned in the expression.  That information is needed
70016 ** for cases like this:
70017 **
70018 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
70019 **
70020 ** The where clause needs to defer the handling of the t1.x=5
70021 ** term until after the t2 loop of the join.  In that way, a
70022 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
70023 ** defer the handling of t1.x=5, it will be processed immediately
70024 ** after the t1 loop and rows with t1.x!=5 will never appear in
70025 ** the output, which is incorrect.
70026 */
70027 static void setJoinExpr(Expr *p, int iTable){
70028   while( p ){
70029     ExprSetProperty(p, EP_FromJoin);
70030     p->iRightJoinTable = iTable;
70031     setJoinExpr(p->pLeft, iTable);
70032     p = p->pRight;
70033   } 
70034 }
70035
70036 /*
70037 ** This routine processes the join information for a SELECT statement.
70038 ** ON and USING clauses are converted into extra terms of the WHERE clause.
70039 ** NATURAL joins also create extra WHERE clause terms.
70040 **
70041 ** The terms of a FROM clause are contained in the Select.pSrc structure.
70042 ** The left most table is the first entry in Select.pSrc.  The right-most
70043 ** table is the last entry.  The join operator is held in the entry to
70044 ** the left.  Thus entry 0 contains the join operator for the join between
70045 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
70046 ** also attached to the left entry.
70047 **
70048 ** This routine returns the number of errors encountered.
70049 */
70050 static int sqliteProcessJoin(Parse *pParse, Select *p){
70051   SrcList *pSrc;                  /* All tables in the FROM clause */
70052   int i, j;                       /* Loop counters */
70053   struct SrcList_item *pLeft;     /* Left table being joined */
70054   struct SrcList_item *pRight;    /* Right table being joined */
70055
70056   pSrc = p->pSrc;
70057   pLeft = &pSrc->a[0];
70058   pRight = &pLeft[1];
70059   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
70060     Table *pLeftTab = pLeft->pTab;
70061     Table *pRightTab = pRight->pTab;
70062     int isOuter;
70063
70064     if( pLeftTab==0 || pRightTab==0 ) continue;
70065     isOuter = (pRight->jointype & JT_OUTER)!=0;
70066
70067     /* When the NATURAL keyword is present, add WHERE clause terms for
70068     ** every column that the two tables have in common.
70069     */
70070     if( pRight->jointype & JT_NATURAL ){
70071       if( pRight->pOn || pRight->pUsing ){
70072         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
70073            "an ON or USING clause", 0);
70074         return 1;
70075       }
70076       for(j=0; j<pLeftTab->nCol; j++){
70077         char *zName = pLeftTab->aCol[j].zName;
70078         if( columnIndex(pRightTab, zName)>=0 ){
70079           addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, 
70080                               pRightTab, pRight->zAlias,
70081                               pRight->iCursor, &p->pWhere, isOuter);
70082           
70083         }
70084       }
70085     }
70086
70087     /* Disallow both ON and USING clauses in the same join
70088     */
70089     if( pRight->pOn && pRight->pUsing ){
70090       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
70091         "clauses in the same join");
70092       return 1;
70093     }
70094
70095     /* Add the ON clause to the end of the WHERE clause, connected by
70096     ** an AND operator.
70097     */
70098     if( pRight->pOn ){
70099       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
70100       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
70101       pRight->pOn = 0;
70102     }
70103
70104     /* Create extra terms on the WHERE clause for each column named
70105     ** in the USING clause.  Example: If the two tables to be joined are 
70106     ** A and B and the USING clause names X, Y, and Z, then add this
70107     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
70108     ** Report an error if any column mentioned in the USING clause is
70109     ** not contained in both tables to be joined.
70110     */
70111     if( pRight->pUsing ){
70112       IdList *pList = pRight->pUsing;
70113       for(j=0; j<pList->nId; j++){
70114         char *zName = pList->a[j].zName;
70115         if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
70116           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
70117             "not present in both tables", zName);
70118           return 1;
70119         }
70120         addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, 
70121                             pRightTab, pRight->zAlias,
70122                             pRight->iCursor, &p->pWhere, isOuter);
70123       }
70124     }
70125   }
70126   return 0;
70127 }
70128
70129 /*
70130 ** Insert code into "v" that will push the record on the top of the
70131 ** stack into the sorter.
70132 */
70133 static void pushOntoSorter(
70134   Parse *pParse,         /* Parser context */
70135   ExprList *pOrderBy,    /* The ORDER BY clause */
70136   Select *pSelect,       /* The whole SELECT statement */
70137   int regData            /* Register holding data to be sorted */
70138 ){
70139   Vdbe *v = pParse->pVdbe;
70140   int nExpr = pOrderBy->nExpr;
70141   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
70142   int regRecord = sqlite3GetTempReg(pParse);
70143   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
70144   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
70145   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
70146   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
70147   sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
70148   sqlite3ReleaseTempReg(pParse, regRecord);
70149   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
70150   if( pSelect->iLimit ){
70151     int addr1, addr2;
70152     int iLimit;
70153     if( pSelect->iOffset ){
70154       iLimit = pSelect->iOffset+1;
70155     }else{
70156       iLimit = pSelect->iLimit;
70157     }
70158     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
70159     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
70160     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
70161     sqlite3VdbeJumpHere(v, addr1);
70162     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
70163     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
70164     sqlite3VdbeJumpHere(v, addr2);
70165     pSelect->iLimit = 0;
70166   }
70167 }
70168
70169 /*
70170 ** Add code to implement the OFFSET
70171 */
70172 static void codeOffset(
70173   Vdbe *v,          /* Generate code into this VM */
70174   Select *p,        /* The SELECT statement being coded */
70175   int iContinue     /* Jump here to skip the current record */
70176 ){
70177   if( p->iOffset && iContinue!=0 ){
70178     int addr;
70179     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
70180     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
70181     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
70182     VdbeComment((v, "skip OFFSET records"));
70183     sqlite3VdbeJumpHere(v, addr);
70184   }
70185 }
70186
70187 /*
70188 ** Add code that will check to make sure the N registers starting at iMem
70189 ** form a distinct entry.  iTab is a sorting index that holds previously
70190 ** seen combinations of the N values.  A new entry is made in iTab
70191 ** if the current N values are new.
70192 **
70193 ** A jump to addrRepeat is made and the N+1 values are popped from the
70194 ** stack if the top N elements are not distinct.
70195 */
70196 static void codeDistinct(
70197   Parse *pParse,     /* Parsing and code generating context */
70198   int iTab,          /* A sorting index used to test for distinctness */
70199   int addrRepeat,    /* Jump to here if not distinct */
70200   int N,             /* Number of elements */
70201   int iMem           /* First element */
70202 ){
70203   Vdbe *v;
70204   int r1;
70205
70206   v = pParse->pVdbe;
70207   r1 = sqlite3GetTempReg(pParse);
70208   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
70209   sqlite3VdbeAddOp3(v, OP_Found, iTab, addrRepeat, r1);
70210   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
70211   sqlite3ReleaseTempReg(pParse, r1);
70212 }
70213
70214 /*
70215 ** Generate an error message when a SELECT is used within a subexpression
70216 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
70217 ** column.  We do this in a subroutine because the error occurs in multiple
70218 ** places.
70219 */
70220 static int checkForMultiColumnSelectError(
70221   Parse *pParse,       /* Parse context. */
70222   SelectDest *pDest,   /* Destination of SELECT results */
70223   int nExpr            /* Number of result columns returned by SELECT */
70224 ){
70225   int eDest = pDest->eDest;
70226   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
70227     sqlite3ErrorMsg(pParse, "only a single result allowed for "
70228        "a SELECT that is part of an expression");
70229     return 1;
70230   }else{
70231     return 0;
70232   }
70233 }
70234
70235 /*
70236 ** This routine generates the code for the inside of the inner loop
70237 ** of a SELECT.
70238 **
70239 ** If srcTab and nColumn are both zero, then the pEList expressions
70240 ** are evaluated in order to get the data for this row.  If nColumn>0
70241 ** then data is pulled from srcTab and pEList is used only to get the
70242 ** datatypes for each column.
70243 */
70244 static void selectInnerLoop(
70245   Parse *pParse,          /* The parser context */
70246   Select *p,              /* The complete select statement being coded */
70247   ExprList *pEList,       /* List of values being extracted */
70248   int srcTab,             /* Pull data from this table */
70249   int nColumn,            /* Number of columns in the source table */
70250   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
70251   int distinct,           /* If >=0, make sure results are distinct */
70252   SelectDest *pDest,      /* How to dispose of the results */
70253   int iContinue,          /* Jump here to continue with next row */
70254   int iBreak              /* Jump here to break out of the inner loop */
70255 ){
70256   Vdbe *v = pParse->pVdbe;
70257   int i;
70258   int hasDistinct;        /* True if the DISTINCT keyword is present */
70259   int regResult;              /* Start of memory holding result set */
70260   int eDest = pDest->eDest;   /* How to dispose of results */
70261   int iParm = pDest->iParm;   /* First argument to disposal method */
70262   int nResultCol;             /* Number of result columns */
70263
70264   if( v==0 ) return;
70265   assert( pEList!=0 );
70266   hasDistinct = distinct>=0;
70267   if( pOrderBy==0 && !hasDistinct ){
70268     codeOffset(v, p, iContinue);
70269   }
70270
70271   /* Pull the requested columns.
70272   */
70273   if( nColumn>0 ){
70274     nResultCol = nColumn;
70275   }else{
70276     nResultCol = pEList->nExpr;
70277   }
70278   if( pDest->iMem==0 ){
70279     pDest->iMem = pParse->nMem+1;
70280     pDest->nMem = nResultCol;
70281     pParse->nMem += nResultCol;
70282   }else if( pDest->nMem!=nResultCol ){
70283     /* This happens when two SELECTs of a compound SELECT have differing
70284     ** numbers of result columns.  The error message will be generated by
70285     ** a higher-level routine. */
70286     return;
70287   }
70288   regResult = pDest->iMem;
70289   if( nColumn>0 ){
70290     for(i=0; i<nColumn; i++){
70291       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
70292     }
70293   }else if( eDest!=SRT_Exists ){
70294     /* If the destination is an EXISTS(...) expression, the actual
70295     ** values returned by the SELECT are not required.
70296     */
70297     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
70298   }
70299   nColumn = nResultCol;
70300
70301   /* If the DISTINCT keyword was present on the SELECT statement
70302   ** and this row has been seen before, then do not make this row
70303   ** part of the result.
70304   */
70305   if( hasDistinct ){
70306     assert( pEList!=0 );
70307     assert( pEList->nExpr==nColumn );
70308     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
70309     if( pOrderBy==0 ){
70310       codeOffset(v, p, iContinue);
70311     }
70312   }
70313
70314   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
70315     return;
70316   }
70317
70318   switch( eDest ){
70319     /* In this mode, write each query result to the key of the temporary
70320     ** table iParm.
70321     */
70322 #ifndef SQLITE_OMIT_COMPOUND_SELECT
70323     case SRT_Union: {
70324       int r1;
70325       r1 = sqlite3GetTempReg(pParse);
70326       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
70327       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
70328       sqlite3ReleaseTempReg(pParse, r1);
70329       break;
70330     }
70331
70332     /* Construct a record from the query result, but instead of
70333     ** saving that record, use it as a key to delete elements from
70334     ** the temporary table iParm.
70335     */
70336     case SRT_Except: {
70337       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
70338       break;
70339     }
70340 #endif
70341
70342     /* Store the result as data using a unique key.
70343     */
70344     case SRT_Table:
70345     case SRT_EphemTab: {
70346       int r1 = sqlite3GetTempReg(pParse);
70347       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
70348       if( pOrderBy ){
70349         pushOntoSorter(pParse, pOrderBy, p, r1);
70350       }else{
70351         int r2 = sqlite3GetTempReg(pParse);
70352         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
70353         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
70354         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
70355         sqlite3ReleaseTempReg(pParse, r2);
70356       }
70357       sqlite3ReleaseTempReg(pParse, r1);
70358       break;
70359     }
70360
70361 #ifndef SQLITE_OMIT_SUBQUERY
70362     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
70363     ** then there should be a single item on the stack.  Write this
70364     ** item into the set table with bogus data.
70365     */
70366     case SRT_Set: {
70367       assert( nColumn==1 );
70368       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
70369       if( pOrderBy ){
70370         /* At first glance you would think we could optimize out the
70371         ** ORDER BY in this case since the order of entries in the set
70372         ** does not matter.  But there might be a LIMIT clause, in which
70373         ** case the order does matter */
70374         pushOntoSorter(pParse, pOrderBy, p, regResult);
70375       }else{
70376         int r1 = sqlite3GetTempReg(pParse);
70377         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
70378         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
70379         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
70380         sqlite3ReleaseTempReg(pParse, r1);
70381       }
70382       break;
70383     }
70384
70385     /* If any row exist in the result set, record that fact and abort.
70386     */
70387     case SRT_Exists: {
70388       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
70389       /* The LIMIT clause will terminate the loop for us */
70390       break;
70391     }
70392
70393     /* If this is a scalar select that is part of an expression, then
70394     ** store the results in the appropriate memory cell and break out
70395     ** of the scan loop.
70396     */
70397     case SRT_Mem: {
70398       assert( nColumn==1 );
70399       if( pOrderBy ){
70400         pushOntoSorter(pParse, pOrderBy, p, regResult);
70401       }else{
70402         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
70403         /* The LIMIT clause will jump out of the loop for us */
70404       }
70405       break;
70406     }
70407 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
70408
70409     /* Send the data to the callback function or to a subroutine.  In the
70410     ** case of a subroutine, the subroutine itself is responsible for
70411     ** popping the data from the stack.
70412     */
70413     case SRT_Coroutine:
70414     case SRT_Output: {
70415       if( pOrderBy ){
70416         int r1 = sqlite3GetTempReg(pParse);
70417         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
70418         pushOntoSorter(pParse, pOrderBy, p, r1);
70419         sqlite3ReleaseTempReg(pParse, r1);
70420       }else if( eDest==SRT_Coroutine ){
70421         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
70422       }else{
70423         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
70424         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
70425       }
70426       break;
70427     }
70428
70429 #if !defined(SQLITE_OMIT_TRIGGER)
70430     /* Discard the results.  This is used for SELECT statements inside
70431     ** the body of a TRIGGER.  The purpose of such selects is to call
70432     ** user-defined functions that have side effects.  We do not care
70433     ** about the actual results of the select.
70434     */
70435     default: {
70436       assert( eDest==SRT_Discard );
70437       break;
70438     }
70439 #endif
70440   }
70441
70442   /* Jump to the end of the loop if the LIMIT is reached.
70443   */
70444   if( p->iLimit ){
70445     assert( pOrderBy==0 );  /* If there is an ORDER BY, the call to
70446                             ** pushOntoSorter() would have cleared p->iLimit */
70447     sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
70448     sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak);
70449   }
70450 }
70451
70452 /*
70453 ** Given an expression list, generate a KeyInfo structure that records
70454 ** the collating sequence for each expression in that expression list.
70455 **
70456 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
70457 ** KeyInfo structure is appropriate for initializing a virtual index to
70458 ** implement that clause.  If the ExprList is the result set of a SELECT
70459 ** then the KeyInfo structure is appropriate for initializing a virtual
70460 ** index to implement a DISTINCT test.
70461 **
70462 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
70463 ** function is responsible for seeing that this structure is eventually
70464 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
70465 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
70466 */
70467 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
70468   sqlite3 *db = pParse->db;
70469   int nExpr;
70470   KeyInfo *pInfo;
70471   struct ExprList_item *pItem;
70472   int i;
70473
70474   nExpr = pList->nExpr;
70475   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
70476   if( pInfo ){
70477     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
70478     pInfo->nField = nExpr;
70479     pInfo->enc = ENC(db);
70480     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
70481       CollSeq *pColl;
70482       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
70483       if( !pColl ){
70484         pColl = db->pDfltColl;
70485       }
70486       pInfo->aColl[i] = pColl;
70487       pInfo->aSortOrder[i] = pItem->sortOrder;
70488     }
70489   }
70490   return pInfo;
70491 }
70492
70493
70494 /*
70495 ** If the inner loop was generated using a non-null pOrderBy argument,
70496 ** then the results were placed in a sorter.  After the loop is terminated
70497 ** we need to run the sorter and output the results.  The following
70498 ** routine generates the code needed to do that.
70499 */
70500 static void generateSortTail(
70501   Parse *pParse,    /* Parsing context */
70502   Select *p,        /* The SELECT statement */
70503   Vdbe *v,          /* Generate code into this VDBE */
70504   int nColumn,      /* Number of columns of data */
70505   SelectDest *pDest /* Write the sorted results here */
70506 ){
70507   int brk = sqlite3VdbeMakeLabel(v);
70508   int cont = sqlite3VdbeMakeLabel(v);
70509   int addr;
70510   int iTab;
70511   int pseudoTab = 0;
70512   ExprList *pOrderBy = p->pOrderBy;
70513
70514   int eDest = pDest->eDest;
70515   int iParm = pDest->iParm;
70516
70517   int regRow;
70518   int regRowid;
70519
70520   iTab = pOrderBy->iECursor;
70521   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
70522     pseudoTab = pParse->nTab++;
70523     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, nColumn);
70524     sqlite3VdbeAddOp2(v, OP_OpenPseudo, pseudoTab, eDest==SRT_Output);
70525   }
70526   addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, brk);
70527   codeOffset(v, p, cont);
70528   regRow = sqlite3GetTempReg(pParse);
70529   regRowid = sqlite3GetTempReg(pParse);
70530   sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
70531   switch( eDest ){
70532     case SRT_Table:
70533     case SRT_EphemTab: {
70534       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
70535       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
70536       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
70537       break;
70538     }
70539 #ifndef SQLITE_OMIT_SUBQUERY
70540     case SRT_Set: {
70541       assert( nColumn==1 );
70542       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
70543       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
70544       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
70545       break;
70546     }
70547     case SRT_Mem: {
70548       assert( nColumn==1 );
70549       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
70550       /* The LIMIT clause will terminate the loop for us */
70551       break;
70552     }
70553 #endif
70554     case SRT_Output:
70555     case SRT_Coroutine: {
70556       int i;
70557       sqlite3VdbeAddOp2(v, OP_Integer, 1, regRowid);
70558       sqlite3VdbeAddOp3(v, OP_Insert, pseudoTab, regRow, regRowid);
70559       for(i=0; i<nColumn; i++){
70560         assert( regRow!=pDest->iMem+i );
70561         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
70562       }
70563       if( eDest==SRT_Output ){
70564         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
70565         sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
70566       }else{
70567         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
70568       }
70569       break;
70570     }
70571     default: {
70572       /* Do nothing */
70573       break;
70574     }
70575   }
70576   sqlite3ReleaseTempReg(pParse, regRow);
70577   sqlite3ReleaseTempReg(pParse, regRowid);
70578
70579   /* LIMIT has been implemented by the pushOntoSorter() routine.
70580   */
70581   assert( p->iLimit==0 );
70582
70583   /* The bottom of the loop
70584   */
70585   sqlite3VdbeResolveLabel(v, cont);
70586   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
70587   sqlite3VdbeResolveLabel(v, brk);
70588   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
70589     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
70590   }
70591
70592 }
70593
70594 /*
70595 ** Return a pointer to a string containing the 'declaration type' of the
70596 ** expression pExpr. The string may be treated as static by the caller.
70597 **
70598 ** The declaration type is the exact datatype definition extracted from the
70599 ** original CREATE TABLE statement if the expression is a column. The
70600 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
70601 ** is considered a column can be complex in the presence of subqueries. The
70602 ** result-set expression in all of the following SELECT statements is 
70603 ** considered a column by this function.
70604 **
70605 **   SELECT col FROM tbl;
70606 **   SELECT (SELECT col FROM tbl;
70607 **   SELECT (SELECT col FROM tbl);
70608 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
70609 ** 
70610 ** The declaration type for any expression other than a column is NULL.
70611 */
70612 static const char *columnType(
70613   NameContext *pNC, 
70614   Expr *pExpr,
70615   const char **pzOriginDb,
70616   const char **pzOriginTab,
70617   const char **pzOriginCol
70618 ){
70619   char const *zType = 0;
70620   char const *zOriginDb = 0;
70621   char const *zOriginTab = 0;
70622   char const *zOriginCol = 0;
70623   int j;
70624   if( pExpr==0 || pNC->pSrcList==0 ) return 0;
70625
70626   switch( pExpr->op ){
70627     case TK_AGG_COLUMN:
70628     case TK_COLUMN: {
70629       /* The expression is a column. Locate the table the column is being
70630       ** extracted from in NameContext.pSrcList. This table may be real
70631       ** database table or a subquery.
70632       */
70633       Table *pTab = 0;            /* Table structure column is extracted from */
70634       Select *pS = 0;             /* Select the column is extracted from */
70635       int iCol = pExpr->iColumn;  /* Index of column in pTab */
70636       while( pNC && !pTab ){
70637         SrcList *pTabList = pNC->pSrcList;
70638         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
70639         if( j<pTabList->nSrc ){
70640           pTab = pTabList->a[j].pTab;
70641           pS = pTabList->a[j].pSelect;
70642         }else{
70643           pNC = pNC->pNext;
70644         }
70645       }
70646
70647       if( pTab==0 ){
70648         /* FIX ME:
70649         ** This can occurs if you have something like "SELECT new.x;" inside
70650         ** a trigger.  In other words, if you reference the special "new"
70651         ** table in the result set of a select.  We do not have a good way
70652         ** to find the actual table type, so call it "TEXT".  This is really
70653         ** something of a bug, but I do not know how to fix it.
70654         **
70655         ** This code does not produce the correct answer - it just prevents
70656         ** a segfault.  See ticket #1229.
70657         */
70658         zType = "TEXT";
70659         break;
70660       }
70661
70662       assert( pTab );
70663       if( pS ){
70664         /* The "table" is actually a sub-select or a view in the FROM clause
70665         ** of the SELECT statement. Return the declaration type and origin
70666         ** data for the result-set column of the sub-select.
70667         */
70668         if( iCol>=0 && iCol<pS->pEList->nExpr ){
70669           /* If iCol is less than zero, then the expression requests the
70670           ** rowid of the sub-select or view. This expression is legal (see 
70671           ** test case misc2.2.2) - it always evaluates to NULL.
70672           */
70673           NameContext sNC;
70674           Expr *p = pS->pEList->a[iCol].pExpr;
70675           sNC.pSrcList = pS->pSrc;
70676           sNC.pNext = 0;
70677           sNC.pParse = pNC->pParse;
70678           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
70679         }
70680       }else if( pTab->pSchema ){
70681         /* A real table */
70682         assert( !pS );
70683         if( iCol<0 ) iCol = pTab->iPKey;
70684         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
70685         if( iCol<0 ){
70686           zType = "INTEGER";
70687           zOriginCol = "rowid";
70688         }else{
70689           zType = pTab->aCol[iCol].zType;
70690           zOriginCol = pTab->aCol[iCol].zName;
70691         }
70692         zOriginTab = pTab->zName;
70693         if( pNC->pParse ){
70694           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
70695           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
70696         }
70697       }
70698       break;
70699     }
70700 #ifndef SQLITE_OMIT_SUBQUERY
70701     case TK_SELECT: {
70702       /* The expression is a sub-select. Return the declaration type and
70703       ** origin info for the single column in the result set of the SELECT
70704       ** statement.
70705       */
70706       NameContext sNC;
70707       Select *pS = pExpr->pSelect;
70708       Expr *p = pS->pEList->a[0].pExpr;
70709       sNC.pSrcList = pS->pSrc;
70710       sNC.pNext = pNC;
70711       sNC.pParse = pNC->pParse;
70712       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
70713       break;
70714     }
70715 #endif
70716   }
70717   
70718   if( pzOriginDb ){
70719     assert( pzOriginTab && pzOriginCol );
70720     *pzOriginDb = zOriginDb;
70721     *pzOriginTab = zOriginTab;
70722     *pzOriginCol = zOriginCol;
70723   }
70724   return zType;
70725 }
70726
70727 /*
70728 ** Generate code that will tell the VDBE the declaration types of columns
70729 ** in the result set.
70730 */
70731 static void generateColumnTypes(
70732   Parse *pParse,      /* Parser context */
70733   SrcList *pTabList,  /* List of tables */
70734   ExprList *pEList    /* Expressions defining the result set */
70735 ){
70736 #ifndef SQLITE_OMIT_DECLTYPE
70737   Vdbe *v = pParse->pVdbe;
70738   int i;
70739   NameContext sNC;
70740   sNC.pSrcList = pTabList;
70741   sNC.pParse = pParse;
70742   for(i=0; i<pEList->nExpr; i++){
70743     Expr *p = pEList->a[i].pExpr;
70744     const char *zType;
70745 #ifdef SQLITE_ENABLE_COLUMN_METADATA
70746     const char *zOrigDb = 0;
70747     const char *zOrigTab = 0;
70748     const char *zOrigCol = 0;
70749     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
70750
70751     /* The vdbe must make its own copy of the column-type and other 
70752     ** column specific strings, in case the schema is reset before this
70753     ** virtual machine is deleted.
70754     */
70755     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
70756     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
70757     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
70758 #else
70759     zType = columnType(&sNC, p, 0, 0, 0);
70760 #endif
70761     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
70762   }
70763 #endif /* SQLITE_OMIT_DECLTYPE */
70764 }
70765
70766 /*
70767 ** Generate code that will tell the VDBE the names of columns
70768 ** in the result set.  This information is used to provide the
70769 ** azCol[] values in the callback.
70770 */
70771 static void generateColumnNames(
70772   Parse *pParse,      /* Parser context */
70773   SrcList *pTabList,  /* List of tables */
70774   ExprList *pEList    /* Expressions defining the result set */
70775 ){
70776   Vdbe *v = pParse->pVdbe;
70777   int i, j;
70778   sqlite3 *db = pParse->db;
70779   int fullNames, shortNames;
70780
70781 #ifndef SQLITE_OMIT_EXPLAIN
70782   /* If this is an EXPLAIN, skip this step */
70783   if( pParse->explain ){
70784     return;
70785   }
70786 #endif
70787
70788   assert( v!=0 );
70789   if( pParse->colNamesSet || v==0 || db->mallocFailed ) return;
70790   pParse->colNamesSet = 1;
70791   fullNames = (db->flags & SQLITE_FullColNames)!=0;
70792   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
70793   sqlite3VdbeSetNumCols(v, pEList->nExpr);
70794   for(i=0; i<pEList->nExpr; i++){
70795     Expr *p;
70796     p = pEList->a[i].pExpr;
70797     if( p==0 ) continue;
70798     if( pEList->a[i].zName ){
70799       char *zName = pEList->a[i].zName;
70800       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
70801     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
70802       Table *pTab;
70803       char *zCol;
70804       int iCol = p->iColumn;
70805       for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
70806       assert( j<pTabList->nSrc );
70807       pTab = pTabList->a[j].pTab;
70808       if( iCol<0 ) iCol = pTab->iPKey;
70809       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
70810       if( iCol<0 ){
70811         zCol = "rowid";
70812       }else{
70813         zCol = pTab->aCol[iCol].zName;
70814       }
70815       if( !shortNames && !fullNames ){
70816         sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
70817             sqlite3DbStrNDup(db, (char*)p->span.z, p->span.n), SQLITE_DYNAMIC);
70818       }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
70819         char *zName = 0;
70820         char *zTab;
70821  
70822         zTab = pTabList->a[j].zAlias;
70823         if( fullNames || zTab==0 ) zTab = pTab->zName;
70824         zName = sqlite3MPrintf(db, "%s.%s", zTab, zCol);
70825         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
70826       }else{
70827         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
70828       }
70829     }else{
70830       sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
70831           sqlite3DbStrNDup(db, (char*)p->span.z, p->span.n), SQLITE_DYNAMIC);
70832     }
70833   }
70834   generateColumnTypes(pParse, pTabList, pEList);
70835 }
70836
70837 #ifndef SQLITE_OMIT_COMPOUND_SELECT
70838 /*
70839 ** Name of the connection operator, used for error messages.
70840 */
70841 static const char *selectOpName(int id){
70842   char *z;
70843   switch( id ){
70844     case TK_ALL:       z = "UNION ALL";   break;
70845     case TK_INTERSECT: z = "INTERSECT";   break;
70846     case TK_EXCEPT:    z = "EXCEPT";      break;
70847     default:           z = "UNION";       break;
70848   }
70849   return z;
70850 }
70851 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
70852
70853 /*
70854 ** Given a an expression list (which is really the list of expressions
70855 ** that form the result set of a SELECT statement) compute appropriate
70856 ** column names for a table that would hold the expression list.
70857 **
70858 ** All column names will be unique.
70859 **
70860 ** Only the column names are computed.  Column.zType, Column.zColl,
70861 ** and other fields of Column are zeroed.
70862 **
70863 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
70864 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
70865 */
70866 static int selectColumnsFromExprList(
70867   Parse *pParse,          /* Parsing context */
70868   ExprList *pEList,       /* Expr list from which to derive column names */
70869   int *pnCol,             /* Write the number of columns here */
70870   Column **paCol          /* Write the new column list here */
70871 ){
70872   sqlite3 *db = pParse->db;
70873   int i, j, cnt;
70874   Column *aCol, *pCol;
70875   int nCol;
70876   Expr *p;
70877   char *zName;
70878   int nName;
70879
70880   *pnCol = nCol = pEList->nExpr;
70881   aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
70882   if( aCol==0 ) return SQLITE_NOMEM;
70883   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
70884     /* Get an appropriate name for the column
70885     */
70886     p = pEList->a[i].pExpr;
70887     assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
70888     if( (zName = pEList->a[i].zName)!=0 ){
70889       /* If the column contains an "AS <name>" phrase, use <name> as the name */
70890       zName = sqlite3DbStrDup(db, zName);
70891     }else{
70892       Expr *pCol = p;
70893       Table *pTab;
70894       while( pCol->op==TK_DOT ) pCol = pCol->pRight;
70895       if( pCol->op==TK_COLUMN && (pTab = pCol->pTab)!=0 ){
70896         /* For columns use the column name name */
70897         int iCol = pCol->iColumn;
70898         if( iCol<0 ) iCol = pTab->iPKey;
70899         zName = sqlite3MPrintf(db, "%s",
70900                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
70901       }else{
70902         /* Use the original text of the column expression as its name */
70903         zName = sqlite3MPrintf(db, "%T", &pCol->span);
70904       }
70905     }
70906     if( db->mallocFailed ){
70907       sqlite3DbFree(db, zName);
70908       break;
70909     }
70910     sqlite3Dequote(zName);
70911
70912     /* Make sure the column name is unique.  If the name is not unique,
70913     ** append a integer to the name so that it becomes unique.
70914     */
70915     nName = strlen(zName);
70916     for(j=cnt=0; j<i; j++){
70917       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
70918         char *zNewName;
70919         zName[nName] = 0;
70920         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
70921         sqlite3DbFree(db, zName);
70922         zName = zNewName;
70923         j = -1;
70924         if( zName==0 ) break;
70925       }
70926     }
70927     pCol->zName = zName;
70928   }
70929   if( db->mallocFailed ){
70930     int j;
70931     for(j=0; j<i; j++){
70932       sqlite3DbFree(db, aCol[j].zName);
70933     }
70934     sqlite3DbFree(db, aCol);
70935     *paCol = 0;
70936     *pnCol = 0;
70937     return SQLITE_NOMEM;
70938   }
70939   return SQLITE_OK;
70940 }
70941
70942 /*
70943 ** Add type and collation information to a column list based on
70944 ** a SELECT statement.
70945 ** 
70946 ** The column list presumably came from selectColumnNamesFromExprList().
70947 ** The column list has only names, not types or collations.  This
70948 ** routine goes through and adds the types and collations.
70949 **
70950 ** This routine requires that all indentifiers in the SELECT
70951 ** statement be resolved.
70952 */
70953 static void selectAddColumnTypeAndCollation(
70954   Parse *pParse,        /* Parsing contexts */
70955   int nCol,             /* Number of columns */
70956   Column *aCol,         /* List of columns */
70957   Select *pSelect       /* SELECT used to determine types and collations */
70958 ){
70959   sqlite3 *db = pParse->db;
70960   NameContext sNC;
70961   Column *pCol;
70962   CollSeq *pColl;
70963   int i;
70964   Expr *p;
70965   struct ExprList_item *a;
70966
70967   assert( pSelect!=0 );
70968   assert( (pSelect->selFlags & SF_Resolved)!=0 );
70969   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
70970   if( db->mallocFailed ) return;
70971   memset(&sNC, 0, sizeof(sNC));
70972   sNC.pSrcList = pSelect->pSrc;
70973   a = pSelect->pEList->a;
70974   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
70975     p = a[i].pExpr;
70976     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
70977     pCol->affinity = sqlite3ExprAffinity(p);
70978     pColl = sqlite3ExprCollSeq(pParse, p);
70979     if( pColl ){
70980       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
70981     }
70982   }
70983 }
70984
70985 /*
70986 ** Given a SELECT statement, generate a Table structure that describes
70987 ** the result set of that SELECT.
70988 */
70989 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
70990   Table *pTab;
70991   sqlite3 *db = pParse->db;
70992   int savedFlags;
70993
70994   savedFlags = db->flags;
70995   db->flags &= ~SQLITE_FullColNames;
70996   db->flags |= SQLITE_ShortColNames;
70997   sqlite3SelectPrep(pParse, pSelect, 0);
70998   if( pParse->nErr ) return 0;
70999   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
71000   db->flags = savedFlags;
71001   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
71002   if( pTab==0 ){
71003     return 0;
71004   }
71005   pTab->db = db;
71006   pTab->nRef = 1;
71007   pTab->zName = 0;
71008   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
71009   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
71010   pTab->iPKey = -1;
71011   if( db->mallocFailed ){
71012     sqlite3DeleteTable(pTab);
71013     return 0;
71014   }
71015   return pTab;
71016 }
71017
71018 /*
71019 ** Get a VDBE for the given parser context.  Create a new one if necessary.
71020 ** If an error occurs, return NULL and leave a message in pParse.
71021 */
71022 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
71023   Vdbe *v = pParse->pVdbe;
71024   if( v==0 ){
71025     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
71026 #ifndef SQLITE_OMIT_TRACE
71027     if( v ){
71028       sqlite3VdbeAddOp0(v, OP_Trace);
71029     }
71030 #endif
71031   }
71032   return v;
71033 }
71034
71035
71036 /*
71037 ** Compute the iLimit and iOffset fields of the SELECT based on the
71038 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
71039 ** that appear in the original SQL statement after the LIMIT and OFFSET
71040 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
71041 ** are the integer memory register numbers for counters used to compute 
71042 ** the limit and offset.  If there is no limit and/or offset, then 
71043 ** iLimit and iOffset are negative.
71044 **
71045 ** This routine changes the values of iLimit and iOffset only if
71046 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
71047 ** iOffset should have been preset to appropriate default values
71048 ** (usually but not always -1) prior to calling this routine.
71049 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
71050 ** redefined.  The UNION ALL operator uses this property to force
71051 ** the reuse of the same limit and offset registers across multiple
71052 ** SELECT statements.
71053 */
71054 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
71055   Vdbe *v = 0;
71056   int iLimit = 0;
71057   int iOffset;
71058   int addr1;
71059   if( p->iLimit ) return;
71060
71061   /* 
71062   ** "LIMIT -1" always shows all rows.  There is some
71063   ** contraversy about what the correct behavior should be.
71064   ** The current implementation interprets "LIMIT 0" to mean
71065   ** no rows.
71066   */
71067   if( p->pLimit ){
71068     p->iLimit = iLimit = ++pParse->nMem;
71069     v = sqlite3GetVdbe(pParse);
71070     if( v==0 ) return;
71071     sqlite3ExprCode(pParse, p->pLimit, iLimit);
71072     sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
71073     VdbeComment((v, "LIMIT counter"));
71074     sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
71075   }
71076   if( p->pOffset ){
71077     p->iOffset = iOffset = ++pParse->nMem;
71078     if( p->pLimit ){
71079       pParse->nMem++;   /* Allocate an extra register for limit+offset */
71080     }
71081     v = sqlite3GetVdbe(pParse);
71082     if( v==0 ) return;
71083     sqlite3ExprCode(pParse, p->pOffset, iOffset);
71084     sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
71085     VdbeComment((v, "OFFSET counter"));
71086     addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
71087     sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
71088     sqlite3VdbeJumpHere(v, addr1);
71089     if( p->pLimit ){
71090       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
71091       VdbeComment((v, "LIMIT+OFFSET"));
71092       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
71093       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
71094       sqlite3VdbeJumpHere(v, addr1);
71095     }
71096   }
71097 }
71098
71099 #ifndef SQLITE_OMIT_COMPOUND_SELECT
71100 /*
71101 ** Return the appropriate collating sequence for the iCol-th column of
71102 ** the result set for the compound-select statement "p".  Return NULL if
71103 ** the column has no default collating sequence.
71104 **
71105 ** The collating sequence for the compound select is taken from the
71106 ** left-most term of the select that has a collating sequence.
71107 */
71108 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
71109   CollSeq *pRet;
71110   if( p->pPrior ){
71111     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
71112   }else{
71113     pRet = 0;
71114   }
71115   if( pRet==0 ){
71116     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
71117   }
71118   return pRet;
71119 }
71120 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
71121
71122 /* Forward reference */
71123 static int multiSelectOrderBy(
71124   Parse *pParse,        /* Parsing context */
71125   Select *p,            /* The right-most of SELECTs to be coded */
71126   SelectDest *pDest     /* What to do with query results */
71127 );
71128
71129
71130 #ifndef SQLITE_OMIT_COMPOUND_SELECT
71131 /*
71132 ** This routine is called to process a compound query form from
71133 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
71134 ** INTERSECT
71135 **
71136 ** "p" points to the right-most of the two queries.  the query on the
71137 ** left is p->pPrior.  The left query could also be a compound query
71138 ** in which case this routine will be called recursively. 
71139 **
71140 ** The results of the total query are to be written into a destination
71141 ** of type eDest with parameter iParm.
71142 **
71143 ** Example 1:  Consider a three-way compound SQL statement.
71144 **
71145 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
71146 **
71147 ** This statement is parsed up as follows:
71148 **
71149 **     SELECT c FROM t3
71150 **      |
71151 **      `----->  SELECT b FROM t2
71152 **                |
71153 **                `------>  SELECT a FROM t1
71154 **
71155 ** The arrows in the diagram above represent the Select.pPrior pointer.
71156 ** So if this routine is called with p equal to the t3 query, then
71157 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
71158 **
71159 ** Notice that because of the way SQLite parses compound SELECTs, the
71160 ** individual selects always group from left to right.
71161 */
71162 static int multiSelect(
71163   Parse *pParse,        /* Parsing context */
71164   Select *p,            /* The right-most of SELECTs to be coded */
71165   SelectDest *pDest     /* What to do with query results */
71166 ){
71167   int rc = SQLITE_OK;   /* Success code from a subroutine */
71168   Select *pPrior;       /* Another SELECT immediately to our left */
71169   Vdbe *v;              /* Generate code to this VDBE */
71170   SelectDest dest;      /* Alternative data destination */
71171   Select *pDelete = 0;  /* Chain of simple selects to delete */
71172   sqlite3 *db;          /* Database connection */
71173
71174   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
71175   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
71176   */
71177   assert( p && p->pPrior );  /* Calling function guarantees this much */
71178   db = pParse->db;
71179   pPrior = p->pPrior;
71180   assert( pPrior->pRightmost!=pPrior );
71181   assert( pPrior->pRightmost==p->pRightmost );
71182   dest = *pDest;
71183   if( pPrior->pOrderBy ){
71184     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
71185       selectOpName(p->op));
71186     rc = 1;
71187     goto multi_select_end;
71188   }
71189   if( pPrior->pLimit ){
71190     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
71191       selectOpName(p->op));
71192     rc = 1;
71193     goto multi_select_end;
71194   }
71195
71196   v = sqlite3GetVdbe(pParse);
71197   assert( v!=0 );  /* The VDBE already created by calling function */
71198
71199   /* Create the destination temporary table if necessary
71200   */
71201   if( dest.eDest==SRT_EphemTab ){
71202     assert( p->pEList );
71203     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
71204     dest.eDest = SRT_Table;
71205   }
71206
71207   /* Make sure all SELECTs in the statement have the same number of elements
71208   ** in their result sets.
71209   */
71210   assert( p->pEList && pPrior->pEList );
71211   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
71212     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
71213       " do not have the same number of result columns", selectOpName(p->op));
71214     rc = 1;
71215     goto multi_select_end;
71216   }
71217
71218   /* Compound SELECTs that have an ORDER BY clause are handled separately.
71219   */
71220   if( p->pOrderBy ){
71221     return multiSelectOrderBy(pParse, p, pDest);
71222   }
71223
71224   /* Generate code for the left and right SELECT statements.
71225   */
71226   switch( p->op ){
71227     case TK_ALL: {
71228       int addr = 0;
71229       assert( !pPrior->pLimit );
71230       pPrior->pLimit = p->pLimit;
71231       pPrior->pOffset = p->pOffset;
71232       rc = sqlite3Select(pParse, pPrior, &dest);
71233       p->pLimit = 0;
71234       p->pOffset = 0;
71235       if( rc ){
71236         goto multi_select_end;
71237       }
71238       p->pPrior = 0;
71239       p->iLimit = pPrior->iLimit;
71240       p->iOffset = pPrior->iOffset;
71241       if( p->iLimit ){
71242         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
71243         VdbeComment((v, "Jump ahead if LIMIT reached"));
71244       }
71245       rc = sqlite3Select(pParse, p, &dest);
71246       pDelete = p->pPrior;
71247       p->pPrior = pPrior;
71248       if( rc ){
71249         goto multi_select_end;
71250       }
71251       if( addr ){
71252         sqlite3VdbeJumpHere(v, addr);
71253       }
71254       break;
71255     }
71256     case TK_EXCEPT:
71257     case TK_UNION: {
71258       int unionTab;    /* Cursor number of the temporary table holding result */
71259       int op = 0;      /* One of the SRT_ operations to apply to self */
71260       int priorOp;     /* The SRT_ operation to apply to prior selects */
71261       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
71262       int addr;
71263       SelectDest uniondest;
71264
71265       priorOp = SRT_Union;
71266       if( dest.eDest==priorOp && !p->pLimit && !p->pOffset ){
71267         /* We can reuse a temporary table generated by a SELECT to our
71268         ** right.
71269         */
71270         unionTab = dest.iParm;
71271       }else{
71272         /* We will need to create our own temporary table to hold the
71273         ** intermediate results.
71274         */
71275         unionTab = pParse->nTab++;
71276         assert( p->pOrderBy==0 );
71277         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
71278         assert( p->addrOpenEphm[0] == -1 );
71279         p->addrOpenEphm[0] = addr;
71280         p->pRightmost->selFlags |= SF_UsesEphemeral;
71281         assert( p->pEList );
71282       }
71283
71284       /* Code the SELECT statements to our left
71285       */
71286       assert( !pPrior->pOrderBy );
71287       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
71288       rc = sqlite3Select(pParse, pPrior, &uniondest);
71289       if( rc ){
71290         goto multi_select_end;
71291       }
71292
71293       /* Code the current SELECT statement
71294       */
71295       if( p->op==TK_EXCEPT ){
71296         op = SRT_Except;
71297       }else{
71298         assert( p->op==TK_UNION );
71299         op = SRT_Union;
71300       }
71301       p->pPrior = 0;
71302       pLimit = p->pLimit;
71303       p->pLimit = 0;
71304       pOffset = p->pOffset;
71305       p->pOffset = 0;
71306       uniondest.eDest = op;
71307       rc = sqlite3Select(pParse, p, &uniondest);
71308       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
71309       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
71310       sqlite3ExprListDelete(db, p->pOrderBy);
71311       pDelete = p->pPrior;
71312       p->pPrior = pPrior;
71313       p->pOrderBy = 0;
71314       sqlite3ExprDelete(db, p->pLimit);
71315       p->pLimit = pLimit;
71316       p->pOffset = pOffset;
71317       p->iLimit = 0;
71318       p->iOffset = 0;
71319       if( rc ){
71320         goto multi_select_end;
71321       }
71322
71323
71324       /* Convert the data in the temporary table into whatever form
71325       ** it is that we currently need.
71326       */      
71327       if( dest.eDest!=priorOp || unionTab!=dest.iParm ){
71328         int iCont, iBreak, iStart;
71329         assert( p->pEList );
71330         if( dest.eDest==SRT_Output ){
71331           Select *pFirst = p;
71332           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
71333           generateColumnNames(pParse, 0, pFirst->pEList);
71334         }
71335         iBreak = sqlite3VdbeMakeLabel(v);
71336         iCont = sqlite3VdbeMakeLabel(v);
71337         computeLimitRegisters(pParse, p, iBreak);
71338         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
71339         iStart = sqlite3VdbeCurrentAddr(v);
71340         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
71341                         0, -1, &dest, iCont, iBreak);
71342         sqlite3VdbeResolveLabel(v, iCont);
71343         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
71344         sqlite3VdbeResolveLabel(v, iBreak);
71345         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
71346       }
71347       break;
71348     }
71349     case TK_INTERSECT: {
71350       int tab1, tab2;
71351       int iCont, iBreak, iStart;
71352       Expr *pLimit, *pOffset;
71353       int addr;
71354       SelectDest intersectdest;
71355       int r1;
71356
71357       /* INTERSECT is different from the others since it requires
71358       ** two temporary tables.  Hence it has its own case.  Begin
71359       ** by allocating the tables we will need.
71360       */
71361       tab1 = pParse->nTab++;
71362       tab2 = pParse->nTab++;
71363       assert( p->pOrderBy==0 );
71364
71365       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
71366       assert( p->addrOpenEphm[0] == -1 );
71367       p->addrOpenEphm[0] = addr;
71368       p->pRightmost->selFlags |= SF_UsesEphemeral;
71369       assert( p->pEList );
71370
71371       /* Code the SELECTs to our left into temporary table "tab1".
71372       */
71373       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
71374       rc = sqlite3Select(pParse, pPrior, &intersectdest);
71375       if( rc ){
71376         goto multi_select_end;
71377       }
71378
71379       /* Code the current SELECT into temporary table "tab2"
71380       */
71381       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
71382       assert( p->addrOpenEphm[1] == -1 );
71383       p->addrOpenEphm[1] = addr;
71384       p->pPrior = 0;
71385       pLimit = p->pLimit;
71386       p->pLimit = 0;
71387       pOffset = p->pOffset;
71388       p->pOffset = 0;
71389       intersectdest.iParm = tab2;
71390       rc = sqlite3Select(pParse, p, &intersectdest);
71391       pDelete = p->pPrior;
71392       p->pPrior = pPrior;
71393       sqlite3ExprDelete(db, p->pLimit);
71394       p->pLimit = pLimit;
71395       p->pOffset = pOffset;
71396       if( rc ){
71397         goto multi_select_end;
71398       }
71399
71400       /* Generate code to take the intersection of the two temporary
71401       ** tables.
71402       */
71403       assert( p->pEList );
71404       if( dest.eDest==SRT_Output ){
71405         Select *pFirst = p;
71406         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
71407         generateColumnNames(pParse, 0, pFirst->pEList);
71408       }
71409       iBreak = sqlite3VdbeMakeLabel(v);
71410       iCont = sqlite3VdbeMakeLabel(v);
71411       computeLimitRegisters(pParse, p, iBreak);
71412       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
71413       r1 = sqlite3GetTempReg(pParse);
71414       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
71415       sqlite3VdbeAddOp3(v, OP_NotFound, tab2, iCont, r1);
71416       sqlite3ReleaseTempReg(pParse, r1);
71417       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
71418                       0, -1, &dest, iCont, iBreak);
71419       sqlite3VdbeResolveLabel(v, iCont);
71420       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
71421       sqlite3VdbeResolveLabel(v, iBreak);
71422       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
71423       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
71424       break;
71425     }
71426   }
71427
71428   /* Compute collating sequences used by 
71429   ** temporary tables needed to implement the compound select.
71430   ** Attach the KeyInfo structure to all temporary tables.
71431   **
71432   ** This section is run by the right-most SELECT statement only.
71433   ** SELECT statements to the left always skip this part.  The right-most
71434   ** SELECT might also skip this part if it has no ORDER BY clause and
71435   ** no temp tables are required.
71436   */
71437   if( p->selFlags & SF_UsesEphemeral ){
71438     int i;                        /* Loop counter */
71439     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
71440     Select *pLoop;                /* For looping through SELECT statements */
71441     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
71442     int nCol;                     /* Number of columns in result set */
71443
71444     assert( p->pRightmost==p );
71445     nCol = p->pEList->nExpr;
71446     pKeyInfo = sqlite3DbMallocZero(db,
71447                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
71448     if( !pKeyInfo ){
71449       rc = SQLITE_NOMEM;
71450       goto multi_select_end;
71451     }
71452
71453     pKeyInfo->enc = ENC(db);
71454     pKeyInfo->nField = nCol;
71455
71456     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
71457       *apColl = multiSelectCollSeq(pParse, p, i);
71458       if( 0==*apColl ){
71459         *apColl = db->pDfltColl;
71460       }
71461     }
71462
71463     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
71464       for(i=0; i<2; i++){
71465         int addr = pLoop->addrOpenEphm[i];
71466         if( addr<0 ){
71467           /* If [0] is unused then [1] is also unused.  So we can
71468           ** always safely abort as soon as the first unused slot is found */
71469           assert( pLoop->addrOpenEphm[1]<0 );
71470           break;
71471         }
71472         sqlite3VdbeChangeP2(v, addr, nCol);
71473         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
71474         pLoop->addrOpenEphm[i] = -1;
71475       }
71476     }
71477     sqlite3DbFree(db, pKeyInfo);
71478   }
71479
71480 multi_select_end:
71481   pDest->iMem = dest.iMem;
71482   pDest->nMem = dest.nMem;
71483   sqlite3SelectDelete(db, pDelete);
71484   return rc;
71485 }
71486 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
71487
71488 /*
71489 ** Code an output subroutine for a coroutine implementation of a
71490 ** SELECT statment.
71491 **
71492 ** The data to be output is contained in pIn->iMem.  There are
71493 ** pIn->nMem columns to be output.  pDest is where the output should
71494 ** be sent.
71495 **
71496 ** regReturn is the number of the register holding the subroutine
71497 ** return address.
71498 **
71499 ** If regPrev>0 then it is a the first register in a vector that
71500 ** records the previous output.  mem[regPrev] is a flag that is false
71501 ** if there has been no previous output.  If regPrev>0 then code is
71502 ** generated to suppress duplicates.  pKeyInfo is used for comparing
71503 ** keys.
71504 **
71505 ** If the LIMIT found in p->iLimit is reached, jump immediately to
71506 ** iBreak.
71507 */
71508 static int generateOutputSubroutine(
71509   Parse *pParse,          /* Parsing context */
71510   Select *p,              /* The SELECT statement */
71511   SelectDest *pIn,        /* Coroutine supplying data */
71512   SelectDest *pDest,      /* Where to send the data */
71513   int regReturn,          /* The return address register */
71514   int regPrev,            /* Previous result register.  No uniqueness if 0 */
71515   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
71516   int p4type,             /* The p4 type for pKeyInfo */
71517   int iBreak              /* Jump here if we hit the LIMIT */
71518 ){
71519   Vdbe *v = pParse->pVdbe;
71520   int iContinue;
71521   int addr;
71522
71523   addr = sqlite3VdbeCurrentAddr(v);
71524   iContinue = sqlite3VdbeMakeLabel(v);
71525
71526   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
71527   */
71528   if( regPrev ){
71529     int j1, j2;
71530     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
71531     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
71532                               (char*)pKeyInfo, p4type);
71533     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
71534     sqlite3VdbeJumpHere(v, j1);
71535     sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
71536     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
71537   }
71538   if( pParse->db->mallocFailed ) return 0;
71539
71540   /* Suppress the the first OFFSET entries if there is an OFFSET clause
71541   */
71542   codeOffset(v, p, iContinue);
71543
71544   switch( pDest->eDest ){
71545     /* Store the result as data using a unique key.
71546     */
71547     case SRT_Table:
71548     case SRT_EphemTab: {
71549       int r1 = sqlite3GetTempReg(pParse);
71550       int r2 = sqlite3GetTempReg(pParse);
71551       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
71552       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
71553       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
71554       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
71555       sqlite3ReleaseTempReg(pParse, r2);
71556       sqlite3ReleaseTempReg(pParse, r1);
71557       break;
71558     }
71559
71560 #ifndef SQLITE_OMIT_SUBQUERY
71561     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
71562     ** then there should be a single item on the stack.  Write this
71563     ** item into the set table with bogus data.
71564     */
71565     case SRT_Set: {
71566       int r1;
71567       assert( pIn->nMem==1 );
71568       p->affinity = 
71569          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
71570       r1 = sqlite3GetTempReg(pParse);
71571       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
71572       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
71573       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
71574       sqlite3ReleaseTempReg(pParse, r1);
71575       break;
71576     }
71577
71578 #if 0  /* Never occurs on an ORDER BY query */
71579     /* If any row exist in the result set, record that fact and abort.
71580     */
71581     case SRT_Exists: {
71582       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
71583       /* The LIMIT clause will terminate the loop for us */
71584       break;
71585     }
71586 #endif
71587
71588     /* If this is a scalar select that is part of an expression, then
71589     ** store the results in the appropriate memory cell and break out
71590     ** of the scan loop.
71591     */
71592     case SRT_Mem: {
71593       assert( pIn->nMem==1 );
71594       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
71595       /* The LIMIT clause will jump out of the loop for us */
71596       break;
71597     }
71598 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
71599
71600     /* The results are stored in a sequence of registers
71601     ** starting at pDest->iMem.  Then the co-routine yields.
71602     */
71603     case SRT_Coroutine: {
71604       if( pDest->iMem==0 ){
71605         pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
71606         pDest->nMem = pIn->nMem;
71607       }
71608       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
71609       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
71610       break;
71611     }
71612
71613     /* Results are stored in a sequence of registers.  Then the
71614     ** OP_ResultRow opcode is used to cause sqlite3_step() to return
71615     ** the next row of result.
71616     */
71617     case SRT_Output: {
71618       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
71619       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
71620       break;
71621     }
71622
71623 #if !defined(SQLITE_OMIT_TRIGGER)
71624     /* Discard the results.  This is used for SELECT statements inside
71625     ** the body of a TRIGGER.  The purpose of such selects is to call
71626     ** user-defined functions that have side effects.  We do not care
71627     ** about the actual results of the select.
71628     */
71629     default: {
71630       break;
71631     }
71632 #endif
71633   }
71634
71635   /* Jump to the end of the loop if the LIMIT is reached.
71636   */
71637   if( p->iLimit ){
71638     sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
71639     sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak);
71640   }
71641
71642   /* Generate the subroutine return
71643   */
71644   sqlite3VdbeResolveLabel(v, iContinue);
71645   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
71646
71647   return addr;
71648 }
71649
71650 /*
71651 ** Alternative compound select code generator for cases when there
71652 ** is an ORDER BY clause.
71653 **
71654 ** We assume a query of the following form:
71655 **
71656 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
71657 **
71658 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
71659 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
71660 ** co-routines.  Then run the co-routines in parallel and merge the results
71661 ** into the output.  In addition to the two coroutines (called selectA and
71662 ** selectB) there are 7 subroutines:
71663 **
71664 **    outA:    Move the output of the selectA coroutine into the output
71665 **             of the compound query.
71666 **
71667 **    outB:    Move the output of the selectB coroutine into the output
71668 **             of the compound query.  (Only generated for UNION and
71669 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
71670 **             appears only in B.)
71671 **
71672 **    AltB:    Called when there is data from both coroutines and A<B.
71673 **
71674 **    AeqB:    Called when there is data from both coroutines and A==B.
71675 **
71676 **    AgtB:    Called when there is data from both coroutines and A>B.
71677 **
71678 **    EofA:    Called when data is exhausted from selectA.
71679 **
71680 **    EofB:    Called when data is exhausted from selectB.
71681 **
71682 ** The implementation of the latter five subroutines depend on which 
71683 ** <operator> is used:
71684 **
71685 **
71686 **             UNION ALL         UNION            EXCEPT          INTERSECT
71687 **          -------------  -----------------  --------------  -----------------
71688 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
71689 **
71690 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
71691 **
71692 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
71693 **
71694 **   EofA:   outB, nextB      outB, nextB          halt             halt
71695 **
71696 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
71697 **
71698 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
71699 ** causes an immediate jump to EofA and an EOF on B following nextB causes
71700 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
71701 ** following nextX causes a jump to the end of the select processing.
71702 **
71703 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
71704 ** within the output subroutine.  The regPrev register set holds the previously
71705 ** output value.  A comparison is made against this value and the output
71706 ** is skipped if the next results would be the same as the previous.
71707 **
71708 ** The implementation plan is to implement the two coroutines and seven
71709 ** subroutines first, then put the control logic at the bottom.  Like this:
71710 **
71711 **          goto Init
71712 **     coA: coroutine for left query (A)
71713 **     coB: coroutine for right query (B)
71714 **    outA: output one row of A
71715 **    outB: output one row of B (UNION and UNION ALL only)
71716 **    EofA: ...
71717 **    EofB: ...
71718 **    AltB: ...
71719 **    AeqB: ...
71720 **    AgtB: ...
71721 **    Init: initialize coroutine registers
71722 **          yield coA
71723 **          if eof(A) goto EofA
71724 **          yield coB
71725 **          if eof(B) goto EofB
71726 **    Cmpr: Compare A, B
71727 **          Jump AltB, AeqB, AgtB
71728 **     End: ...
71729 **
71730 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
71731 ** actually called using Gosub and they do not Return.  EofA and EofB loop
71732 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
71733 ** and AgtB jump to either L2 or to one of EofA or EofB.
71734 */
71735 #ifndef SQLITE_OMIT_COMPOUND_SELECT
71736 static int multiSelectOrderBy(
71737   Parse *pParse,        /* Parsing context */
71738   Select *p,            /* The right-most of SELECTs to be coded */
71739   SelectDest *pDest     /* What to do with query results */
71740 ){
71741   int i, j;             /* Loop counters */
71742   Select *pPrior;       /* Another SELECT immediately to our left */
71743   Vdbe *v;              /* Generate code to this VDBE */
71744   SelectDest destA;     /* Destination for coroutine A */
71745   SelectDest destB;     /* Destination for coroutine B */
71746   int regAddrA;         /* Address register for select-A coroutine */
71747   int regEofA;          /* Flag to indicate when select-A is complete */
71748   int regAddrB;         /* Address register for select-B coroutine */
71749   int regEofB;          /* Flag to indicate when select-B is complete */
71750   int addrSelectA;      /* Address of the select-A coroutine */
71751   int addrSelectB;      /* Address of the select-B coroutine */
71752   int regOutA;          /* Address register for the output-A subroutine */
71753   int regOutB;          /* Address register for the output-B subroutine */
71754   int addrOutA;         /* Address of the output-A subroutine */
71755   int addrOutB;         /* Address of the output-B subroutine */
71756   int addrEofA;         /* Address of the select-A-exhausted subroutine */
71757   int addrEofB;         /* Address of the select-B-exhausted subroutine */
71758   int addrAltB;         /* Address of the A<B subroutine */
71759   int addrAeqB;         /* Address of the A==B subroutine */
71760   int addrAgtB;         /* Address of the A>B subroutine */
71761   int regLimitA;        /* Limit register for select-A */
71762   int regLimitB;        /* Limit register for select-A */
71763   int regPrev;          /* A range of registers to hold previous output */
71764   int savedLimit;       /* Saved value of p->iLimit */
71765   int savedOffset;      /* Saved value of p->iOffset */
71766   int labelCmpr;        /* Label for the start of the merge algorithm */
71767   int labelEnd;         /* Label for the end of the overall SELECT stmt */
71768   int j1;               /* Jump instructions that get retargetted */
71769   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
71770   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
71771   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
71772   sqlite3 *db;          /* Database connection */
71773   ExprList *pOrderBy;   /* The ORDER BY clause */
71774   int nOrderBy;         /* Number of terms in the ORDER BY clause */
71775   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
71776
71777   assert( p->pOrderBy!=0 );
71778   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
71779   db = pParse->db;
71780   v = pParse->pVdbe;
71781   if( v==0 ) return SQLITE_NOMEM;
71782   labelEnd = sqlite3VdbeMakeLabel(v);
71783   labelCmpr = sqlite3VdbeMakeLabel(v);
71784
71785
71786   /* Patch up the ORDER BY clause
71787   */
71788   op = p->op;  
71789   pPrior = p->pPrior;
71790   assert( pPrior->pOrderBy==0 );
71791   pOrderBy = p->pOrderBy;
71792   assert( pOrderBy );
71793   nOrderBy = pOrderBy->nExpr;
71794
71795   /* For operators other than UNION ALL we have to make sure that
71796   ** the ORDER BY clause covers every term of the result set.  Add
71797   ** terms to the ORDER BY clause as necessary.
71798   */
71799   if( op!=TK_ALL ){
71800     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
71801       struct ExprList_item *pItem;
71802       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
71803         assert( pItem->iCol>0 );
71804         if( pItem->iCol==i ) break;
71805       }
71806       if( j==nOrderBy ){
71807         Expr *pNew = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, 0);
71808         if( pNew==0 ) return SQLITE_NOMEM;
71809         pNew->flags |= EP_IntValue;
71810         pNew->iTable = i;
71811         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew, 0);
71812         pOrderBy->a[nOrderBy++].iCol = i;
71813       }
71814     }
71815   }
71816
71817   /* Compute the comparison permutation and keyinfo that is used with
71818   ** the permutation in order to comparisons to determine if the next
71819   ** row of results comes from selectA or selectB.  Also add explicit
71820   ** collations to the ORDER BY clause terms so that when the subqueries
71821   ** to the right and the left are evaluated, they use the correct
71822   ** collation.
71823   */
71824   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
71825   if( aPermute ){
71826     struct ExprList_item *pItem;
71827     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
71828       assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
71829       aPermute[i] = pItem->iCol - 1;
71830     }
71831     pKeyMerge =
71832       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
71833     if( pKeyMerge ){
71834       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
71835       pKeyMerge->nField = nOrderBy;
71836       pKeyMerge->enc = ENC(db);
71837       for(i=0; i<nOrderBy; i++){
71838         CollSeq *pColl;
71839         Expr *pTerm = pOrderBy->a[i].pExpr;
71840         if( pTerm->flags & EP_ExpCollate ){
71841           pColl = pTerm->pColl;
71842         }else{
71843           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
71844           pTerm->flags |= EP_ExpCollate;
71845           pTerm->pColl = pColl;
71846         }
71847         pKeyMerge->aColl[i] = pColl;
71848         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
71849       }
71850     }
71851   }else{
71852     pKeyMerge = 0;
71853   }
71854
71855   /* Reattach the ORDER BY clause to the query.
71856   */
71857   p->pOrderBy = pOrderBy;
71858   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy);
71859
71860   /* Allocate a range of temporary registers and the KeyInfo needed
71861   ** for the logic that removes duplicate result rows when the
71862   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
71863   */
71864   if( op==TK_ALL ){
71865     regPrev = 0;
71866   }else{
71867     int nExpr = p->pEList->nExpr;
71868     assert( nOrderBy>=nExpr || db->mallocFailed );
71869     regPrev = sqlite3GetTempRange(pParse, nExpr+1);
71870     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
71871     pKeyDup = sqlite3DbMallocZero(db,
71872                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
71873     if( pKeyDup ){
71874       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
71875       pKeyDup->nField = nExpr;
71876       pKeyDup->enc = ENC(db);
71877       for(i=0; i<nExpr; i++){
71878         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
71879         pKeyDup->aSortOrder[i] = 0;
71880       }
71881     }
71882   }
71883  
71884   /* Separate the left and the right query from one another
71885   */
71886   p->pPrior = 0;
71887   pPrior->pRightmost = 0;
71888   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
71889   if( pPrior->pPrior==0 ){
71890     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
71891   }
71892
71893   /* Compute the limit registers */
71894   computeLimitRegisters(pParse, p, labelEnd);
71895   if( p->iLimit && op==TK_ALL ){
71896     regLimitA = ++pParse->nMem;
71897     regLimitB = ++pParse->nMem;
71898     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
71899                                   regLimitA);
71900     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
71901   }else{
71902     regLimitA = regLimitB = 0;
71903   }
71904   sqlite3ExprDelete(db, p->pLimit);
71905   p->pLimit = 0;
71906   sqlite3ExprDelete(db, p->pOffset);
71907   p->pOffset = 0;
71908
71909   regAddrA = ++pParse->nMem;
71910   regEofA = ++pParse->nMem;
71911   regAddrB = ++pParse->nMem;
71912   regEofB = ++pParse->nMem;
71913   regOutA = ++pParse->nMem;
71914   regOutB = ++pParse->nMem;
71915   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
71916   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
71917
71918   /* Jump past the various subroutines and coroutines to the main
71919   ** merge loop
71920   */
71921   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
71922   addrSelectA = sqlite3VdbeCurrentAddr(v);
71923
71924
71925   /* Generate a coroutine to evaluate the SELECT statement to the
71926   ** left of the compound operator - the "A" select.
71927   */
71928   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
71929   pPrior->iLimit = regLimitA;
71930   sqlite3Select(pParse, pPrior, &destA);
71931   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
71932   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
71933   VdbeNoopComment((v, "End coroutine for left SELECT"));
71934
71935   /* Generate a coroutine to evaluate the SELECT statement on 
71936   ** the right - the "B" select
71937   */
71938   addrSelectB = sqlite3VdbeCurrentAddr(v);
71939   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
71940   savedLimit = p->iLimit;
71941   savedOffset = p->iOffset;
71942   p->iLimit = regLimitB;
71943   p->iOffset = 0;  
71944   sqlite3Select(pParse, p, &destB);
71945   p->iLimit = savedLimit;
71946   p->iOffset = savedOffset;
71947   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
71948   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
71949   VdbeNoopComment((v, "End coroutine for right SELECT"));
71950
71951   /* Generate a subroutine that outputs the current row of the A
71952   ** select as the next output row of the compound select.
71953   */
71954   VdbeNoopComment((v, "Output routine for A"));
71955   addrOutA = generateOutputSubroutine(pParse,
71956                  p, &destA, pDest, regOutA,
71957                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
71958   
71959   /* Generate a subroutine that outputs the current row of the B
71960   ** select as the next output row of the compound select.
71961   */
71962   if( op==TK_ALL || op==TK_UNION ){
71963     VdbeNoopComment((v, "Output routine for B"));
71964     addrOutB = generateOutputSubroutine(pParse,
71965                  p, &destB, pDest, regOutB,
71966                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
71967   }
71968
71969   /* Generate a subroutine to run when the results from select A
71970   ** are exhausted and only data in select B remains.
71971   */
71972   VdbeNoopComment((v, "eof-A subroutine"));
71973   if( op==TK_EXCEPT || op==TK_INTERSECT ){
71974     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
71975   }else{  
71976     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
71977     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
71978     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
71979     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
71980   }
71981
71982   /* Generate a subroutine to run when the results from select B
71983   ** are exhausted and only data in select A remains.
71984   */
71985   if( op==TK_INTERSECT ){
71986     addrEofB = addrEofA;
71987   }else{  
71988     VdbeNoopComment((v, "eof-B subroutine"));
71989     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
71990     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
71991     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
71992     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
71993   }
71994
71995   /* Generate code to handle the case of A<B
71996   */
71997   VdbeNoopComment((v, "A-lt-B subroutine"));
71998   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
71999   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
72000   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
72001   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
72002
72003   /* Generate code to handle the case of A==B
72004   */
72005   if( op==TK_ALL ){
72006     addrAeqB = addrAltB;
72007   }else if( op==TK_INTERSECT ){
72008     addrAeqB = addrAltB;
72009     addrAltB++;
72010   }else{
72011     VdbeNoopComment((v, "A-eq-B subroutine"));
72012     addrAeqB =
72013     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
72014     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
72015     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
72016   }
72017
72018   /* Generate code to handle the case of A>B
72019   */
72020   VdbeNoopComment((v, "A-gt-B subroutine"));
72021   addrAgtB = sqlite3VdbeCurrentAddr(v);
72022   if( op==TK_ALL || op==TK_UNION ){
72023     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
72024   }
72025   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
72026   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
72027   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
72028
72029   /* This code runs once to initialize everything.
72030   */
72031   sqlite3VdbeJumpHere(v, j1);
72032   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
72033   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
72034   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
72035   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
72036   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
72037   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
72038
72039   /* Implement the main merge loop
72040   */
72041   sqlite3VdbeResolveLabel(v, labelCmpr);
72042   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
72043   sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
72044                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
72045   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
72046
72047   /* Release temporary registers
72048   */
72049   if( regPrev ){
72050     sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
72051   }
72052
72053   /* Jump to the this point in order to terminate the query.
72054   */
72055   sqlite3VdbeResolveLabel(v, labelEnd);
72056
72057   /* Set the number of output columns
72058   */
72059   if( pDest->eDest==SRT_Output ){
72060     Select *pFirst = pPrior;
72061     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
72062     generateColumnNames(pParse, 0, pFirst->pEList);
72063   }
72064
72065   /* Reassembly the compound query so that it will be freed correctly
72066   ** by the calling function */
72067   if( p->pPrior ){
72068     sqlite3SelectDelete(db, p->pPrior);
72069   }
72070   p->pPrior = pPrior;
72071
72072   /*** TBD:  Insert subroutine calls to close cursors on incomplete
72073   **** subqueries ****/
72074   return SQLITE_OK;
72075 }
72076 #endif
72077
72078 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
72079 /* Forward Declarations */
72080 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
72081 static void substSelect(sqlite3*, Select *, int, ExprList *);
72082
72083 /*
72084 ** Scan through the expression pExpr.  Replace every reference to
72085 ** a column in table number iTable with a copy of the iColumn-th
72086 ** entry in pEList.  (But leave references to the ROWID column 
72087 ** unchanged.)
72088 **
72089 ** This routine is part of the flattening procedure.  A subquery
72090 ** whose result set is defined by pEList appears as entry in the
72091 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
72092 ** FORM clause entry is iTable.  This routine make the necessary 
72093 ** changes to pExpr so that it refers directly to the source table
72094 ** of the subquery rather the result set of the subquery.
72095 */
72096 static void substExpr(
72097   sqlite3 *db,        /* Report malloc errors to this connection */
72098   Expr *pExpr,        /* Expr in which substitution occurs */
72099   int iTable,         /* Table to be substituted */
72100   ExprList *pEList    /* Substitute expressions */
72101 ){
72102   if( pExpr==0 ) return;
72103   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
72104     if( pExpr->iColumn<0 ){
72105       pExpr->op = TK_NULL;
72106     }else{
72107       Expr *pNew;
72108       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
72109       assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
72110       pNew = pEList->a[pExpr->iColumn].pExpr;
72111       assert( pNew!=0 );
72112       pExpr->op = pNew->op;
72113       assert( pExpr->pLeft==0 );
72114       pExpr->pLeft = sqlite3ExprDup(db, pNew->pLeft);
72115       assert( pExpr->pRight==0 );
72116       pExpr->pRight = sqlite3ExprDup(db, pNew->pRight);
72117       assert( pExpr->pList==0 );
72118       pExpr->pList = sqlite3ExprListDup(db, pNew->pList);
72119       pExpr->iTable = pNew->iTable;
72120       pExpr->pTab = pNew->pTab;
72121       pExpr->iColumn = pNew->iColumn;
72122       pExpr->iAgg = pNew->iAgg;
72123       sqlite3TokenCopy(db, &pExpr->token, &pNew->token);
72124       sqlite3TokenCopy(db, &pExpr->span, &pNew->span);
72125       pExpr->pSelect = sqlite3SelectDup(db, pNew->pSelect);
72126       pExpr->flags = pNew->flags;
72127     }
72128   }else{
72129     substExpr(db, pExpr->pLeft, iTable, pEList);
72130     substExpr(db, pExpr->pRight, iTable, pEList);
72131     substSelect(db, pExpr->pSelect, iTable, pEList);
72132     substExprList(db, pExpr->pList, iTable, pEList);
72133   }
72134 }
72135 static void substExprList(
72136   sqlite3 *db,         /* Report malloc errors here */
72137   ExprList *pList,     /* List to scan and in which to make substitutes */
72138   int iTable,          /* Table to be substituted */
72139   ExprList *pEList     /* Substitute values */
72140 ){
72141   int i;
72142   if( pList==0 ) return;
72143   for(i=0; i<pList->nExpr; i++){
72144     substExpr(db, pList->a[i].pExpr, iTable, pEList);
72145   }
72146 }
72147 static void substSelect(
72148   sqlite3 *db,         /* Report malloc errors here */
72149   Select *p,           /* SELECT statement in which to make substitutions */
72150   int iTable,          /* Table to be replaced */
72151   ExprList *pEList     /* Substitute values */
72152 ){
72153   SrcList *pSrc;
72154   struct SrcList_item *pItem;
72155   int i;
72156   if( !p ) return;
72157   substExprList(db, p->pEList, iTable, pEList);
72158   substExprList(db, p->pGroupBy, iTable, pEList);
72159   substExprList(db, p->pOrderBy, iTable, pEList);
72160   substExpr(db, p->pHaving, iTable, pEList);
72161   substExpr(db, p->pWhere, iTable, pEList);
72162   substSelect(db, p->pPrior, iTable, pEList);
72163   pSrc = p->pSrc;
72164   if( pSrc ){
72165     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
72166       substSelect(db, pItem->pSelect, iTable, pEList);
72167     }
72168   }
72169 }
72170 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
72171
72172 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
72173 /*
72174 ** This routine attempts to flatten subqueries in order to speed
72175 ** execution.  It returns 1 if it makes changes and 0 if no flattening
72176 ** occurs.
72177 **
72178 ** To understand the concept of flattening, consider the following
72179 ** query:
72180 **
72181 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
72182 **
72183 ** The default way of implementing this query is to execute the
72184 ** subquery first and store the results in a temporary table, then
72185 ** run the outer query on that temporary table.  This requires two
72186 ** passes over the data.  Furthermore, because the temporary table
72187 ** has no indices, the WHERE clause on the outer query cannot be
72188 ** optimized.
72189 **
72190 ** This routine attempts to rewrite queries such as the above into
72191 ** a single flat select, like this:
72192 **
72193 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
72194 **
72195 ** The code generated for this simpification gives the same result
72196 ** but only has to scan the data once.  And because indices might 
72197 ** exist on the table t1, a complete scan of the data might be
72198 ** avoided.
72199 **
72200 ** Flattening is only attempted if all of the following are true:
72201 **
72202 **   (1)  The subquery and the outer query do not both use aggregates.
72203 **
72204 **   (2)  The subquery is not an aggregate or the outer query is not a join.
72205 **
72206 **   (3)  The subquery is not the right operand of a left outer join
72207 **        (Originally ticket #306.  Strenghtened by ticket #3300)
72208 **
72209 **   (4)  The subquery is not DISTINCT or the outer query is not a join.
72210 **
72211 **   (5)  The subquery is not DISTINCT or the outer query does not use
72212 **        aggregates.
72213 **
72214 **   (6)  The subquery does not use aggregates or the outer query is not
72215 **        DISTINCT.
72216 **
72217 **   (7)  The subquery has a FROM clause.
72218 **
72219 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
72220 **
72221 **   (9)  The subquery does not use LIMIT or the outer query does not use
72222 **        aggregates.
72223 **
72224 **  (10)  The subquery does not use aggregates or the outer query does not
72225 **        use LIMIT.
72226 **
72227 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
72228 **
72229 **  (12)  Not implemented.  Subsumed into restriction (3).  Was previously
72230 **        a separate restriction deriving from ticket #350.
72231 **
72232 **  (13)  The subquery and outer query do not both use LIMIT
72233 **
72234 **  (14)  The subquery does not use OFFSET
72235 **
72236 **  (15)  The outer query is not part of a compound select or the
72237 **        subquery does not have both an ORDER BY and a LIMIT clause.
72238 **        (See ticket #2339)
72239 **
72240 **  (16)  The outer query is not an aggregate or the subquery does
72241 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
72242 **        until we introduced the group_concat() function.  
72243 **
72244 **  (17)  The sub-query is not a compound select, or it is a UNION ALL 
72245 **        compound clause made up entirely of non-aggregate queries, and 
72246 **        the parent query:
72247 **
72248 **          * is not itself part of a compound select,
72249 **          * is not an aggregate or DISTINCT query, and
72250 **          * has no other tables or sub-selects in the FROM clause.
72251 **
72252 **        The parent and sub-query may contain WHERE clauses. Subject to
72253 **        rules (11), (13) and (14), they may also contain ORDER BY,
72254 **        LIMIT and OFFSET clauses.
72255 **
72256 **  (18)  If the sub-query is a compound select, then all terms of the
72257 **        ORDER by clause of the parent must be simple references to 
72258 **        columns of the sub-query.
72259 **
72260 **  (19)  The subquery does not use LIMIT or the outer query does not
72261 **        have a WHERE clause.
72262 **
72263 ** In this routine, the "p" parameter is a pointer to the outer query.
72264 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
72265 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
72266 **
72267 ** If flattening is not attempted, this routine is a no-op and returns 0.
72268 ** If flattening is attempted this routine returns 1.
72269 **
72270 ** All of the expression analysis must occur on both the outer query and
72271 ** the subquery before this routine runs.
72272 */
72273 static int flattenSubquery(
72274   Parse *pParse,       /* Parsing context */
72275   Select *p,           /* The parent or outer SELECT statement */
72276   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
72277   int isAgg,           /* True if outer SELECT uses aggregate functions */
72278   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
72279 ){
72280   const char *zSavedAuthContext = pParse->zAuthContext;
72281   Select *pParent;
72282   Select *pSub;       /* The inner query or "subquery" */
72283   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
72284   SrcList *pSrc;      /* The FROM clause of the outer query */
72285   SrcList *pSubSrc;   /* The FROM clause of the subquery */
72286   ExprList *pList;    /* The result set of the outer query */
72287   int iParent;        /* VDBE cursor number of the pSub result set temp table */
72288   int i;              /* Loop counter */
72289   Expr *pWhere;                    /* The WHERE clause */
72290   struct SrcList_item *pSubitem;   /* The subquery */
72291   sqlite3 *db = pParse->db;
72292
72293   /* Check to see if flattening is permitted.  Return 0 if not.
72294   */
72295   assert( p!=0 );
72296   if( p==0 ) return 0;
72297   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
72298   pSrc = p->pSrc;
72299   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
72300   pSubitem = &pSrc->a[iFrom];
72301   iParent = pSubitem->iCursor;
72302   pSub = pSubitem->pSelect;
72303   assert( pSub!=0 );
72304   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
72305   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
72306   pSubSrc = pSub->pSrc;
72307   assert( pSubSrc );
72308   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
72309   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
72310   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
72311   ** became arbitrary expressions, we were forced to add restrictions (13)
72312   ** and (14). */
72313   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
72314   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
72315   if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
72316     return 0;                                            /* Restriction (15) */
72317   }
72318   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
72319   if( ((pSub->selFlags & SF_Distinct)!=0 || pSub->pLimit) 
72320          && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
72321      return 0;       
72322   }
72323   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
72324      return 0;         /* Restriction (6)  */
72325   }
72326   if( p->pOrderBy && pSub->pOrderBy ){
72327      return 0;                                           /* Restriction (11) */
72328   }
72329   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
72330   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
72331
72332   /* OBSOLETE COMMENT 1:
72333   ** Restriction 3:  If the subquery is a join, make sure the subquery is 
72334   ** not used as the right operand of an outer join.  Examples of why this
72335   ** is not allowed:
72336   **
72337   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
72338   **
72339   ** If we flatten the above, we would get
72340   **
72341   **         (t1 LEFT OUTER JOIN t2) JOIN t3
72342   **
72343   ** which is not at all the same thing.
72344   **
72345   ** OBSOLETE COMMENT 2:
72346   ** Restriction 12:  If the subquery is the right operand of a left outer
72347   ** join, make sure the subquery has no WHERE clause.
72348   ** An examples of why this is not allowed:
72349   **
72350   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
72351   **
72352   ** If we flatten the above, we would get
72353   **
72354   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
72355   **
72356   ** But the t2.x>0 test will always fail on a NULL row of t2, which
72357   ** effectively converts the OUTER JOIN into an INNER JOIN.
72358   **
72359   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
72360   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
72361   ** is fraught with danger.  Best to avoid the whole thing.  If the
72362   ** subquery is the right term of a LEFT JOIN, then do not flatten.
72363   */
72364   if( (pSubitem->jointype & JT_OUTER)!=0 ){
72365     return 0;
72366   }
72367
72368   /* Restriction 17: If the sub-query is a compound SELECT, then it must
72369   ** use only the UNION ALL operator. And none of the simple select queries
72370   ** that make up the compound SELECT are allowed to be aggregate or distinct
72371   ** queries.
72372   */
72373   if( pSub->pPrior ){
72374     if( p->pPrior || isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
72375       return 0;
72376     }
72377     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
72378       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
72379        || (pSub1->pPrior && pSub1->op!=TK_ALL) 
72380        || !pSub1->pSrc || pSub1->pSrc->nSrc!=1
72381       ){
72382         return 0;
72383       }
72384     }
72385
72386     /* Restriction 18. */
72387     if( p->pOrderBy ){
72388       int ii;
72389       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
72390         if( p->pOrderBy->a[ii].iCol==0 ) return 0;
72391       }
72392     }
72393   }
72394
72395   /***** If we reach this point, flattening is permitted. *****/
72396
72397   /* Authorize the subquery */
72398   pParse->zAuthContext = pSubitem->zName;
72399   sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
72400   pParse->zAuthContext = zSavedAuthContext;
72401
72402   /* If the sub-query is a compound SELECT statement, then (by restrictions
72403   ** 17 and 18 above) it must be a UNION ALL and the parent query must 
72404   ** be of the form:
72405   **
72406   **     SELECT <expr-list> FROM (<sub-query>) <where-clause> 
72407   **
72408   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
72409   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 
72410   ** OFFSET clauses and joins them to the left-hand-side of the original
72411   ** using UNION ALL operators. In this case N is the number of simple
72412   ** select statements in the compound sub-query.
72413   **
72414   ** Example:
72415   **
72416   **     SELECT a+1 FROM (
72417   **        SELECT x FROM tab
72418   **        UNION ALL
72419   **        SELECT y FROM tab
72420   **        UNION ALL
72421   **        SELECT abs(z*2) FROM tab2
72422   **     ) WHERE a!=5 ORDER BY 1
72423   **
72424   ** Transformed into:
72425   **
72426   **     SELECT x+1 FROM tab WHERE x+1!=5
72427   **     UNION ALL
72428   **     SELECT y+1 FROM tab WHERE y+1!=5
72429   **     UNION ALL
72430   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
72431   **     ORDER BY 1
72432   **
72433   ** We call this the "compound-subquery flattening".
72434   */
72435   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
72436     Select *pNew;
72437     ExprList *pOrderBy = p->pOrderBy;
72438     Expr *pLimit = p->pLimit;
72439     Select *pPrior = p->pPrior;
72440     p->pOrderBy = 0;
72441     p->pSrc = 0;
72442     p->pPrior = 0;
72443     p->pLimit = 0;
72444     pNew = sqlite3SelectDup(db, p);
72445     p->pLimit = pLimit;
72446     p->pOrderBy = pOrderBy;
72447     p->pSrc = pSrc;
72448     p->op = TK_ALL;
72449     p->pRightmost = 0;
72450     if( pNew==0 ){
72451       pNew = pPrior;
72452     }else{
72453       pNew->pPrior = pPrior;
72454       pNew->pRightmost = 0;
72455     }
72456     p->pPrior = pNew;
72457     if( db->mallocFailed ) return 1;
72458   }
72459
72460   /* Begin flattening the iFrom-th entry of the FROM clause 
72461   ** in the outer query.
72462   */
72463   pSub = pSub1 = pSubitem->pSelect;
72464
72465   /* Delete the transient table structure associated with the
72466   ** subquery
72467   */
72468   sqlite3DbFree(db, pSubitem->zDatabase);
72469   sqlite3DbFree(db, pSubitem->zName);
72470   sqlite3DbFree(db, pSubitem->zAlias);
72471   pSubitem->zDatabase = 0;
72472   pSubitem->zName = 0;
72473   pSubitem->zAlias = 0;
72474   pSubitem->pSelect = 0;
72475
72476   /* Defer deleting the Table object associated with the
72477   ** subquery until code generation is
72478   ** complete, since there may still exist Expr.pTab entries that
72479   ** refer to the subquery even after flattening.  Ticket #3346.
72480   */
72481   if( pSubitem->pTab!=0 ){
72482     Table *pTabToDel = pSubitem->pTab;
72483     if( pTabToDel->nRef==1 ){
72484       pTabToDel->pNextZombie = pParse->pZombieTab;
72485       pParse->pZombieTab = pTabToDel;
72486     }else{
72487       pTabToDel->nRef--;
72488     }
72489     pSubitem->pTab = 0;
72490   }
72491
72492   /* The following loop runs once for each term in a compound-subquery
72493   ** flattening (as described above).  If we are doing a different kind
72494   ** of flattening - a flattening other than a compound-subquery flattening -
72495   ** then this loop only runs once.
72496   **
72497   ** This loop moves all of the FROM elements of the subquery into the
72498   ** the FROM clause of the outer query.  Before doing this, remember
72499   ** the cursor number for the original outer query FROM element in
72500   ** iParent.  The iParent cursor will never be used.  Subsequent code
72501   ** will scan expressions looking for iParent references and replace
72502   ** those references with expressions that resolve to the subquery FROM
72503   ** elements we are now copying in.
72504   */
72505   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
72506     int nSubSrc;
72507     int jointype = 0;
72508     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
72509     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
72510     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
72511
72512     if( pSrc ){
72513       assert( pParent==p );  /* First time through the loop */
72514       jointype = pSubitem->jointype;
72515     }else{
72516       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
72517       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
72518       if( pSrc==0 ){
72519         assert( db->mallocFailed );
72520         break;
72521       }
72522     }
72523
72524     /* The subquery uses a single slot of the FROM clause of the outer
72525     ** query.  If the subquery has more than one element in its FROM clause,
72526     ** then expand the outer query to make space for it to hold all elements
72527     ** of the subquery.
72528     **
72529     ** Example:
72530     **
72531     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
72532     **
72533     ** The outer query has 3 slots in its FROM clause.  One slot of the
72534     ** outer query (the middle slot) is used by the subquery.  The next
72535     ** block of code will expand the out query to 4 slots.  The middle
72536     ** slot is expanded to two slots in order to make space for the
72537     ** two elements in the FROM clause of the subquery.
72538     */
72539     if( nSubSrc>1 ){
72540       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
72541       if( db->mallocFailed ){
72542         break;
72543       }
72544     }
72545
72546     /* Transfer the FROM clause terms from the subquery into the
72547     ** outer query.
72548     */
72549     for(i=0; i<nSubSrc; i++){
72550       pSrc->a[i+iFrom] = pSubSrc->a[i];
72551       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
72552     }
72553     pSrc->a[iFrom].jointype = jointype;
72554   
72555     /* Now begin substituting subquery result set expressions for 
72556     ** references to the iParent in the outer query.
72557     ** 
72558     ** Example:
72559     **
72560     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
72561     **   \                     \_____________ subquery __________/          /
72562     **    \_____________________ outer query ______________________________/
72563     **
72564     ** We look at every expression in the outer query and every place we see
72565     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
72566     */
72567     pList = pParent->pEList;
72568     for(i=0; i<pList->nExpr; i++){
72569       Expr *pExpr;
72570       if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
72571         pList->a[i].zName = 
72572                sqlite3DbStrNDup(db, (char*)pExpr->span.z, pExpr->span.n);
72573       }
72574     }
72575     substExprList(db, pParent->pEList, iParent, pSub->pEList);
72576     if( isAgg ){
72577       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
72578       substExpr(db, pParent->pHaving, iParent, pSub->pEList);
72579     }
72580     if( pSub->pOrderBy ){
72581       assert( pParent->pOrderBy==0 );
72582       pParent->pOrderBy = pSub->pOrderBy;
72583       pSub->pOrderBy = 0;
72584     }else if( pParent->pOrderBy ){
72585       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
72586     }
72587     if( pSub->pWhere ){
72588       pWhere = sqlite3ExprDup(db, pSub->pWhere);
72589     }else{
72590       pWhere = 0;
72591     }
72592     if( subqueryIsAgg ){
72593       assert( pParent->pHaving==0 );
72594       pParent->pHaving = pParent->pWhere;
72595       pParent->pWhere = pWhere;
72596       substExpr(db, pParent->pHaving, iParent, pSub->pEList);
72597       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 
72598                                   sqlite3ExprDup(db, pSub->pHaving));
72599       assert( pParent->pGroupBy==0 );
72600       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy);
72601     }else{
72602       substExpr(db, pParent->pWhere, iParent, pSub->pEList);
72603       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
72604     }
72605   
72606     /* The flattened query is distinct if either the inner or the
72607     ** outer query is distinct. 
72608     */
72609     pParent->selFlags |= pSub->selFlags & SF_Distinct;
72610   
72611     /*
72612     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
72613     **
72614     ** One is tempted to try to add a and b to combine the limits.  But this
72615     ** does not work if either limit is negative.
72616     */
72617     if( pSub->pLimit ){
72618       pParent->pLimit = pSub->pLimit;
72619       pSub->pLimit = 0;
72620     }
72621   }
72622
72623   /* Finially, delete what is left of the subquery and return
72624   ** success.
72625   */
72626   sqlite3SelectDelete(db, pSub1);
72627
72628   return 1;
72629 }
72630 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
72631
72632 /*
72633 ** Analyze the SELECT statement passed as an argument to see if it
72634 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if 
72635 ** it is, or 0 otherwise. At present, a query is considered to be
72636 ** a min()/max() query if:
72637 **
72638 **   1. There is a single object in the FROM clause.
72639 **
72640 **   2. There is a single expression in the result set, and it is
72641 **      either min(x) or max(x), where x is a column reference.
72642 */
72643 static int minMaxQuery(Select *p){
72644   Expr *pExpr;
72645   ExprList *pEList = p->pEList;
72646
72647   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
72648   pExpr = pEList->a[0].pExpr;
72649   pEList = pExpr->pList;
72650   if( pExpr->op!=TK_AGG_FUNCTION || pEList==0 || pEList->nExpr!=1 ) return 0;
72651   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
72652   if( pExpr->token.n!=3 ) return WHERE_ORDERBY_NORMAL;
72653   if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){
72654     return WHERE_ORDERBY_MIN;
72655   }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){
72656     return WHERE_ORDERBY_MAX;
72657   }
72658   return WHERE_ORDERBY_NORMAL;
72659 }
72660
72661 /*
72662 ** If the source-list item passed as an argument was augmented with an
72663 ** INDEXED BY clause, then try to locate the specified index. If there
72664 ** was such a clause and the named index cannot be found, return 
72665 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 
72666 ** pFrom->pIndex and return SQLITE_OK.
72667 */
72668 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
72669   if( pFrom->pTab && pFrom->zIndex ){
72670     Table *pTab = pFrom->pTab;
72671     char *zIndex = pFrom->zIndex;
72672     Index *pIdx;
72673     for(pIdx=pTab->pIndex; 
72674         pIdx && sqlite3StrICmp(pIdx->zName, zIndex); 
72675         pIdx=pIdx->pNext
72676     );
72677     if( !pIdx ){
72678       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
72679       return SQLITE_ERROR;
72680     }
72681     pFrom->pIndex = pIdx;
72682   }
72683   return SQLITE_OK;
72684 }
72685
72686 /*
72687 ** This routine is a Walker callback for "expanding" a SELECT statement.
72688 ** "Expanding" means to do the following:
72689 **
72690 **    (1)  Make sure VDBE cursor numbers have been assigned to every
72691 **         element of the FROM clause.
72692 **
72693 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
72694 **         defines FROM clause.  When views appear in the FROM clause,
72695 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
72696 **         that implements the view.  A copy is made of the view's SELECT
72697 **         statement so that we can freely modify or delete that statement
72698 **         without worrying about messing up the presistent representation
72699 **         of the view.
72700 **
72701 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
72702 **         on joins and the ON and USING clause of joins.
72703 **
72704 **    (4)  Scan the list of columns in the result set (pEList) looking
72705 **         for instances of the "*" operator or the TABLE.* operator.
72706 **         If found, expand each "*" to be every column in every table
72707 **         and TABLE.* to be every column in TABLE.
72708 **
72709 */
72710 static int selectExpander(Walker *pWalker, Select *p){
72711   Parse *pParse = pWalker->pParse;
72712   int i, j, k;
72713   SrcList *pTabList;
72714   ExprList *pEList;
72715   struct SrcList_item *pFrom;
72716   sqlite3 *db = pParse->db;
72717
72718   if( db->mallocFailed  ){
72719     return WRC_Abort;
72720   }
72721   if( p->pSrc==0 || (p->selFlags & SF_Expanded)!=0 ){
72722     return WRC_Prune;
72723   }
72724   p->selFlags |= SF_Expanded;
72725   pTabList = p->pSrc;
72726   pEList = p->pEList;
72727
72728   /* Make sure cursor numbers have been assigned to all entries in
72729   ** the FROM clause of the SELECT statement.
72730   */
72731   sqlite3SrcListAssignCursors(pParse, pTabList);
72732
72733   /* Look up every table named in the FROM clause of the select.  If
72734   ** an entry of the FROM clause is a subquery instead of a table or view,
72735   ** then create a transient table structure to describe the subquery.
72736   */
72737   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
72738     Table *pTab;
72739     if( pFrom->pTab!=0 ){
72740       /* This statement has already been prepared.  There is no need
72741       ** to go further. */
72742       assert( i==0 );
72743       return WRC_Prune;
72744     }
72745     if( pFrom->zName==0 ){
72746 #ifndef SQLITE_OMIT_SUBQUERY
72747       Select *pSel = pFrom->pSelect;
72748       /* A sub-query in the FROM clause of a SELECT */
72749       assert( pSel!=0 );
72750       assert( pFrom->pTab==0 );
72751       sqlite3WalkSelect(pWalker, pSel);
72752       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
72753       if( pTab==0 ) return WRC_Abort;
72754       pTab->db = db;
72755       pTab->nRef = 1;
72756       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
72757       while( pSel->pPrior ){ pSel = pSel->pPrior; }
72758       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
72759       pTab->iPKey = -1;
72760       pTab->tabFlags |= TF_Ephemeral;
72761 #endif
72762     }else{
72763       /* An ordinary table or view name in the FROM clause */
72764       assert( pFrom->pTab==0 );
72765       pFrom->pTab = pTab = 
72766         sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
72767       if( pTab==0 ) return WRC_Abort;
72768       pTab->nRef++;
72769 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
72770       if( pTab->pSelect || IsVirtual(pTab) ){
72771         /* We reach here if the named table is a really a view */
72772         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
72773
72774         /* If pFrom->pSelect!=0 it means we are dealing with a
72775         ** view within a view.  The SELECT structure has already been
72776         ** copied by the outer view so we can skip the copy step here
72777         ** in the inner view.
72778         */
72779         if( pFrom->pSelect==0 ){
72780           pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect);
72781           sqlite3WalkSelect(pWalker, pFrom->pSelect);
72782         }
72783       }
72784 #endif
72785     }
72786
72787     /* Locate the index named by the INDEXED BY clause, if any. */
72788     if( sqlite3IndexedByLookup(pParse, pFrom) ){
72789       return WRC_Abort;
72790     }
72791   }
72792
72793   /* Process NATURAL keywords, and ON and USING clauses of joins.
72794   */
72795   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
72796     return WRC_Abort;
72797   }
72798
72799   /* For every "*" that occurs in the column list, insert the names of
72800   ** all columns in all tables.  And for every TABLE.* insert the names
72801   ** of all columns in TABLE.  The parser inserted a special expression
72802   ** with the TK_ALL operator for each "*" that it found in the column list.
72803   ** The following code just has to locate the TK_ALL expressions and expand
72804   ** each one to the list of all columns in all tables.
72805   **
72806   ** The first loop just checks to see if there are any "*" operators
72807   ** that need expanding.
72808   */
72809   for(k=0; k<pEList->nExpr; k++){
72810     Expr *pE = pEList->a[k].pExpr;
72811     if( pE->op==TK_ALL ) break;
72812     if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
72813          && pE->pLeft && pE->pLeft->op==TK_ID ) break;
72814   }
72815   if( k<pEList->nExpr ){
72816     /*
72817     ** If we get here it means the result set contains one or more "*"
72818     ** operators that need to be expanded.  Loop through each expression
72819     ** in the result set and expand them one by one.
72820     */
72821     struct ExprList_item *a = pEList->a;
72822     ExprList *pNew = 0;
72823     int flags = pParse->db->flags;
72824     int longNames = (flags & SQLITE_FullColNames)!=0
72825                       && (flags & SQLITE_ShortColNames)==0;
72826
72827     for(k=0; k<pEList->nExpr; k++){
72828       Expr *pE = a[k].pExpr;
72829       if( pE->op!=TK_ALL &&
72830            (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
72831         /* This particular expression does not need to be expanded.
72832         */
72833         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr, 0);
72834         if( pNew ){
72835           pNew->a[pNew->nExpr-1].zName = a[k].zName;
72836         }
72837         a[k].pExpr = 0;
72838         a[k].zName = 0;
72839       }else{
72840         /* This expression is a "*" or a "TABLE.*" and needs to be
72841         ** expanded. */
72842         int tableSeen = 0;      /* Set to 1 when TABLE matches */
72843         char *zTName;            /* text of name of TABLE */
72844         if( pE->op==TK_DOT && pE->pLeft ){
72845           zTName = sqlite3NameFromToken(db, &pE->pLeft->token);
72846         }else{
72847           zTName = 0;
72848         }
72849         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
72850           Table *pTab = pFrom->pTab;
72851           char *zTabName = pFrom->zAlias;
72852           if( zTabName==0 || zTabName[0]==0 ){ 
72853             zTabName = pTab->zName;
72854           }
72855           if( db->mallocFailed ) break;
72856           if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
72857             continue;
72858           }
72859           tableSeen = 1;
72860           for(j=0; j<pTab->nCol; j++){
72861             Expr *pExpr, *pRight;
72862             char *zName = pTab->aCol[j].zName;
72863
72864             /* If a column is marked as 'hidden' (currently only possible
72865             ** for virtual tables), do not include it in the expanded
72866             ** result-set list.
72867             */
72868             if( IsHiddenColumn(&pTab->aCol[j]) ){
72869               assert(IsVirtual(pTab));
72870               continue;
72871             }
72872
72873             if( i>0 ){
72874               struct SrcList_item *pLeft = &pTabList->a[i-1];
72875               if( (pLeft[1].jointype & JT_NATURAL)!=0 &&
72876                         columnIndex(pLeft->pTab, zName)>=0 ){
72877                 /* In a NATURAL join, omit the join columns from the 
72878                 ** table on the right */
72879                 continue;
72880               }
72881               if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){
72882                 /* In a join with a USING clause, omit columns in the
72883                 ** using clause from the table on the right. */
72884                 continue;
72885               }
72886             }
72887             pRight = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
72888             if( pRight==0 ) break;
72889             setQuotedToken(pParse, &pRight->token, zName);
72890             if( longNames || pTabList->nSrc>1 ){
72891               Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
72892               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
72893               if( pExpr==0 ) break;
72894               setQuotedToken(pParse, &pLeft->token, zTabName);
72895               setToken(&pExpr->span, 
72896                   sqlite3MPrintf(db, "%s.%s", zTabName, zName));
72897               pExpr->span.dyn = 1;
72898               pExpr->token.z = 0;
72899               pExpr->token.n = 0;
72900               pExpr->token.dyn = 0;
72901             }else{
72902               pExpr = pRight;
72903               pExpr->span = pExpr->token;
72904               pExpr->span.dyn = 0;
72905             }
72906             if( longNames ){
72907               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pExpr->span);
72908             }else{
72909               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pRight->token);
72910             }
72911           }
72912         }
72913         if( !tableSeen ){
72914           if( zTName ){
72915             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
72916           }else{
72917             sqlite3ErrorMsg(pParse, "no tables specified");
72918           }
72919         }
72920         sqlite3DbFree(db, zTName);
72921       }
72922     }
72923     sqlite3ExprListDelete(db, pEList);
72924     p->pEList = pNew;
72925   }
72926 #if SQLITE_MAX_COLUMN
72927   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
72928     sqlite3ErrorMsg(pParse, "too many columns in result set");
72929   }
72930 #endif
72931   return WRC_Continue;
72932 }
72933
72934 /*
72935 ** No-op routine for the parse-tree walker.
72936 **
72937 ** When this routine is the Walker.xExprCallback then expression trees
72938 ** are walked without any actions being taken at each node.  Presumably,
72939 ** when this routine is used for Walker.xExprCallback then 
72940 ** Walker.xSelectCallback is set to do something useful for every 
72941 ** subquery in the parser tree.
72942 */
72943 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
72944   UNUSED_PARAMETER2(NotUsed, NotUsed2);
72945   return WRC_Continue;
72946 }
72947
72948 /*
72949 ** This routine "expands" a SELECT statement and all of its subqueries.
72950 ** For additional information on what it means to "expand" a SELECT
72951 ** statement, see the comment on the selectExpand worker callback above.
72952 **
72953 ** Expanding a SELECT statement is the first step in processing a
72954 ** SELECT statement.  The SELECT statement must be expanded before
72955 ** name resolution is performed.
72956 **
72957 ** If anything goes wrong, an error message is written into pParse.
72958 ** The calling function can detect the problem by looking at pParse->nErr
72959 ** and/or pParse->db->mallocFailed.
72960 */
72961 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
72962   Walker w;
72963   w.xSelectCallback = selectExpander;
72964   w.xExprCallback = exprWalkNoop;
72965   w.pParse = pParse;
72966   sqlite3WalkSelect(&w, pSelect);
72967 }
72968
72969
72970 #ifndef SQLITE_OMIT_SUBQUERY
72971 /*
72972 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
72973 ** interface.
72974 **
72975 ** For each FROM-clause subquery, add Column.zType and Column.zColl
72976 ** information to the Table structure that represents the result set
72977 ** of that subquery.
72978 **
72979 ** The Table structure that represents the result set was constructed
72980 ** by selectExpander() but the type and collation information was omitted
72981 ** at that point because identifiers had not yet been resolved.  This
72982 ** routine is called after identifier resolution.
72983 */
72984 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
72985   Parse *pParse;
72986   int i;
72987   SrcList *pTabList;
72988   struct SrcList_item *pFrom;
72989
72990   assert( p->selFlags & SF_Resolved );
72991   if( (p->selFlags & SF_HasTypeInfo)==0 ){
72992     p->selFlags |= SF_HasTypeInfo;
72993     pParse = pWalker->pParse;
72994     pTabList = p->pSrc;
72995     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
72996       Table *pTab = pFrom->pTab;
72997       if( pTab && (pTab->tabFlags & TF_Ephemeral)!=0 ){
72998         /* A sub-query in the FROM clause of a SELECT */
72999         Select *pSel = pFrom->pSelect;
73000         assert( pSel );
73001         while( pSel->pPrior ) pSel = pSel->pPrior;
73002         selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
73003       }
73004     }
73005   }
73006   return WRC_Continue;
73007 }
73008 #endif
73009
73010
73011 /*
73012 ** This routine adds datatype and collating sequence information to
73013 ** the Table structures of all FROM-clause subqueries in a
73014 ** SELECT statement.
73015 **
73016 ** Use this routine after name resolution.
73017 */
73018 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
73019 #ifndef SQLITE_OMIT_SUBQUERY
73020   Walker w;
73021   w.xSelectCallback = selectAddSubqueryTypeInfo;
73022   w.xExprCallback = exprWalkNoop;
73023   w.pParse = pParse;
73024   sqlite3WalkSelect(&w, pSelect);
73025 #endif
73026 }
73027
73028
73029 /*
73030 ** This routine sets of a SELECT statement for processing.  The
73031 ** following is accomplished:
73032 **
73033 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
73034 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
73035 **     *  ON and USING clauses are shifted into WHERE statements
73036 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
73037 **     *  Identifiers in expression are matched to tables.
73038 **
73039 ** This routine acts recursively on all subqueries within the SELECT.
73040 */
73041 SQLITE_PRIVATE void sqlite3SelectPrep(
73042   Parse *pParse,         /* The parser context */
73043   Select *p,             /* The SELECT statement being coded. */
73044   NameContext *pOuterNC  /* Name context for container */
73045 ){
73046   sqlite3 *db;
73047   if( p==0 ) return;
73048   db = pParse->db;
73049   if( p->selFlags & SF_HasTypeInfo ) return;
73050   if( pParse->nErr || db->mallocFailed ) return;
73051   sqlite3SelectExpand(pParse, p);
73052   if( pParse->nErr || db->mallocFailed ) return;
73053   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
73054   if( pParse->nErr || db->mallocFailed ) return;
73055   sqlite3SelectAddTypeInfo(pParse, p);
73056 }
73057
73058 /*
73059 ** Reset the aggregate accumulator.
73060 **
73061 ** The aggregate accumulator is a set of memory cells that hold
73062 ** intermediate results while calculating an aggregate.  This
73063 ** routine simply stores NULLs in all of those memory cells.
73064 */
73065 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
73066   Vdbe *v = pParse->pVdbe;
73067   int i;
73068   struct AggInfo_func *pFunc;
73069   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
73070     return;
73071   }
73072   for(i=0; i<pAggInfo->nColumn; i++){
73073     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
73074   }
73075   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
73076     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
73077     if( pFunc->iDistinct>=0 ){
73078       Expr *pE = pFunc->pExpr;
73079       if( pE->pList==0 || pE->pList->nExpr!=1 ){
73080         sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed "
73081            "by an expression");
73082         pFunc->iDistinct = -1;
73083       }else{
73084         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList);
73085         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
73086                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
73087       }
73088     }
73089   }
73090 }
73091
73092 /*
73093 ** Invoke the OP_AggFinalize opcode for every aggregate function
73094 ** in the AggInfo structure.
73095 */
73096 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
73097   Vdbe *v = pParse->pVdbe;
73098   int i;
73099   struct AggInfo_func *pF;
73100   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
73101     ExprList *pList = pF->pExpr->pList;
73102     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
73103                       (void*)pF->pFunc, P4_FUNCDEF);
73104   }
73105 }
73106
73107 /*
73108 ** Update the accumulator memory cells for an aggregate based on
73109 ** the current cursor position.
73110 */
73111 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
73112   Vdbe *v = pParse->pVdbe;
73113   int i;
73114   struct AggInfo_func *pF;
73115   struct AggInfo_col *pC;
73116
73117   pAggInfo->directMode = 1;
73118   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
73119     int nArg;
73120     int addrNext = 0;
73121     int regAgg;
73122     ExprList *pList = pF->pExpr->pList;
73123     if( pList ){
73124       nArg = pList->nExpr;
73125       regAgg = sqlite3GetTempRange(pParse, nArg);
73126       sqlite3ExprCodeExprList(pParse, pList, regAgg, 0);
73127     }else{
73128       nArg = 0;
73129       regAgg = 0;
73130     }
73131     if( pF->iDistinct>=0 ){
73132       addrNext = sqlite3VdbeMakeLabel(v);
73133       assert( nArg==1 );
73134       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
73135     }
73136     if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
73137       CollSeq *pColl = 0;
73138       struct ExprList_item *pItem;
73139       int j;
73140       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
73141       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
73142         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
73143       }
73144       if( !pColl ){
73145         pColl = pParse->db->pDfltColl;
73146       }
73147       sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
73148     }
73149     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
73150                       (void*)pF->pFunc, P4_FUNCDEF);
73151     sqlite3VdbeChangeP5(v, nArg);
73152     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
73153     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
73154     if( addrNext ){
73155       sqlite3VdbeResolveLabel(v, addrNext);
73156     }
73157   }
73158   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
73159     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
73160   }
73161   pAggInfo->directMode = 0;
73162 }
73163
73164 /*
73165 ** Generate code for the SELECT statement given in the p argument.  
73166 **
73167 ** The results are distributed in various ways depending on the
73168 ** contents of the SelectDest structure pointed to by argument pDest
73169 ** as follows:
73170 **
73171 **     pDest->eDest    Result
73172 **     ------------    -------------------------------------------
73173 **     SRT_Output      Generate a row of output (using the OP_ResultRow
73174 **                     opcode) for each row in the result set.
73175 **
73176 **     SRT_Mem         Only valid if the result is a single column.
73177 **                     Store the first column of the first result row
73178 **                     in register pDest->iParm then abandon the rest
73179 **                     of the query.  This destination implies "LIMIT 1".
73180 **
73181 **     SRT_Set         The result must be a single column.  Store each
73182 **                     row of result as the key in table pDest->iParm. 
73183 **                     Apply the affinity pDest->affinity before storing
73184 **                     results.  Used to implement "IN (SELECT ...)".
73185 **
73186 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
73187 **
73188 **     SRT_Except      Remove results from the temporary table pDest->iParm.
73189 **
73190 **     SRT_Table       Store results in temporary table pDest->iParm.
73191 **                     This is like SRT_EphemTab except that the table
73192 **                     is assumed to already be open.
73193 **
73194 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
73195 **                     the result there. The cursor is left open after
73196 **                     returning.  This is like SRT_Table except that
73197 **                     this destination uses OP_OpenEphemeral to create
73198 **                     the table first.
73199 **
73200 **     SRT_Coroutine   Generate a co-routine that returns a new row of
73201 **                     results each time it is invoked.  The entry point
73202 **                     of the co-routine is stored in register pDest->iParm.
73203 **
73204 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
73205 **                     set is not empty.
73206 **
73207 **     SRT_Discard     Throw the results away.  This is used by SELECT
73208 **                     statements within triggers whose only purpose is
73209 **                     the side-effects of functions.
73210 **
73211 ** This routine returns the number of errors.  If any errors are
73212 ** encountered, then an appropriate error message is left in
73213 ** pParse->zErrMsg.
73214 **
73215 ** This routine does NOT free the Select structure passed in.  The
73216 ** calling function needs to do that.
73217 */
73218 SQLITE_PRIVATE int sqlite3Select(
73219   Parse *pParse,         /* The parser context */
73220   Select *p,             /* The SELECT statement being coded. */
73221   SelectDest *pDest      /* What to do with the query results */
73222 ){
73223   int i, j;              /* Loop counters */
73224   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
73225   Vdbe *v;               /* The virtual machine under construction */
73226   int isAgg;             /* True for select lists like "count(*)" */
73227   ExprList *pEList;      /* List of columns to extract. */
73228   SrcList *pTabList;     /* List of tables to select from */
73229   Expr *pWhere;          /* The WHERE clause.  May be NULL */
73230   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
73231   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
73232   Expr *pHaving;         /* The HAVING clause.  May be NULL */
73233   int isDistinct;        /* True if the DISTINCT keyword is present */
73234   int distinct;          /* Table to use for the distinct set */
73235   int rc = 1;            /* Value to return from this function */
73236   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
73237   AggInfo sAggInfo;      /* Information used by aggregate queries */
73238   int iEnd;              /* Address of the end of the query */
73239   sqlite3 *db;           /* The database connection */
73240
73241   db = pParse->db;
73242   if( p==0 || db->mallocFailed || pParse->nErr ){
73243     return 1;
73244   }
73245   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
73246   memset(&sAggInfo, 0, sizeof(sAggInfo));
73247
73248   pOrderBy = p->pOrderBy;
73249   if( IgnorableOrderby(pDest) ){
73250     p->pOrderBy = 0;
73251
73252     /* In these cases the DISTINCT operator makes no difference to the
73253     ** results, so remove it if it were specified.
73254     */
73255     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
73256            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
73257     p->selFlags &= ~SF_Distinct;
73258   }
73259   sqlite3SelectPrep(pParse, p, 0);
73260   if( pParse->nErr ){
73261     goto select_end;
73262   }
73263   p->pOrderBy = pOrderBy;
73264
73265
73266   /* Make local copies of the parameters for this query.
73267   */
73268   pTabList = p->pSrc;
73269   isAgg = (p->selFlags & SF_Aggregate)!=0;
73270   pEList = p->pEList;
73271   if( pEList==0 ) goto select_end;
73272
73273   /* 
73274   ** Do not even attempt to generate any code if we have already seen
73275   ** errors before this routine starts.
73276   */
73277   if( pParse->nErr>0 ) goto select_end;
73278
73279   /* ORDER BY is ignored for some destinations.
73280   */
73281   if( IgnorableOrderby(pDest) ){
73282     pOrderBy = 0;
73283   }
73284
73285   /* Begin generating code.
73286   */
73287   v = sqlite3GetVdbe(pParse);
73288   if( v==0 ) goto select_end;
73289
73290   /* Generate code for all sub-queries in the FROM clause
73291   */
73292 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
73293   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
73294     struct SrcList_item *pItem = &pTabList->a[i];
73295     SelectDest dest;
73296     Select *pSub = pItem->pSelect;
73297     int isAggSub;
73298
73299     if( pSub==0 || pItem->isPopulated ) continue;
73300
73301     /* Increment Parse.nHeight by the height of the largest expression
73302     ** tree refered to by this, the parent select. The child select
73303     ** may contain expression trees of at most
73304     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
73305     ** more conservative than necessary, but much easier than enforcing
73306     ** an exact limit.
73307     */
73308     pParse->nHeight += sqlite3SelectExprHeight(p);
73309
73310     /* Check to see if the subquery can be absorbed into the parent. */
73311     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
73312     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
73313       if( isAggSub ){
73314         isAgg = 1;
73315         p->selFlags |= SF_Aggregate;
73316       }
73317       i = -1;
73318     }else{
73319       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
73320       assert( pItem->isPopulated==0 );
73321       sqlite3Select(pParse, pSub, &dest);
73322       pItem->isPopulated = 1;
73323     }
73324     if( pParse->nErr || db->mallocFailed ){
73325       goto select_end;
73326     }
73327     pParse->nHeight -= sqlite3SelectExprHeight(p);
73328     pTabList = p->pSrc;
73329     if( !IgnorableOrderby(pDest) ){
73330       pOrderBy = p->pOrderBy;
73331     }
73332   }
73333   pEList = p->pEList;
73334 #endif
73335   pWhere = p->pWhere;
73336   pGroupBy = p->pGroupBy;
73337   pHaving = p->pHaving;
73338   isDistinct = (p->selFlags & SF_Distinct)!=0;
73339
73340 #ifndef SQLITE_OMIT_COMPOUND_SELECT
73341   /* If there is are a sequence of queries, do the earlier ones first.
73342   */
73343   if( p->pPrior ){
73344     if( p->pRightmost==0 ){
73345       Select *pLoop, *pRight = 0;
73346       int cnt = 0;
73347       int mxSelect;
73348       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
73349         pLoop->pRightmost = p;
73350         pLoop->pNext = pRight;
73351         pRight = pLoop;
73352       }
73353       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
73354       if( mxSelect && cnt>mxSelect ){
73355         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
73356         return 1;
73357       }
73358     }
73359     return multiSelect(pParse, p, pDest);
73360   }
73361 #endif
73362
73363   /* If writing to memory or generating a set
73364   ** only a single column may be output.
73365   */
73366 #ifndef SQLITE_OMIT_SUBQUERY
73367   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
73368     goto select_end;
73369   }
73370 #endif
73371
73372   /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
73373   ** GROUP BY might use an index, DISTINCT never does.
73374   */
73375   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct && !p->pGroupBy ){
73376     p->pGroupBy = sqlite3ExprListDup(db, p->pEList);
73377     pGroupBy = p->pGroupBy;
73378     p->selFlags &= ~SF_Distinct;
73379     isDistinct = 0;
73380   }
73381
73382   /* If there is an ORDER BY clause, then this sorting
73383   ** index might end up being unused if the data can be 
73384   ** extracted in pre-sorted order.  If that is the case, then the
73385   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
73386   ** we figure out that the sorting index is not needed.  The addrSortIndex
73387   ** variable is used to facilitate that change.
73388   */
73389   if( pOrderBy ){
73390     KeyInfo *pKeyInfo;
73391     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
73392     pOrderBy->iECursor = pParse->nTab++;
73393     p->addrOpenEphm[2] = addrSortIndex =
73394       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
73395                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
73396                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
73397   }else{
73398     addrSortIndex = -1;
73399   }
73400
73401   /* If the output is destined for a temporary table, open that table.
73402   */
73403   if( pDest->eDest==SRT_EphemTab ){
73404     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
73405   }
73406
73407   /* Set the limiter.
73408   */
73409   iEnd = sqlite3VdbeMakeLabel(v);
73410   computeLimitRegisters(pParse, p, iEnd);
73411
73412   /* Open a virtual index to use for the distinct set.
73413   */
73414   if( isDistinct ){
73415     KeyInfo *pKeyInfo;
73416     assert( isAgg || pGroupBy );
73417     distinct = pParse->nTab++;
73418     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
73419     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
73420                         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
73421   }else{
73422     distinct = -1;
73423   }
73424
73425   /* Aggregate and non-aggregate queries are handled differently */
73426   if( !isAgg && pGroupBy==0 ){
73427     /* This case is for non-aggregate queries
73428     ** Begin the database scan
73429     */
73430     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
73431     if( pWInfo==0 ) goto select_end;
73432
73433     /* If sorting index that was created by a prior OP_OpenEphemeral 
73434     ** instruction ended up not being needed, then change the OP_OpenEphemeral
73435     ** into an OP_Noop.
73436     */
73437     if( addrSortIndex>=0 && pOrderBy==0 ){
73438       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
73439       p->addrOpenEphm[2] = -1;
73440     }
73441
73442     /* Use the standard inner loop
73443     */
73444     assert(!isDistinct);
73445     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
73446                     pWInfo->iContinue, pWInfo->iBreak);
73447
73448     /* End the database scan loop.
73449     */
73450     sqlite3WhereEnd(pWInfo);
73451   }else{
73452     /* This is the processing for aggregate queries */
73453     NameContext sNC;    /* Name context for processing aggregate information */
73454     int iAMem;          /* First Mem address for storing current GROUP BY */
73455     int iBMem;          /* First Mem address for previous GROUP BY */
73456     int iUseFlag;       /* Mem address holding flag indicating that at least
73457                         ** one row of the input to the aggregator has been
73458                         ** processed */
73459     int iAbortFlag;     /* Mem address which causes query abort if positive */
73460     int groupBySort;    /* Rows come from source in GROUP BY order */
73461     int addrEnd;        /* End of processing for this SELECT */
73462
73463     /* Remove any and all aliases between the result set and the
73464     ** GROUP BY clause.
73465     */
73466     if( pGroupBy ){
73467       int i;                        /* Loop counter */
73468       struct ExprList_item *pItem;  /* For looping over expression in a list */
73469
73470       for(i=p->pEList->nExpr, pItem=p->pEList->a; i>0; i--, pItem++){
73471         pItem->iAlias = 0;
73472       }
73473       for(i=pGroupBy->nExpr, pItem=pGroupBy->a; i>0; i--, pItem++){
73474         pItem->iAlias = 0;
73475       }
73476     }
73477
73478  
73479     /* Create a label to jump to when we want to abort the query */
73480     addrEnd = sqlite3VdbeMakeLabel(v);
73481
73482     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
73483     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
73484     ** SELECT statement.
73485     */
73486     memset(&sNC, 0, sizeof(sNC));
73487     sNC.pParse = pParse;
73488     sNC.pSrcList = pTabList;
73489     sNC.pAggInfo = &sAggInfo;
73490     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
73491     sAggInfo.pGroupBy = pGroupBy;
73492     sqlite3ExprAnalyzeAggList(&sNC, pEList);
73493     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
73494     if( pHaving ){
73495       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
73496     }
73497     sAggInfo.nAccumulator = sAggInfo.nColumn;
73498     for(i=0; i<sAggInfo.nFunc; i++){
73499       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList);
73500     }
73501     if( db->mallocFailed ) goto select_end;
73502
73503     /* Processing for aggregates with GROUP BY is very different and
73504     ** much more complex than aggregates without a GROUP BY.
73505     */
73506     if( pGroupBy ){
73507       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
73508       int j1;             /* A-vs-B comparision jump */
73509       int addrOutputRow;  /* Start of subroutine that outputs a result row */
73510       int regOutputRow;   /* Return address register for output subroutine */
73511       int addrSetAbort;   /* Set the abort flag and return */
73512       int addrTopOfLoop;  /* Top of the input loop */
73513       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
73514       int addrReset;      /* Subroutine for resetting the accumulator */
73515       int regReset;       /* Return address register for reset subroutine */
73516
73517       /* If there is a GROUP BY clause we might need a sorting index to
73518       ** implement it.  Allocate that sorting index now.  If it turns out
73519       ** that we do not need it after all, the OpenEphemeral instruction
73520       ** will be converted into a Noop.  
73521       */
73522       sAggInfo.sortingIdx = pParse->nTab++;
73523       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
73524       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 
73525           sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
73526           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
73527
73528       /* Initialize memory locations used by GROUP BY aggregate processing
73529       */
73530       iUseFlag = ++pParse->nMem;
73531       iAbortFlag = ++pParse->nMem;
73532       regOutputRow = ++pParse->nMem;
73533       addrOutputRow = sqlite3VdbeMakeLabel(v);
73534       regReset = ++pParse->nMem;
73535       addrReset = sqlite3VdbeMakeLabel(v);
73536       iAMem = pParse->nMem + 1;
73537       pParse->nMem += pGroupBy->nExpr;
73538       iBMem = pParse->nMem + 1;
73539       pParse->nMem += pGroupBy->nExpr;
73540       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
73541       VdbeComment((v, "clear abort flag"));
73542       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
73543       VdbeComment((v, "indicate accumulator empty"));
73544
73545       /* Begin a loop that will extract all source rows in GROUP BY order.
73546       ** This might involve two separate loops with an OP_Sort in between, or
73547       ** it might be a single loop that uses an index to extract information
73548       ** in the right order to begin with.
73549       */
73550       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
73551       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
73552       if( pWInfo==0 ) goto select_end;
73553       if( pGroupBy==0 ){
73554         /* The optimizer is able to deliver rows in group by order so
73555         ** we do not have to sort.  The OP_OpenEphemeral table will be
73556         ** cancelled later because we still need to use the pKeyInfo
73557         */
73558         pGroupBy = p->pGroupBy;
73559         groupBySort = 0;
73560       }else{
73561         /* Rows are coming out in undetermined order.  We have to push
73562         ** each row into a sorting index, terminate the first loop,
73563         ** then loop over the sorting index in order to get the output
73564         ** in sorted order
73565         */
73566         int regBase;
73567         int regRecord;
73568         int nCol;
73569         int nGroupBy;
73570
73571         groupBySort = 1;
73572         nGroupBy = pGroupBy->nExpr;
73573         nCol = nGroupBy + 1;
73574         j = nGroupBy+1;
73575         for(i=0; i<sAggInfo.nColumn; i++){
73576           if( sAggInfo.aCol[i].iSorterColumn>=j ){
73577             nCol++;
73578             j++;
73579           }
73580         }
73581         regBase = sqlite3GetTempRange(pParse, nCol);
73582         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
73583         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
73584         j = nGroupBy+1;
73585         for(i=0; i<sAggInfo.nColumn; i++){
73586           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
73587           if( pCol->iSorterColumn>=j ){
73588             int r1 = j + regBase;
73589             int r2;
73590
73591             r2 = sqlite3ExprCodeGetColumn(pParse, 
73592                                pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
73593             if( r1!=r2 ){
73594               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
73595             }
73596             j++;
73597           }
73598         }
73599         regRecord = sqlite3GetTempReg(pParse);
73600         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
73601         sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
73602         sqlite3ReleaseTempReg(pParse, regRecord);
73603         sqlite3ReleaseTempRange(pParse, regBase, nCol);
73604         sqlite3WhereEnd(pWInfo);
73605         sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
73606         VdbeComment((v, "GROUP BY sort"));
73607         sAggInfo.useSortingIdx = 1;
73608       }
73609
73610       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
73611       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
73612       ** Then compare the current GROUP BY terms against the GROUP BY terms
73613       ** from the previous row currently stored in a0, a1, a2...
73614       */
73615       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
73616       for(j=0; j<pGroupBy->nExpr; j++){
73617         if( groupBySort ){
73618           sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
73619         }else{
73620           sAggInfo.directMode = 1;
73621           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
73622         }
73623       }
73624       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
73625                           (char*)pKeyInfo, P4_KEYINFO);
73626       j1 = sqlite3VdbeCurrentAddr(v);
73627       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
73628
73629       /* Generate code that runs whenever the GROUP BY changes.
73630       ** Changes in the GROUP BY are detected by the previous code
73631       ** block.  If there were no changes, this block is skipped.
73632       **
73633       ** This code copies current group by terms in b0,b1,b2,...
73634       ** over to a0,a1,a2.  It then calls the output subroutine
73635       ** and resets the aggregate accumulator registers in preparation
73636       ** for the next GROUP BY batch.
73637       */
73638       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
73639       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
73640       VdbeComment((v, "output one row"));
73641       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
73642       VdbeComment((v, "check abort flag"));
73643       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
73644       VdbeComment((v, "reset accumulator"));
73645
73646       /* Update the aggregate accumulators based on the content of
73647       ** the current row
73648       */
73649       sqlite3VdbeJumpHere(v, j1);
73650       updateAccumulator(pParse, &sAggInfo);
73651       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
73652       VdbeComment((v, "indicate data in accumulator"));
73653
73654       /* End of the loop
73655       */
73656       if( groupBySort ){
73657         sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
73658       }else{
73659         sqlite3WhereEnd(pWInfo);
73660         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
73661       }
73662
73663       /* Output the final row of result
73664       */
73665       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
73666       VdbeComment((v, "output final row"));
73667
73668       /* Jump over the subroutines
73669       */
73670       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
73671
73672       /* Generate a subroutine that outputs a single row of the result
73673       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
73674       ** is less than or equal to zero, the subroutine is a no-op.  If
73675       ** the processing calls for the query to abort, this subroutine
73676       ** increments the iAbortFlag memory location before returning in
73677       ** order to signal the caller to abort.
73678       */
73679       addrSetAbort = sqlite3VdbeCurrentAddr(v);
73680       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
73681       VdbeComment((v, "set abort flag"));
73682       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
73683       sqlite3VdbeResolveLabel(v, addrOutputRow);
73684       addrOutputRow = sqlite3VdbeCurrentAddr(v);
73685       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
73686       VdbeComment((v, "Groupby result generator entry point"));
73687       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
73688       finalizeAggFunctions(pParse, &sAggInfo);
73689       if( pHaving ){
73690         sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
73691       }
73692       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
73693                       distinct, pDest,
73694                       addrOutputRow+1, addrSetAbort);
73695       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
73696       VdbeComment((v, "end groupby result generator"));
73697
73698       /* Generate a subroutine that will reset the group-by accumulator
73699       */
73700       sqlite3VdbeResolveLabel(v, addrReset);
73701       resetAccumulator(pParse, &sAggInfo);
73702       sqlite3VdbeAddOp1(v, OP_Return, regReset);
73703      
73704     } /* endif pGroupBy */
73705     else {
73706       ExprList *pMinMax = 0;
73707       ExprList *pDel = 0;
73708       u8 flag;
73709
73710       /* Check if the query is of one of the following forms:
73711       **
73712       **   SELECT min(x) FROM ...
73713       **   SELECT max(x) FROM ...
73714       **
73715       ** If it is, then ask the code in where.c to attempt to sort results
73716       ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 
73717       ** If where.c is able to produce results sorted in this order, then
73718       ** add vdbe code to break out of the processing loop after the 
73719       ** first iteration (since the first iteration of the loop is 
73720       ** guaranteed to operate on the row with the minimum or maximum 
73721       ** value of x, the only row required).
73722       **
73723       ** A special flag must be passed to sqlite3WhereBegin() to slightly
73724       ** modify behaviour as follows:
73725       **
73726       **   + If the query is a "SELECT min(x)", then the loop coded by
73727       **     where.c should not iterate over any values with a NULL value
73728       **     for x.
73729       **
73730       **   + The optimizer code in where.c (the thing that decides which
73731       **     index or indices to use) should place a different priority on 
73732       **     satisfying the 'ORDER BY' clause than it does in other cases.
73733       **     Refer to code and comments in where.c for details.
73734       */
73735       flag = minMaxQuery(p);
73736       if( flag ){
73737         pDel = pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->pList);
73738         if( pMinMax && !db->mallocFailed ){
73739           pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN;
73740           pMinMax->a[0].pExpr->op = TK_COLUMN;
73741         }
73742       }
73743
73744       /* This case runs if the aggregate has no GROUP BY clause.  The
73745       ** processing is much simpler since there is only a single row
73746       ** of output.
73747       */
73748       resetAccumulator(pParse, &sAggInfo);
73749       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
73750       if( pWInfo==0 ){
73751         sqlite3ExprListDelete(db, pDel);
73752         goto select_end;
73753       }
73754       updateAccumulator(pParse, &sAggInfo);
73755       if( !pMinMax && flag ){
73756         sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
73757         VdbeComment((v, "%s() by index",(flag==WHERE_ORDERBY_MIN?"min":"max")));
73758       }
73759       sqlite3WhereEnd(pWInfo);
73760       finalizeAggFunctions(pParse, &sAggInfo);
73761       pOrderBy = 0;
73762       if( pHaving ){
73763         sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
73764       }
73765       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 
73766                       pDest, addrEnd, addrEnd);
73767
73768       sqlite3ExprListDelete(db, pDel);
73769     }
73770     sqlite3VdbeResolveLabel(v, addrEnd);
73771     
73772   } /* endif aggregate query */
73773
73774   /* If there is an ORDER BY clause, then we need to sort the results
73775   ** and send them to the callback one by one.
73776   */
73777   if( pOrderBy ){
73778     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
73779   }
73780
73781   /* Jump here to skip this query
73782   */
73783   sqlite3VdbeResolveLabel(v, iEnd);
73784
73785   /* The SELECT was successfully coded.   Set the return code to 0
73786   ** to indicate no errors.
73787   */
73788   rc = 0;
73789
73790   /* Control jumps to here if an error is encountered above, or upon
73791   ** successful coding of the SELECT.
73792   */
73793 select_end:
73794
73795   /* Identify column names if results of the SELECT are to be output.
73796   */
73797   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
73798     generateColumnNames(pParse, pTabList, pEList);
73799   }
73800
73801   sqlite3DbFree(db, sAggInfo.aCol);
73802   sqlite3DbFree(db, sAggInfo.aFunc);
73803   return rc;
73804 }
73805
73806 #if defined(SQLITE_DEBUG)
73807 /*
73808 *******************************************************************************
73809 ** The following code is used for testing and debugging only.  The code
73810 ** that follows does not appear in normal builds.
73811 **
73812 ** These routines are used to print out the content of all or part of a 
73813 ** parse structures such as Select or Expr.  Such printouts are useful
73814 ** for helping to understand what is happening inside the code generator
73815 ** during the execution of complex SELECT statements.
73816 **
73817 ** These routine are not called anywhere from within the normal
73818 ** code base.  Then are intended to be called from within the debugger
73819 ** or from temporary "printf" statements inserted for debugging.
73820 */
73821 SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
73822   if( p->token.z && p->token.n>0 ){
73823     sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z);
73824   }else{
73825     sqlite3DebugPrintf("(%d", p->op);
73826   }
73827   if( p->pLeft ){
73828     sqlite3DebugPrintf(" ");
73829     sqlite3PrintExpr(p->pLeft);
73830   }
73831   if( p->pRight ){
73832     sqlite3DebugPrintf(" ");
73833     sqlite3PrintExpr(p->pRight);
73834   }
73835   sqlite3DebugPrintf(")");
73836 }
73837 SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
73838   int i;
73839   for(i=0; i<pList->nExpr; i++){
73840     sqlite3PrintExpr(pList->a[i].pExpr);
73841     if( i<pList->nExpr-1 ){
73842       sqlite3DebugPrintf(", ");
73843     }
73844   }
73845 }
73846 SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
73847   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
73848   sqlite3PrintExprList(p->pEList);
73849   sqlite3DebugPrintf("\n");
73850   if( p->pSrc ){
73851     char *zPrefix;
73852     int i;
73853     zPrefix = "FROM";
73854     for(i=0; i<p->pSrc->nSrc; i++){
73855       struct SrcList_item *pItem = &p->pSrc->a[i];
73856       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
73857       zPrefix = "";
73858       if( pItem->pSelect ){
73859         sqlite3DebugPrintf("(\n");
73860         sqlite3PrintSelect(pItem->pSelect, indent+10);
73861         sqlite3DebugPrintf("%*s)", indent+8, "");
73862       }else if( pItem->zName ){
73863         sqlite3DebugPrintf("%s", pItem->zName);
73864       }
73865       if( pItem->pTab ){
73866         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
73867       }
73868       if( pItem->zAlias ){
73869         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
73870       }
73871       if( i<p->pSrc->nSrc-1 ){
73872         sqlite3DebugPrintf(",");
73873       }
73874       sqlite3DebugPrintf("\n");
73875     }
73876   }
73877   if( p->pWhere ){
73878     sqlite3DebugPrintf("%*s WHERE ", indent, "");
73879     sqlite3PrintExpr(p->pWhere);
73880     sqlite3DebugPrintf("\n");
73881   }
73882   if( p->pGroupBy ){
73883     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
73884     sqlite3PrintExprList(p->pGroupBy);
73885     sqlite3DebugPrintf("\n");
73886   }
73887   if( p->pHaving ){
73888     sqlite3DebugPrintf("%*s HAVING ", indent, "");
73889     sqlite3PrintExpr(p->pHaving);
73890     sqlite3DebugPrintf("\n");
73891   }
73892   if( p->pOrderBy ){
73893     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
73894     sqlite3PrintExprList(p->pOrderBy);
73895     sqlite3DebugPrintf("\n");
73896   }
73897 }
73898 /* End of the structure debug printing code
73899 *****************************************************************************/
73900 #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
73901
73902 /************** End of select.c **********************************************/
73903 /************** Begin file table.c *******************************************/
73904 /*
73905 ** 2001 September 15
73906 **
73907 ** The author disclaims copyright to this source code.  In place of
73908 ** a legal notice, here is a blessing:
73909 **
73910 **    May you do good and not evil.
73911 **    May you find forgiveness for yourself and forgive others.
73912 **    May you share freely, never taking more than you give.
73913 **
73914 *************************************************************************
73915 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
73916 ** interface routines.  These are just wrappers around the main
73917 ** interface routine of sqlite3_exec().
73918 **
73919 ** These routines are in a separate files so that they will not be linked
73920 ** if they are not used.
73921 **
73922 ** $Id: table.c,v 1.36 2008/07/08 22:28:49 shane Exp $
73923 */
73924
73925 #ifndef SQLITE_OMIT_GET_TABLE
73926
73927 /*
73928 ** This structure is used to pass data from sqlite3_get_table() through
73929 ** to the callback function is uses to build the result.
73930 */
73931 typedef struct TabResult {
73932   char **azResult;
73933   char *zErrMsg;
73934   int nResult;
73935   int nAlloc;
73936   int nRow;
73937   int nColumn;
73938   int nData;
73939   int rc;
73940 } TabResult;
73941
73942 /*
73943 ** This routine is called once for each row in the result table.  Its job
73944 ** is to fill in the TabResult structure appropriately, allocating new
73945 ** memory as necessary.
73946 */
73947 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
73948   TabResult *p = (TabResult*)pArg;
73949   int need;
73950   int i;
73951   char *z;
73952
73953   /* Make sure there is enough space in p->azResult to hold everything
73954   ** we need to remember from this invocation of the callback.
73955   */
73956   if( p->nRow==0 && argv!=0 ){
73957     need = nCol*2;
73958   }else{
73959     need = nCol;
73960   }
73961   if( p->nData + need >= p->nAlloc ){
73962     char **azNew;
73963     p->nAlloc = p->nAlloc*2 + need + 1;
73964     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
73965     if( azNew==0 ) goto malloc_failed;
73966     p->azResult = azNew;
73967   }
73968
73969   /* If this is the first row, then generate an extra row containing
73970   ** the names of all columns.
73971   */
73972   if( p->nRow==0 ){
73973     p->nColumn = nCol;
73974     for(i=0; i<nCol; i++){
73975       z = sqlite3_mprintf("%s", colv[i]);
73976       if( z==0 ) goto malloc_failed;
73977       p->azResult[p->nData++] = z;
73978     }
73979   }else if( p->nColumn!=nCol ){
73980     sqlite3_free(p->zErrMsg);
73981     p->zErrMsg = sqlite3_mprintf(
73982        "sqlite3_get_table() called with two or more incompatible queries"
73983     );
73984     p->rc = SQLITE_ERROR;
73985     return 1;
73986   }
73987
73988   /* Copy over the row data
73989   */
73990   if( argv!=0 ){
73991     for(i=0; i<nCol; i++){
73992       if( argv[i]==0 ){
73993         z = 0;
73994       }else{
73995         int n = strlen(argv[i])+1;
73996         z = sqlite3_malloc( n );
73997         if( z==0 ) goto malloc_failed;
73998         memcpy(z, argv[i], n);
73999       }
74000       p->azResult[p->nData++] = z;
74001     }
74002     p->nRow++;
74003   }
74004   return 0;
74005
74006 malloc_failed:
74007   p->rc = SQLITE_NOMEM;
74008   return 1;
74009 }
74010
74011 /*
74012 ** Query the database.  But instead of invoking a callback for each row,
74013 ** malloc() for space to hold the result and return the entire results
74014 ** at the conclusion of the call.
74015 **
74016 ** The result that is written to ***pazResult is held in memory obtained
74017 ** from malloc().  But the caller cannot free this memory directly.  
74018 ** Instead, the entire table should be passed to sqlite3_free_table() when
74019 ** the calling procedure is finished using it.
74020 */
74021 SQLITE_API int sqlite3_get_table(
74022   sqlite3 *db,                /* The database on which the SQL executes */
74023   const char *zSql,           /* The SQL to be executed */
74024   char ***pazResult,          /* Write the result table here */
74025   int *pnRow,                 /* Write the number of rows in the result here */
74026   int *pnColumn,              /* Write the number of columns of result here */
74027   char **pzErrMsg             /* Write error messages here */
74028 ){
74029   int rc;
74030   TabResult res;
74031
74032   *pazResult = 0;
74033   if( pnColumn ) *pnColumn = 0;
74034   if( pnRow ) *pnRow = 0;
74035   res.zErrMsg = 0;
74036   res.nResult = 0;
74037   res.nRow = 0;
74038   res.nColumn = 0;
74039   res.nData = 1;
74040   res.nAlloc = 20;
74041   res.rc = SQLITE_OK;
74042   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
74043   if( res.azResult==0 ){
74044      db->errCode = SQLITE_NOMEM;
74045      return SQLITE_NOMEM;
74046   }
74047   res.azResult[0] = 0;
74048   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
74049   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
74050   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
74051   if( (rc&0xff)==SQLITE_ABORT ){
74052     sqlite3_free_table(&res.azResult[1]);
74053     if( res.zErrMsg ){
74054       if( pzErrMsg ){
74055         sqlite3_free(*pzErrMsg);
74056         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
74057       }
74058       sqlite3_free(res.zErrMsg);
74059     }
74060     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
74061     return res.rc;
74062   }
74063   sqlite3_free(res.zErrMsg);
74064   if( rc!=SQLITE_OK ){
74065     sqlite3_free_table(&res.azResult[1]);
74066     return rc;
74067   }
74068   if( res.nAlloc>res.nData ){
74069     char **azNew;
74070     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*(res.nData+1) );
74071     if( azNew==0 ){
74072       sqlite3_free_table(&res.azResult[1]);
74073       db->errCode = SQLITE_NOMEM;
74074       return SQLITE_NOMEM;
74075     }
74076     res.nAlloc = res.nData+1;
74077     res.azResult = azNew;
74078   }
74079   *pazResult = &res.azResult[1];
74080   if( pnColumn ) *pnColumn = res.nColumn;
74081   if( pnRow ) *pnRow = res.nRow;
74082   return rc;
74083 }
74084
74085 /*
74086 ** This routine frees the space the sqlite3_get_table() malloced.
74087 */
74088 SQLITE_API void sqlite3_free_table(
74089   char **azResult            /* Result returned from from sqlite3_get_table() */
74090 ){
74091   if( azResult ){
74092     int i, n;
74093     azResult--;
74094     assert( azResult!=0 );
74095     n = SQLITE_PTR_TO_INT(azResult[0]);
74096     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
74097     sqlite3_free(azResult);
74098   }
74099 }
74100
74101 #endif /* SQLITE_OMIT_GET_TABLE */
74102
74103 /************** End of table.c ***********************************************/
74104 /************** Begin file trigger.c *****************************************/
74105 /*
74106 **
74107 ** The author disclaims copyright to this source code.  In place of
74108 ** a legal notice, here is a blessing:
74109 **
74110 **    May you do good and not evil.
74111 **    May you find forgiveness for yourself and forgive others.
74112 **    May you share freely, never taking more than you give.
74113 **
74114 *************************************************************************
74115 **
74116 **
74117 ** $Id: trigger.c,v 1.130 2008/11/19 09:05:27 danielk1977 Exp $
74118 */
74119
74120 #ifndef SQLITE_OMIT_TRIGGER
74121 /*
74122 ** Delete a linked list of TriggerStep structures.
74123 */
74124 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
74125   while( pTriggerStep ){
74126     TriggerStep * pTmp = pTriggerStep;
74127     pTriggerStep = pTriggerStep->pNext;
74128
74129     if( pTmp->target.dyn ) sqlite3DbFree(db, (char*)pTmp->target.z);
74130     sqlite3ExprDelete(db, pTmp->pWhere);
74131     sqlite3ExprListDelete(db, pTmp->pExprList);
74132     sqlite3SelectDelete(db, pTmp->pSelect);
74133     sqlite3IdListDelete(db, pTmp->pIdList);
74134
74135     sqlite3DbFree(db, pTmp);
74136   }
74137 }
74138
74139 /*
74140 ** This is called by the parser when it sees a CREATE TRIGGER statement
74141 ** up to the point of the BEGIN before the trigger actions.  A Trigger
74142 ** structure is generated based on the information available and stored
74143 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
74144 ** sqlite3FinishTrigger() function is called to complete the trigger
74145 ** construction process.
74146 */
74147 SQLITE_PRIVATE void sqlite3BeginTrigger(
74148   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
74149   Token *pName1,      /* The name of the trigger */
74150   Token *pName2,      /* The name of the trigger */
74151   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
74152   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
74153   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
74154   SrcList *pTableName,/* The name of the table/view the trigger applies to */
74155   Expr *pWhen,        /* WHEN clause */
74156   int isTemp,         /* True if the TEMPORARY keyword is present */
74157   int noErr           /* Suppress errors if the trigger already exists */
74158 ){
74159   Trigger *pTrigger = 0;
74160   Table *pTab;
74161   char *zName = 0;        /* Name of the trigger */
74162   sqlite3 *db = pParse->db;
74163   int iDb;                /* The database to store the trigger in */
74164   Token *pName;           /* The unqualified db name */
74165   DbFixer sFix;
74166   int iTabDb;
74167
74168   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
74169   assert( pName2!=0 );
74170   if( isTemp ){
74171     /* If TEMP was specified, then the trigger name may not be qualified. */
74172     if( pName2->n>0 ){
74173       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
74174       goto trigger_cleanup;
74175     }
74176     iDb = 1;
74177     pName = pName1;
74178   }else{
74179     /* Figure out the db that the the trigger will be created in */
74180     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
74181     if( iDb<0 ){
74182       goto trigger_cleanup;
74183     }
74184   }
74185
74186   /* If the trigger name was unqualified, and the table is a temp table,
74187   ** then set iDb to 1 to create the trigger in the temporary database.
74188   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
74189   ** exist, the error is caught by the block below.
74190   */
74191   if( !pTableName || db->mallocFailed ){
74192     goto trigger_cleanup;
74193   }
74194   pTab = sqlite3SrcListLookup(pParse, pTableName);
74195   if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
74196     iDb = 1;
74197   }
74198
74199   /* Ensure the table name matches database name and that the table exists */
74200   if( db->mallocFailed ) goto trigger_cleanup;
74201   assert( pTableName->nSrc==1 );
74202   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) && 
74203       sqlite3FixSrcList(&sFix, pTableName) ){
74204     goto trigger_cleanup;
74205   }
74206   pTab = sqlite3SrcListLookup(pParse, pTableName);
74207   if( !pTab ){
74208     /* The table does not exist. */
74209     goto trigger_cleanup;
74210   }
74211   if( IsVirtual(pTab) ){
74212     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
74213     goto trigger_cleanup;
74214   }
74215
74216   /* Check that the trigger name is not reserved and that no trigger of the
74217   ** specified name exists */
74218   zName = sqlite3NameFromToken(db, pName);
74219   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
74220     goto trigger_cleanup;
74221   }
74222   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash), zName,strlen(zName)) ){
74223     if( !noErr ){
74224       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
74225     }
74226     goto trigger_cleanup;
74227   }
74228
74229   /* Do not create a trigger on a system table */
74230   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
74231     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
74232     pParse->nErr++;
74233     goto trigger_cleanup;
74234   }
74235
74236   /* INSTEAD of triggers are only for views and views only support INSTEAD
74237   ** of triggers.
74238   */
74239   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
74240     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
74241         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
74242     goto trigger_cleanup;
74243   }
74244   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
74245     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
74246         " trigger on table: %S", pTableName, 0);
74247     goto trigger_cleanup;
74248   }
74249   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
74250
74251 #ifndef SQLITE_OMIT_AUTHORIZATION
74252   {
74253     int code = SQLITE_CREATE_TRIGGER;
74254     const char *zDb = db->aDb[iTabDb].zName;
74255     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
74256     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
74257     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
74258       goto trigger_cleanup;
74259     }
74260     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
74261       goto trigger_cleanup;
74262     }
74263   }
74264 #endif
74265
74266   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
74267   ** cannot appear on views.  So we might as well translate every
74268   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
74269   ** elsewhere.
74270   */
74271   if (tr_tm == TK_INSTEAD){
74272     tr_tm = TK_BEFORE;
74273   }
74274
74275   /* Build the Trigger object */
74276   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
74277   if( pTrigger==0 ) goto trigger_cleanup;
74278   pTrigger->name = zName;
74279   zName = 0;
74280   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
74281   pTrigger->pSchema = db->aDb[iDb].pSchema;
74282   pTrigger->pTabSchema = pTab->pSchema;
74283   pTrigger->op = op;
74284   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
74285   pTrigger->pWhen = sqlite3ExprDup(db, pWhen);
74286   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
74287   sqlite3TokenCopy(db, &pTrigger->nameToken,pName);
74288   assert( pParse->pNewTrigger==0 );
74289   pParse->pNewTrigger = pTrigger;
74290
74291 trigger_cleanup:
74292   sqlite3DbFree(db, zName);
74293   sqlite3SrcListDelete(db, pTableName);
74294   sqlite3IdListDelete(db, pColumns);
74295   sqlite3ExprDelete(db, pWhen);
74296   if( !pParse->pNewTrigger ){
74297     sqlite3DeleteTrigger(db, pTrigger);
74298   }else{
74299     assert( pParse->pNewTrigger==pTrigger );
74300   }
74301 }
74302
74303 /*
74304 ** This routine is called after all of the trigger actions have been parsed
74305 ** in order to complete the process of building the trigger.
74306 */
74307 SQLITE_PRIVATE void sqlite3FinishTrigger(
74308   Parse *pParse,          /* Parser context */
74309   TriggerStep *pStepList, /* The triggered program */
74310   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
74311 ){
74312   Trigger *pTrig = 0;     /* The trigger whose construction is finishing up */
74313   sqlite3 *db = pParse->db;  /* The database */
74314   DbFixer sFix;
74315   int iDb;                   /* Database containing the trigger */
74316
74317   pTrig = pParse->pNewTrigger;
74318   pParse->pNewTrigger = 0;
74319   if( pParse->nErr || !pTrig ) goto triggerfinish_cleanup;
74320   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
74321   pTrig->step_list = pStepList;
74322   while( pStepList ){
74323     pStepList->pTrig = pTrig;
74324     pStepList = pStepList->pNext;
74325   }
74326   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &pTrig->nameToken) 
74327           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
74328     goto triggerfinish_cleanup;
74329   }
74330
74331   /* if we are not initializing, and this trigger is not on a TEMP table, 
74332   ** build the sqlite_master entry
74333   */
74334   if( !db->init.busy ){
74335     Vdbe *v;
74336     char *z;
74337
74338     /* Make an entry in the sqlite_master table */
74339     v = sqlite3GetVdbe(pParse);
74340     if( v==0 ) goto triggerfinish_cleanup;
74341     sqlite3BeginWriteOperation(pParse, 0, iDb);
74342     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
74343     sqlite3NestedParse(pParse,
74344        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
74345        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pTrig->name,
74346        pTrig->table, z);
74347     sqlite3DbFree(db, z);
74348     sqlite3ChangeCookie(pParse, iDb);
74349     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
74350         db, "type='trigger' AND name='%q'", pTrig->name), P4_DYNAMIC
74351     );
74352   }
74353
74354   if( db->init.busy ){
74355     int n;
74356     Table *pTab;
74357     Trigger *pDel;
74358     pDel = sqlite3HashInsert(&db->aDb[iDb].pSchema->trigHash, 
74359                      pTrig->name, strlen(pTrig->name), pTrig);
74360     if( pDel ){
74361       assert( pDel==pTrig );
74362       db->mallocFailed = 1;
74363       goto triggerfinish_cleanup;
74364     }
74365     n = strlen(pTrig->table) + 1;
74366     pTab = sqlite3HashFind(&pTrig->pTabSchema->tblHash, pTrig->table, n);
74367     assert( pTab!=0 );
74368     pTrig->pNext = pTab->pTrigger;
74369     pTab->pTrigger = pTrig;
74370     pTrig = 0;
74371   }
74372
74373 triggerfinish_cleanup:
74374   sqlite3DeleteTrigger(db, pTrig);
74375   assert( !pParse->pNewTrigger );
74376   sqlite3DeleteTriggerStep(db, pStepList);
74377 }
74378
74379 /*
74380 ** Make a copy of all components of the given trigger step.  This has
74381 ** the effect of copying all Expr.token.z values into memory obtained
74382 ** from sqlite3_malloc().  As initially created, the Expr.token.z values
74383 ** all point to the input string that was fed to the parser.  But that
74384 ** string is ephemeral - it will go away as soon as the sqlite3_exec()
74385 ** call that started the parser exits.  This routine makes a persistent
74386 ** copy of all the Expr.token.z strings so that the TriggerStep structure
74387 ** will be valid even after the sqlite3_exec() call returns.
74388 */
74389 static void sqlitePersistTriggerStep(sqlite3 *db, TriggerStep *p){
74390   if( p->target.z ){
74391     p->target.z = (u8*)sqlite3DbStrNDup(db, (char*)p->target.z, p->target.n);
74392     p->target.dyn = 1;
74393   }
74394   if( p->pSelect ){
74395     Select *pNew = sqlite3SelectDup(db, p->pSelect);
74396     sqlite3SelectDelete(db, p->pSelect);
74397     p->pSelect = pNew;
74398   }
74399   if( p->pWhere ){
74400     Expr *pNew = sqlite3ExprDup(db, p->pWhere);
74401     sqlite3ExprDelete(db, p->pWhere);
74402     p->pWhere = pNew;
74403   }
74404   if( p->pExprList ){
74405     ExprList *pNew = sqlite3ExprListDup(db, p->pExprList);
74406     sqlite3ExprListDelete(db, p->pExprList);
74407     p->pExprList = pNew;
74408   }
74409   if( p->pIdList ){
74410     IdList *pNew = sqlite3IdListDup(db, p->pIdList);
74411     sqlite3IdListDelete(db, p->pIdList);
74412     p->pIdList = pNew;
74413   }
74414 }
74415
74416 /*
74417 ** Turn a SELECT statement (that the pSelect parameter points to) into
74418 ** a trigger step.  Return a pointer to a TriggerStep structure.
74419 **
74420 ** The parser calls this routine when it finds a SELECT statement in
74421 ** body of a TRIGGER.  
74422 */
74423 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
74424   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
74425   if( pTriggerStep==0 ) {
74426     sqlite3SelectDelete(db, pSelect);
74427     return 0;
74428   }
74429
74430   pTriggerStep->op = TK_SELECT;
74431   pTriggerStep->pSelect = pSelect;
74432   pTriggerStep->orconf = OE_Default;
74433   sqlitePersistTriggerStep(db, pTriggerStep);
74434
74435   return pTriggerStep;
74436 }
74437
74438 /*
74439 ** Build a trigger step out of an INSERT statement.  Return a pointer
74440 ** to the new trigger step.
74441 **
74442 ** The parser calls this routine when it sees an INSERT inside the
74443 ** body of a trigger.
74444 */
74445 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
74446   sqlite3 *db,        /* The database connection */
74447   Token *pTableName,  /* Name of the table into which we insert */
74448   IdList *pColumn,    /* List of columns in pTableName to insert into */
74449   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
74450   Select *pSelect,    /* A SELECT statement that supplies values */
74451   int orconf          /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
74452 ){
74453   TriggerStep *pTriggerStep;
74454
74455   assert(pEList == 0 || pSelect == 0);
74456   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
74457
74458   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
74459   if( pTriggerStep ){
74460     pTriggerStep->op = TK_INSERT;
74461     pTriggerStep->pSelect = pSelect;
74462     pTriggerStep->target  = *pTableName;
74463     pTriggerStep->pIdList = pColumn;
74464     pTriggerStep->pExprList = pEList;
74465     pTriggerStep->orconf = orconf;
74466     sqlitePersistTriggerStep(db, pTriggerStep);
74467   }else{
74468     sqlite3IdListDelete(db, pColumn);
74469     sqlite3ExprListDelete(db, pEList);
74470     sqlite3SelectDelete(db, pSelect);
74471   }
74472
74473   return pTriggerStep;
74474 }
74475
74476 /*
74477 ** Construct a trigger step that implements an UPDATE statement and return
74478 ** a pointer to that trigger step.  The parser calls this routine when it
74479 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
74480 */
74481 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
74482   sqlite3 *db,         /* The database connection */
74483   Token *pTableName,   /* Name of the table to be updated */
74484   ExprList *pEList,    /* The SET clause: list of column and new values */
74485   Expr *pWhere,        /* The WHERE clause */
74486   int orconf           /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
74487 ){
74488   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
74489   if( pTriggerStep==0 ){
74490      sqlite3ExprListDelete(db, pEList);
74491      sqlite3ExprDelete(db, pWhere);
74492      return 0;
74493   }
74494
74495   pTriggerStep->op = TK_UPDATE;
74496   pTriggerStep->target  = *pTableName;
74497   pTriggerStep->pExprList = pEList;
74498   pTriggerStep->pWhere = pWhere;
74499   pTriggerStep->orconf = orconf;
74500   sqlitePersistTriggerStep(db, pTriggerStep);
74501
74502   return pTriggerStep;
74503 }
74504
74505 /*
74506 ** Construct a trigger step that implements a DELETE statement and return
74507 ** a pointer to that trigger step.  The parser calls this routine when it
74508 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
74509 */
74510 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
74511   sqlite3 *db,            /* Database connection */
74512   Token *pTableName,      /* The table from which rows are deleted */
74513   Expr *pWhere            /* The WHERE clause */
74514 ){
74515   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
74516   if( pTriggerStep==0 ){
74517     sqlite3ExprDelete(db, pWhere);
74518     return 0;
74519   }
74520
74521   pTriggerStep->op = TK_DELETE;
74522   pTriggerStep->target  = *pTableName;
74523   pTriggerStep->pWhere = pWhere;
74524   pTriggerStep->orconf = OE_Default;
74525   sqlitePersistTriggerStep(db, pTriggerStep);
74526
74527   return pTriggerStep;
74528 }
74529
74530 /* 
74531 ** Recursively delete a Trigger structure
74532 */
74533 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
74534   if( pTrigger==0 ) return;
74535   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
74536   sqlite3DbFree(db, pTrigger->name);
74537   sqlite3DbFree(db, pTrigger->table);
74538   sqlite3ExprDelete(db, pTrigger->pWhen);
74539   sqlite3IdListDelete(db, pTrigger->pColumns);
74540   if( pTrigger->nameToken.dyn ) sqlite3DbFree(db, (char*)pTrigger->nameToken.z);
74541   sqlite3DbFree(db, pTrigger);
74542 }
74543
74544 /*
74545 ** This function is called to drop a trigger from the database schema. 
74546 **
74547 ** This may be called directly from the parser and therefore identifies
74548 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
74549 ** same job as this routine except it takes a pointer to the trigger
74550 ** instead of the trigger name.
74551 **/
74552 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
74553   Trigger *pTrigger = 0;
74554   int i;
74555   const char *zDb;
74556   const char *zName;
74557   int nName;
74558   sqlite3 *db = pParse->db;
74559
74560   if( db->mallocFailed ) goto drop_trigger_cleanup;
74561   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
74562     goto drop_trigger_cleanup;
74563   }
74564
74565   assert( pName->nSrc==1 );
74566   zDb = pName->a[0].zDatabase;
74567   zName = pName->a[0].zName;
74568   nName = strlen(zName);
74569   for(i=OMIT_TEMPDB; i<db->nDb; i++){
74570     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
74571     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
74572     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
74573     if( pTrigger ) break;
74574   }
74575   if( !pTrigger ){
74576     if( !noErr ){
74577       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
74578     }
74579     goto drop_trigger_cleanup;
74580   }
74581   sqlite3DropTriggerPtr(pParse, pTrigger);
74582
74583 drop_trigger_cleanup:
74584   sqlite3SrcListDelete(db, pName);
74585 }
74586
74587 /*
74588 ** Return a pointer to the Table structure for the table that a trigger
74589 ** is set on.
74590 */
74591 static Table *tableOfTrigger(Trigger *pTrigger){
74592   int n = strlen(pTrigger->table) + 1;
74593   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
74594 }
74595
74596
74597 /*
74598 ** Drop a trigger given a pointer to that trigger. 
74599 */
74600 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
74601   Table   *pTable;
74602   Vdbe *v;
74603   sqlite3 *db = pParse->db;
74604   int iDb;
74605
74606   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
74607   assert( iDb>=0 && iDb<db->nDb );
74608   pTable = tableOfTrigger(pTrigger);
74609   assert( pTable );
74610   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
74611 #ifndef SQLITE_OMIT_AUTHORIZATION
74612   {
74613     int code = SQLITE_DROP_TRIGGER;
74614     const char *zDb = db->aDb[iDb].zName;
74615     const char *zTab = SCHEMA_TABLE(iDb);
74616     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
74617     if( sqlite3AuthCheck(pParse, code, pTrigger->name, pTable->zName, zDb) ||
74618       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
74619       return;
74620     }
74621   }
74622 #endif
74623
74624   /* Generate code to destroy the database record of the trigger.
74625   */
74626   assert( pTable!=0 );
74627   if( (v = sqlite3GetVdbe(pParse))!=0 ){
74628     int base;
74629     static const VdbeOpList dropTrigger[] = {
74630       { OP_Rewind,     0, ADDR(9),  0},
74631       { OP_String8,    0, 1,        0}, /* 1 */
74632       { OP_Column,     0, 1,        2},
74633       { OP_Ne,         2, ADDR(8),  1},
74634       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
74635       { OP_Column,     0, 0,        2},
74636       { OP_Ne,         2, ADDR(8),  1},
74637       { OP_Delete,     0, 0,        0},
74638       { OP_Next,       0, ADDR(1),  0}, /* 8 */
74639     };
74640
74641     sqlite3BeginWriteOperation(pParse, 0, iDb);
74642     sqlite3OpenMasterTable(pParse, iDb);
74643     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
74644     sqlite3VdbeChangeP4(v, base+1, pTrigger->name, 0);
74645     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
74646     sqlite3ChangeCookie(pParse, iDb);
74647     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
74648     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->name, 0);
74649   }
74650 }
74651
74652 /*
74653 ** Remove a trigger from the hash tables of the sqlite* pointer.
74654 */
74655 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
74656   Trigger *pTrigger;
74657   int nName = strlen(zName);
74658   pTrigger = sqlite3HashInsert(&(db->aDb[iDb].pSchema->trigHash),
74659                                zName, nName, 0);
74660   if( pTrigger ){
74661     Table *pTable = tableOfTrigger(pTrigger);
74662     assert( pTable!=0 );
74663     if( pTable->pTrigger == pTrigger ){
74664       pTable->pTrigger = pTrigger->pNext;
74665     }else{
74666       Trigger *cc = pTable->pTrigger;
74667       while( cc ){ 
74668         if( cc->pNext == pTrigger ){
74669           cc->pNext = cc->pNext->pNext;
74670           break;
74671         }
74672         cc = cc->pNext;
74673       }
74674       assert(cc);
74675     }
74676     sqlite3DeleteTrigger(db, pTrigger);
74677     db->flags |= SQLITE_InternChanges;
74678   }
74679 }
74680
74681 /*
74682 ** pEList is the SET clause of an UPDATE statement.  Each entry
74683 ** in pEList is of the format <id>=<expr>.  If any of the entries
74684 ** in pEList have an <id> which matches an identifier in pIdList,
74685 ** then return TRUE.  If pIdList==NULL, then it is considered a
74686 ** wildcard that matches anything.  Likewise if pEList==NULL then
74687 ** it matches anything so always return true.  Return false only
74688 ** if there is no match.
74689 */
74690 static int checkColumnOverLap(IdList *pIdList, ExprList *pEList){
74691   int e;
74692   if( !pIdList || !pEList ) return 1;
74693   for(e=0; e<pEList->nExpr; e++){
74694     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
74695   }
74696   return 0; 
74697 }
74698
74699 /*
74700 ** Return a bit vector to indicate what kind of triggers exist for operation
74701 ** "op" on table pTab.  If pChanges is not NULL then it is a list of columns
74702 ** that are being updated.  Triggers only match if the ON clause of the
74703 ** trigger definition overlaps the set of columns being updated.
74704 **
74705 ** The returned bit vector is some combination of TRIGGER_BEFORE and
74706 ** TRIGGER_AFTER.
74707 */
74708 SQLITE_PRIVATE int sqlite3TriggersExist(
74709   Table *pTab,            /* The table the contains the triggers */
74710   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
74711   ExprList *pChanges      /* Columns that change in an UPDATE statement */
74712 ){
74713   Trigger *pTrigger;
74714   int mask = 0;
74715
74716   pTrigger = IsVirtual(pTab) ? 0 : pTab->pTrigger;
74717   while( pTrigger ){
74718     if( pTrigger->op==op && checkColumnOverLap(pTrigger->pColumns, pChanges) ){
74719       mask |= pTrigger->tr_tm;
74720     }
74721     pTrigger = pTrigger->pNext;
74722   }
74723   return mask;
74724 }
74725
74726 /*
74727 ** Convert the pStep->target token into a SrcList and return a pointer
74728 ** to that SrcList.
74729 **
74730 ** This routine adds a specific database name, if needed, to the target when
74731 ** forming the SrcList.  This prevents a trigger in one database from
74732 ** referring to a target in another database.  An exception is when the
74733 ** trigger is in TEMP in which case it can refer to any other database it
74734 ** wants.
74735 */
74736 static SrcList *targetSrcList(
74737   Parse *pParse,       /* The parsing context */
74738   TriggerStep *pStep   /* The trigger containing the target token */
74739 ){
74740   Token sDb;           /* Dummy database name token */
74741   int iDb;             /* Index of the database to use */
74742   SrcList *pSrc;       /* SrcList to be returned */
74743
74744   iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
74745   if( iDb==0 || iDb>=2 ){
74746     assert( iDb<pParse->db->nDb );
74747     sDb.z = (u8*)pParse->db->aDb[iDb].zName;
74748     sDb.n = strlen((char*)sDb.z);
74749     pSrc = sqlite3SrcListAppend(pParse->db, 0, &sDb, &pStep->target);
74750   } else {
74751     pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
74752   }
74753   return pSrc;
74754 }
74755
74756 /*
74757 ** Generate VDBE code for zero or more statements inside the body of a
74758 ** trigger.  
74759 */
74760 static int codeTriggerProgram(
74761   Parse *pParse,            /* The parser context */
74762   TriggerStep *pStepList,   /* List of statements inside the trigger body */
74763   int orconfin              /* Conflict algorithm. (OE_Abort, etc) */  
74764 ){
74765   TriggerStep * pTriggerStep = pStepList;
74766   int orconf;
74767   Vdbe *v = pParse->pVdbe;
74768   sqlite3 *db = pParse->db;
74769
74770   assert( pTriggerStep!=0 );
74771   assert( v!=0 );
74772   sqlite3VdbeAddOp2(v, OP_ContextPush, 0, 0);
74773   VdbeComment((v, "begin trigger %s", pStepList->pTrig->name));
74774   while( pTriggerStep ){
74775     orconf = (orconfin == OE_Default)?pTriggerStep->orconf:orconfin;
74776     pParse->trigStack->orconf = orconf;
74777     switch( pTriggerStep->op ){
74778       case TK_SELECT: {
74779         Select *ss = sqlite3SelectDup(db, pTriggerStep->pSelect);
74780         if( ss ){
74781           SelectDest dest;
74782
74783           sqlite3SelectDestInit(&dest, SRT_Discard, 0);
74784           sqlite3Select(pParse, ss, &dest);
74785           sqlite3SelectDelete(db, ss);
74786         }
74787         break;
74788       }
74789       case TK_UPDATE: {
74790         SrcList *pSrc;
74791         pSrc = targetSrcList(pParse, pTriggerStep);
74792         sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
74793         sqlite3Update(pParse, pSrc,
74794                 sqlite3ExprListDup(db, pTriggerStep->pExprList), 
74795                 sqlite3ExprDup(db, pTriggerStep->pWhere), orconf);
74796         sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
74797         break;
74798       }
74799       case TK_INSERT: {
74800         SrcList *pSrc;
74801         pSrc = targetSrcList(pParse, pTriggerStep);
74802         sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
74803         sqlite3Insert(pParse, pSrc,
74804           sqlite3ExprListDup(db, pTriggerStep->pExprList), 
74805           sqlite3SelectDup(db, pTriggerStep->pSelect), 
74806           sqlite3IdListDup(db, pTriggerStep->pIdList), orconf);
74807         sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
74808         break;
74809       }
74810       case TK_DELETE: {
74811         SrcList *pSrc;
74812         sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
74813         pSrc = targetSrcList(pParse, pTriggerStep);
74814         sqlite3DeleteFrom(pParse, pSrc, 
74815                           sqlite3ExprDup(db, pTriggerStep->pWhere));
74816         sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
74817         break;
74818       }
74819       default:
74820         assert(0);
74821     } 
74822     pTriggerStep = pTriggerStep->pNext;
74823   }
74824   sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0);
74825   VdbeComment((v, "end trigger %s", pStepList->pTrig->name));
74826
74827   return 0;
74828 }
74829
74830 /*
74831 ** This is called to code FOR EACH ROW triggers.
74832 **
74833 ** When the code that this function generates is executed, the following 
74834 ** must be true:
74835 **
74836 ** 1. No cursors may be open in the main database.  (But newIdx and oldIdx
74837 **    can be indices of cursors in temporary tables.  See below.)
74838 **
74839 ** 2. If the triggers being coded are ON INSERT or ON UPDATE triggers, then
74840 **    a temporary vdbe cursor (index newIdx) must be open and pointing at
74841 **    a row containing values to be substituted for new.* expressions in the
74842 **    trigger program(s).
74843 **
74844 ** 3. If the triggers being coded are ON DELETE or ON UPDATE triggers, then
74845 **    a temporary vdbe cursor (index oldIdx) must be open and pointing at
74846 **    a row containing values to be substituted for old.* expressions in the
74847 **    trigger program(s).
74848 **
74849 ** If they are not NULL, the piOldColMask and piNewColMask output variables
74850 ** are set to values that describe the columns used by the trigger program
74851 ** in the OLD.* and NEW.* tables respectively. If column N of the 
74852 ** pseudo-table is read at least once, the corresponding bit of the output
74853 ** mask is set. If a column with an index greater than 32 is read, the
74854 ** output mask is set to the special value 0xffffffff.
74855 **
74856 */
74857 SQLITE_PRIVATE int sqlite3CodeRowTrigger(
74858   Parse *pParse,       /* Parse context */
74859   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
74860   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
74861   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
74862   Table *pTab,         /* The table to code triggers from */
74863   int newIdx,          /* The indice of the "new" row to access */
74864   int oldIdx,          /* The indice of the "old" row to access */
74865   int orconf,          /* ON CONFLICT policy */
74866   int ignoreJump,      /* Instruction to jump to for RAISE(IGNORE) */
74867   u32 *piOldColMask,   /* OUT: Mask of columns used from the OLD.* table */
74868   u32 *piNewColMask    /* OUT: Mask of columns used from the NEW.* table */
74869 ){
74870   Trigger *p;
74871   sqlite3 *db = pParse->db;
74872   TriggerStack trigStackEntry;
74873
74874   trigStackEntry.oldColMask = 0;
74875   trigStackEntry.newColMask = 0;
74876
74877   assert(op == TK_UPDATE || op == TK_INSERT || op == TK_DELETE);
74878   assert(tr_tm == TRIGGER_BEFORE || tr_tm == TRIGGER_AFTER );
74879
74880   assert(newIdx != -1 || oldIdx != -1);
74881
74882   for(p=pTab->pTrigger; p; p=p->pNext){
74883     int fire_this = 0;
74884
74885     /* Determine whether we should code this trigger */
74886     if( 
74887       p->op==op && 
74888       p->tr_tm==tr_tm && 
74889       (p->pSchema==p->pTabSchema || p->pSchema==db->aDb[1].pSchema) &&
74890       (op!=TK_UPDATE||!p->pColumns||checkColumnOverLap(p->pColumns,pChanges))
74891     ){
74892       TriggerStack *pS;      /* Pointer to trigger-stack entry */
74893       for(pS=pParse->trigStack; pS && p!=pS->pTrigger; pS=pS->pNext){}
74894       if( !pS ){
74895         fire_this = 1;
74896       }
74897 #if 0    /* Give no warning for recursive triggers.  Just do not do them */
74898       else{
74899         sqlite3ErrorMsg(pParse, "recursive triggers not supported (%s)",
74900             p->name);
74901         return SQLITE_ERROR;
74902       }
74903 #endif
74904     }
74905  
74906     if( fire_this ){
74907       int endTrigger;
74908       Expr * whenExpr;
74909       AuthContext sContext;
74910       NameContext sNC;
74911
74912 #ifndef SQLITE_OMIT_TRACE
74913       sqlite3VdbeAddOp4(pParse->pVdbe, OP_Trace, 0, 0, 0,
74914                         sqlite3MPrintf(db, "-- TRIGGER %s", p->name),
74915                         P4_DYNAMIC);
74916 #endif
74917       memset(&sNC, 0, sizeof(sNC));
74918       sNC.pParse = pParse;
74919
74920       /* Push an entry on to the trigger stack */
74921       trigStackEntry.pTrigger = p;
74922       trigStackEntry.newIdx = newIdx;
74923       trigStackEntry.oldIdx = oldIdx;
74924       trigStackEntry.pTab = pTab;
74925       trigStackEntry.pNext = pParse->trigStack;
74926       trigStackEntry.ignoreJump = ignoreJump;
74927       pParse->trigStack = &trigStackEntry;
74928       sqlite3AuthContextPush(pParse, &sContext, p->name);
74929
74930       /* code the WHEN clause */
74931       endTrigger = sqlite3VdbeMakeLabel(pParse->pVdbe);
74932       whenExpr = sqlite3ExprDup(db, p->pWhen);
74933       if( db->mallocFailed || sqlite3ResolveExprNames(&sNC, whenExpr) ){
74934         pParse->trigStack = trigStackEntry.pNext;
74935         sqlite3ExprDelete(db, whenExpr);
74936         return 1;
74937       }
74938       sqlite3ExprIfFalse(pParse, whenExpr, endTrigger, SQLITE_JUMPIFNULL);
74939       sqlite3ExprDelete(db, whenExpr);
74940
74941       codeTriggerProgram(pParse, p->step_list, orconf); 
74942
74943       /* Pop the entry off the trigger stack */
74944       pParse->trigStack = trigStackEntry.pNext;
74945       sqlite3AuthContextPop(&sContext);
74946
74947       sqlite3VdbeResolveLabel(pParse->pVdbe, endTrigger);
74948     }
74949   }
74950   if( piOldColMask ) *piOldColMask |= trigStackEntry.oldColMask;
74951   if( piNewColMask ) *piNewColMask |= trigStackEntry.newColMask;
74952   return 0;
74953 }
74954 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
74955
74956 /************** End of trigger.c *********************************************/
74957 /************** Begin file update.c ******************************************/
74958 /*
74959 ** 2001 September 15
74960 **
74961 ** The author disclaims copyright to this source code.  In place of
74962 ** a legal notice, here is a blessing:
74963 **
74964 **    May you do good and not evil.
74965 **    May you find forgiveness for yourself and forgive others.
74966 **    May you share freely, never taking more than you give.
74967 **
74968 *************************************************************************
74969 ** This file contains C code routines that are called by the parser
74970 ** to handle UPDATE statements.
74971 **
74972 ** $Id: update.c,v 1.187 2008/11/19 09:05:27 danielk1977 Exp $
74973 */
74974
74975 #ifndef SQLITE_OMIT_VIRTUALTABLE
74976 /* Forward declaration */
74977 static void updateVirtualTable(
74978   Parse *pParse,       /* The parsing context */
74979   SrcList *pSrc,       /* The virtual table to be modified */
74980   Table *pTab,         /* The virtual table */
74981   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
74982   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
74983   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
74984   Expr *pWhere         /* WHERE clause of the UPDATE statement */
74985 );
74986 #endif /* SQLITE_OMIT_VIRTUALTABLE */
74987
74988 /*
74989 ** The most recently coded instruction was an OP_Column to retrieve the
74990 ** i-th column of table pTab. This routine sets the P4 parameter of the 
74991 ** OP_Column to the default value, if any.
74992 **
74993 ** The default value of a column is specified by a DEFAULT clause in the 
74994 ** column definition. This was either supplied by the user when the table
74995 ** was created, or added later to the table definition by an ALTER TABLE
74996 ** command. If the latter, then the row-records in the table btree on disk
74997 ** may not contain a value for the column and the default value, taken
74998 ** from the P4 parameter of the OP_Column instruction, is returned instead.
74999 ** If the former, then all row-records are guaranteed to include a value
75000 ** for the column and the P4 value is not required.
75001 **
75002 ** Column definitions created by an ALTER TABLE command may only have 
75003 ** literal default values specified: a number, null or a string. (If a more
75004 ** complicated default expression value was provided, it is evaluated 
75005 ** when the ALTER TABLE is executed and one of the literal values written
75006 ** into the sqlite_master table.)
75007 **
75008 ** Therefore, the P4 parameter is only required if the default value for
75009 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
75010 ** function is capable of transforming these types of expressions into
75011 ** sqlite3_value objects.
75012 */
75013 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i){
75014   if( pTab && !pTab->pSelect ){
75015     sqlite3_value *pValue;
75016     u8 enc = ENC(sqlite3VdbeDb(v));
75017     Column *pCol = &pTab->aCol[i];
75018     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
75019     assert( i<pTab->nCol );
75020     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, 
75021                          pCol->affinity, &pValue);
75022     if( pValue ){
75023       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
75024     }
75025   }
75026 }
75027
75028 /*
75029 ** Process an UPDATE statement.
75030 **
75031 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
75032 **          \_______/ \________/     \______/       \________________/
75033 *            onError   pTabList      pChanges             pWhere
75034 */
75035 SQLITE_PRIVATE void sqlite3Update(
75036   Parse *pParse,         /* The parser context */
75037   SrcList *pTabList,     /* The table in which we should change things */
75038   ExprList *pChanges,    /* Things to be changed */
75039   Expr *pWhere,          /* The WHERE clause.  May be null */
75040   int onError            /* How to handle constraint errors */
75041 ){
75042   int i, j;              /* Loop counters */
75043   Table *pTab;           /* The table to be updated */
75044   int addr = 0;          /* VDBE instruction address of the start of the loop */
75045   WhereInfo *pWInfo;     /* Information about the WHERE clause */
75046   Vdbe *v;               /* The virtual database engine */
75047   Index *pIdx;           /* For looping over indices */
75048   int nIdx;              /* Number of indices that need updating */
75049   int iCur;              /* VDBE Cursor number of pTab */
75050   sqlite3 *db;           /* The database structure */
75051   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
75052   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
75053                          ** an expression for the i-th column of the table.
75054                          ** aXRef[i]==-1 if the i-th column is not changed. */
75055   int chngRowid;         /* True if the record number is being changed */
75056   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
75057   int openAll = 0;       /* True if all indices need to be opened */
75058   AuthContext sContext;  /* The authorization context */
75059   NameContext sNC;       /* The name-context to resolve expressions in */
75060   int iDb;               /* Database containing the table being updated */
75061   int j1;                /* Addresses of jump instructions */
75062   int okOnePass;         /* True for one-pass algorithm without the FIFO */
75063
75064 #ifndef SQLITE_OMIT_TRIGGER
75065   int isView;                  /* Trying to update a view */
75066   int triggers_exist = 0;      /* True if any row triggers exist */
75067 #endif
75068   int iBeginAfterTrigger;      /* Address of after trigger program */
75069   int iEndAfterTrigger;        /* Exit of after trigger program */
75070   int iBeginBeforeTrigger;     /* Address of before trigger program */
75071   int iEndBeforeTrigger;       /* Exit of before trigger program */
75072   u32 old_col_mask = 0;        /* Mask of OLD.* columns in use */
75073   u32 new_col_mask = 0;        /* Mask of NEW.* columns in use */
75074
75075   int newIdx      = -1;  /* index of trigger "new" temp table       */
75076   int oldIdx      = -1;  /* index of trigger "old" temp table       */
75077
75078   /* Register Allocations */
75079   int regRowCount = 0;   /* A count of rows changed */
75080   int regOldRowid;       /* The old rowid */
75081   int regNewRowid;       /* The new rowid */
75082   int regData;           /* New data for the row */
75083
75084   sContext.pParse = 0;
75085   db = pParse->db;
75086   if( pParse->nErr || db->mallocFailed ){
75087     goto update_cleanup;
75088   }
75089   assert( pTabList->nSrc==1 );
75090
75091   /* Locate the table which we want to update. 
75092   */
75093   pTab = sqlite3SrcListLookup(pParse, pTabList);
75094   if( pTab==0 ) goto update_cleanup;
75095   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
75096
75097   /* Figure out if we have any triggers and if the table being
75098   ** updated is a view
75099   */
75100 #ifndef SQLITE_OMIT_TRIGGER
75101   triggers_exist = sqlite3TriggersExist(pTab, TK_UPDATE, pChanges);
75102   isView = pTab->pSelect!=0;
75103 #else
75104 # define triggers_exist 0
75105 # define isView 0
75106 #endif
75107 #ifdef SQLITE_OMIT_VIEW
75108 # undef isView
75109 # define isView 0
75110 #endif
75111
75112   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
75113     goto update_cleanup;
75114   }
75115   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
75116     goto update_cleanup;
75117   }
75118   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
75119   if( aXRef==0 ) goto update_cleanup;
75120   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
75121
75122   /* If there are FOR EACH ROW triggers, allocate cursors for the
75123   ** special OLD and NEW tables
75124   */
75125   if( triggers_exist ){
75126     newIdx = pParse->nTab++;
75127     oldIdx = pParse->nTab++;
75128   }
75129
75130   /* Allocate a cursors for the main database table and for all indices.
75131   ** The index cursors might not be used, but if they are used they
75132   ** need to occur right after the database cursor.  So go ahead and
75133   ** allocate enough space, just in case.
75134   */
75135   pTabList->a[0].iCursor = iCur = pParse->nTab++;
75136   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
75137     pParse->nTab++;
75138   }
75139
75140   /* Initialize the name-context */
75141   memset(&sNC, 0, sizeof(sNC));
75142   sNC.pParse = pParse;
75143   sNC.pSrcList = pTabList;
75144
75145   /* Resolve the column names in all the expressions of the
75146   ** of the UPDATE statement.  Also find the column index
75147   ** for each column to be updated in the pChanges array.  For each
75148   ** column to be updated, make sure we have authorization to change
75149   ** that column.
75150   */
75151   chngRowid = 0;
75152   for(i=0; i<pChanges->nExpr; i++){
75153     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
75154       goto update_cleanup;
75155     }
75156     for(j=0; j<pTab->nCol; j++){
75157       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
75158         if( j==pTab->iPKey ){
75159           chngRowid = 1;
75160           pRowidExpr = pChanges->a[i].pExpr;
75161         }
75162         aXRef[j] = i;
75163         break;
75164       }
75165     }
75166     if( j>=pTab->nCol ){
75167       if( sqlite3IsRowid(pChanges->a[i].zName) ){
75168         chngRowid = 1;
75169         pRowidExpr = pChanges->a[i].pExpr;
75170       }else{
75171         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
75172         goto update_cleanup;
75173       }
75174     }
75175 #ifndef SQLITE_OMIT_AUTHORIZATION
75176     {
75177       int rc;
75178       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
75179                            pTab->aCol[j].zName, db->aDb[iDb].zName);
75180       if( rc==SQLITE_DENY ){
75181         goto update_cleanup;
75182       }else if( rc==SQLITE_IGNORE ){
75183         aXRef[j] = -1;
75184       }
75185     }
75186 #endif
75187   }
75188
75189   /* Allocate memory for the array aRegIdx[].  There is one entry in the
75190   ** array for each index associated with table being updated.  Fill in
75191   ** the value with a register number for indices that are to be used
75192   ** and with zero for unused indices.
75193   */
75194   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
75195   if( nIdx>0 ){
75196     aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
75197     if( aRegIdx==0 ) goto update_cleanup;
75198   }
75199   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
75200     int reg;
75201     if( chngRowid ){
75202       reg = ++pParse->nMem;
75203     }else{
75204       reg = 0;
75205       for(i=0; i<pIdx->nColumn; i++){
75206         if( aXRef[pIdx->aiColumn[i]]>=0 ){
75207           reg = ++pParse->nMem;
75208           break;
75209         }
75210       }
75211     }
75212     aRegIdx[j] = reg;
75213   }
75214
75215   /* Allocate a block of register used to store the change record
75216   ** sent to sqlite3GenerateConstraintChecks().  There are either
75217   ** one or two registers for holding the rowid.  One rowid register
75218   ** is used if chngRowid is false and two are used if chngRowid is
75219   ** true.  Following these are pTab->nCol register holding column
75220   ** data.
75221   */
75222   regOldRowid = regNewRowid = pParse->nMem + 1;
75223   pParse->nMem += pTab->nCol + 1;
75224   if( chngRowid ){
75225     regNewRowid++;
75226     pParse->nMem++;
75227   }
75228   regData = regNewRowid+1;
75229  
75230
75231   /* Begin generating code.
75232   */
75233   v = sqlite3GetVdbe(pParse);
75234   if( v==0 ) goto update_cleanup;
75235   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
75236   sqlite3BeginWriteOperation(pParse, 1, iDb);
75237
75238 #ifndef SQLITE_OMIT_VIRTUALTABLE
75239   /* Virtual tables must be handled separately */
75240   if( IsVirtual(pTab) ){
75241     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
75242                        pWhere);
75243     pWhere = 0;
75244     pTabList = 0;
75245     goto update_cleanup;
75246   }
75247 #endif
75248
75249   /* Start the view context
75250   */
75251   if( isView ){
75252     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
75253   }
75254
75255   /* Generate the code for triggers.
75256   */
75257   if( triggers_exist ){
75258     int iGoto;
75259
75260     /* Create pseudo-tables for NEW and OLD
75261     */
75262     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
75263     sqlite3VdbeAddOp2(v, OP_OpenPseudo, oldIdx, 0);
75264     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
75265     sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0);
75266
75267     iGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
75268     addr = sqlite3VdbeMakeLabel(v);
75269     iBeginBeforeTrigger = sqlite3VdbeCurrentAddr(v);
75270     if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_BEFORE, pTab,
75271           newIdx, oldIdx, onError, addr, &old_col_mask, &new_col_mask) ){
75272       goto update_cleanup;
75273     }
75274     iEndBeforeTrigger = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
75275     iBeginAfterTrigger = sqlite3VdbeCurrentAddr(v);
75276     if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_AFTER, pTab, 
75277           newIdx, oldIdx, onError, addr, &old_col_mask, &new_col_mask) ){
75278       goto update_cleanup;
75279     }
75280     iEndAfterTrigger = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
75281     sqlite3VdbeJumpHere(v, iGoto);
75282   }
75283
75284   /* If we are trying to update a view, realize that view into
75285   ** a ephemeral table.
75286   */
75287 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
75288   if( isView ){
75289     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
75290   }
75291 #endif
75292
75293   /* Resolve the column names in all the expressions in the
75294   ** WHERE clause.
75295   */
75296   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
75297     goto update_cleanup;
75298   }
75299
75300   /* Begin the database scan
75301   */
75302   sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
75303   pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0,
75304                              WHERE_ONEPASS_DESIRED);
75305   if( pWInfo==0 ) goto update_cleanup;
75306   okOnePass = pWInfo->okOnePass;
75307
75308   /* Remember the rowid of every item to be updated.
75309   */
75310   sqlite3VdbeAddOp2(v, IsVirtual(pTab)?OP_VRowid:OP_Rowid, iCur, regOldRowid);
75311   if( !okOnePass ) sqlite3VdbeAddOp2(v, OP_FifoWrite, regOldRowid, 0);
75312
75313   /* End the database scan loop.
75314   */
75315   sqlite3WhereEnd(pWInfo);
75316
75317   /* Initialize the count of updated rows
75318   */
75319   if( db->flags & SQLITE_CountRows && !pParse->trigStack ){
75320     regRowCount = ++pParse->nMem;
75321     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
75322   }
75323
75324   if( !isView && !IsVirtual(pTab) ){
75325     /* 
75326     ** Open every index that needs updating.  Note that if any
75327     ** index could potentially invoke a REPLACE conflict resolution 
75328     ** action, then we need to open all indices because we might need
75329     ** to be deleting some records.
75330     */
75331     if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); 
75332     if( onError==OE_Replace ){
75333       openAll = 1;
75334     }else{
75335       openAll = 0;
75336       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
75337         if( pIdx->onError==OE_Replace ){
75338           openAll = 1;
75339           break;
75340         }
75341       }
75342     }
75343     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
75344       if( openAll || aRegIdx[i]>0 ){
75345         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
75346         sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
75347                        (char*)pKey, P4_KEYINFO_HANDOFF);
75348         assert( pParse->nTab>iCur+i+1 );
75349       }
75350     }
75351   }
75352   
75353   /* Jump back to this point if a trigger encounters an IGNORE constraint. */
75354   if( triggers_exist ){
75355     sqlite3VdbeResolveLabel(v, addr);
75356   }
75357
75358   /* Top of the update loop */
75359   if( okOnePass ){
75360     int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
75361     addr = sqlite3VdbeAddOp0(v, OP_Goto);
75362     sqlite3VdbeJumpHere(v, a1);
75363   }else{
75364     addr = sqlite3VdbeAddOp2(v, OP_FifoRead, regOldRowid, 0);
75365   }
75366
75367   if( triggers_exist ){
75368     int regRowid;
75369     int regRow;
75370     int regCols;
75371
75372     /* Make cursor iCur point to the record that is being updated.
75373     */
75374     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
75375
75376     /* Generate the OLD table
75377     */
75378     regRowid = sqlite3GetTempReg(pParse);
75379     regRow = sqlite3GetTempReg(pParse);
75380     sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regRowid);
75381     if( !old_col_mask ){
75382       sqlite3VdbeAddOp2(v, OP_Null, 0, regRow);
75383     }else{
75384       sqlite3VdbeAddOp2(v, OP_RowData, iCur, regRow);
75385     }
75386     sqlite3VdbeAddOp3(v, OP_Insert, oldIdx, regRow, regRowid);
75387
75388     /* Generate the NEW table
75389     */
75390     if( chngRowid ){
75391       sqlite3ExprCodeAndCache(pParse, pRowidExpr, regRowid);
75392       sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
75393     }else{
75394       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regRowid);
75395     }
75396     regCols = sqlite3GetTempRange(pParse, pTab->nCol);
75397     for(i=0; i<pTab->nCol; i++){
75398       if( i==pTab->iPKey ){
75399         sqlite3VdbeAddOp2(v, OP_Null, 0, regCols+i);
75400         continue;
75401       }
75402       j = aXRef[i];
75403       if( new_col_mask&((u32)1<<i) || new_col_mask==0xffffffff ){
75404         if( j<0 ){
75405           sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regCols+i);
75406           sqlite3ColumnDefault(v, pTab, i);
75407         }else{
75408           sqlite3ExprCodeAndCache(pParse, pChanges->a[j].pExpr, regCols+i);
75409         }
75410       }else{
75411         sqlite3VdbeAddOp2(v, OP_Null, 0, regCols+i);
75412       }
75413     }
75414     sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRow);
75415     if( !isView ){
75416       sqlite3TableAffinityStr(v, pTab);
75417       sqlite3ExprCacheAffinityChange(pParse, regCols, pTab->nCol);
75418     }
75419     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol);
75420     /* if( pParse->nErr ) goto update_cleanup; */
75421     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRow, regRowid);
75422     sqlite3ReleaseTempReg(pParse, regRowid);
75423     sqlite3ReleaseTempReg(pParse, regRow);
75424
75425     sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginBeforeTrigger);
75426     sqlite3VdbeJumpHere(v, iEndBeforeTrigger);
75427   }
75428
75429   if( !isView && !IsVirtual(pTab) ){
75430     /* Loop over every record that needs updating.  We have to load
75431     ** the old data for each record to be updated because some columns
75432     ** might not change and we will need to copy the old value.
75433     ** Also, the old data is needed to delete the old index entries.
75434     ** So make the cursor point at the old record.
75435     */
75436     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
75437
75438     /* If the record number will change, push the record number as it
75439     ** will be after the update. (The old record number is currently
75440     ** on top of the stack.)
75441     */
75442     if( chngRowid ){
75443       sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
75444       sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
75445     }
75446
75447     /* Compute new data for this record.  
75448     */
75449     for(i=0; i<pTab->nCol; i++){
75450       if( i==pTab->iPKey ){
75451         sqlite3VdbeAddOp2(v, OP_Null, 0, regData+i);
75452         continue;
75453       }
75454       j = aXRef[i];
75455       if( j<0 ){
75456         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regData+i);
75457         sqlite3ColumnDefault(v, pTab, i);
75458       }else{
75459         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regData+i);
75460       }
75461     }
75462
75463     /* Do constraint checks
75464     */
75465     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
75466                                     aRegIdx, chngRowid, 1,
75467                                     onError, addr);
75468
75469     /* Delete the old indices for the current record.
75470     */
75471     j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
75472     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
75473
75474     /* If changing the record number, delete the old record.
75475     */
75476     if( chngRowid ){
75477       sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
75478     }
75479     sqlite3VdbeJumpHere(v, j1);
75480
75481     /* Create the new index entries and the new record.
75482     */
75483     sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, 
75484                              aRegIdx, 1, -1, 0);
75485   }
75486
75487   /* Increment the row counter 
75488   */
75489   if( db->flags & SQLITE_CountRows && !pParse->trigStack){
75490     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
75491   }
75492
75493   /* If there are triggers, close all the cursors after each iteration
75494   ** through the loop.  The fire the after triggers.
75495   */
75496   if( triggers_exist ){
75497     sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginAfterTrigger);
75498     sqlite3VdbeJumpHere(v, iEndAfterTrigger);
75499   }
75500
75501   /* Repeat the above with the next record to be updated, until
75502   ** all record selected by the WHERE clause have been updated.
75503   */
75504   sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
75505   sqlite3VdbeJumpHere(v, addr);
75506
75507   /* Close all tables */
75508   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
75509     if( openAll || aRegIdx[i]>0 ){
75510       sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
75511     }
75512   }
75513   sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
75514   if( triggers_exist ){
75515     sqlite3VdbeAddOp2(v, OP_Close, newIdx, 0);
75516     sqlite3VdbeAddOp2(v, OP_Close, oldIdx, 0);
75517   }
75518
75519   /*
75520   ** Return the number of rows that were changed. If this routine is 
75521   ** generating code because of a call to sqlite3NestedParse(), do not
75522   ** invoke the callback function.
75523   */
75524   if( db->flags & SQLITE_CountRows && !pParse->trigStack && pParse->nested==0 ){
75525     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
75526     sqlite3VdbeSetNumCols(v, 1);
75527     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
75528   }
75529
75530 update_cleanup:
75531   sqlite3AuthContextPop(&sContext);
75532   sqlite3DbFree(db, aRegIdx);
75533   sqlite3DbFree(db, aXRef);
75534   sqlite3SrcListDelete(db, pTabList);
75535   sqlite3ExprListDelete(db, pChanges);
75536   sqlite3ExprDelete(db, pWhere);
75537   return;
75538 }
75539
75540 #ifndef SQLITE_OMIT_VIRTUALTABLE
75541 /*
75542 ** Generate code for an UPDATE of a virtual table.
75543 **
75544 ** The strategy is that we create an ephemerial table that contains
75545 ** for each row to be changed:
75546 **
75547 **   (A)  The original rowid of that row.
75548 **   (B)  The revised rowid for the row. (note1)
75549 **   (C)  The content of every column in the row.
75550 **
75551 ** Then we loop over this ephemeral table and for each row in
75552 ** the ephermeral table call VUpdate.
75553 **
75554 ** When finished, drop the ephemeral table.
75555 **
75556 ** (note1) Actually, if we know in advance that (A) is always the same
75557 ** as (B) we only store (A), then duplicate (A) when pulling
75558 ** it out of the ephemeral table before calling VUpdate.
75559 */
75560 static void updateVirtualTable(
75561   Parse *pParse,       /* The parsing context */
75562   SrcList *pSrc,       /* The virtual table to be modified */
75563   Table *pTab,         /* The virtual table */
75564   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
75565   Expr *pRowid,        /* Expression used to recompute the rowid */
75566   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
75567   Expr *pWhere         /* WHERE clause of the UPDATE statement */
75568 ){
75569   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
75570   ExprList *pEList = 0;     /* The result set of the SELECT statement */
75571   Select *pSelect = 0;      /* The SELECT statement */
75572   Expr *pExpr;              /* Temporary expression */
75573   int ephemTab;             /* Table holding the result of the SELECT */
75574   int i;                    /* Loop counter */
75575   int addr;                 /* Address of top of loop */
75576   int iReg;                 /* First register in set passed to OP_VUpdate */
75577   sqlite3 *db = pParse->db; /* Database connection */
75578   const char *pVtab = (const char*)pTab->pVtab;
75579   SelectDest dest;
75580
75581   /* Construct the SELECT statement that will find the new values for
75582   ** all updated rows. 
75583   */
75584   pEList = sqlite3ExprListAppend(pParse, 0, 
75585                                  sqlite3CreateIdExpr(pParse, "_rowid_"), 0);
75586   if( pRowid ){
75587     pEList = sqlite3ExprListAppend(pParse, pEList,
75588                                    sqlite3ExprDup(db, pRowid), 0);
75589   }
75590   assert( pTab->iPKey<0 );
75591   for(i=0; i<pTab->nCol; i++){
75592     if( aXRef[i]>=0 ){
75593       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr);
75594     }else{
75595       pExpr = sqlite3CreateIdExpr(pParse, pTab->aCol[i].zName);
75596     }
75597     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr, 0);
75598   }
75599   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
75600   
75601   /* Create the ephemeral table into which the update results will
75602   ** be stored.
75603   */
75604   assert( v );
75605   ephemTab = pParse->nTab++;
75606   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
75607
75608   /* fill the ephemeral table 
75609   */
75610   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
75611   sqlite3Select(pParse, pSelect, &dest);
75612
75613   /* Generate code to scan the ephemeral table and call VUpdate. */
75614   iReg = ++pParse->nMem;
75615   pParse->nMem += pTab->nCol+1;
75616   sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
75617   addr = sqlite3VdbeCurrentAddr(v);
75618   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
75619   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
75620   for(i=0; i<pTab->nCol; i++){
75621     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
75622   }
75623   sqlite3VtabMakeWritable(pParse, pTab);
75624   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVtab, P4_VTAB);
75625   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr);
75626   sqlite3VdbeJumpHere(v, addr-1);
75627   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
75628
75629   /* Cleanup */
75630   sqlite3SelectDelete(db, pSelect);  
75631 }
75632 #endif /* SQLITE_OMIT_VIRTUALTABLE */
75633
75634 /* Make sure "isView" gets undefined in case this file becomes part of
75635 ** the amalgamation - so that subsequent files do not see isView as a
75636 ** macro. */
75637 #undef isView
75638
75639 /************** End of update.c **********************************************/
75640 /************** Begin file vacuum.c ******************************************/
75641 /*
75642 ** 2003 April 6
75643 **
75644 ** The author disclaims copyright to this source code.  In place of
75645 ** a legal notice, here is a blessing:
75646 **
75647 **    May you do good and not evil.
75648 **    May you find forgiveness for yourself and forgive others.
75649 **    May you share freely, never taking more than you give.
75650 **
75651 *************************************************************************
75652 ** This file contains code used to implement the VACUUM command.
75653 **
75654 ** Most of the code in this file may be omitted by defining the
75655 ** SQLITE_OMIT_VACUUM macro.
75656 **
75657 ** $Id: vacuum.c,v 1.84 2008/11/17 19:18:55 danielk1977 Exp $
75658 */
75659
75660 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
75661 /*
75662 ** Execute zSql on database db. Return an error code.
75663 */
75664 static int execSql(sqlite3 *db, const char *zSql){
75665   sqlite3_stmt *pStmt;
75666   if( !zSql ){
75667     return SQLITE_NOMEM;
75668   }
75669   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
75670     return sqlite3_errcode(db);
75671   }
75672   while( SQLITE_ROW==sqlite3_step(pStmt) ){}
75673   return sqlite3_finalize(pStmt);
75674 }
75675
75676 /*
75677 ** Execute zSql on database db. The statement returns exactly
75678 ** one column. Execute this as SQL on the same database.
75679 */
75680 static int execExecSql(sqlite3 *db, const char *zSql){
75681   sqlite3_stmt *pStmt;
75682   int rc;
75683
75684   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
75685   if( rc!=SQLITE_OK ) return rc;
75686
75687   while( SQLITE_ROW==sqlite3_step(pStmt) ){
75688     rc = execSql(db, (char*)sqlite3_column_text(pStmt, 0));
75689     if( rc!=SQLITE_OK ){
75690       sqlite3_finalize(pStmt);
75691       return rc;
75692     }
75693   }
75694
75695   return sqlite3_finalize(pStmt);
75696 }
75697
75698 /*
75699 ** The non-standard VACUUM command is used to clean up the database,
75700 ** collapse free space, etc.  It is modelled after the VACUUM command
75701 ** in PostgreSQL.
75702 **
75703 ** In version 1.0.x of SQLite, the VACUUM command would call
75704 ** gdbm_reorganize() on all the database tables.  But beginning
75705 ** with 2.0.0, SQLite no longer uses GDBM so this command has
75706 ** become a no-op.
75707 */
75708 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
75709   Vdbe *v = sqlite3GetVdbe(pParse);
75710   if( v ){
75711     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
75712   }
75713   return;
75714 }
75715
75716 /*
75717 ** This routine implements the OP_Vacuum opcode of the VDBE.
75718 */
75719 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
75720   int rc = SQLITE_OK;     /* Return code from service routines */
75721   Btree *pMain;           /* The database being vacuumed */
75722   Pager *pMainPager;      /* Pager for database being vacuumed */
75723   Btree *pTemp;           /* The temporary database we vacuum into */
75724   char *zSql = 0;         /* SQL statements */
75725   int saved_flags;        /* Saved value of the db->flags */
75726   int saved_nChange;      /* Saved value of db->nChange */
75727   int saved_nTotalChange; /* Saved value of db->nTotalChange */
75728   Db *pDb = 0;            /* Database to detach at end of vacuum */
75729   int isMemDb;            /* True is vacuuming a :memory: database */
75730   int nRes;
75731
75732   /* Save the current value of the write-schema flag before setting it. */
75733   saved_flags = db->flags;
75734   saved_nChange = db->nChange;
75735   saved_nTotalChange = db->nTotalChange;
75736   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
75737
75738   if( !db->autoCommit ){
75739     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
75740     rc = SQLITE_ERROR;
75741     goto end_of_vacuum;
75742   }
75743   pMain = db->aDb[0].pBt;
75744   pMainPager = sqlite3BtreePager(pMain);
75745   isMemDb = sqlite3PagerFile(pMainPager)->pMethods==0;
75746
75747   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
75748   ** can be set to 'off' for this file, as it is not recovered if a crash
75749   ** occurs anyway. The integrity of the database is maintained by a
75750   ** (possibly synchronous) transaction opened on the main database before
75751   ** sqlite3BtreeCopyFile() is called.
75752   **
75753   ** An optimisation would be to use a non-journaled pager.
75754   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
75755   ** that actually made the VACUUM run slower.  Very little journalling
75756   ** actually occurs when doing a vacuum since the vacuum_db is initially
75757   ** empty.  Only the journal header is written.  Apparently it takes more
75758   ** time to parse and run the PRAGMA to turn journalling off than it does
75759   ** to write the journal header file.
75760   */
75761   zSql = "ATTACH '' AS vacuum_db;";
75762   rc = execSql(db, zSql);
75763   if( rc!=SQLITE_OK ) goto end_of_vacuum;
75764   pDb = &db->aDb[db->nDb-1];
75765   assert( strcmp(db->aDb[db->nDb-1].zName,"vacuum_db")==0 );
75766   pTemp = db->aDb[db->nDb-1].pBt;
75767
75768   nRes = sqlite3BtreeGetReserve(pMain);
75769
75770   /* A VACUUM cannot change the pagesize of an encrypted database. */
75771 #ifdef SQLITE_HAS_CODEC
75772   if( db->nextPagesize ){
75773     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
75774     int nKey;
75775     char *zKey;
75776     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
75777     if( nKey ) db->nextPagesize = 0;
75778   }
75779 #endif
75780
75781   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes)
75782    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes))
75783    || db->mallocFailed 
75784   ){
75785     rc = SQLITE_NOMEM;
75786     goto end_of_vacuum;
75787   }
75788   rc = execSql(db, "PRAGMA vacuum_db.synchronous=OFF");
75789   if( rc!=SQLITE_OK ){
75790     goto end_of_vacuum;
75791   }
75792
75793 #ifndef SQLITE_OMIT_AUTOVACUUM
75794   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
75795                                            sqlite3BtreeGetAutoVacuum(pMain));
75796 #endif
75797
75798   /* Begin a transaction */
75799   rc = execSql(db, "BEGIN EXCLUSIVE;");
75800   if( rc!=SQLITE_OK ) goto end_of_vacuum;
75801
75802   /* Query the schema of the main database. Create a mirror schema
75803   ** in the temporary database.
75804   */
75805   rc = execExecSql(db, 
75806       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
75807       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
75808       "   AND rootpage>0"
75809   );
75810   if( rc!=SQLITE_OK ) goto end_of_vacuum;
75811   rc = execExecSql(db, 
75812       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
75813       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
75814   if( rc!=SQLITE_OK ) goto end_of_vacuum;
75815   rc = execExecSql(db, 
75816       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
75817       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
75818   if( rc!=SQLITE_OK ) goto end_of_vacuum;
75819
75820   /* Loop through the tables in the main database. For each, do
75821   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM xxx;" to copy
75822   ** the contents to the temporary database.
75823   */
75824   rc = execExecSql(db, 
75825       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
75826       "|| ' SELECT * FROM ' || quote(name) || ';'"
75827       "FROM sqlite_master "
75828       "WHERE type = 'table' AND name!='sqlite_sequence' "
75829       "  AND rootpage>0"
75830
75831   );
75832   if( rc!=SQLITE_OK ) goto end_of_vacuum;
75833
75834   /* Copy over the sequence table
75835   */
75836   rc = execExecSql(db, 
75837       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
75838       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
75839   );
75840   if( rc!=SQLITE_OK ) goto end_of_vacuum;
75841   rc = execExecSql(db, 
75842       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
75843       "|| ' SELECT * FROM ' || quote(name) || ';' "
75844       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
75845   );
75846   if( rc!=SQLITE_OK ) goto end_of_vacuum;
75847
75848
75849   /* Copy the triggers, views, and virtual tables from the main database
75850   ** over to the temporary database.  None of these objects has any
75851   ** associated storage, so all we have to do is copy their entries
75852   ** from the SQLITE_MASTER table.
75853   */
75854   rc = execSql(db,
75855       "INSERT INTO vacuum_db.sqlite_master "
75856       "  SELECT type, name, tbl_name, rootpage, sql"
75857       "    FROM sqlite_master"
75858       "   WHERE type='view' OR type='trigger'"
75859       "      OR (type='table' AND rootpage=0)"
75860   );
75861   if( rc ) goto end_of_vacuum;
75862
75863   /* At this point, unless the main db was completely empty, there is now a
75864   ** transaction open on the vacuum database, but not on the main database.
75865   ** Open a btree level transaction on the main database. This allows a
75866   ** call to sqlite3BtreeCopyFile(). The main database btree level
75867   ** transaction is then committed, so the SQL level never knows it was
75868   ** opened for writing. This way, the SQL transaction used to create the
75869   ** temporary database never needs to be committed.
75870   */
75871   if( rc==SQLITE_OK ){
75872     u32 meta;
75873     int i;
75874
75875     /* This array determines which meta meta values are preserved in the
75876     ** vacuum.  Even entries are the meta value number and odd entries
75877     ** are an increment to apply to the meta value after the vacuum.
75878     ** The increment is used to increase the schema cookie so that other
75879     ** connections to the same database will know to reread the schema.
75880     */
75881     static const unsigned char aCopy[] = {
75882        1, 1,    /* Add one to the old schema cookie */
75883        3, 0,    /* Preserve the default page cache size */
75884        5, 0,    /* Preserve the default text encoding */
75885        6, 0,    /* Preserve the user version */
75886     };
75887
75888     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
75889     assert( 1==sqlite3BtreeIsInTrans(pMain) );
75890
75891     /* Copy Btree meta values */
75892     for(i=0; i<ArraySize(aCopy); i+=2){
75893       rc = sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
75894       if( rc!=SQLITE_OK ) goto end_of_vacuum;
75895       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
75896       if( rc!=SQLITE_OK ) goto end_of_vacuum;
75897     }
75898
75899     rc = sqlite3BtreeCopyFile(pMain, pTemp);
75900     if( rc!=SQLITE_OK ) goto end_of_vacuum;
75901     rc = sqlite3BtreeCommit(pTemp);
75902     if( rc!=SQLITE_OK ) goto end_of_vacuum;
75903 #ifndef SQLITE_OMIT_AUTOVACUUM
75904     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
75905 #endif
75906     rc = sqlite3BtreeCommit(pMain);
75907   }
75908
75909   if( rc==SQLITE_OK ){
75910     rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes);
75911   }
75912
75913 end_of_vacuum:
75914   /* Restore the original value of db->flags */
75915   db->flags = saved_flags;
75916   db->nChange = saved_nChange;
75917   db->nTotalChange = saved_nTotalChange;
75918
75919   /* Currently there is an SQL level transaction open on the vacuum
75920   ** database. No locks are held on any other files (since the main file
75921   ** was committed at the btree level). So it safe to end the transaction
75922   ** by manually setting the autoCommit flag to true and detaching the
75923   ** vacuum database. The vacuum_db journal file is deleted when the pager
75924   ** is closed by the DETACH.
75925   */
75926   db->autoCommit = 1;
75927
75928   if( pDb ){
75929     sqlite3BtreeClose(pDb->pBt);
75930     pDb->pBt = 0;
75931     pDb->pSchema = 0;
75932   }
75933
75934   sqlite3ResetInternalSchema(db, 0);
75935
75936   return rc;
75937 }
75938 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
75939
75940 /************** End of vacuum.c **********************************************/
75941 /************** Begin file vtab.c ********************************************/
75942 /*
75943 ** 2006 June 10
75944 **
75945 ** The author disclaims copyright to this source code.  In place of
75946 ** a legal notice, here is a blessing:
75947 **
75948 **    May you do good and not evil.
75949 **    May you find forgiveness for yourself and forgive others.
75950 **    May you share freely, never taking more than you give.
75951 **
75952 *************************************************************************
75953 ** This file contains code used to help implement virtual tables.
75954 **
75955 ** $Id: vtab.c,v 1.78 2008/11/13 19:12:36 danielk1977 Exp $
75956 */
75957 #ifndef SQLITE_OMIT_VIRTUALTABLE
75958
75959 static int createModule(
75960   sqlite3 *db,                    /* Database in which module is registered */
75961   const char *zName,              /* Name assigned to this module */
75962   const sqlite3_module *pModule,  /* The definition of the module */
75963   void *pAux,                     /* Context pointer for xCreate/xConnect */
75964   void (*xDestroy)(void *)        /* Module destructor function */
75965 ) {
75966   int rc, nName;
75967   Module *pMod;
75968
75969   sqlite3_mutex_enter(db->mutex);
75970   nName = strlen(zName);
75971   pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
75972   if( pMod ){
75973     Module *pDel;
75974     char *zCopy = (char *)(&pMod[1]);
75975     memcpy(zCopy, zName, nName+1);
75976     pMod->zName = zCopy;
75977     pMod->pModule = pModule;
75978     pMod->pAux = pAux;
75979     pMod->xDestroy = xDestroy;
75980     pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
75981     if( pDel && pDel->xDestroy ){
75982       pDel->xDestroy(pDel->pAux);
75983     }
75984     sqlite3DbFree(db, pDel);
75985     if( pDel==pMod ){
75986       db->mallocFailed = 1;
75987     }
75988     sqlite3ResetInternalSchema(db, 0);
75989   }else if( xDestroy ){
75990     xDestroy(pAux);
75991   }
75992   rc = sqlite3ApiExit(db, SQLITE_OK);
75993   sqlite3_mutex_leave(db->mutex);
75994   return rc;
75995 }
75996
75997
75998 /*
75999 ** External API function used to create a new virtual-table module.
76000 */
76001 SQLITE_API int sqlite3_create_module(
76002   sqlite3 *db,                    /* Database in which module is registered */
76003   const char *zName,              /* Name assigned to this module */
76004   const sqlite3_module *pModule,  /* The definition of the module */
76005   void *pAux                      /* Context pointer for xCreate/xConnect */
76006 ){
76007   return createModule(db, zName, pModule, pAux, 0);
76008 }
76009
76010 /*
76011 ** External API function used to create a new virtual-table module.
76012 */
76013 SQLITE_API int sqlite3_create_module_v2(
76014   sqlite3 *db,                    /* Database in which module is registered */
76015   const char *zName,              /* Name assigned to this module */
76016   const sqlite3_module *pModule,  /* The definition of the module */
76017   void *pAux,                     /* Context pointer for xCreate/xConnect */
76018   void (*xDestroy)(void *)        /* Module destructor function */
76019 ){
76020   return createModule(db, zName, pModule, pAux, xDestroy);
76021 }
76022
76023 /*
76024 ** Lock the virtual table so that it cannot be disconnected.
76025 ** Locks nest.  Every lock should have a corresponding unlock.
76026 ** If an unlock is omitted, resources leaks will occur.  
76027 **
76028 ** If a disconnect is attempted while a virtual table is locked,
76029 ** the disconnect is deferred until all locks have been removed.
76030 */
76031 SQLITE_PRIVATE void sqlite3VtabLock(sqlite3_vtab *pVtab){
76032   pVtab->nRef++;
76033 }
76034
76035 /*
76036 ** Unlock a virtual table.  When the last lock is removed,
76037 ** disconnect the virtual table.
76038 */
76039 SQLITE_PRIVATE void sqlite3VtabUnlock(sqlite3 *db, sqlite3_vtab *pVtab){
76040   pVtab->nRef--;
76041   assert(db);
76042   assert( sqlite3SafetyCheckOk(db) );
76043   if( pVtab->nRef==0 ){
76044     if( db->magic==SQLITE_MAGIC_BUSY ){
76045       (void)sqlite3SafetyOff(db);
76046       pVtab->pModule->xDisconnect(pVtab);
76047       (void)sqlite3SafetyOn(db);
76048     } else {
76049       pVtab->pModule->xDisconnect(pVtab);
76050     }
76051   }
76052 }
76053
76054 /*
76055 ** Clear any and all virtual-table information from the Table record.
76056 ** This routine is called, for example, just before deleting the Table
76057 ** record.
76058 */
76059 SQLITE_PRIVATE void sqlite3VtabClear(Table *p){
76060   sqlite3_vtab *pVtab = p->pVtab;
76061   sqlite3 *db = p->db;
76062   if( pVtab ){
76063     assert( p->pMod && p->pMod->pModule );
76064     sqlite3VtabUnlock(db, pVtab);
76065     p->pVtab = 0;
76066   }
76067   if( p->azModuleArg ){
76068     int i;
76069     for(i=0; i<p->nModuleArg; i++){
76070       sqlite3DbFree(db, p->azModuleArg[i]);
76071     }
76072     sqlite3DbFree(db, p->azModuleArg);
76073   }
76074 }
76075
76076 /*
76077 ** Add a new module argument to pTable->azModuleArg[].
76078 ** The string is not copied - the pointer is stored.  The
76079 ** string will be freed automatically when the table is
76080 ** deleted.
76081 */
76082 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
76083   int i = pTable->nModuleArg++;
76084   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
76085   char **azModuleArg;
76086   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
76087   if( azModuleArg==0 ){
76088     int j;
76089     for(j=0; j<i; j++){
76090       sqlite3DbFree(db, pTable->azModuleArg[j]);
76091     }
76092     sqlite3DbFree(db, zArg);
76093     sqlite3DbFree(db, pTable->azModuleArg);
76094     pTable->nModuleArg = 0;
76095   }else{
76096     azModuleArg[i] = zArg;
76097     azModuleArg[i+1] = 0;
76098   }
76099   pTable->azModuleArg = azModuleArg;
76100 }
76101
76102 /*
76103 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
76104 ** statement.  The module name has been parsed, but the optional list
76105 ** of parameters that follow the module name are still pending.
76106 */
76107 SQLITE_PRIVATE void sqlite3VtabBeginParse(
76108   Parse *pParse,        /* Parsing context */
76109   Token *pName1,        /* Name of new table, or database name */
76110   Token *pName2,        /* Name of new table or NULL */
76111   Token *pModuleName    /* Name of the module for the virtual table */
76112 ){
76113   int iDb;              /* The database the table is being created in */
76114   Table *pTable;        /* The new virtual table */
76115   sqlite3 *db;          /* Database connection */
76116
76117   if( pParse->db->flags & SQLITE_SharedCache ){
76118     sqlite3ErrorMsg(pParse, "Cannot use virtual tables in shared-cache mode");
76119     return;
76120   }
76121
76122   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
76123   pTable = pParse->pNewTable;
76124   if( pTable==0 || pParse->nErr ) return;
76125   assert( 0==pTable->pIndex );
76126
76127   db = pParse->db;
76128   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
76129   assert( iDb>=0 );
76130
76131   pTable->tabFlags |= TF_Virtual;
76132   pTable->nModuleArg = 0;
76133   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
76134   addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
76135   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
76136   pParse->sNameToken.n = pModuleName->z + pModuleName->n - pName1->z;
76137
76138 #ifndef SQLITE_OMIT_AUTHORIZATION
76139   /* Creating a virtual table invokes the authorization callback twice.
76140   ** The first invocation, to obtain permission to INSERT a row into the
76141   ** sqlite_master table, has already been made by sqlite3StartTable().
76142   ** The second call, to obtain permission to create the table, is made now.
76143   */
76144   if( pTable->azModuleArg ){
76145     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
76146             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
76147   }
76148 #endif
76149 }
76150
76151 /*
76152 ** This routine takes the module argument that has been accumulating
76153 ** in pParse->zArg[] and appends it to the list of arguments on the
76154 ** virtual table currently under construction in pParse->pTable.
76155 */
76156 static void addArgumentToVtab(Parse *pParse){
76157   if( pParse->sArg.z && pParse->pNewTable ){
76158     const char *z = (const char*)pParse->sArg.z;
76159     int n = pParse->sArg.n;
76160     sqlite3 *db = pParse->db;
76161     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
76162   }
76163 }
76164
76165 /*
76166 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
76167 ** has been completely parsed.
76168 */
76169 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
76170   Table *pTab;        /* The table being constructed */
76171   sqlite3 *db;        /* The database connection */
76172   char *zModule;      /* The module name of the table: USING modulename */
76173   Module *pMod = 0;
76174
76175   addArgumentToVtab(pParse);
76176   pParse->sArg.z = 0;
76177
76178   /* Lookup the module name. */
76179   pTab = pParse->pNewTable;
76180   if( pTab==0 ) return;
76181   db = pParse->db;
76182   if( pTab->nModuleArg<1 ) return;
76183   zModule = pTab->azModuleArg[0];
76184   pMod = (Module *)sqlite3HashFind(&db->aModule, zModule, strlen(zModule));
76185   pTab->pMod = pMod;
76186   
76187   /* If the CREATE VIRTUAL TABLE statement is being entered for the
76188   ** first time (in other words if the virtual table is actually being
76189   ** created now instead of just being read out of sqlite_master) then
76190   ** do additional initialization work and store the statement text
76191   ** in the sqlite_master table.
76192   */
76193   if( !db->init.busy ){
76194     char *zStmt;
76195     char *zWhere;
76196     int iDb;
76197     Vdbe *v;
76198
76199     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
76200     if( pEnd ){
76201       pParse->sNameToken.n = pEnd->z - pParse->sNameToken.z + pEnd->n;
76202     }
76203     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
76204
76205     /* A slot for the record has already been allocated in the 
76206     ** SQLITE_MASTER table.  We just need to update that slot with all
76207     ** the information we've collected.  
76208     **
76209     ** The VM register number pParse->regRowid holds the rowid of an
76210     ** entry in the sqlite_master table tht was created for this vtab
76211     ** by sqlite3StartTable().
76212     */
76213     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
76214     sqlite3NestedParse(pParse,
76215       "UPDATE %Q.%s "
76216          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
76217        "WHERE rowid=#%d",
76218       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
76219       pTab->zName,
76220       pTab->zName,
76221       zStmt,
76222       pParse->regRowid
76223     );
76224     sqlite3DbFree(db, zStmt);
76225     v = sqlite3GetVdbe(pParse);
76226     sqlite3ChangeCookie(pParse, iDb);
76227
76228     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
76229     zWhere = sqlite3MPrintf(db, "name='%q'", pTab->zName);
76230     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 1, 0, zWhere, P4_DYNAMIC);
76231     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, 
76232                          pTab->zName, strlen(pTab->zName) + 1);
76233   }
76234
76235   /* If we are rereading the sqlite_master table create the in-memory
76236   ** record of the table. If the module has already been registered,
76237   ** also call the xConnect method here.
76238   */
76239   else {
76240     Table *pOld;
76241     Schema *pSchema = pTab->pSchema;
76242     const char *zName = pTab->zName;
76243     int nName = strlen(zName) + 1;
76244     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
76245     if( pOld ){
76246       db->mallocFailed = 1;
76247       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
76248       return;
76249     }
76250     pSchema->db = pParse->db;
76251     pParse->pNewTable = 0;
76252   }
76253 }
76254
76255 /*
76256 ** The parser calls this routine when it sees the first token
76257 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
76258 */
76259 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
76260   addArgumentToVtab(pParse);
76261   pParse->sArg.z = 0;
76262   pParse->sArg.n = 0;
76263 }
76264
76265 /*
76266 ** The parser calls this routine for each token after the first token
76267 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
76268 */
76269 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
76270   Token *pArg = &pParse->sArg;
76271   if( pArg->z==0 ){
76272     pArg->z = p->z;
76273     pArg->n = p->n;
76274   }else{
76275     assert(pArg->z < p->z);
76276     pArg->n = (p->z + p->n - pArg->z);
76277   }
76278 }
76279
76280 /*
76281 ** Invoke a virtual table constructor (either xCreate or xConnect). The
76282 ** pointer to the function to invoke is passed as the fourth parameter
76283 ** to this procedure.
76284 */
76285 static int vtabCallConstructor(
76286   sqlite3 *db, 
76287   Table *pTab,
76288   Module *pMod,
76289   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
76290   char **pzErr
76291 ){
76292   int rc;
76293   int rc2;
76294   sqlite3_vtab *pVtab = 0;
76295   const char *const*azArg = (const char *const*)pTab->azModuleArg;
76296   int nArg = pTab->nModuleArg;
76297   char *zErr = 0;
76298   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
76299
76300   if( !zModuleName ){
76301     return SQLITE_NOMEM;
76302   }
76303
76304   assert( !db->pVTab );
76305   assert( xConstruct );
76306
76307   db->pVTab = pTab;
76308   rc = sqlite3SafetyOff(db);
76309   assert( rc==SQLITE_OK );
76310   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVtab, &zErr);
76311   rc2 = sqlite3SafetyOn(db);
76312   if( rc==SQLITE_OK && pVtab ){
76313     pVtab->pModule = pMod->pModule;
76314     pVtab->nRef = 1;
76315     pTab->pVtab = pVtab;
76316   }
76317
76318   if( SQLITE_OK!=rc ){
76319     if( zErr==0 ){
76320       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
76321     }else {
76322       *pzErr = sqlite3MPrintf(db, "%s", zErr);
76323       sqlite3DbFree(db, zErr);
76324     }
76325   }else if( db->pVTab ){
76326     const char *zFormat = "vtable constructor did not declare schema: %s";
76327     *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
76328     rc = SQLITE_ERROR;
76329   } 
76330   if( rc==SQLITE_OK ){
76331     rc = rc2;
76332   }
76333   db->pVTab = 0;
76334   sqlite3DbFree(db, zModuleName);
76335
76336   /* If everything went according to plan, loop through the columns
76337   ** of the table to see if any of them contain the token "hidden".
76338   ** If so, set the Column.isHidden flag and remove the token from
76339   ** the type string.
76340   */
76341   if( rc==SQLITE_OK ){
76342     int iCol;
76343     for(iCol=0; iCol<pTab->nCol; iCol++){
76344       char *zType = pTab->aCol[iCol].zType;
76345       int nType;
76346       int i = 0;
76347       if( !zType ) continue;
76348       nType = strlen(zType);
76349       if( sqlite3StrNICmp("hidden", zType, 6) || (zType[6] && zType[6]!=' ') ){
76350         for(i=0; i<nType; i++){
76351           if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
76352            && (zType[i+7]=='\0' || zType[i+7]==' ')
76353           ){
76354             i++;
76355             break;
76356           }
76357         }
76358       }
76359       if( i<nType ){
76360         int j;
76361         int nDel = 6 + (zType[i+6] ? 1 : 0);
76362         for(j=i; (j+nDel)<=nType; j++){
76363           zType[j] = zType[j+nDel];
76364         }
76365         if( zType[i]=='\0' && i>0 ){
76366           assert(zType[i-1]==' ');
76367           zType[i-1] = '\0';
76368         }
76369         pTab->aCol[iCol].isHidden = 1;
76370       }
76371     }
76372   }
76373   return rc;
76374 }
76375
76376 /*
76377 ** This function is invoked by the parser to call the xConnect() method
76378 ** of the virtual table pTab. If an error occurs, an error code is returned 
76379 ** and an error left in pParse.
76380 **
76381 ** This call is a no-op if table pTab is not a virtual table.
76382 */
76383 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
76384   Module *pMod;
76385   int rc = SQLITE_OK;
76386
76387   if( !pTab || (pTab->tabFlags & TF_Virtual)==0 || pTab->pVtab ){
76388     return SQLITE_OK;
76389   }
76390
76391   pMod = pTab->pMod;
76392   if( !pMod ){
76393     const char *zModule = pTab->azModuleArg[0];
76394     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
76395     rc = SQLITE_ERROR;
76396   } else {
76397     char *zErr = 0;
76398     sqlite3 *db = pParse->db;
76399     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
76400     if( rc!=SQLITE_OK ){
76401       sqlite3ErrorMsg(pParse, "%s", zErr);
76402     }
76403     sqlite3DbFree(db, zErr);
76404   }
76405
76406   return rc;
76407 }
76408
76409 /*
76410 ** Add the virtual table pVtab to the array sqlite3.aVTrans[].
76411 */
76412 static int addToVTrans(sqlite3 *db, sqlite3_vtab *pVtab){
76413   const int ARRAY_INCR = 5;
76414
76415   /* Grow the sqlite3.aVTrans array if required */
76416   if( (db->nVTrans%ARRAY_INCR)==0 ){
76417     sqlite3_vtab **aVTrans;
76418     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
76419     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
76420     if( !aVTrans ){
76421       return SQLITE_NOMEM;
76422     }
76423     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
76424     db->aVTrans = aVTrans;
76425   }
76426
76427   /* Add pVtab to the end of sqlite3.aVTrans */
76428   db->aVTrans[db->nVTrans++] = pVtab;
76429   sqlite3VtabLock(pVtab);
76430   return SQLITE_OK;
76431 }
76432
76433 /*
76434 ** This function is invoked by the vdbe to call the xCreate method
76435 ** of the virtual table named zTab in database iDb. 
76436 **
76437 ** If an error occurs, *pzErr is set to point an an English language
76438 ** description of the error and an SQLITE_XXX error code is returned.
76439 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
76440 */
76441 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
76442   int rc = SQLITE_OK;
76443   Table *pTab;
76444   Module *pMod;
76445   const char *zModule;
76446
76447   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
76448   assert(pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVtab);
76449   pMod = pTab->pMod;
76450   zModule = pTab->azModuleArg[0];
76451
76452   /* If the module has been registered and includes a Create method, 
76453   ** invoke it now. If the module has not been registered, return an 
76454   ** error. Otherwise, do nothing.
76455   */
76456   if( !pMod ){
76457     *pzErr = sqlite3MPrintf(db, "no such module: %s", zModule);
76458     rc = SQLITE_ERROR;
76459   }else{
76460     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
76461   }
76462
76463   if( rc==SQLITE_OK && pTab->pVtab ){
76464       rc = addToVTrans(db, pTab->pVtab);
76465   }
76466
76467   return rc;
76468 }
76469
76470 /*
76471 ** This function is used to set the schema of a virtual table.  It is only
76472 ** valid to call this function from within the xCreate() or xConnect() of a
76473 ** virtual table module.
76474 */
76475 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
76476   Parse sParse;
76477
76478   int rc = SQLITE_OK;
76479   Table *pTab;
76480   char *zErr = 0;
76481
76482   sqlite3_mutex_enter(db->mutex);
76483   pTab = db->pVTab;
76484   if( !pTab ){
76485     sqlite3Error(db, SQLITE_MISUSE, 0);
76486     sqlite3_mutex_leave(db->mutex);
76487     return SQLITE_MISUSE;
76488   }
76489   assert((pTab->tabFlags & TF_Virtual)!=0 && pTab->nCol==0 && pTab->aCol==0);
76490
76491   memset(&sParse, 0, sizeof(Parse));
76492   sParse.declareVtab = 1;
76493   sParse.db = db;
76494
76495   if( 
76496       SQLITE_OK == sqlite3RunParser(&sParse, zCreateTable, &zErr) && 
76497       sParse.pNewTable && 
76498       !sParse.pNewTable->pSelect && 
76499       (sParse.pNewTable->tabFlags & TF_Virtual)==0
76500   ){
76501     pTab->aCol = sParse.pNewTable->aCol;
76502     pTab->nCol = sParse.pNewTable->nCol;
76503     sParse.pNewTable->nCol = 0;
76504     sParse.pNewTable->aCol = 0;
76505     db->pVTab = 0;
76506   } else {
76507     sqlite3Error(db, SQLITE_ERROR, zErr);
76508     sqlite3DbFree(db, zErr);
76509     rc = SQLITE_ERROR;
76510   }
76511   sParse.declareVtab = 0;
76512
76513   sqlite3_finalize((sqlite3_stmt*)sParse.pVdbe);
76514   sqlite3DeleteTable(sParse.pNewTable);
76515   sParse.pNewTable = 0;
76516
76517   assert( (rc&0xff)==rc );
76518   rc = sqlite3ApiExit(db, rc);
76519   sqlite3_mutex_leave(db->mutex);
76520   return rc;
76521 }
76522
76523 /*
76524 ** This function is invoked by the vdbe to call the xDestroy method
76525 ** of the virtual table named zTab in database iDb. This occurs
76526 ** when a DROP TABLE is mentioned.
76527 **
76528 ** This call is a no-op if zTab is not a virtual table.
76529 */
76530 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab)
76531 {
76532   int rc = SQLITE_OK;
76533   Table *pTab;
76534
76535   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
76536   assert(pTab);
76537   if( pTab->pVtab ){
76538     int (*xDestroy)(sqlite3_vtab *pVTab) = pTab->pMod->pModule->xDestroy;
76539     rc = sqlite3SafetyOff(db);
76540     assert( rc==SQLITE_OK );
76541     if( xDestroy ){
76542       rc = xDestroy(pTab->pVtab);
76543     }
76544     (void)sqlite3SafetyOn(db);
76545     if( rc==SQLITE_OK ){
76546       int i;
76547       for(i=0; i<db->nVTrans; i++){
76548         if( db->aVTrans[i]==pTab->pVtab ){
76549           db->aVTrans[i] = db->aVTrans[--db->nVTrans];
76550           break;
76551         }
76552       }
76553       pTab->pVtab = 0;
76554     }
76555   }
76556
76557   return rc;
76558 }
76559
76560 /*
76561 ** This function invokes either the xRollback or xCommit method
76562 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
76563 ** called is identified by the second argument, "offset", which is
76564 ** the offset of the method to call in the sqlite3_module structure.
76565 **
76566 ** The array is cleared after invoking the callbacks. 
76567 */
76568 static void callFinaliser(sqlite3 *db, int offset){
76569   int i;
76570   if( db->aVTrans ){
76571     for(i=0; i<db->nVTrans && db->aVTrans[i]; i++){
76572       sqlite3_vtab *pVtab = db->aVTrans[i];
76573       int (*x)(sqlite3_vtab *);
76574       x = *(int (**)(sqlite3_vtab *))((char *)pVtab->pModule + offset);
76575       if( x ) x(pVtab);
76576       sqlite3VtabUnlock(db, pVtab);
76577     }
76578     sqlite3DbFree(db, db->aVTrans);
76579     db->nVTrans = 0;
76580     db->aVTrans = 0;
76581   }
76582 }
76583
76584 /*
76585 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
76586 ** array. Return the error code for the first error that occurs, or
76587 ** SQLITE_OK if all xSync operations are successful.
76588 **
76589 ** Set *pzErrmsg to point to a buffer that should be released using 
76590 ** sqlite3DbFree() containing an error message, if one is available.
76591 */
76592 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
76593   int i;
76594   int rc = SQLITE_OK;
76595   int rcsafety;
76596   sqlite3_vtab **aVTrans = db->aVTrans;
76597
76598   rc = sqlite3SafetyOff(db);
76599   db->aVTrans = 0;
76600   for(i=0; rc==SQLITE_OK && i<db->nVTrans && aVTrans[i]; i++){
76601     sqlite3_vtab *pVtab = aVTrans[i];
76602     int (*x)(sqlite3_vtab *);
76603     x = pVtab->pModule->xSync;
76604     if( x ){
76605       rc = x(pVtab);
76606       sqlite3DbFree(db, *pzErrmsg);
76607       *pzErrmsg = pVtab->zErrMsg;
76608       pVtab->zErrMsg = 0;
76609     }
76610   }
76611   db->aVTrans = aVTrans;
76612   rcsafety = sqlite3SafetyOn(db);
76613
76614   if( rc==SQLITE_OK ){
76615     rc = rcsafety;
76616   }
76617   return rc;
76618 }
76619
76620 /*
76621 ** Invoke the xRollback method of all virtual tables in the 
76622 ** sqlite3.aVTrans array. Then clear the array itself.
76623 */
76624 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
76625   callFinaliser(db, offsetof(sqlite3_module,xRollback));
76626   return SQLITE_OK;
76627 }
76628
76629 /*
76630 ** Invoke the xCommit method of all virtual tables in the 
76631 ** sqlite3.aVTrans array. Then clear the array itself.
76632 */
76633 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
76634   callFinaliser(db, offsetof(sqlite3_module,xCommit));
76635   return SQLITE_OK;
76636 }
76637
76638 /*
76639 ** If the virtual table pVtab supports the transaction interface
76640 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
76641 ** not currently open, invoke the xBegin method now.
76642 **
76643 ** If the xBegin call is successful, place the sqlite3_vtab pointer
76644 ** in the sqlite3.aVTrans array.
76645 */
76646 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, sqlite3_vtab *pVtab){
76647   int rc = SQLITE_OK;
76648   const sqlite3_module *pModule;
76649
76650   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
76651   ** than zero, then this function is being called from within a
76652   ** virtual module xSync() callback. It is illegal to write to 
76653   ** virtual module tables in this case, so return SQLITE_LOCKED.
76654   */
76655   if( sqlite3VtabInSync(db) ){
76656     return SQLITE_LOCKED;
76657   }
76658   if( !pVtab ){
76659     return SQLITE_OK;
76660   } 
76661   pModule = pVtab->pModule;
76662
76663   if( pModule->xBegin ){
76664     int i;
76665
76666
76667     /* If pVtab is already in the aVTrans array, return early */
76668     for(i=0; (i<db->nVTrans) && 0!=db->aVTrans[i]; i++){
76669       if( db->aVTrans[i]==pVtab ){
76670         return SQLITE_OK;
76671       }
76672     }
76673
76674     /* Invoke the xBegin method */
76675     rc = pModule->xBegin(pVtab);
76676     if( rc==SQLITE_OK ){
76677       rc = addToVTrans(db, pVtab);
76678     }
76679   }
76680   return rc;
76681 }
76682
76683 /*
76684 ** The first parameter (pDef) is a function implementation.  The
76685 ** second parameter (pExpr) is the first argument to this function.
76686 ** If pExpr is a column in a virtual table, then let the virtual
76687 ** table implementation have an opportunity to overload the function.
76688 **
76689 ** This routine is used to allow virtual table implementations to
76690 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
76691 **
76692 ** Return either the pDef argument (indicating no change) or a 
76693 ** new FuncDef structure that is marked as ephemeral using the
76694 ** SQLITE_FUNC_EPHEM flag.
76695 */
76696 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
76697   sqlite3 *db,    /* Database connection for reporting malloc problems */
76698   FuncDef *pDef,  /* Function to possibly overload */
76699   int nArg,       /* Number of arguments to the function */
76700   Expr *pExpr     /* First argument to the function */
76701 ){
76702   Table *pTab;
76703   sqlite3_vtab *pVtab;
76704   sqlite3_module *pMod;
76705   void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
76706   void *pArg;
76707   FuncDef *pNew;
76708   int rc = 0;
76709   char *zLowerName;
76710   unsigned char *z;
76711
76712
76713   /* Check to see the left operand is a column in a virtual table */
76714   if( pExpr==0 ) return pDef;
76715   if( pExpr->op!=TK_COLUMN ) return pDef;
76716   pTab = pExpr->pTab;
76717   if( pTab==0 ) return pDef;
76718   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
76719   pVtab = pTab->pVtab;
76720   assert( pVtab!=0 );
76721   assert( pVtab->pModule!=0 );
76722   pMod = (sqlite3_module *)pVtab->pModule;
76723   if( pMod->xFindFunction==0 ) return pDef;
76724  
76725   /* Call the xFindFunction method on the virtual table implementation
76726   ** to see if the implementation wants to overload this function 
76727   */
76728   zLowerName = sqlite3DbStrDup(db, pDef->zName);
76729   if( zLowerName ){
76730     for(z=(unsigned char*)zLowerName; *z; z++){
76731       *z = sqlite3UpperToLower[*z];
76732     }
76733     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
76734     sqlite3DbFree(db, zLowerName);
76735     if( pVtab->zErrMsg ){
76736       sqlite3Error(db, rc, "%s", pVtab->zErrMsg);
76737       sqlite3DbFree(db, pVtab->zErrMsg);
76738       pVtab->zErrMsg = 0;
76739     }
76740   }
76741   if( rc==0 ){
76742     return pDef;
76743   }
76744
76745   /* Create a new ephemeral function definition for the overloaded
76746   ** function */
76747   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) + strlen(pDef->zName) );
76748   if( pNew==0 ){
76749     return pDef;
76750   }
76751   *pNew = *pDef;
76752   pNew->zName = (char *)&pNew[1];
76753   memcpy(pNew->zName, pDef->zName, strlen(pDef->zName)+1);
76754   pNew->xFunc = xFunc;
76755   pNew->pUserData = pArg;
76756   pNew->flags |= SQLITE_FUNC_EPHEM;
76757   return pNew;
76758 }
76759
76760 /*
76761 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
76762 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
76763 ** array if it is missing.  If pTab is already in the array, this routine
76764 ** is a no-op.
76765 */
76766 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
76767   int i, n;
76768   assert( IsVirtual(pTab) );
76769   for(i=0; i<pParse->nVtabLock; i++){
76770     if( pTab==pParse->apVtabLock[i] ) return;
76771   }
76772   n = (pParse->nVtabLock+1)*sizeof(pParse->apVtabLock[0]);
76773   pParse->apVtabLock = sqlite3_realloc(pParse->apVtabLock, n);
76774   if( pParse->apVtabLock ){
76775     pParse->apVtabLock[pParse->nVtabLock++] = pTab;
76776   }else{
76777     pParse->db->mallocFailed = 1;
76778   }
76779 }
76780
76781 #endif /* SQLITE_OMIT_VIRTUALTABLE */
76782
76783 /************** End of vtab.c ************************************************/
76784 /************** Begin file where.c *******************************************/
76785 /*
76786 ** 2001 September 15
76787 **
76788 ** The author disclaims copyright to this source code.  In place of
76789 ** a legal notice, here is a blessing:
76790 **
76791 **    May you do good and not evil.
76792 **    May you find forgiveness for yourself and forgive others.
76793 **    May you share freely, never taking more than you give.
76794 **
76795 *************************************************************************
76796 ** This module contains C code that generates VDBE code used to process
76797 ** the WHERE clause of SQL statements.  This module is responsible for
76798 ** generating the code that loops through a table looking for applicable
76799 ** rows.  Indices are selected and used to speed the search when doing
76800 ** so is applicable.  Because this module is responsible for selecting
76801 ** indices, you might also think of this module as the "query optimizer".
76802 **
76803 ** $Id: where.c,v 1.330 2008/11/17 19:18:55 danielk1977 Exp $
76804 */
76805
76806 /*
76807 ** Trace output macros
76808 */
76809 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
76810 SQLITE_PRIVATE int sqlite3WhereTrace = 0;
76811 #endif
76812 #if 0
76813 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
76814 #else
76815 # define WHERETRACE(X)
76816 #endif
76817
76818 /* Forward reference
76819 */
76820 typedef struct WhereClause WhereClause;
76821 typedef struct ExprMaskSet ExprMaskSet;
76822
76823 /*
76824 ** The query generator uses an array of instances of this structure to
76825 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
76826 ** clause subexpression is separated from the others by an AND operator.
76827 **
76828 ** All WhereTerms are collected into a single WhereClause structure.  
76829 ** The following identity holds:
76830 **
76831 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
76832 **
76833 ** When a term is of the form:
76834 **
76835 **              X <op> <expr>
76836 **
76837 ** where X is a column name and <op> is one of certain operators,
76838 ** then WhereTerm.leftCursor and WhereTerm.leftColumn record the
76839 ** cursor number and column number for X.  WhereTerm.operator records
76840 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
76841 ** use of a bitmask encoding for the operator allows us to search
76842 ** quickly for terms that match any of several different operators.
76843 **
76844 ** prereqRight and prereqAll record sets of cursor numbers,
76845 ** but they do so indirectly.  A single ExprMaskSet structure translates
76846 ** cursor number into bits and the translated bit is stored in the prereq
76847 ** fields.  The translation is used in order to maximize the number of
76848 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
76849 ** spread out over the non-negative integers.  For example, the cursor
76850 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The ExprMaskSet
76851 ** translates these sparse cursor numbers into consecutive integers
76852 ** beginning with 0 in order to make the best possible use of the available
76853 ** bits in the Bitmask.  So, in the example above, the cursor numbers
76854 ** would be mapped into integers 0 through 7.
76855 */
76856 typedef struct WhereTerm WhereTerm;
76857 struct WhereTerm {
76858   Expr *pExpr;            /* Pointer to the subexpression */
76859   i16 iParent;            /* Disable pWC->a[iParent] when this term disabled */
76860   i16 leftCursor;         /* Cursor number of X in "X <op> <expr>" */
76861   i16 leftColumn;         /* Column number of X in "X <op> <expr>" */
76862   u16 eOperator;          /* A WO_xx value describing <op> */
76863   u8 flags;               /* Bit flags.  See below */
76864   u8 nChild;              /* Number of children that must disable us */
76865   WhereClause *pWC;       /* The clause this term is part of */
76866   Bitmask prereqRight;    /* Bitmask of tables used by pRight */
76867   Bitmask prereqAll;      /* Bitmask of tables referenced by p */
76868 };
76869
76870 /*
76871 ** Allowed values of WhereTerm.flags
76872 */
76873 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
76874 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
76875 #define TERM_CODED      0x04   /* This term is already coded */
76876 #define TERM_COPIED     0x08   /* Has a child */
76877 #define TERM_OR_OK      0x10   /* Used during OR-clause processing */
76878
76879 /*
76880 ** An instance of the following structure holds all information about a
76881 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
76882 */
76883 struct WhereClause {
76884   Parse *pParse;           /* The parser context */
76885   ExprMaskSet *pMaskSet;   /* Mapping of table indices to bitmasks */
76886   int nTerm;               /* Number of terms */
76887   int nSlot;               /* Number of entries in a[] */
76888   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
76889   WhereTerm aStatic[10];   /* Initial static space for a[] */
76890 };
76891
76892 /*
76893 ** An instance of the following structure keeps track of a mapping
76894 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
76895 **
76896 ** The VDBE cursor numbers are small integers contained in 
76897 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
76898 ** clause, the cursor numbers might not begin with 0 and they might
76899 ** contain gaps in the numbering sequence.  But we want to make maximum
76900 ** use of the bits in our bitmasks.  This structure provides a mapping
76901 ** from the sparse cursor numbers into consecutive integers beginning
76902 ** with 0.
76903 **
76904 ** If ExprMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
76905 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
76906 **
76907 ** For example, if the WHERE clause expression used these VDBE
76908 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  ExprMaskSet structure
76909 ** would map those cursor numbers into bits 0 through 5.
76910 **
76911 ** Note that the mapping is not necessarily ordered.  In the example
76912 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
76913 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
76914 ** does not really matter.  What is important is that sparse cursor
76915 ** numbers all get mapped into bit numbers that begin with 0 and contain
76916 ** no gaps.
76917 */
76918 struct ExprMaskSet {
76919   int n;                        /* Number of assigned cursor values */
76920   int ix[BMS];                  /* Cursor assigned to each bit */
76921 };
76922
76923
76924 /*
76925 ** Bitmasks for the operators that indices are able to exploit.  An
76926 ** OR-ed combination of these values can be used when searching for
76927 ** terms in the where clause.
76928 */
76929 #define WO_IN     1
76930 #define WO_EQ     2
76931 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
76932 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
76933 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
76934 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
76935 #define WO_MATCH  64
76936 #define WO_ISNULL 128
76937
76938 /*
76939 ** Value for flags returned by bestIndex().  
76940 **
76941 ** The least significant byte is reserved as a mask for WO_ values above.
76942 ** The WhereLevel.flags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
76943 ** But if the table is the right table of a left join, WhereLevel.flags
76944 ** is set to WO_IN|WO_EQ.  The WhereLevel.flags field can then be used as
76945 ** the "op" parameter to findTerm when we are resolving equality constraints.
76946 ** ISNULL constraints will then not be used on the right table of a left
76947 ** join.  Tickets #2177 and #2189.
76948 */
76949 #define WHERE_ROWID_EQ     0x000100   /* rowid=EXPR or rowid IN (...) */
76950 #define WHERE_ROWID_RANGE  0x000200   /* rowid<EXPR and/or rowid>EXPR */
76951 #define WHERE_COLUMN_EQ    0x001000   /* x=EXPR or x IN (...) */
76952 #define WHERE_COLUMN_RANGE 0x002000   /* x<EXPR and/or x>EXPR */
76953 #define WHERE_COLUMN_IN    0x004000   /* x IN (...) */
76954 #define WHERE_TOP_LIMIT    0x010000   /* x<EXPR or x<=EXPR constraint */
76955 #define WHERE_BTM_LIMIT    0x020000   /* x>EXPR or x>=EXPR constraint */
76956 #define WHERE_IDX_ONLY     0x080000   /* Use index only - omit table */
76957 #define WHERE_ORDERBY      0x100000   /* Output will appear in correct order */
76958 #define WHERE_REVERSE      0x200000   /* Scan in reverse order */
76959 #define WHERE_UNIQUE       0x400000   /* Selects no more than one row */
76960 #define WHERE_VIRTUALTABLE 0x800000   /* Use virtual-table processing */
76961
76962 /*
76963 ** Initialize a preallocated WhereClause structure.
76964 */
76965 static void whereClauseInit(
76966   WhereClause *pWC,        /* The WhereClause to be initialized */
76967   Parse *pParse,           /* The parsing context */
76968   ExprMaskSet *pMaskSet    /* Mapping from table indices to bitmasks */
76969 ){
76970   pWC->pParse = pParse;
76971   pWC->pMaskSet = pMaskSet;
76972   pWC->nTerm = 0;
76973   pWC->nSlot = ArraySize(pWC->aStatic);
76974   pWC->a = pWC->aStatic;
76975 }
76976
76977 /*
76978 ** Deallocate a WhereClause structure.  The WhereClause structure
76979 ** itself is not freed.  This routine is the inverse of whereClauseInit().
76980 */
76981 static void whereClauseClear(WhereClause *pWC){
76982   int i;
76983   WhereTerm *a;
76984   sqlite3 *db = pWC->pParse->db;
76985   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
76986     if( a->flags & TERM_DYNAMIC ){
76987       sqlite3ExprDelete(db, a->pExpr);
76988     }
76989   }
76990   if( pWC->a!=pWC->aStatic ){
76991     sqlite3DbFree(db, pWC->a);
76992   }
76993 }
76994
76995 /*
76996 ** Add a new entries to the WhereClause structure.  Increase the allocated
76997 ** space as necessary.
76998 **
76999 ** If the flags argument includes TERM_DYNAMIC, then responsibility
77000 ** for freeing the expression p is assumed by the WhereClause object.
77001 **
77002 ** WARNING:  This routine might reallocate the space used to store
77003 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
77004 ** calling this routine.  Such pointers may be reinitialized by referencing
77005 ** the pWC->a[] array.
77006 */
77007 static int whereClauseInsert(WhereClause *pWC, Expr *p, int flags){
77008   WhereTerm *pTerm;
77009   int idx;
77010   if( pWC->nTerm>=pWC->nSlot ){
77011     WhereTerm *pOld = pWC->a;
77012     sqlite3 *db = pWC->pParse->db;
77013     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
77014     if( pWC->a==0 ){
77015       if( flags & TERM_DYNAMIC ){
77016         sqlite3ExprDelete(db, p);
77017       }
77018       pWC->a = pOld;
77019       return 0;
77020     }
77021     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
77022     if( pOld!=pWC->aStatic ){
77023       sqlite3DbFree(db, pOld);
77024     }
77025     pWC->nSlot *= 2;
77026   }
77027   pTerm = &pWC->a[idx = pWC->nTerm];
77028   pWC->nTerm++;
77029   pTerm->pExpr = p;
77030   pTerm->flags = flags;
77031   pTerm->pWC = pWC;
77032   pTerm->iParent = -1;
77033   return idx;
77034 }
77035
77036 /*
77037 ** This routine identifies subexpressions in the WHERE clause where
77038 ** each subexpression is separated by the AND operator or some other
77039 ** operator specified in the op parameter.  The WhereClause structure
77040 ** is filled with pointers to subexpressions.  For example:
77041 **
77042 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
77043 **           \________/     \_______________/     \________________/
77044 **            slot[0]            slot[1]               slot[2]
77045 **
77046 ** The original WHERE clause in pExpr is unaltered.  All this routine
77047 ** does is make slot[] entries point to substructure within pExpr.
77048 **
77049 ** In the previous sentence and in the diagram, "slot[]" refers to
77050 ** the WhereClause.a[] array.  This array grows as needed to contain
77051 ** all terms of the WHERE clause.
77052 */
77053 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
77054   if( pExpr==0 ) return;
77055   if( pExpr->op!=op ){
77056     whereClauseInsert(pWC, pExpr, 0);
77057   }else{
77058     whereSplit(pWC, pExpr->pLeft, op);
77059     whereSplit(pWC, pExpr->pRight, op);
77060   }
77061 }
77062
77063 /*
77064 ** Initialize an expression mask set
77065 */
77066 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
77067
77068 /*
77069 ** Return the bitmask for the given cursor number.  Return 0 if
77070 ** iCursor is not in the set.
77071 */
77072 static Bitmask getMask(ExprMaskSet *pMaskSet, int iCursor){
77073   int i;
77074   for(i=0; i<pMaskSet->n; i++){
77075     if( pMaskSet->ix[i]==iCursor ){
77076       return ((Bitmask)1)<<i;
77077     }
77078   }
77079   return 0;
77080 }
77081
77082 /*
77083 ** Create a new mask for cursor iCursor.
77084 **
77085 ** There is one cursor per table in the FROM clause.  The number of
77086 ** tables in the FROM clause is limited by a test early in the
77087 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
77088 ** array will never overflow.
77089 */
77090 static void createMask(ExprMaskSet *pMaskSet, int iCursor){
77091   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
77092   pMaskSet->ix[pMaskSet->n++] = iCursor;
77093 }
77094
77095 /*
77096 ** This routine walks (recursively) an expression tree and generates
77097 ** a bitmask indicating which tables are used in that expression
77098 ** tree.
77099 **
77100 ** In order for this routine to work, the calling function must have
77101 ** previously invoked sqlite3ResolveExprNames() on the expression.  See
77102 ** the header comment on that routine for additional information.
77103 ** The sqlite3ResolveExprNames() routines looks for column names and
77104 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
77105 ** the VDBE cursor number of the table.  This routine just has to
77106 ** translate the cursor numbers into bitmask values and OR all
77107 ** the bitmasks together.
77108 */
77109 static Bitmask exprListTableUsage(ExprMaskSet*, ExprList*);
77110 static Bitmask exprSelectTableUsage(ExprMaskSet*, Select*);
77111 static Bitmask exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
77112   Bitmask mask = 0;
77113   if( p==0 ) return 0;
77114   if( p->op==TK_COLUMN ){
77115     mask = getMask(pMaskSet, p->iTable);
77116     return mask;
77117   }
77118   mask = exprTableUsage(pMaskSet, p->pRight);
77119   mask |= exprTableUsage(pMaskSet, p->pLeft);
77120   mask |= exprListTableUsage(pMaskSet, p->pList);
77121   mask |= exprSelectTableUsage(pMaskSet, p->pSelect);
77122   return mask;
77123 }
77124 static Bitmask exprListTableUsage(ExprMaskSet *pMaskSet, ExprList *pList){
77125   int i;
77126   Bitmask mask = 0;
77127   if( pList ){
77128     for(i=0; i<pList->nExpr; i++){
77129       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
77130     }
77131   }
77132   return mask;
77133 }
77134 static Bitmask exprSelectTableUsage(ExprMaskSet *pMaskSet, Select *pS){
77135   Bitmask mask = 0;
77136   while( pS ){
77137     mask |= exprListTableUsage(pMaskSet, pS->pEList);
77138     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
77139     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
77140     mask |= exprTableUsage(pMaskSet, pS->pWhere);
77141     mask |= exprTableUsage(pMaskSet, pS->pHaving);
77142     pS = pS->pPrior;
77143   }
77144   return mask;
77145 }
77146
77147 /*
77148 ** Return TRUE if the given operator is one of the operators that is
77149 ** allowed for an indexable WHERE clause term.  The allowed operators are
77150 ** "=", "<", ">", "<=", ">=", and "IN".
77151 */
77152 static int allowedOp(int op){
77153   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
77154   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
77155   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
77156   assert( TK_GE==TK_EQ+4 );
77157   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
77158 }
77159
77160 /*
77161 ** Swap two objects of type T.
77162 */
77163 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
77164
77165 /*
77166 ** Commute a comparison operator.  Expressions of the form "X op Y"
77167 ** are converted into "Y op X".
77168 **
77169 ** If a collation sequence is associated with either the left or right
77170 ** side of the comparison, it remains associated with the same side after
77171 ** the commutation. So "Y collate NOCASE op X" becomes 
77172 ** "X collate NOCASE op Y". This is because any collation sequence on
77173 ** the left hand side of a comparison overrides any collation sequence 
77174 ** attached to the right. For the same reason the EP_ExpCollate flag
77175 ** is not commuted.
77176 */
77177 static void exprCommute(Parse *pParse, Expr *pExpr){
77178   u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
77179   u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
77180   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
77181   pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
77182   pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
77183   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
77184   pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
77185   pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
77186   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
77187   if( pExpr->op>=TK_GT ){
77188     assert( TK_LT==TK_GT+2 );
77189     assert( TK_GE==TK_LE+2 );
77190     assert( TK_GT>TK_EQ );
77191     assert( TK_GT<TK_LE );
77192     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
77193     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
77194   }
77195 }
77196
77197 /*
77198 ** Translate from TK_xx operator to WO_xx bitmask.
77199 */
77200 static int operatorMask(int op){
77201   int c;
77202   assert( allowedOp(op) );
77203   if( op==TK_IN ){
77204     c = WO_IN;
77205   }else if( op==TK_ISNULL ){
77206     c = WO_ISNULL;
77207   }else{
77208     c = WO_EQ<<(op-TK_EQ);
77209   }
77210   assert( op!=TK_ISNULL || c==WO_ISNULL );
77211   assert( op!=TK_IN || c==WO_IN );
77212   assert( op!=TK_EQ || c==WO_EQ );
77213   assert( op!=TK_LT || c==WO_LT );
77214   assert( op!=TK_LE || c==WO_LE );
77215   assert( op!=TK_GT || c==WO_GT );
77216   assert( op!=TK_GE || c==WO_GE );
77217   return c;
77218 }
77219
77220 /*
77221 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
77222 ** where X is a reference to the iColumn of table iCur and <op> is one of
77223 ** the WO_xx operator codes specified by the op parameter.
77224 ** Return a pointer to the term.  Return 0 if not found.
77225 */
77226 static WhereTerm *findTerm(
77227   WhereClause *pWC,     /* The WHERE clause to be searched */
77228   int iCur,             /* Cursor number of LHS */
77229   int iColumn,          /* Column number of LHS */
77230   Bitmask notReady,     /* RHS must not overlap with this mask */
77231   u16 op,               /* Mask of WO_xx values describing operator */
77232   Index *pIdx           /* Must be compatible with this index, if not NULL */
77233 ){
77234   WhereTerm *pTerm;
77235   int k;
77236   assert( iCur>=0 );
77237   for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
77238     if( pTerm->leftCursor==iCur
77239        && (pTerm->prereqRight & notReady)==0
77240        && pTerm->leftColumn==iColumn
77241        && (pTerm->eOperator & op)!=0
77242     ){
77243       if( pIdx && pTerm->eOperator!=WO_ISNULL ){
77244         Expr *pX = pTerm->pExpr;
77245         CollSeq *pColl;
77246         char idxaff;
77247         int j;
77248         Parse *pParse = pWC->pParse;
77249
77250         idxaff = pIdx->pTable->aCol[iColumn].affinity;
77251         if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
77252
77253         /* Figure out the collation sequence required from an index for
77254         ** it to be useful for optimising expression pX. Store this
77255         ** value in variable pColl.
77256         */
77257         assert(pX->pLeft);
77258         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
77259         if( !pColl ){
77260           pColl = pParse->db->pDfltColl;
77261         }
77262
77263         for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
77264           if( NEVER(j>=pIdx->nColumn) ) return 0;
77265         }
77266         if( sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
77267       }
77268       return pTerm;
77269     }
77270   }
77271   return 0;
77272 }
77273
77274 /* Forward reference */
77275 static void exprAnalyze(SrcList*, WhereClause*, int);
77276
77277 /*
77278 ** Call exprAnalyze on all terms in a WHERE clause.  
77279 **
77280 **
77281 */
77282 static void exprAnalyzeAll(
77283   SrcList *pTabList,       /* the FROM clause */
77284   WhereClause *pWC         /* the WHERE clause to be analyzed */
77285 ){
77286   int i;
77287   for(i=pWC->nTerm-1; i>=0; i--){
77288     exprAnalyze(pTabList, pWC, i);
77289   }
77290 }
77291
77292 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
77293 /*
77294 ** Check to see if the given expression is a LIKE or GLOB operator that
77295 ** can be optimized using inequality constraints.  Return TRUE if it is
77296 ** so and false if not.
77297 **
77298 ** In order for the operator to be optimizible, the RHS must be a string
77299 ** literal that does not begin with a wildcard.  
77300 */
77301 static int isLikeOrGlob(
77302   Parse *pParse,    /* Parsing and code generating context */
77303   Expr *pExpr,      /* Test this expression */
77304   int *pnPattern,   /* Number of non-wildcard prefix characters */
77305   int *pisComplete, /* True if the only wildcard is % in the last character */
77306   int *pnoCase      /* True if uppercase is equivalent to lowercase */
77307 ){
77308   const char *z;
77309   Expr *pRight, *pLeft;
77310   ExprList *pList;
77311   int c, cnt;
77312   char wc[3];
77313   CollSeq *pColl;
77314   sqlite3 *db = pParse->db;
77315
77316   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
77317     return 0;
77318   }
77319 #ifdef SQLITE_EBCDIC
77320   if( *pnoCase ) return 0;
77321 #endif
77322   pList = pExpr->pList;
77323   pRight = pList->a[0].pExpr;
77324   if( pRight->op!=TK_STRING
77325    && (pRight->op!=TK_REGISTER || pRight->iColumn!=TK_STRING) ){
77326     return 0;
77327   }
77328   pLeft = pList->a[1].pExpr;
77329   if( pLeft->op!=TK_COLUMN ){
77330     return 0;
77331   }
77332   pColl = sqlite3ExprCollSeq(pParse, pLeft);
77333   assert( pColl!=0 || pLeft->iColumn==-1 );
77334   if( pColl==0 ){
77335     /* No collation is defined for the ROWID.  Use the default. */
77336     pColl = db->pDfltColl;
77337   }
77338   if( (pColl->type!=SQLITE_COLL_BINARY || *pnoCase) &&
77339       (pColl->type!=SQLITE_COLL_NOCASE || !*pnoCase) ){
77340     return 0;
77341   }
77342   sqlite3DequoteExpr(db, pRight);
77343   z = (char *)pRight->token.z;
77344   cnt = 0;
77345   if( z ){
77346     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){ cnt++; }
77347   }
77348   if( cnt==0 || 255==(u8)z[cnt] ){
77349     return 0;
77350   }
77351   *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
77352   *pnPattern = cnt;
77353   return 1;
77354 }
77355 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
77356
77357
77358 #ifndef SQLITE_OMIT_VIRTUALTABLE
77359 /*
77360 ** Check to see if the given expression is of the form
77361 **
77362 **         column MATCH expr
77363 **
77364 ** If it is then return TRUE.  If not, return FALSE.
77365 */
77366 static int isMatchOfColumn(
77367   Expr *pExpr      /* Test this expression */
77368 ){
77369   ExprList *pList;
77370
77371   if( pExpr->op!=TK_FUNCTION ){
77372     return 0;
77373   }
77374   if( pExpr->token.n!=5 ||
77375        sqlite3StrNICmp((const char*)pExpr->token.z,"match",5)!=0 ){
77376     return 0;
77377   }
77378   pList = pExpr->pList;
77379   if( pList->nExpr!=2 ){
77380     return 0;
77381   }
77382   if( pList->a[1].pExpr->op != TK_COLUMN ){
77383     return 0;
77384   }
77385   return 1;
77386 }
77387 #endif /* SQLITE_OMIT_VIRTUALTABLE */
77388
77389 /*
77390 ** If the pBase expression originated in the ON or USING clause of
77391 ** a join, then transfer the appropriate markings over to derived.
77392 */
77393 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
77394   pDerived->flags |= pBase->flags & EP_FromJoin;
77395   pDerived->iRightJoinTable = pBase->iRightJoinTable;
77396 }
77397
77398 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
77399 /*
77400 ** Return TRUE if the given term of an OR clause can be converted
77401 ** into an IN clause.  The iCursor and iColumn define the left-hand
77402 ** side of the IN clause.
77403 **
77404 ** The context is that we have multiple OR-connected equality terms
77405 ** like this:
77406 **
77407 **           a=<expr1> OR  a=<expr2> OR b=<expr3>  OR ...
77408 **
77409 ** The pOrTerm input to this routine corresponds to a single term of
77410 ** this OR clause.  In order for the term to be a candidate for
77411 ** conversion to an IN operator, the following must be true:
77412 **
77413 **     *  The left-hand side of the term must be the column which
77414 **        is identified by iCursor and iColumn.
77415 **
77416 **     *  If the right-hand side is also a column, then the affinities
77417 **        of both right and left sides must be such that no type
77418 **        conversions are required on the right.  (Ticket #2249)
77419 **
77420 ** If both of these conditions are true, then return true.  Otherwise
77421 ** return false.
77422 */
77423 static int orTermIsOptCandidate(WhereTerm *pOrTerm, int iCursor, int iColumn){
77424   int affLeft, affRight;
77425   assert( pOrTerm->eOperator==WO_EQ );
77426   if( pOrTerm->leftCursor!=iCursor ){
77427     return 0;
77428   }
77429   if( pOrTerm->leftColumn!=iColumn ){
77430     return 0;
77431   }
77432   affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
77433   if( affRight==0 ){
77434     return 1;
77435   }
77436   affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
77437   if( affRight!=affLeft ){
77438     return 0;
77439   }
77440   return 1;
77441 }
77442
77443 /*
77444 ** Return true if the given term of an OR clause can be ignored during
77445 ** a check to make sure all OR terms are candidates for optimization.
77446 ** In other words, return true if a call to the orTermIsOptCandidate()
77447 ** above returned false but it is not necessary to disqualify the
77448 ** optimization.
77449 **
77450 ** Suppose the original OR phrase was this:
77451 **
77452 **           a=4  OR  a=11  OR  a=b
77453 **
77454 ** During analysis, the third term gets flipped around and duplicate
77455 ** so that we are left with this:
77456 **
77457 **           a=4  OR  a=11  OR  a=b  OR  b=a
77458 **
77459 ** Since the last two terms are duplicates, only one of them
77460 ** has to qualify in order for the whole phrase to qualify.  When
77461 ** this routine is called, we know that pOrTerm did not qualify.
77462 ** This routine merely checks to see if pOrTerm has a duplicate that
77463 ** might qualify.  If there is a duplicate that has not yet been
77464 ** disqualified, then return true.  If there are no duplicates, or
77465 ** the duplicate has also been disqualified, return false.
77466 */
77467 static int orTermHasOkDuplicate(WhereClause *pOr, WhereTerm *pOrTerm){
77468   if( pOrTerm->flags & TERM_COPIED ){
77469     /* This is the original term.  The duplicate is to the left had
77470     ** has not yet been analyzed and thus has not yet been disqualified. */
77471     return 1;
77472   }
77473   if( (pOrTerm->flags & TERM_VIRTUAL)!=0
77474      && (pOr->a[pOrTerm->iParent].flags & TERM_OR_OK)!=0 ){
77475     /* This is a duplicate term.  The original qualified so this one
77476     ** does not have to. */
77477     return 1;
77478   }
77479   /* This is either a singleton term or else it is a duplicate for
77480   ** which the original did not qualify.  Either way we are done for. */
77481   return 0;
77482 }
77483 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
77484
77485 /*
77486 ** The input to this routine is an WhereTerm structure with only the
77487 ** "pExpr" field filled in.  The job of this routine is to analyze the
77488 ** subexpression and populate all the other fields of the WhereTerm
77489 ** structure.
77490 **
77491 ** If the expression is of the form "<expr> <op> X" it gets commuted
77492 ** to the standard form of "X <op> <expr>".  If the expression is of
77493 ** the form "X <op> Y" where both X and Y are columns, then the original
77494 ** expression is unchanged and a new virtual expression of the form
77495 ** "Y <op> X" is added to the WHERE clause and analyzed separately.
77496 */
77497 static void exprAnalyze(
77498   SrcList *pSrc,            /* the FROM clause */
77499   WhereClause *pWC,         /* the WHERE clause */
77500   int idxTerm               /* Index of the term to be analyzed */
77501 ){
77502   WhereTerm *pTerm;
77503   ExprMaskSet *pMaskSet;
77504   Expr *pExpr;
77505   Bitmask prereqLeft;
77506   Bitmask prereqAll;
77507   Bitmask extraRight = 0;
77508   int nPattern;
77509   int isComplete;
77510   int noCase;
77511   int op;
77512   Parse *pParse = pWC->pParse;
77513   sqlite3 *db = pParse->db;
77514
77515   if( db->mallocFailed ){
77516     return;
77517   }
77518   pTerm = &pWC->a[idxTerm];
77519   pMaskSet = pWC->pMaskSet;
77520   pExpr = pTerm->pExpr;
77521   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
77522   op = pExpr->op;
77523   if( op==TK_IN ){
77524     assert( pExpr->pRight==0 );
77525     pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->pList)
77526                           | exprSelectTableUsage(pMaskSet, pExpr->pSelect);
77527   }else if( op==TK_ISNULL ){
77528     pTerm->prereqRight = 0;
77529   }else{
77530     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
77531   }
77532   prereqAll = exprTableUsage(pMaskSet, pExpr);
77533   if( ExprHasProperty(pExpr, EP_FromJoin) ){
77534     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
77535     prereqAll |= x;
77536     extraRight = x-1;  /* ON clause terms may not be used with an index
77537                        ** on left table of a LEFT JOIN.  Ticket #3015 */
77538   }
77539   pTerm->prereqAll = prereqAll;
77540   pTerm->leftCursor = -1;
77541   pTerm->iParent = -1;
77542   pTerm->eOperator = 0;
77543   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
77544     Expr *pLeft = pExpr->pLeft;
77545     Expr *pRight = pExpr->pRight;
77546     if( pLeft->op==TK_COLUMN ){
77547       pTerm->leftCursor = pLeft->iTable;
77548       pTerm->leftColumn = pLeft->iColumn;
77549       pTerm->eOperator = operatorMask(op);
77550     }
77551     if( pRight && pRight->op==TK_COLUMN ){
77552       WhereTerm *pNew;
77553       Expr *pDup;
77554       if( pTerm->leftCursor>=0 ){
77555         int idxNew;
77556         pDup = sqlite3ExprDup(db, pExpr);
77557         if( db->mallocFailed ){
77558           sqlite3ExprDelete(db, pDup);
77559           return;
77560         }
77561         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
77562         if( idxNew==0 ) return;
77563         pNew = &pWC->a[idxNew];
77564         pNew->iParent = idxTerm;
77565         pTerm = &pWC->a[idxTerm];
77566         pTerm->nChild = 1;
77567         pTerm->flags |= TERM_COPIED;
77568       }else{
77569         pDup = pExpr;
77570         pNew = pTerm;
77571       }
77572       exprCommute(pParse, pDup);
77573       pLeft = pDup->pLeft;
77574       pNew->leftCursor = pLeft->iTable;
77575       pNew->leftColumn = pLeft->iColumn;
77576       pNew->prereqRight = prereqLeft;
77577       pNew->prereqAll = prereqAll;
77578       pNew->eOperator = operatorMask(pDup->op);
77579     }
77580   }
77581
77582 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
77583   /* If a term is the BETWEEN operator, create two new virtual terms
77584   ** that define the range that the BETWEEN implements.
77585   */
77586   else if( pExpr->op==TK_BETWEEN ){
77587     ExprList *pList = pExpr->pList;
77588     int i;
77589     static const u8 ops[] = {TK_GE, TK_LE};
77590     assert( pList!=0 );
77591     assert( pList->nExpr==2 );
77592     for(i=0; i<2; i++){
77593       Expr *pNewExpr;
77594       int idxNew;
77595       pNewExpr = sqlite3Expr(db, ops[i], sqlite3ExprDup(db, pExpr->pLeft),
77596                              sqlite3ExprDup(db, pList->a[i].pExpr), 0);
77597       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
77598       exprAnalyze(pSrc, pWC, idxNew);
77599       pTerm = &pWC->a[idxTerm];
77600       pWC->a[idxNew].iParent = idxTerm;
77601     }
77602     pTerm->nChild = 2;
77603   }
77604 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
77605
77606 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
77607   /* Attempt to convert OR-connected terms into an IN operator so that
77608   ** they can make use of indices.  Example:
77609   **
77610   **      x = expr1  OR  expr2 = x  OR  x = expr3
77611   **
77612   ** is converted into
77613   **
77614   **      x IN (expr1,expr2,expr3)
77615   **
77616   ** This optimization must be omitted if OMIT_SUBQUERY is defined because
77617   ** the compiler for the the IN operator is part of sub-queries.
77618   */
77619   else if( pExpr->op==TK_OR ){
77620     int ok;
77621     int i, j;
77622     int iColumn, iCursor;
77623     WhereClause sOr;
77624     WhereTerm *pOrTerm;
77625
77626     assert( (pTerm->flags & TERM_DYNAMIC)==0 );
77627     whereClauseInit(&sOr, pWC->pParse, pMaskSet);
77628     whereSplit(&sOr, pExpr, TK_OR);
77629     exprAnalyzeAll(pSrc, &sOr);
77630     assert( sOr.nTerm>=2 );
77631     j = 0;
77632     if( db->mallocFailed ) goto or_not_possible;
77633     do{
77634       assert( j<sOr.nTerm );
77635       iColumn = sOr.a[j].leftColumn;
77636       iCursor = sOr.a[j].leftCursor;
77637       ok = iCursor>=0;
77638       for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0 && ok; i--, pOrTerm++){
77639         if( pOrTerm->eOperator!=WO_EQ ){
77640           goto or_not_possible;
77641         }
77642         if( orTermIsOptCandidate(pOrTerm, iCursor, iColumn) ){
77643           pOrTerm->flags |= TERM_OR_OK;
77644         }else if( orTermHasOkDuplicate(&sOr, pOrTerm) ){
77645           pOrTerm->flags &= ~TERM_OR_OK;
77646         }else{
77647           ok = 0;
77648         }
77649       }
77650     }while( !ok && (sOr.a[j++].flags & TERM_COPIED)!=0 && j<2 );
77651     if( ok ){
77652       ExprList *pList = 0;
77653       Expr *pNew, *pDup;
77654       Expr *pLeft = 0;
77655       for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0; i--, pOrTerm++){
77656         if( (pOrTerm->flags & TERM_OR_OK)==0 ) continue;
77657         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight);
77658         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup, 0);
77659         pLeft = pOrTerm->pExpr->pLeft;
77660       }
77661       assert( pLeft!=0 );
77662       pDup = sqlite3ExprDup(db, pLeft);
77663       pNew = sqlite3Expr(db, TK_IN, pDup, 0, 0);
77664       if( pNew ){
77665         int idxNew;
77666         transferJoinMarkings(pNew, pExpr);
77667         pNew->pList = pList;
77668         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
77669         exprAnalyze(pSrc, pWC, idxNew);
77670         pTerm = &pWC->a[idxTerm];
77671         pWC->a[idxNew].iParent = idxTerm;
77672         pTerm->nChild = 1;
77673       }else{
77674         sqlite3ExprListDelete(db, pList);
77675       }
77676     }
77677 or_not_possible:
77678     whereClauseClear(&sOr);
77679   }
77680 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
77681
77682 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
77683   /* Add constraints to reduce the search space on a LIKE or GLOB
77684   ** operator.
77685   **
77686   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
77687   **
77688   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
77689   **
77690   ** The last character of the prefix "abc" is incremented to form the
77691   ** termination condition "abd".
77692   */
77693   if( isLikeOrGlob(pParse, pExpr, &nPattern, &isComplete, &noCase) ){
77694     Expr *pLeft, *pRight;
77695     Expr *pStr1, *pStr2;
77696     Expr *pNewExpr1, *pNewExpr2;
77697     int idxNew1, idxNew2;
77698
77699     pLeft = pExpr->pList->a[1].pExpr;
77700     pRight = pExpr->pList->a[0].pExpr;
77701     pStr1 = sqlite3PExpr(pParse, TK_STRING, 0, 0, 0);
77702     if( pStr1 ){
77703       sqlite3TokenCopy(db, &pStr1->token, &pRight->token);
77704       pStr1->token.n = nPattern;
77705       pStr1->flags = EP_Dequoted;
77706     }
77707     pStr2 = sqlite3ExprDup(db, pStr1);
77708     if( !db->mallocFailed ){
77709       u8 c, *pC;
77710       assert( pStr2->token.dyn );
77711       pC = (u8*)&pStr2->token.z[nPattern-1];
77712       c = *pC;
77713       if( noCase ){
77714         if( c=='@' ) isComplete = 0;
77715         c = sqlite3UpperToLower[c];
77716       }
77717       *pC = c + 1;
77718     }
77719     pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprDup(db,pLeft), pStr1, 0);
77720     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
77721     exprAnalyze(pSrc, pWC, idxNew1);
77722     pNewExpr2 = sqlite3PExpr(pParse, TK_LT, sqlite3ExprDup(db,pLeft), pStr2, 0);
77723     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
77724     exprAnalyze(pSrc, pWC, idxNew2);
77725     pTerm = &pWC->a[idxTerm];
77726     if( isComplete ){
77727       pWC->a[idxNew1].iParent = idxTerm;
77728       pWC->a[idxNew2].iParent = idxTerm;
77729       pTerm->nChild = 2;
77730     }
77731   }
77732 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
77733
77734 #ifndef SQLITE_OMIT_VIRTUALTABLE
77735   /* Add a WO_MATCH auxiliary term to the constraint set if the
77736   ** current expression is of the form:  column MATCH expr.
77737   ** This information is used by the xBestIndex methods of
77738   ** virtual tables.  The native query optimizer does not attempt
77739   ** to do anything with MATCH functions.
77740   */
77741   if( isMatchOfColumn(pExpr) ){
77742     int idxNew;
77743     Expr *pRight, *pLeft;
77744     WhereTerm *pNewTerm;
77745     Bitmask prereqColumn, prereqExpr;
77746
77747     pRight = pExpr->pList->a[0].pExpr;
77748     pLeft = pExpr->pList->a[1].pExpr;
77749     prereqExpr = exprTableUsage(pMaskSet, pRight);
77750     prereqColumn = exprTableUsage(pMaskSet, pLeft);
77751     if( (prereqExpr & prereqColumn)==0 ){
77752       Expr *pNewExpr;
77753       pNewExpr = sqlite3Expr(db, TK_MATCH, 0, sqlite3ExprDup(db, pRight), 0);
77754       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
77755       pNewTerm = &pWC->a[idxNew];
77756       pNewTerm->prereqRight = prereqExpr;
77757       pNewTerm->leftCursor = pLeft->iTable;
77758       pNewTerm->leftColumn = pLeft->iColumn;
77759       pNewTerm->eOperator = WO_MATCH;
77760       pNewTerm->iParent = idxTerm;
77761       pTerm = &pWC->a[idxTerm];
77762       pTerm->nChild = 1;
77763       pTerm->flags |= TERM_COPIED;
77764       pNewTerm->prereqAll = pTerm->prereqAll;
77765     }
77766   }
77767 #endif /* SQLITE_OMIT_VIRTUALTABLE */
77768
77769   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
77770   ** an index for tables to the left of the join.
77771   */
77772   pTerm->prereqRight |= extraRight;
77773 }
77774
77775 /*
77776 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
77777 ** a reference to any table other than the iBase table.
77778 */
77779 static int referencesOtherTables(
77780   ExprList *pList,          /* Search expressions in ths list */
77781   ExprMaskSet *pMaskSet,    /* Mapping from tables to bitmaps */
77782   int iFirst,               /* Be searching with the iFirst-th expression */
77783   int iBase                 /* Ignore references to this table */
77784 ){
77785   Bitmask allowed = ~getMask(pMaskSet, iBase);
77786   while( iFirst<pList->nExpr ){
77787     if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
77788       return 1;
77789     }
77790   }
77791   return 0;
77792 }
77793
77794
77795 /*
77796 ** This routine decides if pIdx can be used to satisfy the ORDER BY
77797 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
77798 ** ORDER BY clause, this routine returns 0.
77799 **
77800 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
77801 ** left-most table in the FROM clause of that same SELECT statement and
77802 ** the table has a cursor number of "base".  pIdx is an index on pTab.
77803 **
77804 ** nEqCol is the number of columns of pIdx that are used as equality
77805 ** constraints.  Any of these columns may be missing from the ORDER BY
77806 ** clause and the match can still be a success.
77807 **
77808 ** All terms of the ORDER BY that match against the index must be either
77809 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
77810 ** index do not need to satisfy this constraint.)  The *pbRev value is
77811 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
77812 ** the ORDER BY clause is all ASC.
77813 */
77814 static int isSortingIndex(
77815   Parse *pParse,          /* Parsing context */
77816   ExprMaskSet *pMaskSet,  /* Mapping from table indices to bitmaps */
77817   Index *pIdx,            /* The index we are testing */
77818   int base,               /* Cursor number for the table to be sorted */
77819   ExprList *pOrderBy,     /* The ORDER BY clause */
77820   int nEqCol,             /* Number of index columns with == constraints */
77821   int *pbRev              /* Set to 1 if ORDER BY is DESC */
77822 ){
77823   int i, j;                       /* Loop counters */
77824   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
77825   int nTerm;                      /* Number of ORDER BY terms */
77826   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
77827   sqlite3 *db = pParse->db;
77828
77829   assert( pOrderBy!=0 );
77830   nTerm = pOrderBy->nExpr;
77831   assert( nTerm>0 );
77832
77833   /* Match terms of the ORDER BY clause against columns of
77834   ** the index.
77835   **
77836   ** Note that indices have pIdx->nColumn regular columns plus
77837   ** one additional column containing the rowid.  The rowid column
77838   ** of the index is also allowed to match against the ORDER BY
77839   ** clause.
77840   */
77841   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
77842     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
77843     CollSeq *pColl;    /* The collating sequence of pExpr */
77844     int termSortOrder; /* Sort order for this term */
77845     int iColumn;       /* The i-th column of the index.  -1 for rowid */
77846     int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
77847     const char *zColl; /* Name of the collating sequence for i-th index term */
77848
77849     pExpr = pTerm->pExpr;
77850     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
77851       /* Can not use an index sort on anything that is not a column in the
77852       ** left-most table of the FROM clause */
77853       break;
77854     }
77855     pColl = sqlite3ExprCollSeq(pParse, pExpr);
77856     if( !pColl ){
77857       pColl = db->pDfltColl;
77858     }
77859     if( i<pIdx->nColumn ){
77860       iColumn = pIdx->aiColumn[i];
77861       if( iColumn==pIdx->pTable->iPKey ){
77862         iColumn = -1;
77863       }
77864       iSortOrder = pIdx->aSortOrder[i];
77865       zColl = pIdx->azColl[i];
77866     }else{
77867       iColumn = -1;
77868       iSortOrder = 0;
77869       zColl = pColl->zName;
77870     }
77871     if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
77872       /* Term j of the ORDER BY clause does not match column i of the index */
77873       if( i<nEqCol ){
77874         /* If an index column that is constrained by == fails to match an
77875         ** ORDER BY term, that is OK.  Just ignore that column of the index
77876         */
77877         continue;
77878       }else if( i==pIdx->nColumn ){
77879         /* Index column i is the rowid.  All other terms match. */
77880         break;
77881       }else{
77882         /* If an index column fails to match and is not constrained by ==
77883         ** then the index cannot satisfy the ORDER BY constraint.
77884         */
77885         return 0;
77886       }
77887     }
77888     assert( pIdx->aSortOrder!=0 );
77889     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
77890     assert( iSortOrder==0 || iSortOrder==1 );
77891     termSortOrder = iSortOrder ^ pTerm->sortOrder;
77892     if( i>nEqCol ){
77893       if( termSortOrder!=sortOrder ){
77894         /* Indices can only be used if all ORDER BY terms past the
77895         ** equality constraints are all either DESC or ASC. */
77896         return 0;
77897       }
77898     }else{
77899       sortOrder = termSortOrder;
77900     }
77901     j++;
77902     pTerm++;
77903     if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
77904       /* If the indexed column is the primary key and everything matches
77905       ** so far and none of the ORDER BY terms to the right reference other
77906       ** tables in the join, then we are assured that the index can be used 
77907       ** to sort because the primary key is unique and so none of the other
77908       ** columns will make any difference
77909       */
77910       j = nTerm;
77911     }
77912   }
77913
77914   *pbRev = sortOrder!=0;
77915   if( j>=nTerm ){
77916     /* All terms of the ORDER BY clause are covered by this index so
77917     ** this index can be used for sorting. */
77918     return 1;
77919   }
77920   if( pIdx->onError!=OE_None && i==pIdx->nColumn
77921       && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
77922     /* All terms of this index match some prefix of the ORDER BY clause
77923     ** and the index is UNIQUE and no terms on the tail of the ORDER BY
77924     ** clause reference other tables in a join.  If this is all true then
77925     ** the order by clause is superfluous. */
77926     return 1;
77927   }
77928   return 0;
77929 }
77930
77931 /*
77932 ** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
77933 ** by sorting in order of ROWID.  Return true if so and set *pbRev to be
77934 ** true for reverse ROWID and false for forward ROWID order.
77935 */
77936 static int sortableByRowid(
77937   int base,               /* Cursor number for table to be sorted */
77938   ExprList *pOrderBy,     /* The ORDER BY clause */
77939   ExprMaskSet *pMaskSet,  /* Mapping from tables to bitmaps */
77940   int *pbRev              /* Set to 1 if ORDER BY is DESC */
77941 ){
77942   Expr *p;
77943
77944   assert( pOrderBy!=0 );
77945   assert( pOrderBy->nExpr>0 );
77946   p = pOrderBy->a[0].pExpr;
77947   if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1
77948     && !referencesOtherTables(pOrderBy, pMaskSet, 1, base) ){
77949     *pbRev = pOrderBy->a[0].sortOrder;
77950     return 1;
77951   }
77952   return 0;
77953 }
77954
77955 /*
77956 ** Prepare a crude estimate of the logarithm of the input value.
77957 ** The results need not be exact.  This is only used for estimating
77958 ** the total cost of performing operations with O(logN) or O(NlogN)
77959 ** complexity.  Because N is just a guess, it is no great tragedy if
77960 ** logN is a little off.
77961 */
77962 static double estLog(double N){
77963   double logN = 1;
77964   double x = 10;
77965   while( N>x ){
77966     logN += 1;
77967     x *= 10;
77968   }
77969   return logN;
77970 }
77971
77972 /*
77973 ** Two routines for printing the content of an sqlite3_index_info
77974 ** structure.  Used for testing and debugging only.  If neither
77975 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
77976 ** are no-ops.
77977 */
77978 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
77979 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
77980   int i;
77981   if( !sqlite3WhereTrace ) return;
77982   for(i=0; i<p->nConstraint; i++){
77983     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
77984        i,
77985        p->aConstraint[i].iColumn,
77986        p->aConstraint[i].iTermOffset,
77987        p->aConstraint[i].op,
77988        p->aConstraint[i].usable);
77989   }
77990   for(i=0; i<p->nOrderBy; i++){
77991     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
77992        i,
77993        p->aOrderBy[i].iColumn,
77994        p->aOrderBy[i].desc);
77995   }
77996 }
77997 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
77998   int i;
77999   if( !sqlite3WhereTrace ) return;
78000   for(i=0; i<p->nConstraint; i++){
78001     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
78002        i,
78003        p->aConstraintUsage[i].argvIndex,
78004        p->aConstraintUsage[i].omit);
78005   }
78006   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
78007   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
78008   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
78009   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
78010 }
78011 #else
78012 #define TRACE_IDX_INPUTS(A)
78013 #define TRACE_IDX_OUTPUTS(A)
78014 #endif
78015
78016 #ifndef SQLITE_OMIT_VIRTUALTABLE
78017 /*
78018 ** Compute the best index for a virtual table.
78019 **
78020 ** The best index is computed by the xBestIndex method of the virtual
78021 ** table module.  This routine is really just a wrapper that sets up
78022 ** the sqlite3_index_info structure that is used to communicate with
78023 ** xBestIndex.
78024 **
78025 ** In a join, this routine might be called multiple times for the
78026 ** same virtual table.  The sqlite3_index_info structure is created
78027 ** and initialized on the first invocation and reused on all subsequent
78028 ** invocations.  The sqlite3_index_info structure is also used when
78029 ** code is generated to access the virtual table.  The whereInfoDelete() 
78030 ** routine takes care of freeing the sqlite3_index_info structure after
78031 ** everybody has finished with it.
78032 */
78033 static double bestVirtualIndex(
78034   Parse *pParse,                 /* The parsing context */
78035   WhereClause *pWC,              /* The WHERE clause */
78036   struct SrcList_item *pSrc,     /* The FROM clause term to search */
78037   Bitmask notReady,              /* Mask of cursors that are not available */
78038   ExprList *pOrderBy,            /* The order by clause */
78039   int orderByUsable,             /* True if we can potential sort */
78040   sqlite3_index_info **ppIdxInfo /* Index information passed to xBestIndex */
78041 ){
78042   Table *pTab = pSrc->pTab;
78043   sqlite3_vtab *pVtab = pTab->pVtab;
78044   sqlite3_index_info *pIdxInfo;
78045   struct sqlite3_index_constraint *pIdxCons;
78046   struct sqlite3_index_orderby *pIdxOrderBy;
78047   struct sqlite3_index_constraint_usage *pUsage;
78048   WhereTerm *pTerm;
78049   int i, j;
78050   int nOrderBy;
78051   int rc;
78052
78053   /* If the sqlite3_index_info structure has not been previously
78054   ** allocated and initialized for this virtual table, then allocate
78055   ** and initialize it now
78056   */
78057   pIdxInfo = *ppIdxInfo;
78058   if( pIdxInfo==0 ){
78059     WhereTerm *pTerm;
78060     int nTerm;
78061     WHERETRACE(("Recomputing index info for %s...\n", pTab->zName));
78062
78063     /* Count the number of possible WHERE clause constraints referring
78064     ** to this virtual table */
78065     for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
78066       if( pTerm->leftCursor != pSrc->iCursor ) continue;
78067       assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
78068       testcase( pTerm->eOperator==WO_IN );
78069       testcase( pTerm->eOperator==WO_ISNULL );
78070       if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
78071       nTerm++;
78072     }
78073
78074     /* If the ORDER BY clause contains only columns in the current 
78075     ** virtual table then allocate space for the aOrderBy part of
78076     ** the sqlite3_index_info structure.
78077     */
78078     nOrderBy = 0;
78079     if( pOrderBy ){
78080       for(i=0; i<pOrderBy->nExpr; i++){
78081         Expr *pExpr = pOrderBy->a[i].pExpr;
78082         if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
78083       }
78084       if( i==pOrderBy->nExpr ){
78085         nOrderBy = pOrderBy->nExpr;
78086       }
78087     }
78088
78089     /* Allocate the sqlite3_index_info structure
78090     */
78091     pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
78092                              + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
78093                              + sizeof(*pIdxOrderBy)*nOrderBy );
78094     if( pIdxInfo==0 ){
78095       sqlite3ErrorMsg(pParse, "out of memory");
78096       return 0.0;
78097     }
78098     *ppIdxInfo = pIdxInfo;
78099
78100     /* Initialize the structure.  The sqlite3_index_info structure contains
78101     ** many fields that are declared "const" to prevent xBestIndex from
78102     ** changing them.  We have to do some funky casting in order to
78103     ** initialize those fields.
78104     */
78105     pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
78106     pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
78107     pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
78108     *(int*)&pIdxInfo->nConstraint = nTerm;
78109     *(int*)&pIdxInfo->nOrderBy = nOrderBy;
78110     *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
78111     *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
78112     *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
78113                                                                      pUsage;
78114
78115     for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
78116       if( pTerm->leftCursor != pSrc->iCursor ) continue;
78117       assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
78118       testcase( pTerm->eOperator==WO_IN );
78119       testcase( pTerm->eOperator==WO_ISNULL );
78120       if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
78121       pIdxCons[j].iColumn = pTerm->leftColumn;
78122       pIdxCons[j].iTermOffset = i;
78123       pIdxCons[j].op = pTerm->eOperator;
78124       /* The direct assignment in the previous line is possible only because
78125       ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
78126       ** following asserts verify this fact. */
78127       assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
78128       assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
78129       assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
78130       assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
78131       assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
78132       assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
78133       assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
78134       j++;
78135     }
78136     for(i=0; i<nOrderBy; i++){
78137       Expr *pExpr = pOrderBy->a[i].pExpr;
78138       pIdxOrderBy[i].iColumn = pExpr->iColumn;
78139       pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
78140     }
78141   }
78142
78143   /* At this point, the sqlite3_index_info structure that pIdxInfo points
78144   ** to will have been initialized, either during the current invocation or
78145   ** during some prior invocation.  Now we just have to customize the
78146   ** details of pIdxInfo for the current invocation and pass it to
78147   ** xBestIndex.
78148   */
78149
78150   /* The module name must be defined. Also, by this point there must
78151   ** be a pointer to an sqlite3_vtab structure. Otherwise
78152   ** sqlite3ViewGetColumnNames() would have picked up the error. 
78153   */
78154   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
78155   assert( pVtab );
78156 #if 0
78157   if( pTab->pVtab==0 ){
78158     sqlite3ErrorMsg(pParse, "undefined module %s for table %s",
78159         pTab->azModuleArg[0], pTab->zName);
78160     return 0.0;
78161   }
78162 #endif
78163
78164   /* Set the aConstraint[].usable fields and initialize all 
78165   ** output variables to zero.
78166   **
78167   ** aConstraint[].usable is true for constraints where the right-hand
78168   ** side contains only references to tables to the left of the current
78169   ** table.  In other words, if the constraint is of the form:
78170   **
78171   **           column = expr
78172   **
78173   ** and we are evaluating a join, then the constraint on column is 
78174   ** only valid if all tables referenced in expr occur to the left
78175   ** of the table containing column.
78176   **
78177   ** The aConstraints[] array contains entries for all constraints
78178   ** on the current table.  That way we only have to compute it once
78179   ** even though we might try to pick the best index multiple times.
78180   ** For each attempt at picking an index, the order of tables in the
78181   ** join might be different so we have to recompute the usable flag
78182   ** each time.
78183   */
78184   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
78185   pUsage = pIdxInfo->aConstraintUsage;
78186   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
78187     j = pIdxCons->iTermOffset;
78188     pTerm = &pWC->a[j];
78189     pIdxCons->usable =  (pTerm->prereqRight & notReady)==0;
78190   }
78191   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
78192   if( pIdxInfo->needToFreeIdxStr ){
78193     sqlite3_free(pIdxInfo->idxStr);
78194   }
78195   pIdxInfo->idxStr = 0;
78196   pIdxInfo->idxNum = 0;
78197   pIdxInfo->needToFreeIdxStr = 0;
78198   pIdxInfo->orderByConsumed = 0;
78199   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / 2.0;
78200   nOrderBy = pIdxInfo->nOrderBy;
78201   if( pIdxInfo->nOrderBy && !orderByUsable ){
78202     *(int*)&pIdxInfo->nOrderBy = 0;
78203   }
78204
78205   (void)sqlite3SafetyOff(pParse->db);
78206   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
78207   TRACE_IDX_INPUTS(pIdxInfo);
78208   rc = pVtab->pModule->xBestIndex(pVtab, pIdxInfo);
78209   TRACE_IDX_OUTPUTS(pIdxInfo);
78210   (void)sqlite3SafetyOn(pParse->db);
78211
78212   if( rc!=SQLITE_OK ){
78213     if( rc==SQLITE_NOMEM ){
78214       pParse->db->mallocFailed = 1;
78215     }else if( !pVtab->zErrMsg ){
78216       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
78217     }else{
78218       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
78219     }
78220   }
78221   sqlite3DbFree(pParse->db, pVtab->zErrMsg);
78222   pVtab->zErrMsg = 0;
78223
78224   for(i=0; i<pIdxInfo->nConstraint; i++){
78225     if( !pIdxInfo->aConstraint[i].usable && pUsage[i].argvIndex>0 ){
78226       sqlite3ErrorMsg(pParse, 
78227           "table %s: xBestIndex returned an invalid plan", pTab->zName);
78228       return 0.0;
78229     }
78230   }
78231
78232   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
78233   return pIdxInfo->estimatedCost;
78234 }
78235 #endif /* SQLITE_OMIT_VIRTUALTABLE */
78236
78237 /*
78238 ** Find the best index for accessing a particular table.  Return a pointer
78239 ** to the index, flags that describe how the index should be used, the
78240 ** number of equality constraints, and the "cost" for this index.
78241 **
78242 ** The lowest cost index wins.  The cost is an estimate of the amount of
78243 ** CPU and disk I/O need to process the request using the selected index.
78244 ** Factors that influence cost include:
78245 **
78246 **    *  The estimated number of rows that will be retrieved.  (The
78247 **       fewer the better.)
78248 **
78249 **    *  Whether or not sorting must occur.
78250 **
78251 **    *  Whether or not there must be separate lookups in the
78252 **       index and in the main table.
78253 **
78254 ** If there was an INDEXED BY clause attached to the table in the SELECT
78255 ** statement, then this function only considers strategies using the 
78256 ** named index. If one cannot be found, then the returned cost is
78257 ** SQLITE_BIG_DBL. If a strategy can be found that uses the named index, 
78258 ** then the cost is calculated in the usual way.
78259 **
78260 ** If a NOT INDEXED clause was attached to the table in the SELECT 
78261 ** statement, then no indexes are considered. However, the selected 
78262 ** stategy may still take advantage of the tables built-in rowid
78263 ** index.
78264 */
78265 static double bestIndex(
78266   Parse *pParse,              /* The parsing context */
78267   WhereClause *pWC,           /* The WHERE clause */
78268   struct SrcList_item *pSrc,  /* The FROM clause term to search */
78269   Bitmask notReady,           /* Mask of cursors that are not available */
78270   ExprList *pOrderBy,         /* The order by clause */
78271   Index **ppIndex,            /* Make *ppIndex point to the best index */
78272   int *pFlags,                /* Put flags describing this choice in *pFlags */
78273   int *pnEq                   /* Put the number of == or IN constraints here */
78274 ){
78275   WhereTerm *pTerm;
78276   Index *bestIdx = 0;         /* Index that gives the lowest cost */
78277   double lowestCost;          /* The cost of using bestIdx */
78278   int bestFlags = 0;          /* Flags associated with bestIdx */
78279   int bestNEq = 0;            /* Best value for nEq */
78280   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
78281   Index *pProbe;              /* An index we are evaluating */
78282   int rev;                    /* True to scan in reverse order */
78283   int flags;                  /* Flags associated with pProbe */
78284   int nEq;                    /* Number of == or IN constraints */
78285   int eqTermMask;             /* Mask of valid equality operators */
78286   double cost;                /* Cost of using pProbe */
78287
78288   WHERETRACE(("bestIndex: tbl=%s notReady=%llx\n", pSrc->pTab->zName, notReady));
78289   lowestCost = SQLITE_BIG_DBL;
78290   pProbe = pSrc->pTab->pIndex;
78291   if( pSrc->notIndexed ){
78292     pProbe = 0;
78293   }
78294
78295   /* If the table has no indices and there are no terms in the where
78296   ** clause that refer to the ROWID, then we will never be able to do
78297   ** anything other than a full table scan on this table.  We might as
78298   ** well put it first in the join order.  That way, perhaps it can be
78299   ** referenced by other tables in the join.
78300   */
78301   if( pProbe==0 &&
78302      findTerm(pWC, iCur, -1, 0, WO_EQ|WO_IN|WO_LT|WO_LE|WO_GT|WO_GE,0)==0 &&
78303      (pOrderBy==0 || !sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev)) ){
78304     *pFlags = 0;
78305     *ppIndex = 0;
78306     *pnEq = 0;
78307     return 0.0;
78308   }
78309
78310   /* Check for a rowid=EXPR or rowid IN (...) constraints. If there was
78311   ** an INDEXED BY clause attached to this table, skip this step.
78312   */
78313   if( !pSrc->pIndex ){
78314     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
78315     if( pTerm ){
78316       Expr *pExpr;
78317       *ppIndex = 0;
78318       bestFlags = WHERE_ROWID_EQ;
78319       if( pTerm->eOperator & WO_EQ ){
78320         /* Rowid== is always the best pick.  Look no further.  Because only
78321         ** a single row is generated, output is always in sorted order */
78322         *pFlags = WHERE_ROWID_EQ | WHERE_UNIQUE;
78323         *pnEq = 1;
78324         WHERETRACE(("... best is rowid\n"));
78325         return 0.0;
78326       }else if( (pExpr = pTerm->pExpr)->pList!=0 ){
78327         /* Rowid IN (LIST): cost is NlogN where N is the number of list
78328         ** elements.  */
78329         lowestCost = pExpr->pList->nExpr;
78330         lowestCost *= estLog(lowestCost);
78331       }else{
78332         /* Rowid IN (SELECT): cost is NlogN where N is the number of rows
78333         ** in the result of the inner select.  We have no way to estimate
78334         ** that value so make a wild guess. */
78335         lowestCost = 200;
78336       }
78337       WHERETRACE(("... rowid IN cost: %.9g\n", lowestCost));
78338     }
78339   
78340     /* Estimate the cost of a table scan.  If we do not know how many
78341     ** entries are in the table, use 1 million as a guess.
78342     */
78343     cost = pProbe ? pProbe->aiRowEst[0] : 1000000;
78344     WHERETRACE(("... table scan base cost: %.9g\n", cost));
78345     flags = WHERE_ROWID_RANGE;
78346   
78347     /* Check for constraints on a range of rowids in a table scan.
78348     */
78349     pTerm = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE|WO_GT|WO_GE, 0);
78350     if( pTerm ){
78351       if( findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0) ){
78352         flags |= WHERE_TOP_LIMIT;
78353         cost /= 3;  /* Guess that rowid<EXPR eliminates two-thirds or rows */
78354       }
78355       if( findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0) ){
78356         flags |= WHERE_BTM_LIMIT;
78357         cost /= 3;  /* Guess that rowid>EXPR eliminates two-thirds of rows */
78358       }
78359       WHERETRACE(("... rowid range reduces cost to %.9g\n", cost));
78360     }else{
78361       flags = 0;
78362     }
78363   
78364     /* If the table scan does not satisfy the ORDER BY clause, increase
78365     ** the cost by NlogN to cover the expense of sorting. */
78366     if( pOrderBy ){
78367       if( sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev) ){
78368         flags |= WHERE_ORDERBY|WHERE_ROWID_RANGE;
78369         if( rev ){
78370           flags |= WHERE_REVERSE;
78371         }
78372       }else{
78373         cost += cost*estLog(cost);
78374         WHERETRACE(("... sorting increases cost to %.9g\n", cost));
78375       }
78376     }
78377     if( cost<lowestCost ){
78378       lowestCost = cost;
78379       bestFlags = flags;
78380     }
78381   }
78382
78383   /* If the pSrc table is the right table of a LEFT JOIN then we may not
78384   ** use an index to satisfy IS NULL constraints on that table.  This is
78385   ** because columns might end up being NULL if the table does not match -
78386   ** a circumstance which the index cannot help us discover.  Ticket #2177.
78387   */
78388   if( (pSrc->jointype & JT_LEFT)!=0 ){
78389     eqTermMask = WO_EQ|WO_IN;
78390   }else{
78391     eqTermMask = WO_EQ|WO_IN|WO_ISNULL;
78392   }
78393
78394   /* Look at each index.
78395   */
78396   if( pSrc->pIndex ){
78397     pProbe = pSrc->pIndex;
78398   }
78399   for(; pProbe; pProbe=(pSrc->pIndex ? 0 : pProbe->pNext)){
78400     int i;                       /* Loop counter */
78401     double inMultiplier = 1;
78402
78403     WHERETRACE(("... index %s:\n", pProbe->zName));
78404
78405     /* Count the number of columns in the index that are satisfied
78406     ** by x=EXPR constraints or x IN (...) constraints.
78407     */
78408     flags = 0;
78409     for(i=0; i<pProbe->nColumn; i++){
78410       int j = pProbe->aiColumn[i];
78411       pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pProbe);
78412       if( pTerm==0 ) break;
78413       flags |= WHERE_COLUMN_EQ;
78414       if( pTerm->eOperator & WO_IN ){
78415         Expr *pExpr = pTerm->pExpr;
78416         flags |= WHERE_COLUMN_IN;
78417         if( pExpr->pSelect!=0 ){
78418           inMultiplier *= 25;
78419         }else if( ALWAYS(pExpr->pList) ){
78420           inMultiplier *= pExpr->pList->nExpr + 1;
78421         }
78422       }
78423     }
78424     cost = pProbe->aiRowEst[i] * inMultiplier * estLog(inMultiplier);
78425     nEq = i;
78426     if( pProbe->onError!=OE_None && (flags & WHERE_COLUMN_IN)==0
78427          && nEq==pProbe->nColumn ){
78428       flags |= WHERE_UNIQUE;
78429     }
78430     WHERETRACE(("...... nEq=%d inMult=%.9g cost=%.9g\n",nEq,inMultiplier,cost));
78431
78432     /* Look for range constraints
78433     */
78434     if( nEq<pProbe->nColumn ){
78435       int j = pProbe->aiColumn[nEq];
78436       pTerm = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pProbe);
78437       if( pTerm ){
78438         flags |= WHERE_COLUMN_RANGE;
78439         if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pProbe) ){
78440           flags |= WHERE_TOP_LIMIT;
78441           cost /= 3;
78442         }
78443         if( findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pProbe) ){
78444           flags |= WHERE_BTM_LIMIT;
78445           cost /= 3;
78446         }
78447         WHERETRACE(("...... range reduces cost to %.9g\n", cost));
78448       }
78449     }
78450
78451     /* Add the additional cost of sorting if that is a factor.
78452     */
78453     if( pOrderBy ){
78454       if( (flags & WHERE_COLUMN_IN)==0 &&
78455            isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev) ){
78456         if( flags==0 ){
78457           flags = WHERE_COLUMN_RANGE;
78458         }
78459         flags |= WHERE_ORDERBY;
78460         if( rev ){
78461           flags |= WHERE_REVERSE;
78462         }
78463       }else{
78464         cost += cost*estLog(cost);
78465         WHERETRACE(("...... orderby increases cost to %.9g\n", cost));
78466       }
78467     }
78468
78469     /* Check to see if we can get away with using just the index without
78470     ** ever reading the table.  If that is the case, then halve the
78471     ** cost of this index.
78472     */
78473     if( flags && pSrc->colUsed < (((Bitmask)1)<<(BMS-1)) ){
78474       Bitmask m = pSrc->colUsed;
78475       int j;
78476       for(j=0; j<pProbe->nColumn; j++){
78477         int x = pProbe->aiColumn[j];
78478         if( x<BMS-1 ){
78479           m &= ~(((Bitmask)1)<<x);
78480         }
78481       }
78482       if( m==0 ){
78483         flags |= WHERE_IDX_ONLY;
78484         cost /= 2;
78485         WHERETRACE(("...... idx-only reduces cost to %.9g\n", cost));
78486       }
78487     }
78488
78489     /* If this index has achieved the lowest cost so far, then use it.
78490     */
78491     if( flags && cost < lowestCost ){
78492       bestIdx = pProbe;
78493       lowestCost = cost;
78494       bestFlags = flags;
78495       bestNEq = nEq;
78496     }
78497   }
78498
78499   /* Report the best result
78500   */
78501   *ppIndex = bestIdx;
78502   WHERETRACE(("best index is %s, cost=%.9g, flags=%x, nEq=%d\n",
78503         bestIdx ? bestIdx->zName : "(none)", lowestCost, bestFlags, bestNEq));
78504   *pFlags = bestFlags | eqTermMask;
78505   *pnEq = bestNEq;
78506   return lowestCost;
78507 }
78508
78509
78510 /*
78511 ** Disable a term in the WHERE clause.  Except, do not disable the term
78512 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
78513 ** or USING clause of that join.
78514 **
78515 ** Consider the term t2.z='ok' in the following queries:
78516 **
78517 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
78518 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
78519 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
78520 **
78521 ** The t2.z='ok' is disabled in the in (2) because it originates
78522 ** in the ON clause.  The term is disabled in (3) because it is not part
78523 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
78524 **
78525 ** Disabling a term causes that term to not be tested in the inner loop
78526 ** of the join.  Disabling is an optimization.  When terms are satisfied
78527 ** by indices, we disable them to prevent redundant tests in the inner
78528 ** loop.  We would get the correct results if nothing were ever disabled,
78529 ** but joins might run a little slower.  The trick is to disable as much
78530 ** as we can without disabling too much.  If we disabled in (1), we'd get
78531 ** the wrong answer.  See ticket #813.
78532 */
78533 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
78534   if( pTerm
78535       && ALWAYS((pTerm->flags & TERM_CODED)==0)
78536       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
78537   ){
78538     pTerm->flags |= TERM_CODED;
78539     if( pTerm->iParent>=0 ){
78540       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
78541       if( (--pOther->nChild)==0 ){
78542         disableTerm(pLevel, pOther);
78543       }
78544     }
78545   }
78546 }
78547
78548 /*
78549 ** Apply the affinities associated with the first n columns of index
78550 ** pIdx to the values in the n registers starting at base.
78551 */
78552 static void codeApplyAffinity(Parse *pParse, int base, int n, Index *pIdx){
78553   if( n>0 ){
78554     Vdbe *v = pParse->pVdbe;
78555     assert( v!=0 );
78556     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
78557     sqlite3IndexAffinityStr(v, pIdx);
78558     sqlite3ExprCacheAffinityChange(pParse, base, n);
78559   }
78560 }
78561
78562
78563 /*
78564 ** Generate code for a single equality term of the WHERE clause.  An equality
78565 ** term can be either X=expr or X IN (...).   pTerm is the term to be 
78566 ** coded.
78567 **
78568 ** The current value for the constraint is left in register iReg.
78569 **
78570 ** For a constraint of the form X=expr, the expression is evaluated and its
78571 ** result is left on the stack.  For constraints of the form X IN (...)
78572 ** this routine sets up a loop that will iterate over all values of X.
78573 */
78574 static int codeEqualityTerm(
78575   Parse *pParse,      /* The parsing context */
78576   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
78577   WhereLevel *pLevel, /* When level of the FROM clause we are working on */
78578   int iTarget         /* Attempt to leave results in this register */
78579 ){
78580   Expr *pX = pTerm->pExpr;
78581   Vdbe *v = pParse->pVdbe;
78582   int iReg;                  /* Register holding results */
78583
78584   assert( iTarget>0 );
78585   if( pX->op==TK_EQ ){
78586     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
78587   }else if( pX->op==TK_ISNULL ){
78588     iReg = iTarget;
78589     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
78590 #ifndef SQLITE_OMIT_SUBQUERY
78591   }else{
78592     int eType;
78593     int iTab;
78594     struct InLoop *pIn;
78595
78596     assert( pX->op==TK_IN );
78597     iReg = iTarget;
78598     eType = sqlite3FindInIndex(pParse, pX, 0);
78599     iTab = pX->iTable;
78600     sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
78601     VdbeComment((v, "%.*s", pX->span.n, pX->span.z));
78602     if( pLevel->nIn==0 ){
78603       pLevel->nxt = sqlite3VdbeMakeLabel(v);
78604     }
78605     pLevel->nIn++;
78606     pLevel->aInLoop = sqlite3DbReallocOrFree(pParse->db, pLevel->aInLoop,
78607                                     sizeof(pLevel->aInLoop[0])*pLevel->nIn);
78608     pIn = pLevel->aInLoop;
78609     if( pIn ){
78610       pIn += pLevel->nIn - 1;
78611       pIn->iCur = iTab;
78612       if( eType==IN_INDEX_ROWID ){
78613         pIn->topAddr = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
78614       }else{
78615         pIn->topAddr = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
78616       }
78617       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
78618     }else{
78619       pLevel->nIn = 0;
78620     }
78621 #endif
78622   }
78623   disableTerm(pLevel, pTerm);
78624   return iReg;
78625 }
78626
78627 /*
78628 ** Generate code that will evaluate all == and IN constraints for an
78629 ** index.  The values for all constraints are left on the stack.
78630 **
78631 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
78632 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
78633 ** The index has as many as three equality constraints, but in this
78634 ** example, the third "c" value is an inequality.  So only two 
78635 ** constraints are coded.  This routine will generate code to evaluate
78636 ** a==5 and b IN (1,2,3).  The current values for a and b will be left
78637 ** on the stack - a is the deepest and b the shallowest.
78638 **
78639 ** In the example above nEq==2.  But this subroutine works for any value
78640 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
78641 ** The only thing it does is allocate the pLevel->iMem memory cell.
78642 **
78643 ** This routine always allocates at least one memory cell and puts
78644 ** the address of that memory cell in pLevel->iMem.  The code that
78645 ** calls this routine will use pLevel->iMem to store the termination
78646 ** key value of the loop.  If one or more IN operators appear, then
78647 ** this routine allocates an additional nEq memory cells for internal
78648 ** use.
78649 */
78650 static int codeAllEqualityTerms(
78651   Parse *pParse,        /* Parsing context */
78652   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
78653   WhereClause *pWC,     /* The WHERE clause */
78654   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
78655   int nExtraReg         /* Number of extra registers to allocate */
78656 ){
78657   int nEq = pLevel->nEq;        /* The number of == or IN constraints to code */
78658   Vdbe *v = pParse->pVdbe;      /* The virtual machine under construction */
78659   Index *pIdx = pLevel->pIdx;   /* The index being used for this loop */
78660   int iCur = pLevel->iTabCur;   /* The cursor of the table */
78661   WhereTerm *pTerm;             /* A single constraint term */
78662   int j;                        /* Loop counter */
78663   int regBase;                  /* Base register */
78664
78665   /* Figure out how many memory cells we will need then allocate them.
78666   ** We always need at least one used to store the loop terminator
78667   ** value.  If there are IN operators we'll need one for each == or
78668   ** IN constraint.
78669   */
78670   pLevel->iMem = pParse->nMem + 1;
78671   regBase = pParse->nMem + 2;
78672   pParse->nMem += pLevel->nEq + 2 + nExtraReg;
78673
78674   /* Evaluate the equality constraints
78675   */
78676   assert( pIdx->nColumn>=nEq );
78677   for(j=0; j<nEq; j++){
78678     int r1;
78679     int k = pIdx->aiColumn[j];
78680     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->flags, pIdx);
78681     if( NEVER(pTerm==0) ) break;
78682     assert( (pTerm->flags & TERM_CODED)==0 );
78683     r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
78684     if( r1!=regBase+j ){
78685       sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
78686     }
78687     testcase( pTerm->eOperator & WO_ISNULL );
78688     testcase( pTerm->eOperator & WO_IN );
78689     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
78690       sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->brk);
78691     }
78692   }
78693   return regBase;
78694 }
78695
78696 #if defined(SQLITE_TEST)
78697 /*
78698 ** The following variable holds a text description of query plan generated
78699 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
78700 ** overwrites the previous.  This information is used for testing and
78701 ** analysis only.
78702 */
78703 SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
78704 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
78705
78706 #endif /* SQLITE_TEST */
78707
78708
78709 /*
78710 ** Free a WhereInfo structure
78711 */
78712 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
78713   if( pWInfo ){
78714     int i;
78715     for(i=0; i<pWInfo->nLevel; i++){
78716       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
78717       if( pInfo ){
78718         assert( pInfo->needToFreeIdxStr==0 );
78719         sqlite3DbFree(db, pInfo);
78720       }
78721     }
78722     sqlite3DbFree(db, pWInfo);
78723   }
78724 }
78725
78726
78727 /*
78728 ** Generate the beginning of the loop used for WHERE clause processing.
78729 ** The return value is a pointer to an opaque structure that contains
78730 ** information needed to terminate the loop.  Later, the calling routine
78731 ** should invoke sqlite3WhereEnd() with the return value of this function
78732 ** in order to complete the WHERE clause processing.
78733 **
78734 ** If an error occurs, this routine returns NULL.
78735 **
78736 ** The basic idea is to do a nested loop, one loop for each table in
78737 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
78738 ** same as a SELECT with only a single table in the FROM clause.)  For
78739 ** example, if the SQL is this:
78740 **
78741 **       SELECT * FROM t1, t2, t3 WHERE ...;
78742 **
78743 ** Then the code generated is conceptually like the following:
78744 **
78745 **      foreach row1 in t1 do       \    Code generated
78746 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
78747 **          foreach row3 in t3 do   /
78748 **            ...
78749 **          end                     \    Code generated
78750 **        end                        |-- by sqlite3WhereEnd()
78751 **      end                         /
78752 **
78753 ** Note that the loops might not be nested in the order in which they
78754 ** appear in the FROM clause if a different order is better able to make
78755 ** use of indices.  Note also that when the IN operator appears in
78756 ** the WHERE clause, it might result in additional nested loops for
78757 ** scanning through all values on the right-hand side of the IN.
78758 **
78759 ** There are Btree cursors associated with each table.  t1 uses cursor
78760 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
78761 ** And so forth.  This routine generates code to open those VDBE cursors
78762 ** and sqlite3WhereEnd() generates the code to close them.
78763 **
78764 ** The code that sqlite3WhereBegin() generates leaves the cursors named
78765 ** in pTabList pointing at their appropriate entries.  The [...] code
78766 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
78767 ** data from the various tables of the loop.
78768 **
78769 ** If the WHERE clause is empty, the foreach loops must each scan their
78770 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
78771 ** the tables have indices and there are terms in the WHERE clause that
78772 ** refer to those indices, a complete table scan can be avoided and the
78773 ** code will run much faster.  Most of the work of this routine is checking
78774 ** to see if there are indices that can be used to speed up the loop.
78775 **
78776 ** Terms of the WHERE clause are also used to limit which rows actually
78777 ** make it to the "..." in the middle of the loop.  After each "foreach",
78778 ** terms of the WHERE clause that use only terms in that loop and outer
78779 ** loops are evaluated and if false a jump is made around all subsequent
78780 ** inner loops (or around the "..." if the test occurs within the inner-
78781 ** most loop)
78782 **
78783 ** OUTER JOINS
78784 **
78785 ** An outer join of tables t1 and t2 is conceptally coded as follows:
78786 **
78787 **    foreach row1 in t1 do
78788 **      flag = 0
78789 **      foreach row2 in t2 do
78790 **        start:
78791 **          ...
78792 **          flag = 1
78793 **      end
78794 **      if flag==0 then
78795 **        move the row2 cursor to a null row
78796 **        goto start
78797 **      fi
78798 **    end
78799 **
78800 ** ORDER BY CLAUSE PROCESSING
78801 **
78802 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
78803 ** if there is one.  If there is no ORDER BY clause or if this routine
78804 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
78805 **
78806 ** If an index can be used so that the natural output order of the table
78807 ** scan is correct for the ORDER BY clause, then that index is used and
78808 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
78809 ** unnecessary sort of the result set if an index appropriate for the
78810 ** ORDER BY clause already exists.
78811 **
78812 ** If the where clause loops cannot be arranged to provide the correct
78813 ** output order, then the *ppOrderBy is unchanged.
78814 */
78815 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
78816   Parse *pParse,        /* The parser context */
78817   SrcList *pTabList,    /* A list of all tables to be scanned */
78818   Expr *pWhere,         /* The WHERE clause */
78819   ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
78820   u8 wflags             /* One of the WHERE_* flags defined in sqliteInt.h */
78821 ){
78822   int i;                     /* Loop counter */
78823   WhereInfo *pWInfo;         /* Will become the return value of this function */
78824   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
78825   int brk, cont = 0;         /* Addresses used during code generation */
78826   Bitmask notReady;          /* Cursors that are not yet positioned */
78827   WhereTerm *pTerm;          /* A single term in the WHERE clause */
78828   ExprMaskSet maskSet;       /* The expression mask set */
78829   WhereClause wc;            /* The WHERE clause is divided into these terms */
78830   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
78831   WhereLevel *pLevel;             /* A single level in the pWInfo list */
78832   int iFrom;                      /* First unused FROM clause element */
78833   int andFlags;              /* AND-ed combination of all wc.a[].flags */
78834   sqlite3 *db;               /* Database connection */
78835   ExprList *pOrderBy = 0;
78836
78837   /* The number of tables in the FROM clause is limited by the number of
78838   ** bits in a Bitmask 
78839   */
78840   if( pTabList->nSrc>BMS ){
78841     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
78842     return 0;
78843   }
78844
78845   if( ppOrderBy ){
78846     pOrderBy = *ppOrderBy;
78847   }
78848
78849   /* Split the WHERE clause into separate subexpressions where each
78850   ** subexpression is separated by an AND operator.
78851   */
78852   initMaskSet(&maskSet);
78853   whereClauseInit(&wc, pParse, &maskSet);
78854   sqlite3ExprCodeConstants(pParse, pWhere);
78855   whereSplit(&wc, pWhere, TK_AND);
78856     
78857   /* Allocate and initialize the WhereInfo structure that will become the
78858   ** return value.
78859   */
78860   db = pParse->db;
78861   pWInfo = sqlite3DbMallocZero(db,  
78862                       sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
78863   if( db->mallocFailed ){
78864     goto whereBeginError;
78865   }
78866   pWInfo->nLevel = pTabList->nSrc;
78867   pWInfo->pParse = pParse;
78868   pWInfo->pTabList = pTabList;
78869   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
78870
78871   /* Special case: a WHERE clause that is constant.  Evaluate the
78872   ** expression and either jump over all of the code or fall thru.
78873   */
78874   if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
78875     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
78876     pWhere = 0;
78877   }
78878
78879   /* Assign a bit from the bitmask to every term in the FROM clause.
78880   **
78881   ** When assigning bitmask values to FROM clause cursors, it must be
78882   ** the case that if X is the bitmask for the N-th FROM clause term then
78883   ** the bitmask for all FROM clause terms to the left of the N-th term
78884   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
78885   ** its Expr.iRightJoinTable value to find the bitmask of the right table
78886   ** of the join.  Subtracting one from the right table bitmask gives a
78887   ** bitmask for all tables to the left of the join.  Knowing the bitmask
78888   ** for all tables to the left of a left join is important.  Ticket #3015.
78889   */
78890   for(i=0; i<pTabList->nSrc; i++){
78891     createMask(&maskSet, pTabList->a[i].iCursor);
78892   }
78893 #ifndef NDEBUG
78894   {
78895     Bitmask toTheLeft = 0;
78896     for(i=0; i<pTabList->nSrc; i++){
78897       Bitmask m = getMask(&maskSet, pTabList->a[i].iCursor);
78898       assert( (m-1)==toTheLeft );
78899       toTheLeft |= m;
78900     }
78901   }
78902 #endif
78903
78904   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
78905   ** add new virtual terms onto the end of the WHERE clause.  We do not
78906   ** want to analyze these virtual terms, so start analyzing at the end
78907   ** and work forward so that the added virtual terms are never processed.
78908   */
78909   exprAnalyzeAll(pTabList, &wc);
78910   if( db->mallocFailed ){
78911     goto whereBeginError;
78912   }
78913
78914   /* Chose the best index to use for each table in the FROM clause.
78915   **
78916   ** This loop fills in the following fields:
78917   **
78918   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
78919   **   pWInfo->a[].flags     WHERE_xxx flags associated with pIdx
78920   **   pWInfo->a[].nEq       The number of == and IN constraints
78921   **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
78922   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
78923   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
78924   **
78925   ** This loop also figures out the nesting order of tables in the FROM
78926   ** clause.
78927   */
78928   notReady = ~(Bitmask)0;
78929   pTabItem = pTabList->a;
78930   pLevel = pWInfo->a;
78931   andFlags = ~0;
78932   WHERETRACE(("*** Optimizer Start ***\n"));
78933   for(i=iFrom=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
78934     Index *pIdx;                /* Index for FROM table at pTabItem */
78935     int flags;                  /* Flags asssociated with pIdx */
78936     int nEq;                    /* Number of == or IN constraints */
78937     double cost;                /* The cost for pIdx */
78938     int j;                      /* For looping over FROM tables */
78939     Index *pBest = 0;           /* The best index seen so far */
78940     int bestFlags = 0;          /* Flags associated with pBest */
78941     int bestNEq = 0;            /* nEq associated with pBest */
78942     double lowestCost;          /* Cost of the pBest */
78943     int bestJ = 0;              /* The value of j */
78944     Bitmask m;                  /* Bitmask value for j or bestJ */
78945     int once = 0;               /* True when first table is seen */
78946     sqlite3_index_info *pIndex; /* Current virtual index */
78947
78948     lowestCost = SQLITE_BIG_DBL;
78949     for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
78950       int doNotReorder;  /* True if this table should not be reordered */
78951
78952       doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
78953       if( once && doNotReorder ) break;
78954       m = getMask(&maskSet, pTabItem->iCursor);
78955       if( (m & notReady)==0 ){
78956         if( j==iFrom ) iFrom++;
78957         continue;
78958       }
78959       assert( pTabItem->pTab );
78960 #ifndef SQLITE_OMIT_VIRTUALTABLE
78961       if( IsVirtual(pTabItem->pTab) ){
78962         sqlite3_index_info **ppIdxInfo = &pWInfo->a[j].pIdxInfo;
78963         cost = bestVirtualIndex(pParse, &wc, pTabItem, notReady,
78964                                 ppOrderBy ? *ppOrderBy : 0, i==0,
78965                                 ppIdxInfo);
78966         flags = WHERE_VIRTUALTABLE;
78967         pIndex = *ppIdxInfo;
78968         if( pIndex && pIndex->orderByConsumed ){
78969           flags = WHERE_VIRTUALTABLE | WHERE_ORDERBY;
78970         }
78971         pIdx = 0;
78972         nEq = 0;
78973         if( (SQLITE_BIG_DBL/2.0)<cost ){
78974           /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
78975           ** inital value of lowestCost in this loop. If it is, then
78976           ** the (cost<lowestCost) test below will never be true and
78977           ** pLevel->pBestIdx never set.
78978           */ 
78979           cost = (SQLITE_BIG_DBL/2.0);
78980         }
78981       }else 
78982 #endif
78983       {
78984         cost = bestIndex(pParse, &wc, pTabItem, notReady,
78985                          (i==0 && ppOrderBy) ? *ppOrderBy : 0,
78986                          &pIdx, &flags, &nEq);
78987         pIndex = 0;
78988       }
78989       if( cost<lowestCost ){
78990         once = 1;
78991         lowestCost = cost;
78992         pBest = pIdx;
78993         bestFlags = flags;
78994         bestNEq = nEq;
78995         bestJ = j;
78996         pLevel->pBestIdx = pIndex;
78997       }
78998       if( doNotReorder ) break;
78999     }
79000     WHERETRACE(("*** Optimizer selects table %d for loop %d\n", bestJ,
79001            pLevel-pWInfo->a));
79002     if( (bestFlags & WHERE_ORDERBY)!=0 ){
79003       *ppOrderBy = 0;
79004     }
79005     andFlags &= bestFlags;
79006     pLevel->flags = bestFlags;
79007     pLevel->pIdx = pBest;
79008     pLevel->nEq = bestNEq;
79009     pLevel->aInLoop = 0;
79010     pLevel->nIn = 0;
79011     if( pBest ){
79012       pLevel->iIdxCur = pParse->nTab++;
79013     }else{
79014       pLevel->iIdxCur = -1;
79015     }
79016     notReady &= ~getMask(&maskSet, pTabList->a[bestJ].iCursor);
79017     pLevel->iFrom = bestJ;
79018
79019     /* Check that if the table scanned by this loop iteration had an
79020     ** INDEXED BY clause attached to it, that the named index is being
79021     ** used for the scan. If not, then query compilation has failed.
79022     ** Return an error.
79023     */
79024     pIdx = pTabList->a[bestJ].pIndex;
79025     assert( !pIdx || !pBest || pIdx==pBest );
79026     if( pIdx && pBest!=pIdx ){
79027       sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
79028       goto whereBeginError;
79029     }
79030   }
79031   WHERETRACE(("*** Optimizer Finished ***\n"));
79032
79033   /* If the total query only selects a single row, then the ORDER BY
79034   ** clause is irrelevant.
79035   */
79036   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
79037     *ppOrderBy = 0;
79038   }
79039
79040   /* If the caller is an UPDATE or DELETE statement that is requesting
79041   ** to use a one-pass algorithm, determine if this is appropriate.
79042   ** The one-pass algorithm only works if the WHERE clause constraints
79043   ** the statement to update a single row.
79044   */
79045   assert( (wflags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
79046   if( (wflags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
79047     pWInfo->okOnePass = 1;
79048     pWInfo->a[0].flags &= ~WHERE_IDX_ONLY;
79049   }
79050
79051   /* Open all tables in the pTabList and any indices selected for
79052   ** searching those tables.
79053   */
79054   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
79055   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
79056     Table *pTab;     /* Table to open */
79057     Index *pIx;      /* Index used to access pTab (if any) */
79058     int iDb;         /* Index of database containing table/index */
79059     int iIdxCur = pLevel->iIdxCur;
79060
79061 #ifndef SQLITE_OMIT_EXPLAIN
79062     if( pParse->explain==2 ){
79063       char *zMsg;
79064       struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
79065       zMsg = sqlite3MPrintf(db, "TABLE %s", pItem->zName);
79066       if( pItem->zAlias ){
79067         zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
79068       }
79069       if( (pIx = pLevel->pIdx)!=0 ){
79070         zMsg = sqlite3MAppendf(db, zMsg, "%s WITH INDEX %s", zMsg, pIx->zName);
79071       }else if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
79072         zMsg = sqlite3MAppendf(db, zMsg, "%s USING PRIMARY KEY", zMsg);
79073       }
79074 #ifndef SQLITE_OMIT_VIRTUALTABLE
79075       else if( pLevel->pBestIdx ){
79076         sqlite3_index_info *pBestIdx = pLevel->pBestIdx;
79077         zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
79078                     pBestIdx->idxNum, pBestIdx->idxStr);
79079       }
79080 #endif
79081       if( pLevel->flags & WHERE_ORDERBY ){
79082         zMsg = sqlite3MAppendf(db, zMsg, "%s ORDER BY", zMsg);
79083       }
79084       sqlite3VdbeAddOp4(v, OP_Explain, i, pLevel->iFrom, 0, zMsg, P4_DYNAMIC);
79085     }
79086 #endif /* SQLITE_OMIT_EXPLAIN */
79087     pTabItem = &pTabList->a[pLevel->iFrom];
79088     pTab = pTabItem->pTab;
79089     iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
79090     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
79091 #ifndef SQLITE_OMIT_VIRTUALTABLE
79092     if( pLevel->pBestIdx ){
79093       int iCur = pTabItem->iCursor;
79094       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0,
79095                         (const char*)pTab->pVtab, P4_VTAB);
79096     }else
79097 #endif
79098     if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
79099       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
79100       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
79101       if( !pWInfo->okOnePass && pTab->nCol<BMS ){
79102         Bitmask b = pTabItem->colUsed;
79103         int n = 0;
79104         for(; b; b=b>>1, n++){}
79105         sqlite3VdbeChangeP2(v, sqlite3VdbeCurrentAddr(v)-2, n);
79106         assert( n<=pTab->nCol );
79107       }
79108     }else{
79109       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
79110     }
79111     pLevel->iTabCur = pTabItem->iCursor;
79112     if( (pIx = pLevel->pIdx)!=0 ){
79113       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
79114       assert( pIx->pSchema==pTab->pSchema );
79115       sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pIx->nColumn+1);
79116       sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
79117                         (char*)pKey, P4_KEYINFO_HANDOFF);
79118       VdbeComment((v, "%s", pIx->zName));
79119     }
79120     sqlite3CodeVerifySchema(pParse, iDb);
79121   }
79122   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
79123
79124   /* Generate the code to do the search.  Each iteration of the for
79125   ** loop below generates code for a single nested loop of the VM
79126   ** program.
79127   */
79128   notReady = ~(Bitmask)0;
79129   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
79130     int j, k;
79131     int iCur = pTabItem->iCursor;  /* The VDBE cursor for the table */
79132     Index *pIdx;       /* The index we will be using */
79133     int nxt;           /* Where to jump to continue with the next IN case */
79134     int iIdxCur;       /* The VDBE cursor for the index */
79135     int omitTable;     /* True if we use the index only */
79136     int bRev;          /* True if we need to scan in reverse order */
79137
79138     pTabItem = &pTabList->a[pLevel->iFrom];
79139     iCur = pTabItem->iCursor;
79140     pIdx = pLevel->pIdx;
79141     iIdxCur = pLevel->iIdxCur;
79142     bRev = (pLevel->flags & WHERE_REVERSE)!=0;
79143     omitTable = (pLevel->flags & WHERE_IDX_ONLY)!=0;
79144
79145     /* Create labels for the "break" and "continue" instructions
79146     ** for the current loop.  Jump to brk to break out of a loop.
79147     ** Jump to cont to go immediately to the next iteration of the
79148     ** loop.
79149     **
79150     ** When there is an IN operator, we also have a "nxt" label that
79151     ** means to continue with the next IN value combination.  When
79152     ** there are no IN operators in the constraints, the "nxt" label
79153     ** is the same as "brk".
79154     */
79155     brk = pLevel->brk = pLevel->nxt = sqlite3VdbeMakeLabel(v);
79156     cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
79157
79158     /* If this is the right table of a LEFT OUTER JOIN, allocate and
79159     ** initialize a memory cell that records if this table matches any
79160     ** row of the left table of the join.
79161     */
79162     if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
79163       pLevel->iLeftJoin = ++pParse->nMem;
79164       sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
79165       VdbeComment((v, "init LEFT JOIN no-match flag"));
79166     }
79167
79168 #ifndef SQLITE_OMIT_VIRTUALTABLE
79169     if( pLevel->pBestIdx ){
79170       /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
79171       **          to access the data.
79172       */
79173       int j;
79174       int iReg;   /* P3 Value for OP_VFilter */
79175       sqlite3_index_info *pBestIdx = pLevel->pBestIdx;
79176       int nConstraint = pBestIdx->nConstraint;
79177       struct sqlite3_index_constraint_usage *aUsage =
79178                                                   pBestIdx->aConstraintUsage;
79179       const struct sqlite3_index_constraint *aConstraint =
79180                                                   pBestIdx->aConstraint;
79181
79182       iReg = sqlite3GetTempRange(pParse, nConstraint+2);
79183       pParse->disableColCache++;
79184       for(j=1; j<=nConstraint; j++){
79185         int k;
79186         for(k=0; k<nConstraint; k++){
79187           if( aUsage[k].argvIndex==j ){
79188             int iTerm = aConstraint[k].iTermOffset;
79189             assert( pParse->disableColCache );
79190             sqlite3ExprCode(pParse, wc.a[iTerm].pExpr->pRight, iReg+j+1);
79191             break;
79192           }
79193         }
79194         if( k==nConstraint ) break;
79195       }
79196       assert( pParse->disableColCache );
79197       pParse->disableColCache--;
79198       sqlite3VdbeAddOp2(v, OP_Integer, pBestIdx->idxNum, iReg);
79199       sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
79200       sqlite3VdbeAddOp4(v, OP_VFilter, iCur, brk, iReg, pBestIdx->idxStr,
79201                         pBestIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
79202       sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
79203       pBestIdx->needToFreeIdxStr = 0;
79204       for(j=0; j<nConstraint; j++){
79205         if( aUsage[j].omit ){
79206           int iTerm = aConstraint[j].iTermOffset;
79207           disableTerm(pLevel, &wc.a[iTerm]);
79208         }
79209       }
79210       pLevel->op = OP_VNext;
79211       pLevel->p1 = iCur;
79212       pLevel->p2 = sqlite3VdbeCurrentAddr(v);
79213     }else
79214 #endif /* SQLITE_OMIT_VIRTUALTABLE */
79215
79216     if( pLevel->flags & WHERE_ROWID_EQ ){
79217       /* Case 1:  We can directly reference a single row using an
79218       **          equality comparison against the ROWID field.  Or
79219       **          we reference multiple rows using a "rowid IN (...)"
79220       **          construct.
79221       */
79222       int r1;
79223       int rtmp = sqlite3GetTempReg(pParse);
79224       pTerm = findTerm(&wc, iCur, -1, notReady, WO_EQ|WO_IN, 0);
79225       assert( pTerm!=0 );
79226       assert( pTerm->pExpr!=0 );
79227       assert( pTerm->leftCursor==iCur );
79228       assert( omitTable==0 );
79229       r1 = codeEqualityTerm(pParse, pTerm, pLevel, rtmp);
79230       nxt = pLevel->nxt;
79231       sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, nxt);
79232       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, nxt, r1);
79233       sqlite3ReleaseTempReg(pParse, rtmp);
79234       VdbeComment((v, "pk"));
79235       pLevel->op = OP_Noop;
79236     }else if( pLevel->flags & WHERE_ROWID_RANGE ){
79237       /* Case 2:  We have an inequality comparison against the ROWID field.
79238       */
79239       int testOp = OP_Noop;
79240       int start;
79241       WhereTerm *pStart, *pEnd;
79242
79243       assert( omitTable==0 );
79244       pStart = findTerm(&wc, iCur, -1, notReady, WO_GT|WO_GE, 0);
79245       pEnd = findTerm(&wc, iCur, -1, notReady, WO_LT|WO_LE, 0);
79246       if( bRev ){
79247         pTerm = pStart;
79248         pStart = pEnd;
79249         pEnd = pTerm;
79250       }
79251       if( pStart ){
79252         Expr *pX;
79253         int r1;
79254         pX = pStart->pExpr;
79255         assert( pX!=0 );
79256         assert( pStart->leftCursor==iCur );
79257
79258         /* The ForceInt instruction may modify the register that it operates
79259         ** on. For example it may replace a real value with an integer one,
79260         ** or if p3 is true it may increment the register value. For this
79261         ** reason we need to make sure that register r1 is really a newly
79262         ** allocated temporary register, and not part of the column-cache.
79263         ** For this reason we cannot use sqlite3ExprCodeTemp() here.
79264         */
79265         r1 = sqlite3GetTempReg(pParse);
79266         sqlite3ExprCode(pParse, pX->pRight, r1);
79267
79268         sqlite3VdbeAddOp3(v, OP_ForceInt, r1, brk, 
79269                              pX->op==TK_LE || pX->op==TK_GT);
79270         sqlite3VdbeAddOp3(v, bRev ? OP_MoveLt : OP_MoveGe, iCur, brk, r1);
79271         VdbeComment((v, "pk"));
79272         sqlite3ReleaseTempReg(pParse, r1);
79273         disableTerm(pLevel, pStart);
79274       }else{
79275         sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, brk);
79276       }
79277       if( pEnd ){
79278         Expr *pX;
79279         pX = pEnd->pExpr;
79280         assert( pX!=0 );
79281         assert( pEnd->leftCursor==iCur );
79282         pLevel->iMem = ++pParse->nMem;
79283         sqlite3ExprCode(pParse, pX->pRight, pLevel->iMem);
79284         if( pX->op==TK_LT || pX->op==TK_GT ){
79285           testOp = bRev ? OP_Le : OP_Ge;
79286         }else{
79287           testOp = bRev ? OP_Lt : OP_Gt;
79288         }
79289         disableTerm(pLevel, pEnd);
79290       }
79291       start = sqlite3VdbeCurrentAddr(v);
79292       pLevel->op = bRev ? OP_Prev : OP_Next;
79293       pLevel->p1 = iCur;
79294       pLevel->p2 = start;
79295       if( testOp!=OP_Noop ){
79296         int r1 = sqlite3GetTempReg(pParse);
79297         sqlite3VdbeAddOp2(v, OP_Rowid, iCur, r1);
79298         /* sqlite3VdbeAddOp2(v, OP_SCopy, pLevel->iMem, 0); */
79299         sqlite3VdbeAddOp3(v, testOp, pLevel->iMem, brk, r1);
79300         sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
79301         sqlite3ReleaseTempReg(pParse, r1);
79302       }
79303     }else if( pLevel->flags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
79304       /* Case 3: A scan using an index.
79305       **
79306       **         The WHERE clause may contain zero or more equality 
79307       **         terms ("==" or "IN" operators) that refer to the N
79308       **         left-most columns of the index. It may also contain
79309       **         inequality constraints (>, <, >= or <=) on the indexed
79310       **         column that immediately follows the N equalities. Only 
79311       **         the right-most column can be an inequality - the rest must
79312       **         use the "==" and "IN" operators. For example, if the 
79313       **         index is on (x,y,z), then the following clauses are all 
79314       **         optimized:
79315       **
79316       **            x=5
79317       **            x=5 AND y=10
79318       **            x=5 AND y<10
79319       **            x=5 AND y>5 AND y<10
79320       **            x=5 AND y=5 AND z<=10
79321       **
79322       **         The z<10 term of the following cannot be used, only
79323       **         the x=5 term:
79324       **
79325       **            x=5 AND z<10
79326       **
79327       **         N may be zero if there are inequality constraints.
79328       **         If there are no inequality constraints, then N is at
79329       **         least one.
79330       **
79331       **         This case is also used when there are no WHERE clause
79332       **         constraints but an index is selected anyway, in order
79333       **         to force the output order to conform to an ORDER BY.
79334       */  
79335       int aStartOp[] = {
79336         0,
79337         0,
79338         OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
79339         OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
79340         OP_MoveGt,           /* 4: (start_constraints  && !startEq && !bRev) */
79341         OP_MoveLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
79342         OP_MoveGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
79343         OP_MoveLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
79344       };
79345       int aEndOp[] = {
79346         OP_Noop,             /* 0: (!end_constraints) */
79347         OP_IdxGE,            /* 1: (end_constraints && !bRev) */
79348         OP_IdxLT             /* 2: (end_constraints && bRev) */
79349       };
79350       int nEq = pLevel->nEq;
79351       int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
79352       int regBase;                 /* Base register holding constraint values */
79353       int r1;                      /* Temp register */
79354       WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
79355       WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
79356       int startEq;                 /* True if range start uses ==, >= or <= */
79357       int endEq;                   /* True if range end uses ==, >= or <= */
79358       int start_constraints;       /* Start of range is constrained */
79359       int k = pIdx->aiColumn[nEq]; /* Column for inequality constraints */
79360       int nConstraint;             /* Number of constraint terms */
79361       int op;
79362
79363       /* Generate code to evaluate all constraint terms using == or IN
79364       ** and store the values of those terms in an array of registers
79365       ** starting at regBase.
79366       */
79367       regBase = codeAllEqualityTerms(pParse, pLevel, &wc, notReady, 2);
79368       nxt = pLevel->nxt;
79369
79370       /* If this loop satisfies a sort order (pOrderBy) request that 
79371       ** was passed to this function to implement a "SELECT min(x) ..." 
79372       ** query, then the caller will only allow the loop to run for
79373       ** a single iteration. This means that the first row returned
79374       ** should not have a NULL value stored in 'x'. If column 'x' is
79375       ** the first one after the nEq equality constraints in the index,
79376       ** this requires some special handling.
79377       */
79378       if( (wflags&WHERE_ORDERBY_MIN)!=0
79379        && (pLevel->flags&WHERE_ORDERBY)
79380        && (pIdx->nColumn>nEq)
79381       ){
79382         assert( pOrderBy->nExpr==1 );
79383         assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] );
79384         isMinQuery = 1;
79385       }
79386
79387       /* Find any inequality constraint terms for the start and end 
79388       ** of the range. 
79389       */
79390       if( pLevel->flags & WHERE_TOP_LIMIT ){
79391         pRangeEnd = findTerm(&wc, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
79392       }
79393       if( pLevel->flags & WHERE_BTM_LIMIT ){
79394         pRangeStart = findTerm(&wc, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
79395       }
79396
79397       /* If we are doing a reverse order scan on an ascending index, or
79398       ** a forward order scan on a descending index, interchange the 
79399       ** start and end terms (pRangeStart and pRangeEnd).
79400       */
79401       if( bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
79402         SWAP(WhereTerm *, pRangeEnd, pRangeStart);
79403       }
79404
79405       testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
79406       testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
79407       testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
79408       testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
79409       startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
79410       endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
79411       start_constraints = pRangeStart || nEq>0;
79412
79413       /* Seek the index cursor to the start of the range. */
79414       nConstraint = nEq;
79415       if( pRangeStart ){
79416         int dcc = pParse->disableColCache;
79417         if( pRangeEnd ){
79418           pParse->disableColCache++;
79419         }
79420         sqlite3ExprCode(pParse, pRangeStart->pExpr->pRight, regBase+nEq);
79421         pParse->disableColCache = dcc;
79422         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, nxt);
79423         nConstraint++;
79424       }else if( isMinQuery ){
79425         sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
79426         nConstraint++;
79427         startEq = 0;
79428         start_constraints = 1;
79429       }
79430       codeApplyAffinity(pParse, regBase, nConstraint, pIdx);
79431       op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
79432       assert( op!=0 );
79433       testcase( op==OP_Rewind );
79434       testcase( op==OP_Last );
79435       testcase( op==OP_MoveGt );
79436       testcase( op==OP_MoveGe );
79437       testcase( op==OP_MoveLe );
79438       testcase( op==OP_MoveLt );
79439       sqlite3VdbeAddOp4(v, op, iIdxCur, nxt, regBase, 
79440                         SQLITE_INT_TO_PTR(nConstraint), P4_INT32);
79441
79442       /* Load the value for the inequality constraint at the end of the
79443       ** range (if any).
79444       */
79445       nConstraint = nEq;
79446       if( pRangeEnd ){
79447         sqlite3ExprCode(pParse, pRangeEnd->pExpr->pRight, regBase+nEq);
79448         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, nxt);
79449         codeApplyAffinity(pParse, regBase, nEq+1, pIdx);
79450         nConstraint++;
79451       }
79452
79453       /* Top of the loop body */
79454       pLevel->p2 = sqlite3VdbeCurrentAddr(v);
79455
79456       /* Check if the index cursor is past the end of the range. */
79457       op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
79458       testcase( op==OP_Noop );
79459       testcase( op==OP_IdxGE );
79460       testcase( op==OP_IdxLT );
79461       sqlite3VdbeAddOp4(v, op, iIdxCur, nxt, regBase,
79462                         SQLITE_INT_TO_PTR(nConstraint), P4_INT32);
79463       sqlite3VdbeChangeP5(v, endEq!=bRev);
79464
79465       /* If there are inequality constraints, check that the value
79466       ** of the table column that the inequality contrains is not NULL.
79467       ** If it is, jump to the next iteration of the loop.
79468       */
79469       r1 = sqlite3GetTempReg(pParse);
79470       testcase( pLevel->flags & WHERE_BTM_LIMIT );
79471       testcase( pLevel->flags & WHERE_TOP_LIMIT );
79472       if( pLevel->flags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT) ){
79473         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
79474         sqlite3VdbeAddOp2(v, OP_IsNull, r1, cont);
79475       }
79476
79477       /* Seek the table cursor, if required */
79478       if( !omitTable ){
79479         sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, r1);
79480         sqlite3VdbeAddOp3(v, OP_MoveGe, iCur, 0, r1);  /* Deferred seek */
79481       }
79482       sqlite3ReleaseTempReg(pParse, r1);
79483
79484       /* Record the instruction used to terminate the loop. Disable 
79485       ** WHERE clause terms made redundant by the index range scan.
79486       */
79487       pLevel->op = bRev ? OP_Prev : OP_Next;
79488       pLevel->p1 = iIdxCur;
79489       disableTerm(pLevel, pRangeStart);
79490       disableTerm(pLevel, pRangeEnd);
79491     }else{
79492       /* Case 4:  There is no usable index.  We must do a complete
79493       **          scan of the entire table.
79494       */
79495       assert( omitTable==0 );
79496       assert( bRev==0 );
79497       pLevel->op = OP_Next;
79498       pLevel->p1 = iCur;
79499       pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, OP_Rewind, iCur, brk);
79500       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
79501     }
79502     notReady &= ~getMask(&maskSet, iCur);
79503
79504     /* Insert code to test every subexpression that can be completely
79505     ** computed using the current set of tables.
79506     */
79507     k = 0;
79508     for(pTerm=wc.a, j=wc.nTerm; j>0; j--, pTerm++){
79509       Expr *pE;
79510       testcase( pTerm->flags & TERM_VIRTUAL );
79511       testcase( pTerm->flags & TERM_CODED );
79512       if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
79513       if( (pTerm->prereqAll & notReady)!=0 ) continue;
79514       pE = pTerm->pExpr;
79515       assert( pE!=0 );
79516       if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
79517         continue;
79518       }
79519       pParse->disableColCache += k;
79520       sqlite3ExprIfFalse(pParse, pE, cont, SQLITE_JUMPIFNULL);
79521       pParse->disableColCache -= k;
79522       k = 1;
79523       pTerm->flags |= TERM_CODED;
79524     }
79525
79526     /* For a LEFT OUTER JOIN, generate code that will record the fact that
79527     ** at least one row of the right table has matched the left table.  
79528     */
79529     if( pLevel->iLeftJoin ){
79530       pLevel->top = sqlite3VdbeCurrentAddr(v);
79531       sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
79532       VdbeComment((v, "record LEFT JOIN hit"));
79533       sqlite3ExprClearColumnCache(pParse, pLevel->iTabCur);
79534       sqlite3ExprClearColumnCache(pParse, pLevel->iIdxCur);
79535       for(pTerm=wc.a, j=0; j<wc.nTerm; j++, pTerm++){
79536         testcase( pTerm->flags & TERM_VIRTUAL );
79537         testcase( pTerm->flags & TERM_CODED );
79538         if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
79539         if( (pTerm->prereqAll & notReady)!=0 ) continue;
79540         assert( pTerm->pExpr );
79541         sqlite3ExprIfFalse(pParse, pTerm->pExpr, cont, SQLITE_JUMPIFNULL);
79542         pTerm->flags |= TERM_CODED;
79543       }
79544     }
79545   }
79546
79547 #ifdef SQLITE_TEST  /* For testing and debugging use only */
79548   /* Record in the query plan information about the current table
79549   ** and the index used to access it (if any).  If the table itself
79550   ** is not used, its name is just '{}'.  If no index is used
79551   ** the index is listed as "{}".  If the primary key is used the
79552   ** index name is '*'.
79553   */
79554   for(i=0; i<pTabList->nSrc; i++){
79555     char *z;
79556     int n;
79557     pLevel = &pWInfo->a[i];
79558     pTabItem = &pTabList->a[pLevel->iFrom];
79559     z = pTabItem->zAlias;
79560     if( z==0 ) z = pTabItem->pTab->zName;
79561     n = strlen(z);
79562     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
79563       if( pLevel->flags & WHERE_IDX_ONLY ){
79564         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
79565         nQPlan += 2;
79566       }else{
79567         memcpy(&sqlite3_query_plan[nQPlan], z, n);
79568         nQPlan += n;
79569       }
79570       sqlite3_query_plan[nQPlan++] = ' ';
79571     }
79572     testcase( pLevel->flags & WHERE_ROWID_EQ );
79573     testcase( pLevel->flags & WHERE_ROWID_RANGE );
79574     if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
79575       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
79576       nQPlan += 2;
79577     }else if( pLevel->pIdx==0 ){
79578       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
79579       nQPlan += 3;
79580     }else{
79581       n = strlen(pLevel->pIdx->zName);
79582       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
79583         memcpy(&sqlite3_query_plan[nQPlan], pLevel->pIdx->zName, n);
79584         nQPlan += n;
79585         sqlite3_query_plan[nQPlan++] = ' ';
79586       }
79587     }
79588   }
79589   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
79590     sqlite3_query_plan[--nQPlan] = 0;
79591   }
79592   sqlite3_query_plan[nQPlan] = 0;
79593   nQPlan = 0;
79594 #endif /* SQLITE_TEST // Testing and debugging use only */
79595
79596   /* Record the continuation address in the WhereInfo structure.  Then
79597   ** clean up and return.
79598   */
79599   pWInfo->iContinue = cont;
79600   whereClauseClear(&wc);
79601   return pWInfo;
79602
79603   /* Jump here if malloc fails */
79604 whereBeginError:
79605   whereClauseClear(&wc);
79606   whereInfoFree(db, pWInfo);
79607   return 0;
79608 }
79609
79610 /*
79611 ** Generate the end of the WHERE loop.  See comments on 
79612 ** sqlite3WhereBegin() for additional information.
79613 */
79614 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
79615   Parse *pParse = pWInfo->pParse;
79616   Vdbe *v = pParse->pVdbe;
79617   int i;
79618   WhereLevel *pLevel;
79619   SrcList *pTabList = pWInfo->pTabList;
79620   sqlite3 *db = pParse->db;
79621
79622   /* Generate loop termination code.
79623   */
79624   sqlite3ExprClearColumnCache(pParse, -1);
79625   for(i=pTabList->nSrc-1; i>=0; i--){
79626     pLevel = &pWInfo->a[i];
79627     sqlite3VdbeResolveLabel(v, pLevel->cont);
79628     if( pLevel->op!=OP_Noop ){
79629       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
79630       sqlite3VdbeChangeP5(v, pLevel->p5);
79631     }
79632     if( pLevel->nIn ){
79633       struct InLoop *pIn;
79634       int j;
79635       sqlite3VdbeResolveLabel(v, pLevel->nxt);
79636       for(j=pLevel->nIn, pIn=&pLevel->aInLoop[j-1]; j>0; j--, pIn--){
79637         sqlite3VdbeJumpHere(v, pIn->topAddr+1);
79638         sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->topAddr);
79639         sqlite3VdbeJumpHere(v, pIn->topAddr-1);
79640       }
79641       sqlite3DbFree(db, pLevel->aInLoop);
79642     }
79643     sqlite3VdbeResolveLabel(v, pLevel->brk);
79644     if( pLevel->iLeftJoin ){
79645       int addr;
79646       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
79647       sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
79648       if( pLevel->iIdxCur>=0 ){
79649         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
79650       }
79651       sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->top);
79652       sqlite3VdbeJumpHere(v, addr);
79653     }
79654   }
79655
79656   /* The "break" point is here, just past the end of the outer loop.
79657   ** Set it.
79658   */
79659   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
79660
79661   /* Close all of the cursors that were opened by sqlite3WhereBegin.
79662   */
79663   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
79664     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
79665     Table *pTab = pTabItem->pTab;
79666     assert( pTab!=0 );
79667     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
79668     if( !pWInfo->okOnePass && (pLevel->flags & WHERE_IDX_ONLY)==0 ){
79669       sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
79670     }
79671     if( pLevel->pIdx!=0 ){
79672       sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
79673     }
79674
79675     /* If this scan uses an index, make code substitutions to read data
79676     ** from the index in preference to the table. Sometimes, this means
79677     ** the table need never be read from. This is a performance boost,
79678     ** as the vdbe level waits until the table is read before actually
79679     ** seeking the table cursor to the record corresponding to the current
79680     ** position in the index.
79681     ** 
79682     ** Calls to the code generator in between sqlite3WhereBegin and
79683     ** sqlite3WhereEnd will have created code that references the table
79684     ** directly.  This loop scans all that code looking for opcodes
79685     ** that reference the table and converts them into opcodes that
79686     ** reference the index.
79687     */
79688     if( pLevel->pIdx ){
79689       int k, j, last;
79690       VdbeOp *pOp;
79691       Index *pIdx = pLevel->pIdx;
79692       int useIndexOnly = pLevel->flags & WHERE_IDX_ONLY;
79693
79694       assert( pIdx!=0 );
79695       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
79696       last = sqlite3VdbeCurrentAddr(v);
79697       for(k=pWInfo->iTop; k<last; k++, pOp++){
79698         if( pOp->p1!=pLevel->iTabCur ) continue;
79699         if( pOp->opcode==OP_Column ){
79700           for(j=0; j<pIdx->nColumn; j++){
79701             if( pOp->p2==pIdx->aiColumn[j] ){
79702               pOp->p2 = j;
79703               pOp->p1 = pLevel->iIdxCur;
79704               break;
79705             }
79706           }
79707           assert(!useIndexOnly || j<pIdx->nColumn);
79708         }else if( pOp->opcode==OP_Rowid ){
79709           pOp->p1 = pLevel->iIdxCur;
79710           pOp->opcode = OP_IdxRowid;
79711         }else if( pOp->opcode==OP_NullRow && useIndexOnly ){
79712           pOp->opcode = OP_Noop;
79713         }
79714       }
79715     }
79716   }
79717
79718   /* Final cleanup
79719   */
79720   whereInfoFree(db, pWInfo);
79721   return;
79722 }
79723
79724 /************** End of where.c ***********************************************/
79725 /************** Begin file parse.c *******************************************/
79726 /* Driver template for the LEMON parser generator.
79727 ** The author disclaims copyright to this source code.
79728 */
79729 /* First off, code is included that follows the "include" declaration
79730 ** in the input grammar file. */
79731
79732
79733 /*
79734 ** An instance of this structure holds information about the
79735 ** LIMIT clause of a SELECT statement.
79736 */
79737 struct LimitVal {
79738   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
79739   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
79740 };
79741
79742 /*
79743 ** An instance of this structure is used to store the LIKE,
79744 ** GLOB, NOT LIKE, and NOT GLOB operators.
79745 */
79746 struct LikeOp {
79747   Token eOperator;  /* "like" or "glob" or "regexp" */
79748   int not;         /* True if the NOT keyword is present */
79749 };
79750
79751 /*
79752 ** An instance of the following structure describes the event of a
79753 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
79754 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
79755 **
79756 **      UPDATE ON (a,b,c)
79757 **
79758 ** Then the "b" IdList records the list "a,b,c".
79759 */
79760 struct TrigEvent { int a; IdList * b; };
79761
79762 /*
79763 ** An instance of this structure holds the ATTACH key and the key type.
79764 */
79765 struct AttachKey { int type;  Token key; };
79766
79767 /* Next is all token values, in a form suitable for use by makeheaders.
79768 ** This section will be null unless lemon is run with the -m switch.
79769 */
79770 /* 
79771 ** These constants (all generated automatically by the parser generator)
79772 ** specify the various kinds of tokens (terminals) that the parser
79773 ** understands. 
79774 **
79775 ** Each symbol here is a terminal symbol in the grammar.
79776 */
79777 /* Make sure the INTERFACE macro is defined.
79778 */
79779 #ifndef INTERFACE
79780 # define INTERFACE 1
79781 #endif
79782 /* The next thing included is series of defines which control
79783 ** various aspects of the generated parser.
79784 **    YYCODETYPE         is the data type used for storing terminal
79785 **                       and nonterminal numbers.  "unsigned char" is
79786 **                       used if there are fewer than 250 terminals
79787 **                       and nonterminals.  "int" is used otherwise.
79788 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
79789 **                       to no legal terminal or nonterminal number.  This
79790 **                       number is used to fill in empty slots of the hash 
79791 **                       table.
79792 **    YYFALLBACK         If defined, this indicates that one or more tokens
79793 **                       have fall-back values which should be used if the
79794 **                       original value of the token will not parse.
79795 **    YYACTIONTYPE       is the data type used for storing terminal
79796 **                       and nonterminal numbers.  "unsigned char" is
79797 **                       used if there are fewer than 250 rules and
79798 **                       states combined.  "int" is used otherwise.
79799 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given 
79800 **                       directly to the parser from the tokenizer.
79801 **    YYMINORTYPE        is the data type used for all minor tokens.
79802 **                       This is typically a union of many types, one of
79803 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
79804 **                       for base tokens is called "yy0".
79805 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
79806 **                       zero the stack is dynamically sized using realloc()
79807 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
79808 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
79809 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
79810 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
79811 **    YYNSTATE           the combined number of states.
79812 **    YYNRULE            the number of rules in the grammar
79813 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
79814 **                       defined, then do no error processing.
79815 */
79816 #define YYCODETYPE unsigned char
79817 #define YYNOCODE 249
79818 #define YYACTIONTYPE unsigned short int
79819 #define YYWILDCARD 59
79820 #define sqlite3ParserTOKENTYPE Token
79821 typedef union {
79822   sqlite3ParserTOKENTYPE yy0;
79823   Select* yy43;
79824   TriggerStep* yy75;
79825   struct LimitVal yy84;
79826   struct LikeOp yy86;
79827   struct {int value; int mask;} yy207;
79828   ExprList* yy242;
79829   int yy316;
79830   IdList* yy352;
79831   struct TrigEvent yy354;
79832   SrcList* yy419;
79833   Expr* yy450;
79834 } YYMINORTYPE;
79835 #ifndef YYSTACKDEPTH
79836 #define YYSTACKDEPTH 100
79837 #endif
79838 #define sqlite3ParserARG_SDECL Parse *pParse;
79839 #define sqlite3ParserARG_PDECL ,Parse *pParse
79840 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
79841 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
79842 #define YYNSTATE 598
79843 #define YYNRULE 315
79844 #define YYFALLBACK 1
79845 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
79846 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
79847 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
79848
79849 /* The yyzerominor constant is used to initialize instances of
79850 ** YYMINORTYPE objects to zero. */
79851 #if 0
79852 static YYMINORTYPE yyzerominor;
79853 #else
79854 static const YYMINORTYPE yyzerominor;
79855 #endif
79856
79857 /* Next are the tables used to determine what action to take based on the
79858 ** current state and lookahead token.  These tables are used to implement
79859 ** functions that take a state number and lookahead value and return an
79860 ** action integer.  
79861 **
79862 ** Suppose the action integer is N.  Then the action is determined as
79863 ** follows
79864 **
79865 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
79866 **                                      token onto the stack and goto state N.
79867 **
79868 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
79869 **
79870 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
79871 **
79872 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
79873 **
79874 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
79875 **                                      slots in the yy_action[] table.
79876 **
79877 ** The action table is constructed as a single large table named yy_action[].
79878 ** Given state S and lookahead X, the action is computed as
79879 **
79880 **      yy_action[ yy_shift_ofst[S] + X ]
79881 **
79882 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
79883 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
79884 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
79885 ** and that yy_default[S] should be used instead.  
79886 **
79887 ** The formula above is for computing the action when the lookahead is
79888 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
79889 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
79890 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
79891 ** YY_SHIFT_USE_DFLT.
79892 **
79893 ** The following are the tables generated in this section:
79894 **
79895 **  yy_action[]        A single table containing all actions.
79896 **  yy_lookahead[]     A table containing the lookahead for each entry in
79897 **                     yy_action.  Used to detect hash collisions.
79898 **  yy_shift_ofst[]    For each state, the offset into yy_action for
79899 **                     shifting terminals.
79900 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
79901 **                     shifting non-terminals after a reduce.
79902 **  yy_default[]       Default action for each state.
79903 */
79904 static const YYACTIONTYPE yy_action[] = {
79905  /*     0 */   296,  914,  120,  597,    2,  172,  425,  425,   62,   62,
79906  /*    10 */    62,   62,  210,   64,   64,   64,   64,   65,   65,   66,
79907  /*    20 */    66,   66,   67,  212,  398,  395,  432,  438,   69,   64,
79908  /*    30 */    64,   64,   64,   65,   65,   66,   66,   66,   67,  212,
79909  /*    40 */   458,  456,  327,  168,   61,   60,  301,  442,  443,  439,
79910  /*    50 */   439,   63,   63,   62,   62,   62,   62,  256,   64,   64,
79911  /*    60 */    64,   64,   65,   65,   66,   66,   66,   67,  212,  296,
79912  /*    70 */   498,  425,  425,  212,  427,   83,   68,  469,   70,  154,
79913  /*    80 */    64,   64,   64,   64,   65,   65,   66,   66,   66,   67,
79914  /*    90 */   212,   68,  307,   70,  154,  432,  438,  454,  214,   59,
79915  /*   100 */    65,   65,   66,   66,   66,   67,  212,  429,  429,  429,
79916  /*   110 */   497,  583,  296,   61,   60,  301,  442,  443,  439,  439,
79917  /*   120 */    63,   63,   62,   62,   62,   62,  321,   64,   64,   64,
79918  /*   130 */    64,   65,   65,   66,   66,   66,   67,  212,  432,  438,
79919  /*   140 */    95,   66,   66,   66,   67,  212,  403,  256,  421,   35,
79920  /*   150 */    57,   67,  212,  175,  417,  499,   61,   60,  301,  442,
79921  /*   160 */   443,  439,  439,   63,   63,   62,   62,   62,   62,   19,
79922  /*   170 */    64,   64,   64,   64,   65,   65,   66,   66,   66,   67,
79923  /*   180 */   212,  296,  225,  532,  299,  581,  109,  422,  242,  458,
79924  /*   190 */   416,  335,  414,   21,  502,  503,  346,  403,  527,  176,
79925  /*   200 */   160,  454,  214,  580,  579,  344,  500,  432,  438,  149,
79926  /*   210 */   150,  404,  405,  539,  514,  418,  151,  541,    8,  498,
79927  /*   220 */   538,  577,  578,  427,  296,   61,   60,  301,  442,  443,
79928  /*   230 */   439,  439,   63,   63,   62,   62,   62,   62,  196,   64,
79929  /*   240 */    64,   64,   64,   65,   65,   66,   66,   66,   67,  212,
79930  /*   250 */   432,  438,  454,  598,  398,  395,  429,  429,  429,  369,
79931  /*   260 */   558,  481,  404,  405,  372,  576,  213,  296,   61,   60,
79932  /*   270 */   301,  442,  443,  439,  439,   63,   63,   62,   62,   62,
79933  /*   280 */    62,  321,   64,   64,   64,   64,   65,   65,   66,   66,
79934  /*   290 */    66,   67,  212,  432,  438,  555,  503,  304,  557,  532,
79935  /*   300 */   218,  557,  552,  421,   36,  234,  397,    2,  542,   21,
79936  /*   310 */   540,   61,   60,  301,  442,  443,  439,  439,   63,   63,
79937  /*   320 */    62,   62,   62,   62,  388,   64,   64,   64,   64,   65,
79938  /*   330 */    65,   66,   66,   66,   67,  212,  415,  530,   85,  381,
79939  /*   340 */    78,  323,  296,  210,  304,  527,  493,  492,  379,  274,
79940  /*   350 */   273,  379,  274,  273,  347,  463,  241,  387,  268,  210,
79941  /*   360 */   533,  581,  210,  403,   20,  224,  144,  464,  432,  438,
79942  /*   370 */   485,  164,  114,  248,  349,  253,  350,  177,  554,  580,
79943  /*   380 */   465,  420,  331,   81,  257,  419,   61,   60,  301,  442,
79944  /*   390 */   443,  439,  439,   63,   63,   62,   62,   62,   62,  391,
79945  /*   400 */    64,   64,   64,   64,   65,   65,   66,   66,   66,   67,
79946  /*   410 */   212,  296,  224,  203,  249,  496,  403,  440,  837,  114,
79947  /*   420 */   248,  349,  253,  350,  177,  250,  321,  152,  404,  405,
79948  /*   430 */   321,  257,  303,  324,  155,  445,  445,  432,  438,  317,
79949  /*   440 */   400,  389,  213,   68,  209,   70,  154,  422,  421,   35,
79950  /*   450 */   393,  202,  421,   42,  481,   61,   60,  301,  442,  443,
79951  /*   460 */   439,  439,   63,   63,   62,   62,   62,   62,  422,   64,
79952  /*   470 */    64,   64,   64,   65,   65,   66,   66,   66,   67,  212,
79953  /*   480 */   296,  404,  405,  183,  513,  422,  351,  354,  355,  403,
79954  /*   490 */    77,  335,   79,  489,  216,  183,  334,  356,  351,  354,
79955  /*   500 */   355,  433,  434,  406,  407,  408,  432,  438,  235,  356,
79956  /*   510 */   386,   68,  291,   70,  154,  456,  531,  168,  198,  302,
79957  /*   520 */   449,  450,  436,  437,   61,   60,  301,  442,  443,  439,
79958  /*   530 */   439,   63,   63,   62,   62,   62,   62,  394,   64,   64,
79959  /*   540 */    64,   64,   65,   65,   66,   66,   66,   67,  212,  296,
79960  /*   550 */   321,  435,  422,  260,  404,  405,  321,  183,  153,  321,
79961  /*   560 */   351,  354,  355,  446,  332,  321,  595,  905,  321,  905,
79962  /*   570 */     1,  356,  421,   28,  403,  432,  438,  376,  421,   42,
79963  /*   580 */   477,  421,   35,  213,  548,  366,  548,  421,   50,  159,
79964  /*   590 */   421,   50,  422,   61,   60,  301,  442,  443,  439,  439,
79965  /*   600 */    63,   63,   62,   62,   62,   62,  592,   64,   64,   64,
79966  /*   610 */    64,   65,   65,   66,   66,   66,   67,  212,  296,  337,
79967  /*   620 */   217,  463,  256,   94,  339,  326,  449,  450,  172,  340,
79968  /*   630 */   425,  345,  532,  464,  312,  595,  904,  313,  904,  404,
79969  /*   640 */   405,  588,   21,  226,  432,  438,  465,  243,  504,  324,
79970  /*   650 */   322,  445,  445,  421,    3,  459,  230,  308,  505,  194,
79971  /*   660 */   278,  296,   61,   60,  301,  442,  443,  439,  439,   63,
79972  /*   670 */    63,   62,   62,   62,   62,  592,   64,   64,   64,   64,
79973  /*   680 */    65,   65,   66,   66,   66,   67,  212,  432,  438,  213,
79974  /*   690 */   179,  180,  181,  422,  324,  425,  445,  445,  281,  262,
79975  /*   700 */   279,  402,  194,  481,  296,   61,   60,  301,  442,  443,
79976  /*   710 */   439,  439,   63,   63,   62,   62,   62,   62,  377,   64,
79977  /*   720 */    64,   64,   64,   65,   65,   66,   66,   66,   67,  212,
79978  /*   730 */   432,  438,  591,  295,  115,  268,  422,  266,  211,  264,
79979  /*   740 */   373,  324,  246,  445,  445,   56,  256,  296,   61,   71,
79980  /*   750 */   301,  442,  443,  439,  439,   63,   63,   62,   62,   62,
79981  /*   760 */    62,  377,   64,   64,   64,   64,   65,   65,   66,   66,
79982  /*   770 */    66,   67,  212,  432,  438,  550,  269,  474,   18,  549,
79983  /*   780 */   280,  309,  343,  380,  171,  160,  256,  268,    5,  268,
79984  /*   790 */   296,  368,   60,  301,  442,  443,  439,  439,   63,   63,
79985  /*   800 */    62,   62,   62,   62,  321,   64,   64,   64,   64,   65,
79986  /*   810 */    65,   66,   66,   66,   67,  212,  432,  438,  403,   10,
79987  /*   820 */   403,  310,  268,  403,  268,  485,  421,   29,  566,   22,
79988  /*   830 */   568,  420,  428,  425,  376,  419,  301,  442,  443,  439,
79989  /*   840 */   439,   63,   63,   62,   62,   62,   62,  321,   64,   64,
79990  /*   850 */    64,   64,   65,   65,   66,   66,   66,   67,  212,   73,
79991  /*   860 */   328,  485,    4,  569,  268,  570,  300,  268,  147,  421,
79992  /*   870 */    24,  321,  359,  321,  325,   73,  328,  491,    4,  455,
79993  /*   880 */   321,  342,  300,  404,  405,  404,  405,  367,  404,  405,
79994  /*   890 */   325,  330,  321,  421,   33,  421,   54,  321,  425,  178,
79995  /*   900 */   229,  458,  421,   53,  321,  227,  321,  330,  228,  478,
79996  /*   910 */   165,  321,  315,  119,  421,   99,  333,  458,  321,  421,
79997  /*   920 */    97,   76,   75,  311,  268,  519,  421,  102,  421,  103,
79998  /*   930 */    74,  319,  320,  421,  108,  427,  467,   76,   75,  490,
79999  /*   940 */   421,  110,  452,  452,  321,  520,   74,  319,  320,   73,
80000  /*   950 */   328,  427,    4,  210,  298,  321,  300,  321,  156,  257,
80001  /*   960 */   321,  210,  185,  182,  325,  284,  421,   17,  429,  429,
80002  /*   970 */   429,  430,  431,   12,  593,  378,  188,  421,  100,  421,
80003  /*   980 */    34,  330,  421,   98,  429,  429,  429,  430,  431,   12,
80004  /*   990 */   475,  458,  422,  162,  480,  321,  422,  306,  231,  232,
80005  /*  1000 */   233,  105,  484,  632,  476,  321,  486,  447,  321,   23,
80006  /*  1010 */   422,   76,   75,  594,  207,  178,  286,  421,   25,  254,
80007  /*  1020 */    74,  319,  320,  287,  321,  427,  321,  421,   55,  321,
80008  /*  1030 */   421,  111,  321,  471,  321,  205,  515,  557,  511,  363,
80009  /*  1040 */   472,  204,  321,  516,  206,  321,  421,  112,  421,  113,
80010  /*  1050 */   321,  421,   26,  321,  421,   37,  421,   38,  429,  429,
80011  /*  1060 */   429,  430,  431,   12,  421,   27,  521,  421,   39,  321,
80012  /*  1070 */   298,  158,  421,   40,  255,  421,   41,  321,  483,  321,
80013  /*  1080 */   173,  523,  321,  182,  321,  522,  321,  384,  283,  273,
80014  /*  1090 */   321,  421,   43,  297,  534,  321,  476,  321,  210,  421,
80015  /*  1100 */    44,  421,   45,  321,  421,   30,  421,   31,  421,   46,
80016  /*  1110 */   508,  509,  421,   47,  259,  321,  182,  421,   48,  421,
80017  /*  1120 */    49,  321,  358,  390,  182,  421,   32,  321,  261,  518,
80018  /*  1130 */   517,  553,  561,  182,  173,  412,  191,  421,   11,  562,
80019  /*  1140 */   573,   92,   92,  421,   51,  590,  263,  294,  265,  421,
80020  /*  1150 */    52,  267,  272,  371,  146,  374,  375,  275,  276,  277,
80021  /*  1160 */   565,  575,  285,  288,  289,  587,  470,  451,  236,  453,
80022  /*  1170 */   329,  244,  473,  514,  251,  524,  560,  163,  401,  572,
80023  /*  1180 */   426,  525,  282,  528,  409,    7,  410,  411,  385,  318,
80024  /*  1190 */    85,  237,  338,  526,   84,  336,  353,   58,   80,  215,
80025  /*  1200 */   170,  468,  121,   86,  341,  348,  305,  501,  506,  124,
80026  /*  1210 */   511,  222,  360,  423,  252,  186,  512,  510,  221,  223,
80027  /*  1220 */   238,  507,  239,  535,  240,  292,  424,  529,  536,  537,
80028  /*  1230 */   293,  543,  187,  189,  245,  362,  482,  488,  247,  190,
80029  /*  1240 */   364,   89,  545,  192,  117,  370,  132,  556,  563,  195,
80030  /*  1250 */   382,  383,  314,  133,  134,  571,  138,  135,  136,  584,
80031  /*  1260 */   589,  585,  142,  399,  101,  413,  220,  586,  270,  104,
80032  /*  1270 */   141,  633,  634,  166,  167,  441,  444,   72,  460,  448,
80033  /*  1280 */   457,  546,  143,  157,    6,  461,   14,  479,  169,  462,
80034  /*  1290 */    93,  466,   82,  122,   13,  174,  487,   96,  123,  161,
80035  /*  1300 */   494,  495,   87,  125,  126,  116,  258,   88,  127,  184,
80036  /*  1310 */   250,  361,  219,  107,  544,  145,  128,  193,  365,  118,
80037  /*  1320 */   352,  357,  173,  271,  130,    9,  316,  559,  197,   90,
80038  /*  1330 */   547,  131,  129,   15,  199,  551,  564,  200,  567,  201,
80039  /*  1340 */   139,  137,  582,   91,   16,  106,  140,  208,  574,  392,
80040  /*  1350 */   396,  290,  148,  596,
80041 };
80042 static const YYCODETYPE yy_lookahead[] = {
80043  /*     0 */    16,  140,  141,  142,  143,   21,   23,   23,   69,   70,
80044  /*    10 */    71,   72,  110,   74,   75,   76,   77,   78,   79,   80,
80045  /*    20 */    81,   82,   83,   84,    1,    2,   42,   43,   73,   74,
80046  /*    30 */    75,   76,   77,   78,   79,   80,   81,   82,   83,   84,
80047  /*    40 */    58,  162,  163,  164,   60,   61,   62,   63,   64,   65,
80048  /*    50 */    66,   67,   68,   69,   70,   71,   72,  148,   74,   75,
80049  /*    60 */    76,   77,   78,   79,   80,   81,   82,   83,   84,   16,
80050  /*    70 */    88,   88,   88,   84,   92,   22,  219,  220,  221,  222,
80051  /*    80 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
80052  /*    90 */    84,  219,  183,  221,  222,   42,   43,   78,   79,   46,
80053  /*   100 */    78,   79,   80,   81,   82,   83,   84,  125,  126,  127,
80054  /*   110 */   170,  239,   16,   60,   61,   62,   63,   64,   65,   66,
80055  /*   120 */    67,   68,   69,   70,   71,   72,  148,   74,   75,   76,
80056  /*   130 */    77,   78,   79,   80,   81,   82,   83,   84,   42,   43,
80057  /*   140 */    44,   80,   81,   82,   83,   84,   23,  148,  170,  171,
80058  /*   150 */    19,   83,   84,  156,   23,  170,   60,   61,   62,   63,
80059  /*   160 */    64,   65,   66,   67,   68,   69,   70,   71,   72,   19,
80060  /*   170 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
80061  /*   180 */    84,   16,  183,  148,  151,  148,   21,  190,  148,   58,
80062  /*   190 */   169,  213,  157,  158,  186,  187,  218,   23,  177,  202,
80063  /*   200 */   203,   78,   79,  166,  167,  208,  161,   42,   43,   78,
80064  /*   210 */    79,   88,   89,  177,  178,  170,  181,  182,   68,   88,
80065  /*   220 */   184,   98,   99,   92,   16,   60,   61,   62,   63,   64,
80066  /*   230 */    65,   66,   67,   68,   69,   70,   71,   72,   22,   74,
80067  /*   240 */    75,   76,   77,   78,   79,   80,   81,   82,   83,   84,
80068  /*   250 */    42,   43,   78,    0,    1,    2,  125,  126,  127,  226,
80069  /*   260 */    11,  162,   88,   89,  231,  228,  229,   16,   60,   61,
80070  /*   270 */    62,   63,   64,   65,   66,   67,   68,   69,   70,   71,
80071  /*   280 */    72,  148,   74,   75,   76,   77,   78,   79,   80,   81,
80072  /*   290 */    82,   83,   84,   42,   43,  186,  187,   16,   49,  148,
80073  /*   300 */   201,   49,   18,  170,  171,  154,  142,  143,  157,  158,
80074  /*   310 */   182,   60,   61,   62,   63,   64,   65,   66,   67,   68,
80075  /*   320 */    69,   70,   71,   72,   91,   74,   75,   76,   77,   78,
80076  /*   330 */    79,   80,   81,   82,   83,   84,  168,  169,  122,   55,
80077  /*   340 */   132,   16,   16,  110,   16,  177,   20,   20,   99,  100,
80078  /*   350 */   101,   99,  100,  101,   80,   12,  223,  124,  148,  110,
80079  /*   360 */   182,  148,  110,   23,   19,   84,   21,   24,   42,   43,
80080  /*   370 */   148,   90,   91,   92,   93,   94,   95,   96,   94,  166,
80081  /*   380 */    37,  107,   39,  132,  103,  111,   60,   61,   62,   63,
80082  /*   390 */    64,   65,   66,   67,   68,   69,   70,   71,   72,  189,
80083  /*   400 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
80084  /*   410 */    84,   16,   84,  156,   92,   20,   23,   92,  134,   91,
80085  /*   420 */    92,   93,   94,   95,   96,  103,  148,   22,   88,   89,
80086  /*   430 */   148,  103,  210,  106,  156,  108,  109,   42,   43,  144,
80087  /*   440 */   145,  228,  229,  219,  149,  221,  222,  190,  170,  171,
80088  /*   450 */   240,  156,  170,  171,  162,   60,   61,   62,   63,   64,
80089  /*   460 */    65,   66,   67,   68,   69,   70,   71,   72,  190,   74,
80090  /*   470 */    75,   76,   77,   78,   79,   80,   81,   82,   83,   84,
80091  /*   480 */    16,   88,   89,   90,   20,  190,   93,   94,   95,   23,
80092  /*   490 */   131,  213,  133,  201,  212,   90,  218,  104,   93,   94,
80093  /*   500 */    95,   42,   43,    7,    8,    9,   42,   43,  191,  104,
80094  /*   510 */   215,  219,  159,  221,  222,  162,  163,  164,  156,  165,
80095  /*   520 */   166,  167,   63,   64,   60,   61,   62,   63,   64,   65,
80096  /*   530 */    66,   67,   68,   69,   70,   71,   72,  242,   74,   75,
80097  /*   540 */    76,   77,   78,   79,   80,   81,   82,   83,   84,   16,
80098  /*   550 */   148,   92,  190,   20,   88,   89,  148,   90,  156,  148,
80099  /*   560 */    93,   94,   95,   20,  187,  148,   19,   20,  148,   22,
80100  /*   570 */    19,  104,  170,  171,   23,   42,   43,  148,  170,  171,
80101  /*   580 */   114,  170,  171,  229,   99,  100,  101,  170,  171,  148,
80102  /*   590 */   170,  171,  190,   60,   61,   62,   63,   64,   65,   66,
80103  /*   600 */    67,   68,   69,   70,   71,   72,   59,   74,   75,   76,
80104  /*   610 */    77,   78,   79,   80,   81,   82,   83,   84,   16,  211,
80105  /*   620 */   212,   12,  148,   21,  213,  165,  166,  167,   21,  148,
80106  /*   630 */    23,  148,  148,   24,  217,   19,   20,  217,   22,   88,
80107  /*   640 */    89,  157,  158,  214,   42,   43,   37,  148,   39,  106,
80108  /*   650 */   148,  108,  109,  170,  171,   20,  146,  183,   49,  156,
80109  /*   660 */    14,   16,   60,   61,   62,   63,   64,   65,   66,   67,
80110  /*   670 */    68,   69,   70,   71,   72,   59,   74,   75,   76,   77,
80111  /*   680 */    78,   79,   80,   81,   82,   83,   84,   42,   43,  229,
80112  /*   690 */    99,  100,  101,  190,  106,   88,  108,  109,   52,   14,
80113  /*   700 */    54,  148,  156,  162,   16,   60,   61,   62,   63,   64,
80114  /*   710 */    65,   66,   67,   68,   69,   70,   71,   72,  215,   74,
80115  /*   720 */    75,   76,   77,   78,   79,   80,   81,   82,   83,   84,
80116  /*   730 */    42,   43,  245,  246,  148,  148,  190,   52,  193,   54,
80117  /*   740 */   237,  106,  201,  108,  109,  200,  148,   16,   60,   61,
80118  /*   750 */    62,   63,   64,   65,   66,   67,   68,   69,   70,   71,
80119  /*   760 */    72,  215,   74,   75,   76,   77,   78,   79,   80,   81,
80120  /*   770 */    82,   83,   84,   42,   43,   25,  189,   22,  232,   29,
80121  /*   780 */   134,  183,   16,  237,  202,  203,  148,  148,  192,  148,
80122  /*   790 */    16,   41,   61,   62,   63,   64,   65,   66,   67,   68,
80123  /*   800 */    69,   70,   71,   72,  148,   74,   75,   76,   77,   78,
80124  /*   810 */    79,   80,   81,   82,   83,   84,   42,   43,   23,   19,
80125  /*   820 */    23,  183,  148,   23,  148,  148,  170,  171,  189,   19,
80126  /*   830 */   189,  107,  148,   23,  148,  111,   62,   63,   64,   65,
80127  /*   840 */    66,   67,   68,   69,   70,   71,   72,  148,   74,   75,
80128  /*   850 */    76,   77,   78,   79,   80,   81,   82,   83,   84,   16,
80129  /*   860 */    17,  148,   19,  189,  148,  189,   23,  148,  113,  170,
80130  /*   870 */   171,  148,   16,  148,   31,   16,   17,   80,   19,  162,
80131  /*   880 */   148,  115,   23,   88,   89,   88,   89,  210,   88,   89,
80132  /*   890 */    31,   48,  148,  170,  171,  170,  171,  148,   88,   43,
80133  /*   900 */   214,   58,  170,  171,  148,  189,  148,   48,  189,  114,
80134  /*   910 */    19,  148,  243,  244,  170,  171,  148,   58,  148,  170,
80135  /*   920 */   171,   78,   79,  210,  148,   30,  170,  171,  170,  171,
80136  /*   930 */    87,   88,   89,  170,  171,   92,  148,   78,   79,   80,
80137  /*   940 */   170,  171,  125,  126,  148,   50,   87,   88,   89,   16,
80138  /*   950 */    17,   92,   19,  110,   98,  148,   23,  148,  156,  103,
80139  /*   960 */   148,  110,  156,   22,   31,  189,  170,  171,  125,  126,
80140  /*   970 */   127,  128,  129,  130,   20,  124,  156,  170,  171,  170,
80141  /*   980 */   171,   48,  170,  171,  125,  126,  127,  128,  129,  130,
80142  /*   990 */   204,   58,  190,    5,  148,  148,  190,  102,   10,   11,
80143  /*  1000 */    12,   13,  148,  112,   22,  148,  148,   20,  148,   22,
80144  /*  1010 */   190,   78,   79,   59,   26,   43,   28,  170,  171,  148,
80145  /*  1020 */    87,   88,   89,   35,  148,   92,  148,  170,  171,  148,
80146  /*  1030 */   170,  171,  148,   27,  148,   47,  148,   49,   97,  234,
80147  /*  1040 */    34,   53,  148,  179,   56,  148,  170,  171,  170,  171,
80148  /*  1050 */   148,  170,  171,  148,  170,  171,  170,  171,  125,  126,
80149  /*  1060 */   127,  128,  129,  130,  170,  171,  179,  170,  171,  148,
80150  /*  1070 */    98,   89,  170,  171,  148,  170,  171,  148,   20,  148,
80151  /*  1080 */    22,   20,  148,   22,  148,  179,  148,   99,  100,  101,
80152  /*  1090 */   148,  170,  171,  105,  148,  148,  114,  148,  110,  170,
80153  /*  1100 */   171,  170,  171,  148,  170,  171,  170,  171,  170,  171,
80154  /*  1110 */     7,    8,  170,  171,   20,  148,   22,  170,  171,  170,
80155  /*  1120 */   171,  148,   20,  135,   22,  170,  171,  148,  148,   91,
80156  /*  1130 */    92,   20,   20,   22,   22,  150,  233,  170,  171,   20,
80157  /*  1140 */    20,   22,   22,  170,  171,   20,  148,   22,  148,  170,
80158  /*  1150 */   171,  148,  148,  148,  192,  148,  148,  148,  148,  148,
80159  /*  1160 */   148,  148,  148,  148,  148,  148,  173,  230,  194,  230,
80160  /*  1170 */   225,  205,  173,  178,  173,  173,  195,    6,  147,  195,
80161  /*  1180 */   162,  162,  205,  162,  147,   22,  147,  147,  205,  155,
80162  /*  1190 */   122,  195,  119,  173,  120,  118,  174,  121,  131,  224,
80163  /*  1200 */   112,  153,  153,   98,  117,   98,   40,  172,  172,   19,
80164  /*  1210 */    97,   84,   15,  190,  172,  152,  172,  174,  227,  227,
80165  /*  1220 */   196,  180,  197,  172,  198,  175,  199,  180,  172,  172,
80166  /*  1230 */   175,  153,  152,  152,  206,  153,  207,  207,  206,  153,
80167  /*  1240 */    38,  131,  153,  152,   60,  153,   19,  185,  195,  185,
80168  /*  1250 */   153,   15,  153,  188,  188,  195,  185,  188,  188,   33,
80169  /*  1260 */   138,  153,  216,    1,  160,   20,  176,  153,  235,  176,
80170  /*  1270 */   216,  112,  112,  112,  112,   92,  107,   19,   11,   20,
80171  /*  1280 */    20,  236,   19,   19,  116,   20,  116,  114,   22,   20,
80172  /*  1290 */   238,   20,   22,   19,   22,  116,  115,  238,   20,  112,
80173  /*  1300 */    20,   20,   19,   19,   19,   32,   20,   19,   19,   96,
80174  /*  1310 */   103,   16,   44,  241,   17,   21,   98,   98,   36,  244,
80175  /*  1320 */    44,   44,   22,  134,   19,    5,  247,    1,  123,   68,
80176  /*  1330 */    51,  102,   45,   19,  113,   45,    1,   14,   17,  117,
80177  /*  1340 */   102,  113,   20,   68,   19,   14,  123,  136,  124,   57,
80178  /*  1350 */     3,  137,   19,    4,
80179 };
80180 #define YY_SHIFT_USE_DFLT (-99)
80181 #define YY_SHIFT_MAX 396
80182 static const short yy_shift_ofst[] = {
80183  /*     0 */    23,  843,  988,  -16,  843,  933,  933,  393,  123,  252,
80184  /*    10 */   -98,   96,  933,  933,  933,  933,  933,  -45,  249,  174,
80185  /*    20 */   340,  -17,   19,   19,   53,  165,  208,  251,  326,  395,
80186  /*    30 */   464,  533,  602,  645,  688,  645,  645,  645,  645,  645,
80187  /*    40 */   645,  645,  645,  645,  645,  645,  645,  645,  645,  645,
80188  /*    50 */   645,  645,  645,  731,  774,  774,  859,  933,  933,  933,
80189  /*    60 */   933,  933,  933,  933,  933,  933,  933,  933,  933,  933,
80190  /*    70 */   933,  933,  933,  933,  933,  933,  933,  933,  933,  933,
80191  /*    80 */   933,  933,  933,  933,  933,  933,  933,  933,  933,  933,
80192  /*    90 */   933,  933,  933,  933,  933,  933,  933,  -61,  -61,    6,
80193  /*   100 */     6,  281,   22,   61,  856,  284,  340,  340,   68,  -17,
80194  /*   110 */   -11,  -99,  -99,  -99,  131,  328,  609,  609,  547,  616,
80195  /*   120 */   253,  607,  340,  607,  340,  340,  340,  340,  340,  340,
80196  /*   130 */   340,  340,  340,  340,  340,  340,  340,  340,  340,  340,
80197  /*   140 */   340,  233,  851,  -98,  -98,  -98,  -99,  -99,  -99,  -18,
80198  /*   150 */   -18,  405,  467,  327,  551,  543,  635,  343,  466,  795,
80199  /*   160 */   800,  797,  496,  340,  340,  274,  340,  340,  810,  340,
80200  /*   170 */   340,  982,  340,  340,  340,  588,  982,  340,  340,  895,
80201  /*   180 */   895,  895,  340,  340,  340,  588,  340,  340,  588,  340,
80202  /*   190 */   750,  485,  340,  340,  588,  340,  340,  340,  588,  340,
80203  /*   200 */   340,  340,  588,  588,  340,  340,  340,  340,  340,  345,
80204  /*   210 */   724,  755,  -17,  817,  817,  359, 1006, 1006,  766, 1006,
80205  /*   220 */   972, 1006,  -17, 1006,  -17,  941,  216,  766,  766,  216,
80206  /*   230 */  1171, 1171, 1171, 1171, 1163,  -98, 1068, 1073, 1074, 1077,
80207  /*   240 */  1076, 1067, 1088, 1088, 1105, 1087, 1105, 1087, 1107, 1107,
80208  /*   250 */  1166, 1107, 1113, 1107, 1190, 1127, 1127, 1166, 1107, 1107,
80209  /*   260 */  1107, 1190, 1197, 1088, 1197, 1088, 1197, 1088, 1088, 1202,
80210  /*   270 */  1110, 1197, 1088, 1184, 1184, 1227, 1068, 1088, 1236, 1236,
80211  /*   280 */  1236, 1236, 1068, 1184, 1227, 1088, 1226, 1226, 1088, 1088,
80212  /*   290 */  1122,  -99,  -99,  -99,  -99,  -99,  459,  646,  591,  685,
80213  /*   300 */   891,  325,  987, 1058,  322, 1103, 1038, 1061, 1094, 1102,
80214  /*   310 */  1111, 1112, 1119, 1120,  150, 1125,  954, 1262, 1245, 1159,
80215  /*   320 */  1160, 1161, 1162, 1183, 1169, 1258, 1259, 1260, 1263, 1267,
80216  /*   330 */  1264, 1265, 1266, 1269, 1271, 1270, 1168, 1272, 1170, 1270,
80217  /*   340 */  1173, 1274, 1179, 1181, 1278, 1187, 1280, 1281, 1273, 1268,
80218  /*   350 */  1283, 1276, 1284, 1286, 1285, 1288, 1277, 1289, 1213, 1207,
80219  /*   360 */  1295, 1297, 1294, 1218, 1282, 1279, 1287, 1300, 1290, 1189,
80220  /*   370 */  1219, 1305, 1320, 1326, 1229, 1261, 1275, 1205, 1314, 1221,
80221  /*   380 */  1335, 1323, 1222, 1321, 1228, 1238, 1223, 1325, 1224, 1322,
80222  /*   390 */  1331, 1292, 1211, 1214, 1333, 1347, 1349,
80223 };
80224 #define YY_REDUCE_USE_DFLT (-144)
80225 #define YY_REDUCE_MAX 295
80226 static const short yy_reduce_ofst[] = {
80227  /*     0 */  -139,  278,  295,  292,  402,  -22,  408,   35,   37,  546,
80228  /*    10 */    -3, -128,  133,  282,  411,  417,  420, -143,  503,  213,
80229  /*    20 */   151,  353,  354,  460,  224,  224,  224,  224,  224,  224,
80230  /*    30 */   224,  224,  224,  224,  224,  224,  224,  224,  224,  224,
80231  /*    40 */   224,  224,  224,  224,  224,  224,  224,  224,  224,  224,
80232  /*    50 */   224,  224,  224,  224,  224,  224,  483,  656,  699,  723,
80233  /*    60 */   725,  732,  744,  749,  756,  758,  763,  770,  796,  807,
80234  /*    70 */   809,  812,  847,  857,  860,  876,  878,  881,  884,  886,
80235  /*    80 */   894,  897,  902,  905,  921,  929,  931,  934,  936,  938,
80236  /*    90 */   942,  947,  949,  955,  967,  973,  979,  224,  224,  224,
80237  /*   100 */   224,  168,  224,  224,   36,   33,  210,  484,  224, -121,
80238  /*   110 */   224,  224,  224,  224,   45,   21,    8,  109,  487,  487,
80239  /*   120 */   164,   99,  222,  541,  -91,   -1,  474,  598,  587,  677,
80240  /*   130 */   638,  429,  713,  639,  641,  674,  676,  716,  719,  686,
80241  /*   140 */   776,  257,  362,  802,  806,  820,  545,  582,  669,  -60,
80242  /*   150 */   -15,  128,  178,  317,   40,  317,  317,  377,  441,  481,
80243  /*   160 */   499,  502,  510,  553,  586,  596,  502,  684,  717,  768,
80244  /*   170 */   788,  786,  846,  854,  858,  317,  786,  871,  888,  864,
80245  /*   180 */   887,  906,  926,  946,  980,  317,  998, 1000,  317, 1003,
80246  /*   190 */   903,  805, 1004, 1005,  317, 1007, 1008, 1009,  317, 1010,
80247  /*   200 */  1011, 1012,  317,  317, 1013, 1014, 1015, 1016, 1017,  985,
80248  /*   210 */   962,  974, 1018,  937,  939,  945,  993,  999,  966, 1001,
80249  /*   220 */   995, 1002, 1019, 1020, 1021, 1022,  981,  977,  983,  984,
80250  /*   230 */  1031, 1037, 1039, 1040, 1034, 1023,  996, 1024, 1025, 1026,
80251  /*   240 */  1027,  975, 1048, 1049, 1028, 1029, 1032, 1030, 1035, 1036,
80252  /*   250 */  1041, 1042, 1043, 1044, 1050,  991,  992, 1047, 1051, 1056,
80253  /*   260 */  1057, 1055, 1063, 1078, 1080, 1082, 1081, 1086, 1089, 1033,
80254  /*   270 */  1045, 1091, 1092, 1062, 1064, 1046, 1053, 1097, 1065, 1066,
80255  /*   280 */  1069, 1070, 1060, 1071, 1054, 1099, 1052, 1059, 1108, 1114,
80256  /*   290 */  1072, 1104, 1090, 1093, 1075, 1079,
80257 };
80258 static const YYACTIONTYPE yy_default[] = {
80259  /*     0 */   603,  832,  913,  719,  913,  832,  913,  913,  859,  913,
80260  /*    10 */   723,  888,  830,  913,  913,  913,  913,  804,  913,  859,
80261  /*    20 */   913,  635,  859,  859,  755,  913,  913,  913,  913,  913,
80262  /*    30 */   913,  913,  913,  756,  913,  834,  829,  825,  827,  826,
80263  /*    40 */   833,  757,  746,  753,  760,  735,  872,  762,  763,  769,
80264  /*    50 */   770,  889,  887,  792,  791,  810,  913,  913,  913,  913,
80265  /*    60 */   913,  913,  913,  913,  913,  913,  913,  913,  913,  913,
80266  /*    70 */   913,  913,  913,  913,  913,  913,  913,  913,  913,  913,
80267  /*    80 */   913,  913,  913,  913,  913,  913,  913,  913,  913,  913,
80268  /*    90 */   913,  913,  913,  913,  913,  913,  913,  794,  816,  793,
80269  /*   100 */   803,  628,  795,  796,  688,  623,  913,  913,  797,  913,
80270  /*   110 */   798,  811,  812,  813,  913,  913,  913,  913,  913,  913,
80271  /*   120 */   603,  719,  913,  719,  913,  913,  913,  913,  913,  913,
80272  /*   130 */   913,  913,  913,  913,  913,  913,  913,  913,  913,  913,
80273  /*   140 */   913,  913,  913,  913,  913,  913,  713,  723,  906,  913,
80274  /*   150 */   913,  679,  913,  913,  913,  913,  913,  913,  913,  913,
80275  /*   160 */   913,  913,  611,  609,  913,  711,  913,  913,  637,  913,
80276  /*   170 */   913,  721,  913,  913,  913,  726,  727,  913,  913,  913,
80277  /*   180 */   913,  913,  913,  913,  913,  625,  913,  913,  700,  913,
80278  /*   190 */   865,  913,  913,  913,  879,  913,  913,  913,  877,  913,
80279  /*   200 */   913,  913,  702,  765,  845,  913,  892,  894,  913,  913,
80280  /*   210 */   711,  720,  913,  913,  913,  828,  749,  749,  737,  749,
80281  /*   220 */   658,  749,  913,  749,  913,  661,  759,  737,  737,  759,
80282  /*   230 */   608,  608,  608,  608,  678,  913,  759,  750,  752,  742,
80283  /*   240 */   754,  913,  728,  728,  736,  741,  736,  741,  690,  690,
80284  /*   250 */   675,  690,  661,  690,  838,  842,  842,  675,  690,  690,
80285  /*   260 */   690,  838,  620,  728,  620,  728,  620,  728,  728,  869,
80286  /*   270 */   871,  620,  728,  692,  692,  771,  759,  728,  699,  699,
80287  /*   280 */   699,  699,  759,  692,  771,  728,  891,  891,  728,  728,
80288  /*   290 */   899,  645,  663,  663,  906,  911,  913,  913,  913,  913,
80289  /*   300 */   778,  913,  913,  913,  913,  913,  913,  913,  913,  913,
80290  /*   310 */   913,  913,  913,  913,  852,  913,  913,  913,  913,  783,
80291  /*   320 */   779,  913,  780,  913,  705,  913,  913,  913,  913,  913,
80292  /*   330 */   913,  913,  913,  913,  913,  831,  913,  743,  913,  751,
80293  /*   340 */   913,  913,  913,  913,  913,  913,  913,  913,  913,  913,
80294  /*   350 */   913,  913,  913,  913,  913,  913,  913,  913,  913,  913,
80295  /*   360 */   913,  913,  913,  913,  913,  913,  867,  868,  913,  913,
80296  /*   370 */   913,  913,  913,  913,  913,  913,  913,  913,  913,  913,
80297  /*   380 */   913,  913,  913,  913,  913,  913,  913,  913,  913,  913,
80298  /*   390 */   913,  898,  913,  913,  901,  604,  913,  599,  601,  602,
80299  /*   400 */   606,  607,  610,  632,  633,  634,  612,  613,  614,  615,
80300  /*   410 */   616,  617,  618,  624,  626,  644,  646,  630,  648,  709,
80301  /*   420 */   710,  775,  703,  704,  708,  631,  786,  777,  781,  782,
80302  /*   430 */   784,  785,  799,  800,  802,  808,  815,  818,  801,  806,
80303  /*   440 */   807,  809,  814,  817,  706,  707,  821,  638,  639,  642,
80304  /*   450 */   643,  855,  857,  856,  858,  641,  640,  787,  790,  823,
80305  /*   460 */   824,  880,  881,  882,  883,  884,  819,  729,  822,  805,
80306  /*   470 */   744,  747,  748,  745,  712,  722,  731,  732,  733,  734,
80307  /*   480 */   717,  718,  724,  740,  773,  774,  738,  739,  725,  714,
80308  /*   490 */   715,  716,  820,  776,  788,  789,  649,  650,  783,  651,
80309  /*   500 */   652,  653,  691,  694,  695,  696,  654,  673,  676,  677,
80310  /*   510 */   655,  662,  656,  657,  664,  665,  666,  669,  670,  671,
80311  /*   520 */   672,  667,  668,  839,  840,  843,  841,  659,  660,  674,
80312  /*   530 */   647,  636,  629,  680,  683,  684,  685,  686,  687,  689,
80313  /*   540 */   681,  682,  627,  619,  621,  730,  861,  870,  866,  862,
80314  /*   550 */   863,  864,  622,  835,  836,  693,  767,  768,  860,  873,
80315  /*   560 */   875,  772,  876,  878,  874,  903,  697,  698,  701,  844,
80316  /*   570 */   885,  758,  761,  764,  766,  846,  847,  848,  849,  850,
80317  /*   580 */   853,  854,  851,  886,  890,  893,  895,  896,  897,  900,
80318  /*   590 */   902,  907,  908,  909,  912,  910,  605,  600,
80319 };
80320 #define YY_SZ_ACTTAB (int)(sizeof(yy_action)/sizeof(yy_action[0]))
80321
80322 /* The next table maps tokens into fallback tokens.  If a construct
80323 ** like the following:
80324 ** 
80325 **      %fallback ID X Y Z.
80326 **
80327 ** appears in the grammar, then ID becomes a fallback token for X, Y,
80328 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
80329 ** but it does not parse, the type of the token is changed to ID and
80330 ** the parse is retried before an error is thrown.
80331 */
80332 #ifdef YYFALLBACK
80333 static const YYCODETYPE yyFallback[] = {
80334     0,  /*          $ => nothing */
80335     0,  /*       SEMI => nothing */
80336    23,  /*    EXPLAIN => ID */
80337    23,  /*      QUERY => ID */
80338    23,  /*       PLAN => ID */
80339    23,  /*      BEGIN => ID */
80340     0,  /* TRANSACTION => nothing */
80341    23,  /*   DEFERRED => ID */
80342    23,  /*  IMMEDIATE => ID */
80343    23,  /*  EXCLUSIVE => ID */
80344     0,  /*     COMMIT => nothing */
80345    23,  /*        END => ID */
80346     0,  /*   ROLLBACK => nothing */
80347     0,  /*     CREATE => nothing */
80348     0,  /*      TABLE => nothing */
80349    23,  /*         IF => ID */
80350     0,  /*        NOT => nothing */
80351     0,  /*     EXISTS => nothing */
80352    23,  /*       TEMP => ID */
80353     0,  /*         LP => nothing */
80354     0,  /*         RP => nothing */
80355     0,  /*         AS => nothing */
80356     0,  /*      COMMA => nothing */
80357     0,  /*         ID => nothing */
80358    23,  /*      ABORT => ID */
80359    23,  /*      AFTER => ID */
80360    23,  /*    ANALYZE => ID */
80361    23,  /*        ASC => ID */
80362    23,  /*     ATTACH => ID */
80363    23,  /*     BEFORE => ID */
80364    23,  /*    CASCADE => ID */
80365    23,  /*       CAST => ID */
80366    23,  /*   CONFLICT => ID */
80367    23,  /*   DATABASE => ID */
80368    23,  /*       DESC => ID */
80369    23,  /*     DETACH => ID */
80370    23,  /*       EACH => ID */
80371    23,  /*       FAIL => ID */
80372    23,  /*        FOR => ID */
80373    23,  /*     IGNORE => ID */
80374    23,  /*  INITIALLY => ID */
80375    23,  /*    INSTEAD => ID */
80376    23,  /*    LIKE_KW => ID */
80377    23,  /*      MATCH => ID */
80378    23,  /*        KEY => ID */
80379    23,  /*         OF => ID */
80380    23,  /*     OFFSET => ID */
80381    23,  /*     PRAGMA => ID */
80382    23,  /*      RAISE => ID */
80383    23,  /*    REPLACE => ID */
80384    23,  /*   RESTRICT => ID */
80385    23,  /*        ROW => ID */
80386    23,  /*    TRIGGER => ID */
80387    23,  /*     VACUUM => ID */
80388    23,  /*       VIEW => ID */
80389    23,  /*    VIRTUAL => ID */
80390    23,  /*    REINDEX => ID */
80391    23,  /*     RENAME => ID */
80392    23,  /*   CTIME_KW => ID */
80393     0,  /*        ANY => nothing */
80394     0,  /*         OR => nothing */
80395     0,  /*        AND => nothing */
80396     0,  /*         IS => nothing */
80397     0,  /*    BETWEEN => nothing */
80398     0,  /*         IN => nothing */
80399     0,  /*     ISNULL => nothing */
80400     0,  /*    NOTNULL => nothing */
80401     0,  /*         NE => nothing */
80402     0,  /*         EQ => nothing */
80403     0,  /*         GT => nothing */
80404     0,  /*         LE => nothing */
80405     0,  /*         LT => nothing */
80406     0,  /*         GE => nothing */
80407     0,  /*     ESCAPE => nothing */
80408     0,  /*     BITAND => nothing */
80409     0,  /*      BITOR => nothing */
80410     0,  /*     LSHIFT => nothing */
80411     0,  /*     RSHIFT => nothing */
80412     0,  /*       PLUS => nothing */
80413     0,  /*      MINUS => nothing */
80414     0,  /*       STAR => nothing */
80415     0,  /*      SLASH => nothing */
80416     0,  /*        REM => nothing */
80417     0,  /*     CONCAT => nothing */
80418     0,  /*    COLLATE => nothing */
80419     0,  /*     UMINUS => nothing */
80420     0,  /*      UPLUS => nothing */
80421     0,  /*     BITNOT => nothing */
80422     0,  /*     STRING => nothing */
80423     0,  /*    JOIN_KW => nothing */
80424     0,  /* CONSTRAINT => nothing */
80425     0,  /*    DEFAULT => nothing */
80426     0,  /*       NULL => nothing */
80427     0,  /*    PRIMARY => nothing */
80428     0,  /*     UNIQUE => nothing */
80429     0,  /*      CHECK => nothing */
80430     0,  /* REFERENCES => nothing */
80431     0,  /*   AUTOINCR => nothing */
80432     0,  /*         ON => nothing */
80433     0,  /*     DELETE => nothing */
80434     0,  /*     UPDATE => nothing */
80435     0,  /*     INSERT => nothing */
80436     0,  /*        SET => nothing */
80437     0,  /* DEFERRABLE => nothing */
80438     0,  /*    FOREIGN => nothing */
80439     0,  /*       DROP => nothing */
80440     0,  /*      UNION => nothing */
80441     0,  /*        ALL => nothing */
80442     0,  /*     EXCEPT => nothing */
80443     0,  /*  INTERSECT => nothing */
80444     0,  /*     SELECT => nothing */
80445     0,  /*   DISTINCT => nothing */
80446     0,  /*        DOT => nothing */
80447     0,  /*       FROM => nothing */
80448     0,  /*       JOIN => nothing */
80449     0,  /*    INDEXED => nothing */
80450     0,  /*         BY => nothing */
80451     0,  /*      USING => nothing */
80452     0,  /*      ORDER => nothing */
80453     0,  /*      GROUP => nothing */
80454     0,  /*     HAVING => nothing */
80455     0,  /*      LIMIT => nothing */
80456     0,  /*      WHERE => nothing */
80457     0,  /*       INTO => nothing */
80458     0,  /*     VALUES => nothing */
80459     0,  /*    INTEGER => nothing */
80460     0,  /*      FLOAT => nothing */
80461     0,  /*       BLOB => nothing */
80462     0,  /*   REGISTER => nothing */
80463     0,  /*   VARIABLE => nothing */
80464     0,  /*       CASE => nothing */
80465     0,  /*       WHEN => nothing */
80466     0,  /*       THEN => nothing */
80467     0,  /*       ELSE => nothing */
80468     0,  /*      INDEX => nothing */
80469     0,  /*      ALTER => nothing */
80470     0,  /*         TO => nothing */
80471     0,  /*        ADD => nothing */
80472     0,  /*   COLUMNKW => nothing */
80473 };
80474 #endif /* YYFALLBACK */
80475
80476 /* The following structure represents a single element of the
80477 ** parser's stack.  Information stored includes:
80478 **
80479 **   +  The state number for the parser at this level of the stack.
80480 **
80481 **   +  The value of the token stored at this level of the stack.
80482 **      (In other words, the "major" token.)
80483 **
80484 **   +  The semantic value stored at this level of the stack.  This is
80485 **      the information used by the action routines in the grammar.
80486 **      It is sometimes called the "minor" token.
80487 */
80488 struct yyStackEntry {
80489   YYACTIONTYPE stateno;  /* The state-number */
80490   YYCODETYPE major;      /* The major token value.  This is the code
80491                          ** number for the token at this stack level */
80492   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
80493                          ** is the value of the token  */
80494 };
80495 typedef struct yyStackEntry yyStackEntry;
80496
80497 /* The state of the parser is completely contained in an instance of
80498 ** the following structure */
80499 struct yyParser {
80500   int yyidx;                    /* Index of top element in stack */
80501 #ifdef YYTRACKMAXSTACKDEPTH
80502   int yyidxMax;                 /* Maximum value of yyidx */
80503 #endif
80504   int yyerrcnt;                 /* Shifts left before out of the error */
80505   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
80506 #if YYSTACKDEPTH<=0
80507   int yystksz;                  /* Current side of the stack */
80508   yyStackEntry *yystack;        /* The parser's stack */
80509 #else
80510   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
80511 #endif
80512 };
80513 typedef struct yyParser yyParser;
80514
80515 #ifndef NDEBUG
80516 static FILE *yyTraceFILE = 0;
80517 static char *yyTracePrompt = 0;
80518 #endif /* NDEBUG */
80519
80520 #ifndef NDEBUG
80521 /* 
80522 ** Turn parser tracing on by giving a stream to which to write the trace
80523 ** and a prompt to preface each trace message.  Tracing is turned off
80524 ** by making either argument NULL 
80525 **
80526 ** Inputs:
80527 ** <ul>
80528 ** <li> A FILE* to which trace output should be written.
80529 **      If NULL, then tracing is turned off.
80530 ** <li> A prefix string written at the beginning of every
80531 **      line of trace output.  If NULL, then tracing is
80532 **      turned off.
80533 ** </ul>
80534 **
80535 ** Outputs:
80536 ** None.
80537 */
80538 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
80539   yyTraceFILE = TraceFILE;
80540   yyTracePrompt = zTracePrompt;
80541   if( yyTraceFILE==0 ) yyTracePrompt = 0;
80542   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
80543 }
80544 #endif /* NDEBUG */
80545
80546 #ifndef NDEBUG
80547 /* For tracing shifts, the names of all terminals and nonterminals
80548 ** are required.  The following table supplies these names */
80549 static const char *const yyTokenName[] = { 
80550   "$",             "SEMI",          "EXPLAIN",       "QUERY",       
80551   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",    
80552   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",         
80553   "ROLLBACK",      "CREATE",        "TABLE",         "IF",          
80554   "NOT",           "EXISTS",        "TEMP",          "LP",          
80555   "RP",            "AS",            "COMMA",         "ID",          
80556   "ABORT",         "AFTER",         "ANALYZE",       "ASC",         
80557   "ATTACH",        "BEFORE",        "CASCADE",       "CAST",        
80558   "CONFLICT",      "DATABASE",      "DESC",          "DETACH",      
80559   "EACH",          "FAIL",          "FOR",           "IGNORE",      
80560   "INITIALLY",     "INSTEAD",       "LIKE_KW",       "MATCH",       
80561   "KEY",           "OF",            "OFFSET",        "PRAGMA",      
80562   "RAISE",         "REPLACE",       "RESTRICT",      "ROW",         
80563   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",     
80564   "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",         
80565   "OR",            "AND",           "IS",            "BETWEEN",     
80566   "IN",            "ISNULL",        "NOTNULL",       "NE",          
80567   "EQ",            "GT",            "LE",            "LT",          
80568   "GE",            "ESCAPE",        "BITAND",        "BITOR",       
80569   "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",       
80570   "STAR",          "SLASH",         "REM",           "CONCAT",      
80571   "COLLATE",       "UMINUS",        "UPLUS",         "BITNOT",      
80572   "STRING",        "JOIN_KW",       "CONSTRAINT",    "DEFAULT",     
80573   "NULL",          "PRIMARY",       "UNIQUE",        "CHECK",       
80574   "REFERENCES",    "AUTOINCR",      "ON",            "DELETE",      
80575   "UPDATE",        "INSERT",        "SET",           "DEFERRABLE",  
80576   "FOREIGN",       "DROP",          "UNION",         "ALL",         
80577   "EXCEPT",        "INTERSECT",     "SELECT",        "DISTINCT",    
80578   "DOT",           "FROM",          "JOIN",          "INDEXED",     
80579   "BY",            "USING",         "ORDER",         "GROUP",       
80580   "HAVING",        "LIMIT",         "WHERE",         "INTO",        
80581   "VALUES",        "INTEGER",       "FLOAT",         "BLOB",        
80582   "REGISTER",      "VARIABLE",      "CASE",          "WHEN",        
80583   "THEN",          "ELSE",          "INDEX",         "ALTER",       
80584   "TO",            "ADD",           "COLUMNKW",      "error",       
80585   "input",         "cmdlist",       "ecmd",          "explain",     
80586   "cmdx",          "cmd",           "transtype",     "trans_opt",   
80587   "nm",            "create_table",  "create_table_args",  "temp",        
80588   "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
80589   "select",        "column",        "columnid",      "type",        
80590   "carglist",      "id",            "ids",           "typetoken",   
80591   "typename",      "signed",        "plus_num",      "minus_num",   
80592   "carg",          "ccons",         "term",          "expr",        
80593   "onconf",        "sortorder",     "autoinc",       "idxlist_opt", 
80594   "refargs",       "defer_subclause",  "refarg",        "refact",      
80595   "init_deferred_pred_opt",  "conslist",      "tcons",         "idxlist",     
80596   "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",   
80597   "ifexists",      "fullname",      "oneselect",     "multiselect_op",
80598   "distinct",      "selcollist",    "from",          "where_opt",   
80599   "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",   
80600   "sclp",          "as",            "seltablist",    "stl_prefix",  
80601   "joinop",        "indexed_opt",   "on_opt",        "using_opt",   
80602   "seltablist_paren",  "joinop2",       "inscollist",    "sortlist",    
80603   "sortitem",      "nexprlist",     "setlist",       "insert_cmd",  
80604   "inscollist_opt",  "itemlist",      "exprlist",      "likeop",      
80605   "escape",        "between_op",    "in_op",         "case_operand",
80606   "case_exprlist",  "case_else",     "uniqueflag",    "collate",     
80607   "nmnum",         "plus_opt",      "number",        "trigger_decl",
80608   "trigger_cmd_list",  "trigger_time",  "trigger_event",  "foreach_clause",
80609   "when_clause",   "trigger_cmd",   "database_kw_opt",  "key_opt",     
80610   "add_column_fullname",  "kwcolumn_opt",  "create_vtab",   "vtabarglist", 
80611   "vtabarg",       "vtabargtoken",  "lp",            "anylist",     
80612 };
80613 #endif /* NDEBUG */
80614
80615 #ifndef NDEBUG
80616 /* For tracing reduce actions, the names of all rules are required.
80617 */
80618 static const char *const yyRuleName[] = {
80619  /*   0 */ "input ::= cmdlist",
80620  /*   1 */ "cmdlist ::= cmdlist ecmd",
80621  /*   2 */ "cmdlist ::= ecmd",
80622  /*   3 */ "ecmd ::= SEMI",
80623  /*   4 */ "ecmd ::= explain cmdx SEMI",
80624  /*   5 */ "explain ::=",
80625  /*   6 */ "explain ::= EXPLAIN",
80626  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
80627  /*   8 */ "cmdx ::= cmd",
80628  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
80629  /*  10 */ "trans_opt ::=",
80630  /*  11 */ "trans_opt ::= TRANSACTION",
80631  /*  12 */ "trans_opt ::= TRANSACTION nm",
80632  /*  13 */ "transtype ::=",
80633  /*  14 */ "transtype ::= DEFERRED",
80634  /*  15 */ "transtype ::= IMMEDIATE",
80635  /*  16 */ "transtype ::= EXCLUSIVE",
80636  /*  17 */ "cmd ::= COMMIT trans_opt",
80637  /*  18 */ "cmd ::= END trans_opt",
80638  /*  19 */ "cmd ::= ROLLBACK trans_opt",
80639  /*  20 */ "cmd ::= create_table create_table_args",
80640  /*  21 */ "create_table ::= CREATE temp TABLE ifnotexists nm dbnm",
80641  /*  22 */ "ifnotexists ::=",
80642  /*  23 */ "ifnotexists ::= IF NOT EXISTS",
80643  /*  24 */ "temp ::= TEMP",
80644  /*  25 */ "temp ::=",
80645  /*  26 */ "create_table_args ::= LP columnlist conslist_opt RP",
80646  /*  27 */ "create_table_args ::= AS select",
80647  /*  28 */ "columnlist ::= columnlist COMMA column",
80648  /*  29 */ "columnlist ::= column",
80649  /*  30 */ "column ::= columnid type carglist",
80650  /*  31 */ "columnid ::= nm",
80651  /*  32 */ "id ::= ID",
80652  /*  33 */ "ids ::= ID|STRING",
80653  /*  34 */ "nm ::= ID",
80654  /*  35 */ "nm ::= STRING",
80655  /*  36 */ "nm ::= JOIN_KW",
80656  /*  37 */ "type ::=",
80657  /*  38 */ "type ::= typetoken",
80658  /*  39 */ "typetoken ::= typename",
80659  /*  40 */ "typetoken ::= typename LP signed RP",
80660  /*  41 */ "typetoken ::= typename LP signed COMMA signed RP",
80661  /*  42 */ "typename ::= ids",
80662  /*  43 */ "typename ::= typename ids",
80663  /*  44 */ "signed ::= plus_num",
80664  /*  45 */ "signed ::= minus_num",
80665  /*  46 */ "carglist ::= carglist carg",
80666  /*  47 */ "carglist ::=",
80667  /*  48 */ "carg ::= CONSTRAINT nm ccons",
80668  /*  49 */ "carg ::= ccons",
80669  /*  50 */ "ccons ::= DEFAULT term",
80670  /*  51 */ "ccons ::= DEFAULT LP expr RP",
80671  /*  52 */ "ccons ::= DEFAULT PLUS term",
80672  /*  53 */ "ccons ::= DEFAULT MINUS term",
80673  /*  54 */ "ccons ::= DEFAULT id",
80674  /*  55 */ "ccons ::= NULL onconf",
80675  /*  56 */ "ccons ::= NOT NULL onconf",
80676  /*  57 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
80677  /*  58 */ "ccons ::= UNIQUE onconf",
80678  /*  59 */ "ccons ::= CHECK LP expr RP",
80679  /*  60 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
80680  /*  61 */ "ccons ::= defer_subclause",
80681  /*  62 */ "ccons ::= COLLATE ids",
80682  /*  63 */ "autoinc ::=",
80683  /*  64 */ "autoinc ::= AUTOINCR",
80684  /*  65 */ "refargs ::=",
80685  /*  66 */ "refargs ::= refargs refarg",
80686  /*  67 */ "refarg ::= MATCH nm",
80687  /*  68 */ "refarg ::= ON DELETE refact",
80688  /*  69 */ "refarg ::= ON UPDATE refact",
80689  /*  70 */ "refarg ::= ON INSERT refact",
80690  /*  71 */ "refact ::= SET NULL",
80691  /*  72 */ "refact ::= SET DEFAULT",
80692  /*  73 */ "refact ::= CASCADE",
80693  /*  74 */ "refact ::= RESTRICT",
80694  /*  75 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
80695  /*  76 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
80696  /*  77 */ "init_deferred_pred_opt ::=",
80697  /*  78 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
80698  /*  79 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
80699  /*  80 */ "conslist_opt ::=",
80700  /*  81 */ "conslist_opt ::= COMMA conslist",
80701  /*  82 */ "conslist ::= conslist COMMA tcons",
80702  /*  83 */ "conslist ::= conslist tcons",
80703  /*  84 */ "conslist ::= tcons",
80704  /*  85 */ "tcons ::= CONSTRAINT nm",
80705  /*  86 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
80706  /*  87 */ "tcons ::= UNIQUE LP idxlist RP onconf",
80707  /*  88 */ "tcons ::= CHECK LP expr RP onconf",
80708  /*  89 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
80709  /*  90 */ "defer_subclause_opt ::=",
80710  /*  91 */ "defer_subclause_opt ::= defer_subclause",
80711  /*  92 */ "onconf ::=",
80712  /*  93 */ "onconf ::= ON CONFLICT resolvetype",
80713  /*  94 */ "orconf ::=",
80714  /*  95 */ "orconf ::= OR resolvetype",
80715  /*  96 */ "resolvetype ::= raisetype",
80716  /*  97 */ "resolvetype ::= IGNORE",
80717  /*  98 */ "resolvetype ::= REPLACE",
80718  /*  99 */ "cmd ::= DROP TABLE ifexists fullname",
80719  /* 100 */ "ifexists ::= IF EXISTS",
80720  /* 101 */ "ifexists ::=",
80721  /* 102 */ "cmd ::= CREATE temp VIEW ifnotexists nm dbnm AS select",
80722  /* 103 */ "cmd ::= DROP VIEW ifexists fullname",
80723  /* 104 */ "cmd ::= select",
80724  /* 105 */ "select ::= oneselect",
80725  /* 106 */ "select ::= select multiselect_op oneselect",
80726  /* 107 */ "multiselect_op ::= UNION",
80727  /* 108 */ "multiselect_op ::= UNION ALL",
80728  /* 109 */ "multiselect_op ::= EXCEPT|INTERSECT",
80729  /* 110 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
80730  /* 111 */ "distinct ::= DISTINCT",
80731  /* 112 */ "distinct ::= ALL",
80732  /* 113 */ "distinct ::=",
80733  /* 114 */ "sclp ::= selcollist COMMA",
80734  /* 115 */ "sclp ::=",
80735  /* 116 */ "selcollist ::= sclp expr as",
80736  /* 117 */ "selcollist ::= sclp STAR",
80737  /* 118 */ "selcollist ::= sclp nm DOT STAR",
80738  /* 119 */ "as ::= AS nm",
80739  /* 120 */ "as ::= ids",
80740  /* 121 */ "as ::=",
80741  /* 122 */ "from ::=",
80742  /* 123 */ "from ::= FROM seltablist",
80743  /* 124 */ "stl_prefix ::= seltablist joinop",
80744  /* 125 */ "stl_prefix ::=",
80745  /* 126 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
80746  /* 127 */ "seltablist ::= stl_prefix LP seltablist_paren RP as on_opt using_opt",
80747  /* 128 */ "seltablist_paren ::= select",
80748  /* 129 */ "seltablist_paren ::= seltablist",
80749  /* 130 */ "dbnm ::=",
80750  /* 131 */ "dbnm ::= DOT nm",
80751  /* 132 */ "fullname ::= nm dbnm",
80752  /* 133 */ "joinop ::= COMMA|JOIN",
80753  /* 134 */ "joinop ::= JOIN_KW JOIN",
80754  /* 135 */ "joinop ::= JOIN_KW nm JOIN",
80755  /* 136 */ "joinop ::= JOIN_KW nm nm JOIN",
80756  /* 137 */ "on_opt ::= ON expr",
80757  /* 138 */ "on_opt ::=",
80758  /* 139 */ "indexed_opt ::=",
80759  /* 140 */ "indexed_opt ::= INDEXED BY nm",
80760  /* 141 */ "indexed_opt ::= NOT INDEXED",
80761  /* 142 */ "using_opt ::= USING LP inscollist RP",
80762  /* 143 */ "using_opt ::=",
80763  /* 144 */ "orderby_opt ::=",
80764  /* 145 */ "orderby_opt ::= ORDER BY sortlist",
80765  /* 146 */ "sortlist ::= sortlist COMMA sortitem sortorder",
80766  /* 147 */ "sortlist ::= sortitem sortorder",
80767  /* 148 */ "sortitem ::= expr",
80768  /* 149 */ "sortorder ::= ASC",
80769  /* 150 */ "sortorder ::= DESC",
80770  /* 151 */ "sortorder ::=",
80771  /* 152 */ "groupby_opt ::=",
80772  /* 153 */ "groupby_opt ::= GROUP BY nexprlist",
80773  /* 154 */ "having_opt ::=",
80774  /* 155 */ "having_opt ::= HAVING expr",
80775  /* 156 */ "limit_opt ::=",
80776  /* 157 */ "limit_opt ::= LIMIT expr",
80777  /* 158 */ "limit_opt ::= LIMIT expr OFFSET expr",
80778  /* 159 */ "limit_opt ::= LIMIT expr COMMA expr",
80779  /* 160 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
80780  /* 161 */ "where_opt ::=",
80781  /* 162 */ "where_opt ::= WHERE expr",
80782  /* 163 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
80783  /* 164 */ "setlist ::= setlist COMMA nm EQ expr",
80784  /* 165 */ "setlist ::= nm EQ expr",
80785  /* 166 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
80786  /* 167 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
80787  /* 168 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
80788  /* 169 */ "insert_cmd ::= INSERT orconf",
80789  /* 170 */ "insert_cmd ::= REPLACE",
80790  /* 171 */ "itemlist ::= itemlist COMMA expr",
80791  /* 172 */ "itemlist ::= expr",
80792  /* 173 */ "inscollist_opt ::=",
80793  /* 174 */ "inscollist_opt ::= LP inscollist RP",
80794  /* 175 */ "inscollist ::= inscollist COMMA nm",
80795  /* 176 */ "inscollist ::= nm",
80796  /* 177 */ "expr ::= term",
80797  /* 178 */ "expr ::= LP expr RP",
80798  /* 179 */ "term ::= NULL",
80799  /* 180 */ "expr ::= ID",
80800  /* 181 */ "expr ::= JOIN_KW",
80801  /* 182 */ "expr ::= nm DOT nm",
80802  /* 183 */ "expr ::= nm DOT nm DOT nm",
80803  /* 184 */ "term ::= INTEGER|FLOAT|BLOB",
80804  /* 185 */ "term ::= STRING",
80805  /* 186 */ "expr ::= REGISTER",
80806  /* 187 */ "expr ::= VARIABLE",
80807  /* 188 */ "expr ::= expr COLLATE ids",
80808  /* 189 */ "expr ::= CAST LP expr AS typetoken RP",
80809  /* 190 */ "expr ::= ID LP distinct exprlist RP",
80810  /* 191 */ "expr ::= ID LP STAR RP",
80811  /* 192 */ "term ::= CTIME_KW",
80812  /* 193 */ "expr ::= expr AND expr",
80813  /* 194 */ "expr ::= expr OR expr",
80814  /* 195 */ "expr ::= expr LT|GT|GE|LE expr",
80815  /* 196 */ "expr ::= expr EQ|NE expr",
80816  /* 197 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
80817  /* 198 */ "expr ::= expr PLUS|MINUS expr",
80818  /* 199 */ "expr ::= expr STAR|SLASH|REM expr",
80819  /* 200 */ "expr ::= expr CONCAT expr",
80820  /* 201 */ "likeop ::= LIKE_KW",
80821  /* 202 */ "likeop ::= NOT LIKE_KW",
80822  /* 203 */ "likeop ::= MATCH",
80823  /* 204 */ "likeop ::= NOT MATCH",
80824  /* 205 */ "escape ::= ESCAPE expr",
80825  /* 206 */ "escape ::=",
80826  /* 207 */ "expr ::= expr likeop expr escape",
80827  /* 208 */ "expr ::= expr ISNULL|NOTNULL",
80828  /* 209 */ "expr ::= expr IS NULL",
80829  /* 210 */ "expr ::= expr NOT NULL",
80830  /* 211 */ "expr ::= expr IS NOT NULL",
80831  /* 212 */ "expr ::= NOT expr",
80832  /* 213 */ "expr ::= BITNOT expr",
80833  /* 214 */ "expr ::= MINUS expr",
80834  /* 215 */ "expr ::= PLUS expr",
80835  /* 216 */ "between_op ::= BETWEEN",
80836  /* 217 */ "between_op ::= NOT BETWEEN",
80837  /* 218 */ "expr ::= expr between_op expr AND expr",
80838  /* 219 */ "in_op ::= IN",
80839  /* 220 */ "in_op ::= NOT IN",
80840  /* 221 */ "expr ::= expr in_op LP exprlist RP",
80841  /* 222 */ "expr ::= LP select RP",
80842  /* 223 */ "expr ::= expr in_op LP select RP",
80843  /* 224 */ "expr ::= expr in_op nm dbnm",
80844  /* 225 */ "expr ::= EXISTS LP select RP",
80845  /* 226 */ "expr ::= CASE case_operand case_exprlist case_else END",
80846  /* 227 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
80847  /* 228 */ "case_exprlist ::= WHEN expr THEN expr",
80848  /* 229 */ "case_else ::= ELSE expr",
80849  /* 230 */ "case_else ::=",
80850  /* 231 */ "case_operand ::= expr",
80851  /* 232 */ "case_operand ::=",
80852  /* 233 */ "exprlist ::= nexprlist",
80853  /* 234 */ "exprlist ::=",
80854  /* 235 */ "nexprlist ::= nexprlist COMMA expr",
80855  /* 236 */ "nexprlist ::= expr",
80856  /* 237 */ "cmd ::= CREATE uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
80857  /* 238 */ "uniqueflag ::= UNIQUE",
80858  /* 239 */ "uniqueflag ::=",
80859  /* 240 */ "idxlist_opt ::=",
80860  /* 241 */ "idxlist_opt ::= LP idxlist RP",
80861  /* 242 */ "idxlist ::= idxlist COMMA nm collate sortorder",
80862  /* 243 */ "idxlist ::= nm collate sortorder",
80863  /* 244 */ "collate ::=",
80864  /* 245 */ "collate ::= COLLATE ids",
80865  /* 246 */ "cmd ::= DROP INDEX ifexists fullname",
80866  /* 247 */ "cmd ::= VACUUM",
80867  /* 248 */ "cmd ::= VACUUM nm",
80868  /* 249 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
80869  /* 250 */ "cmd ::= PRAGMA nm dbnm EQ ON",
80870  /* 251 */ "cmd ::= PRAGMA nm dbnm EQ DELETE",
80871  /* 252 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
80872  /* 253 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
80873  /* 254 */ "cmd ::= PRAGMA nm dbnm",
80874  /* 255 */ "nmnum ::= plus_num",
80875  /* 256 */ "nmnum ::= nm",
80876  /* 257 */ "plus_num ::= plus_opt number",
80877  /* 258 */ "minus_num ::= MINUS number",
80878  /* 259 */ "number ::= INTEGER|FLOAT",
80879  /* 260 */ "plus_opt ::= PLUS",
80880  /* 261 */ "plus_opt ::=",
80881  /* 262 */ "cmd ::= CREATE trigger_decl BEGIN trigger_cmd_list END",
80882  /* 263 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
80883  /* 264 */ "trigger_time ::= BEFORE",
80884  /* 265 */ "trigger_time ::= AFTER",
80885  /* 266 */ "trigger_time ::= INSTEAD OF",
80886  /* 267 */ "trigger_time ::=",
80887  /* 268 */ "trigger_event ::= DELETE|INSERT",
80888  /* 269 */ "trigger_event ::= UPDATE",
80889  /* 270 */ "trigger_event ::= UPDATE OF inscollist",
80890  /* 271 */ "foreach_clause ::=",
80891  /* 272 */ "foreach_clause ::= FOR EACH ROW",
80892  /* 273 */ "when_clause ::=",
80893  /* 274 */ "when_clause ::= WHEN expr",
80894  /* 275 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
80895  /* 276 */ "trigger_cmd_list ::= trigger_cmd SEMI",
80896  /* 277 */ "trigger_cmd ::= UPDATE orconf nm SET setlist where_opt",
80897  /* 278 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP",
80898  /* 279 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt select",
80899  /* 280 */ "trigger_cmd ::= DELETE FROM nm where_opt",
80900  /* 281 */ "trigger_cmd ::= select",
80901  /* 282 */ "expr ::= RAISE LP IGNORE RP",
80902  /* 283 */ "expr ::= RAISE LP raisetype COMMA nm RP",
80903  /* 284 */ "raisetype ::= ROLLBACK",
80904  /* 285 */ "raisetype ::= ABORT",
80905  /* 286 */ "raisetype ::= FAIL",
80906  /* 287 */ "cmd ::= DROP TRIGGER ifexists fullname",
80907  /* 288 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
80908  /* 289 */ "cmd ::= DETACH database_kw_opt expr",
80909  /* 290 */ "key_opt ::=",
80910  /* 291 */ "key_opt ::= KEY expr",
80911  /* 292 */ "database_kw_opt ::= DATABASE",
80912  /* 293 */ "database_kw_opt ::=",
80913  /* 294 */ "cmd ::= REINDEX",
80914  /* 295 */ "cmd ::= REINDEX nm dbnm",
80915  /* 296 */ "cmd ::= ANALYZE",
80916  /* 297 */ "cmd ::= ANALYZE nm dbnm",
80917  /* 298 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
80918  /* 299 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
80919  /* 300 */ "add_column_fullname ::= fullname",
80920  /* 301 */ "kwcolumn_opt ::=",
80921  /* 302 */ "kwcolumn_opt ::= COLUMNKW",
80922  /* 303 */ "cmd ::= create_vtab",
80923  /* 304 */ "cmd ::= create_vtab LP vtabarglist RP",
80924  /* 305 */ "create_vtab ::= CREATE VIRTUAL TABLE nm dbnm USING nm",
80925  /* 306 */ "vtabarglist ::= vtabarg",
80926  /* 307 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
80927  /* 308 */ "vtabarg ::=",
80928  /* 309 */ "vtabarg ::= vtabarg vtabargtoken",
80929  /* 310 */ "vtabargtoken ::= ANY",
80930  /* 311 */ "vtabargtoken ::= lp anylist RP",
80931  /* 312 */ "lp ::= LP",
80932  /* 313 */ "anylist ::=",
80933  /* 314 */ "anylist ::= anylist ANY",
80934 };
80935 #endif /* NDEBUG */
80936
80937
80938 #if YYSTACKDEPTH<=0
80939 /*
80940 ** Try to increase the size of the parser stack.
80941 */
80942 static void yyGrowStack(yyParser *p){
80943   int newSize;
80944   yyStackEntry *pNew;
80945
80946   newSize = p->yystksz*2 + 100;
80947   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
80948   if( pNew ){
80949     p->yystack = pNew;
80950     p->yystksz = newSize;
80951 #ifndef NDEBUG
80952     if( yyTraceFILE ){
80953       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
80954               yyTracePrompt, p->yystksz);
80955     }
80956 #endif
80957   }
80958 }
80959 #endif
80960
80961 /* 
80962 ** This function allocates a new parser.
80963 ** The only argument is a pointer to a function which works like
80964 ** malloc.
80965 **
80966 ** Inputs:
80967 ** A pointer to the function used to allocate memory.
80968 **
80969 ** Outputs:
80970 ** A pointer to a parser.  This pointer is used in subsequent calls
80971 ** to sqlite3Parser and sqlite3ParserFree.
80972 */
80973 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
80974   yyParser *pParser;
80975   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
80976   if( pParser ){
80977     pParser->yyidx = -1;
80978 #ifdef YYTRACKMAXSTACKDEPTH
80979     pParser->yyidxMax = 0;
80980 #endif
80981 #if YYSTACKDEPTH<=0
80982     pParser->yystack = NULL;
80983     pParser->yystksz = 0;
80984     yyGrowStack(pParser);
80985 #endif
80986   }
80987   return pParser;
80988 }
80989
80990 /* The following function deletes the value associated with a
80991 ** symbol.  The symbol can be either a terminal or nonterminal.
80992 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
80993 ** the value.
80994 */
80995 static void yy_destructor(
80996   yyParser *yypParser,    /* The parser */
80997   YYCODETYPE yymajor,     /* Type code for object to destroy */
80998   YYMINORTYPE *yypminor   /* The object to be destroyed */
80999 ){
81000   sqlite3ParserARG_FETCH;
81001   switch( yymajor ){
81002     /* Here is inserted the actions which take place when a
81003     ** terminal or non-terminal is destroyed.  This can happen
81004     ** when the symbol is popped from the stack during a
81005     ** reduce or during error processing or when a parser is 
81006     ** being destroyed before it is finished parsing.
81007     **
81008     ** Note: during a reduce, the only symbols destroyed are those
81009     ** which appear on the RHS of the rule, but which are not used
81010     ** inside the C code.
81011     */
81012     case 156: /* select */
81013     case 190: /* oneselect */
81014     case 208: /* seltablist_paren */
81015 {
81016 sqlite3SelectDelete(pParse->db, (yypminor->yy43));
81017 }
81018       break;
81019     case 170: /* term */
81020     case 171: /* expr */
81021     case 195: /* where_opt */
81022     case 197: /* having_opt */
81023     case 206: /* on_opt */
81024     case 212: /* sortitem */
81025     case 220: /* escape */
81026     case 223: /* case_operand */
81027     case 225: /* case_else */
81028     case 236: /* when_clause */
81029     case 239: /* key_opt */
81030 {
81031 sqlite3ExprDelete(pParse->db, (yypminor->yy450));
81032 }
81033       break;
81034     case 175: /* idxlist_opt */
81035     case 183: /* idxlist */
81036     case 193: /* selcollist */
81037     case 196: /* groupby_opt */
81038     case 198: /* orderby_opt */
81039     case 200: /* sclp */
81040     case 211: /* sortlist */
81041     case 213: /* nexprlist */
81042     case 214: /* setlist */
81043     case 217: /* itemlist */
81044     case 218: /* exprlist */
81045     case 224: /* case_exprlist */
81046 {
81047 sqlite3ExprListDelete(pParse->db, (yypminor->yy242));
81048 }
81049       break;
81050     case 189: /* fullname */
81051     case 194: /* from */
81052     case 202: /* seltablist */
81053     case 203: /* stl_prefix */
81054 {
81055 sqlite3SrcListDelete(pParse->db, (yypminor->yy419));
81056 }
81057       break;
81058     case 207: /* using_opt */
81059     case 210: /* inscollist */
81060     case 216: /* inscollist_opt */
81061 {
81062 sqlite3IdListDelete(pParse->db, (yypminor->yy352));
81063 }
81064       break;
81065     case 232: /* trigger_cmd_list */
81066     case 237: /* trigger_cmd */
81067 {
81068 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy75));
81069 }
81070       break;
81071     case 234: /* trigger_event */
81072 {
81073 sqlite3IdListDelete(pParse->db, (yypminor->yy354).b);
81074 }
81075       break;
81076     default:  break;   /* If no destructor action specified: do nothing */
81077   }
81078 }
81079
81080 /*
81081 ** Pop the parser's stack once.
81082 **
81083 ** If there is a destructor routine associated with the token which
81084 ** is popped from the stack, then call it.
81085 **
81086 ** Return the major token number for the symbol popped.
81087 */
81088 static int yy_pop_parser_stack(yyParser *pParser){
81089   YYCODETYPE yymajor;
81090   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
81091
81092   if( pParser->yyidx<0 ) return 0;
81093 #ifndef NDEBUG
81094   if( yyTraceFILE && pParser->yyidx>=0 ){
81095     fprintf(yyTraceFILE,"%sPopping %s\n",
81096       yyTracePrompt,
81097       yyTokenName[yytos->major]);
81098   }
81099 #endif
81100   yymajor = yytos->major;
81101   yy_destructor(pParser, yymajor, &yytos->minor);
81102   pParser->yyidx--;
81103   return yymajor;
81104 }
81105
81106 /* 
81107 ** Deallocate and destroy a parser.  Destructors are all called for
81108 ** all stack elements before shutting the parser down.
81109 **
81110 ** Inputs:
81111 ** <ul>
81112 ** <li>  A pointer to the parser.  This should be a pointer
81113 **       obtained from sqlite3ParserAlloc.
81114 ** <li>  A pointer to a function used to reclaim memory obtained
81115 **       from malloc.
81116 ** </ul>
81117 */
81118 SQLITE_PRIVATE void sqlite3ParserFree(
81119   void *p,                    /* The parser to be deleted */
81120   void (*freeProc)(void*)     /* Function used to reclaim memory */
81121 ){
81122   yyParser *pParser = (yyParser*)p;
81123   if( pParser==0 ) return;
81124   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
81125 #if YYSTACKDEPTH<=0
81126   free(pParser->yystack);
81127 #endif
81128   (*freeProc)((void*)pParser);
81129 }
81130
81131 /*
81132 ** Return the peak depth of the stack for a parser.
81133 */
81134 #ifdef YYTRACKMAXSTACKDEPTH
81135 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
81136   yyParser *pParser = (yyParser*)p;
81137   return pParser->yyidxMax;
81138 }
81139 #endif
81140
81141 /*
81142 ** Find the appropriate action for a parser given the terminal
81143 ** look-ahead token iLookAhead.
81144 **
81145 ** If the look-ahead token is YYNOCODE, then check to see if the action is
81146 ** independent of the look-ahead.  If it is, return the action, otherwise
81147 ** return YY_NO_ACTION.
81148 */
81149 static int yy_find_shift_action(
81150   yyParser *pParser,        /* The parser */
81151   YYCODETYPE iLookAhead     /* The look-ahead token */
81152 ){
81153   int i;
81154   int stateno = pParser->yystack[pParser->yyidx].stateno;
81155  
81156   if( stateno>YY_SHIFT_MAX || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
81157     return yy_default[stateno];
81158   }
81159   assert( iLookAhead!=YYNOCODE );
81160   i += iLookAhead;
81161   if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){
81162     if( iLookAhead>0 ){
81163 #ifdef YYFALLBACK
81164       int iFallback;            /* Fallback token */
81165       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
81166              && (iFallback = yyFallback[iLookAhead])!=0 ){
81167 #ifndef NDEBUG
81168         if( yyTraceFILE ){
81169           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
81170              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
81171         }
81172 #endif
81173         return yy_find_shift_action(pParser, iFallback);
81174       }
81175 #endif
81176 #ifdef YYWILDCARD
81177       {
81178         int j = i - iLookAhead + YYWILDCARD;
81179         if( j>=0 && j<YY_SZ_ACTTAB && yy_lookahead[j]==YYWILDCARD ){
81180 #ifndef NDEBUG
81181           if( yyTraceFILE ){
81182             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
81183                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
81184           }
81185 #endif /* NDEBUG */
81186           return yy_action[j];
81187         }
81188       }
81189 #endif /* YYWILDCARD */
81190     }
81191     return yy_default[stateno];
81192   }else{
81193     return yy_action[i];
81194   }
81195 }
81196
81197 /*
81198 ** Find the appropriate action for a parser given the non-terminal
81199 ** look-ahead token iLookAhead.
81200 **
81201 ** If the look-ahead token is YYNOCODE, then check to see if the action is
81202 ** independent of the look-ahead.  If it is, return the action, otherwise
81203 ** return YY_NO_ACTION.
81204 */
81205 static int yy_find_reduce_action(
81206   int stateno,              /* Current state number */
81207   YYCODETYPE iLookAhead     /* The look-ahead token */
81208 ){
81209   int i;
81210 #ifdef YYERRORSYMBOL
81211   if( stateno>YY_REDUCE_MAX ){
81212     return yy_default[stateno];
81213   }
81214 #else
81215   assert( stateno<=YY_REDUCE_MAX );
81216 #endif
81217   i = yy_reduce_ofst[stateno];
81218   assert( i!=YY_REDUCE_USE_DFLT );
81219   assert( iLookAhead!=YYNOCODE );
81220   i += iLookAhead;
81221 #ifdef YYERRORSYMBOL
81222   if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){
81223     return yy_default[stateno];
81224   }
81225 #else
81226   assert( i>=0 && i<YY_SZ_ACTTAB );
81227   assert( yy_lookahead[i]==iLookAhead );
81228 #endif
81229   return yy_action[i];
81230 }
81231
81232 /*
81233 ** The following routine is called if the stack overflows.
81234 */
81235 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
81236    sqlite3ParserARG_FETCH;
81237    yypParser->yyidx--;
81238 #ifndef NDEBUG
81239    if( yyTraceFILE ){
81240      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
81241    }
81242 #endif
81243    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
81244    /* Here code is inserted which will execute if the parser
81245    ** stack every overflows */
81246
81247   sqlite3ErrorMsg(pParse, "parser stack overflow");
81248   pParse->parseError = 1;
81249    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
81250 }
81251
81252 /*
81253 ** Perform a shift action.
81254 */
81255 static void yy_shift(
81256   yyParser *yypParser,          /* The parser to be shifted */
81257   int yyNewState,               /* The new state to shift in */
81258   int yyMajor,                  /* The major token to shift in */
81259   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
81260 ){
81261   yyStackEntry *yytos;
81262   yypParser->yyidx++;
81263 #ifdef YYTRACKMAXSTACKDEPTH
81264   if( yypParser->yyidx>yypParser->yyidxMax ){
81265     yypParser->yyidxMax = yypParser->yyidx;
81266   }
81267 #endif
81268 #if YYSTACKDEPTH>0 
81269   if( yypParser->yyidx>=YYSTACKDEPTH ){
81270     yyStackOverflow(yypParser, yypMinor);
81271     return;
81272   }
81273 #else
81274   if( yypParser->yyidx>=yypParser->yystksz ){
81275     yyGrowStack(yypParser);
81276     if( yypParser->yyidx>=yypParser->yystksz ){
81277       yyStackOverflow(yypParser, yypMinor);
81278       return;
81279     }
81280   }
81281 #endif
81282   yytos = &yypParser->yystack[yypParser->yyidx];
81283   yytos->stateno = yyNewState;
81284   yytos->major = yyMajor;
81285   yytos->minor = *yypMinor;
81286 #ifndef NDEBUG
81287   if( yyTraceFILE && yypParser->yyidx>0 ){
81288     int i;
81289     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
81290     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
81291     for(i=1; i<=yypParser->yyidx; i++)
81292       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
81293     fprintf(yyTraceFILE,"\n");
81294   }
81295 #endif
81296 }
81297
81298 /* The following table contains information about every rule that
81299 ** is used during the reduce.
81300 */
81301 static const struct {
81302   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
81303   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
81304 } yyRuleInfo[] = {
81305   { 140, 1 },
81306   { 141, 2 },
81307   { 141, 1 },
81308   { 142, 1 },
81309   { 142, 3 },
81310   { 143, 0 },
81311   { 143, 1 },
81312   { 143, 3 },
81313   { 144, 1 },
81314   { 145, 3 },
81315   { 147, 0 },
81316   { 147, 1 },
81317   { 147, 2 },
81318   { 146, 0 },
81319   { 146, 1 },
81320   { 146, 1 },
81321   { 146, 1 },
81322   { 145, 2 },
81323   { 145, 2 },
81324   { 145, 2 },
81325   { 145, 2 },
81326   { 149, 6 },
81327   { 152, 0 },
81328   { 152, 3 },
81329   { 151, 1 },
81330   { 151, 0 },
81331   { 150, 4 },
81332   { 150, 2 },
81333   { 154, 3 },
81334   { 154, 1 },
81335   { 157, 3 },
81336   { 158, 1 },
81337   { 161, 1 },
81338   { 162, 1 },
81339   { 148, 1 },
81340   { 148, 1 },
81341   { 148, 1 },
81342   { 159, 0 },
81343   { 159, 1 },
81344   { 163, 1 },
81345   { 163, 4 },
81346   { 163, 6 },
81347   { 164, 1 },
81348   { 164, 2 },
81349   { 165, 1 },
81350   { 165, 1 },
81351   { 160, 2 },
81352   { 160, 0 },
81353   { 168, 3 },
81354   { 168, 1 },
81355   { 169, 2 },
81356   { 169, 4 },
81357   { 169, 3 },
81358   { 169, 3 },
81359   { 169, 2 },
81360   { 169, 2 },
81361   { 169, 3 },
81362   { 169, 5 },
81363   { 169, 2 },
81364   { 169, 4 },
81365   { 169, 4 },
81366   { 169, 1 },
81367   { 169, 2 },
81368   { 174, 0 },
81369   { 174, 1 },
81370   { 176, 0 },
81371   { 176, 2 },
81372   { 178, 2 },
81373   { 178, 3 },
81374   { 178, 3 },
81375   { 178, 3 },
81376   { 179, 2 },
81377   { 179, 2 },
81378   { 179, 1 },
81379   { 179, 1 },
81380   { 177, 3 },
81381   { 177, 2 },
81382   { 180, 0 },
81383   { 180, 2 },
81384   { 180, 2 },
81385   { 155, 0 },
81386   { 155, 2 },
81387   { 181, 3 },
81388   { 181, 2 },
81389   { 181, 1 },
81390   { 182, 2 },
81391   { 182, 7 },
81392   { 182, 5 },
81393   { 182, 5 },
81394   { 182, 10 },
81395   { 184, 0 },
81396   { 184, 1 },
81397   { 172, 0 },
81398   { 172, 3 },
81399   { 185, 0 },
81400   { 185, 2 },
81401   { 186, 1 },
81402   { 186, 1 },
81403   { 186, 1 },
81404   { 145, 4 },
81405   { 188, 2 },
81406   { 188, 0 },
81407   { 145, 8 },
81408   { 145, 4 },
81409   { 145, 1 },
81410   { 156, 1 },
81411   { 156, 3 },
81412   { 191, 1 },
81413   { 191, 2 },
81414   { 191, 1 },
81415   { 190, 9 },
81416   { 192, 1 },
81417   { 192, 1 },
81418   { 192, 0 },
81419   { 200, 2 },
81420   { 200, 0 },
81421   { 193, 3 },
81422   { 193, 2 },
81423   { 193, 4 },
81424   { 201, 2 },
81425   { 201, 1 },
81426   { 201, 0 },
81427   { 194, 0 },
81428   { 194, 2 },
81429   { 203, 2 },
81430   { 203, 0 },
81431   { 202, 7 },
81432   { 202, 7 },
81433   { 208, 1 },
81434   { 208, 1 },
81435   { 153, 0 },
81436   { 153, 2 },
81437   { 189, 2 },
81438   { 204, 1 },
81439   { 204, 2 },
81440   { 204, 3 },
81441   { 204, 4 },
81442   { 206, 2 },
81443   { 206, 0 },
81444   { 205, 0 },
81445   { 205, 3 },
81446   { 205, 2 },
81447   { 207, 4 },
81448   { 207, 0 },
81449   { 198, 0 },
81450   { 198, 3 },
81451   { 211, 4 },
81452   { 211, 2 },
81453   { 212, 1 },
81454   { 173, 1 },
81455   { 173, 1 },
81456   { 173, 0 },
81457   { 196, 0 },
81458   { 196, 3 },
81459   { 197, 0 },
81460   { 197, 2 },
81461   { 199, 0 },
81462   { 199, 2 },
81463   { 199, 4 },
81464   { 199, 4 },
81465   { 145, 5 },
81466   { 195, 0 },
81467   { 195, 2 },
81468   { 145, 7 },
81469   { 214, 5 },
81470   { 214, 3 },
81471   { 145, 8 },
81472   { 145, 5 },
81473   { 145, 6 },
81474   { 215, 2 },
81475   { 215, 1 },
81476   { 217, 3 },
81477   { 217, 1 },
81478   { 216, 0 },
81479   { 216, 3 },
81480   { 210, 3 },
81481   { 210, 1 },
81482   { 171, 1 },
81483   { 171, 3 },
81484   { 170, 1 },
81485   { 171, 1 },
81486   { 171, 1 },
81487   { 171, 3 },
81488   { 171, 5 },
81489   { 170, 1 },
81490   { 170, 1 },
81491   { 171, 1 },
81492   { 171, 1 },
81493   { 171, 3 },
81494   { 171, 6 },
81495   { 171, 5 },
81496   { 171, 4 },
81497   { 170, 1 },
81498   { 171, 3 },
81499   { 171, 3 },
81500   { 171, 3 },
81501   { 171, 3 },
81502   { 171, 3 },
81503   { 171, 3 },
81504   { 171, 3 },
81505   { 171, 3 },
81506   { 219, 1 },
81507   { 219, 2 },
81508   { 219, 1 },
81509   { 219, 2 },
81510   { 220, 2 },
81511   { 220, 0 },
81512   { 171, 4 },
81513   { 171, 2 },
81514   { 171, 3 },
81515   { 171, 3 },
81516   { 171, 4 },
81517   { 171, 2 },
81518   { 171, 2 },
81519   { 171, 2 },
81520   { 171, 2 },
81521   { 221, 1 },
81522   { 221, 2 },
81523   { 171, 5 },
81524   { 222, 1 },
81525   { 222, 2 },
81526   { 171, 5 },
81527   { 171, 3 },
81528   { 171, 5 },
81529   { 171, 4 },
81530   { 171, 4 },
81531   { 171, 5 },
81532   { 224, 5 },
81533   { 224, 4 },
81534   { 225, 2 },
81535   { 225, 0 },
81536   { 223, 1 },
81537   { 223, 0 },
81538   { 218, 1 },
81539   { 218, 0 },
81540   { 213, 3 },
81541   { 213, 1 },
81542   { 145, 11 },
81543   { 226, 1 },
81544   { 226, 0 },
81545   { 175, 0 },
81546   { 175, 3 },
81547   { 183, 5 },
81548   { 183, 3 },
81549   { 227, 0 },
81550   { 227, 2 },
81551   { 145, 4 },
81552   { 145, 1 },
81553   { 145, 2 },
81554   { 145, 5 },
81555   { 145, 5 },
81556   { 145, 5 },
81557   { 145, 5 },
81558   { 145, 6 },
81559   { 145, 3 },
81560   { 228, 1 },
81561   { 228, 1 },
81562   { 166, 2 },
81563   { 167, 2 },
81564   { 230, 1 },
81565   { 229, 1 },
81566   { 229, 0 },
81567   { 145, 5 },
81568   { 231, 11 },
81569   { 233, 1 },
81570   { 233, 1 },
81571   { 233, 2 },
81572   { 233, 0 },
81573   { 234, 1 },
81574   { 234, 1 },
81575   { 234, 3 },
81576   { 235, 0 },
81577   { 235, 3 },
81578   { 236, 0 },
81579   { 236, 2 },
81580   { 232, 3 },
81581   { 232, 2 },
81582   { 237, 6 },
81583   { 237, 8 },
81584   { 237, 5 },
81585   { 237, 4 },
81586   { 237, 1 },
81587   { 171, 4 },
81588   { 171, 6 },
81589   { 187, 1 },
81590   { 187, 1 },
81591   { 187, 1 },
81592   { 145, 4 },
81593   { 145, 6 },
81594   { 145, 3 },
81595   { 239, 0 },
81596   { 239, 2 },
81597   { 238, 1 },
81598   { 238, 0 },
81599   { 145, 1 },
81600   { 145, 3 },
81601   { 145, 1 },
81602   { 145, 3 },
81603   { 145, 6 },
81604   { 145, 6 },
81605   { 240, 1 },
81606   { 241, 0 },
81607   { 241, 1 },
81608   { 145, 1 },
81609   { 145, 4 },
81610   { 242, 7 },
81611   { 243, 1 },
81612   { 243, 3 },
81613   { 244, 0 },
81614   { 244, 2 },
81615   { 245, 1 },
81616   { 245, 3 },
81617   { 246, 1 },
81618   { 247, 0 },
81619   { 247, 2 },
81620 };
81621
81622 static void yy_accept(yyParser*);  /* Forward Declaration */
81623
81624 /*
81625 ** Perform a reduce action and the shift that must immediately
81626 ** follow the reduce.
81627 */
81628 static void yy_reduce(
81629   yyParser *yypParser,         /* The parser */
81630   int yyruleno                 /* Number of the rule by which to reduce */
81631 ){
81632   int yygoto;                     /* The next state */
81633   int yyact;                      /* The next action */
81634   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
81635   yyStackEntry *yymsp;            /* The top of the parser's stack */
81636   int yysize;                     /* Amount to pop the stack */
81637   sqlite3ParserARG_FETCH;
81638   yymsp = &yypParser->yystack[yypParser->yyidx];
81639 #ifndef NDEBUG
81640   if( yyTraceFILE && yyruleno>=0 
81641         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
81642     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
81643       yyRuleName[yyruleno]);
81644   }
81645 #endif /* NDEBUG */
81646
81647   /* Silence complaints from purify about yygotominor being uninitialized
81648   ** in some cases when it is copied into the stack after the following
81649   ** switch.  yygotominor is uninitialized when a rule reduces that does
81650   ** not set the value of its left-hand side nonterminal.  Leaving the
81651   ** value of the nonterminal uninitialized is utterly harmless as long
81652   ** as the value is never used.  So really the only thing this code
81653   ** accomplishes is to quieten purify.  
81654   **
81655   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
81656   ** without this code, their parser segfaults.  I'm not sure what there
81657   ** parser is doing to make this happen.  This is the second bug report
81658   ** from wireshark this week.  Clearly they are stressing Lemon in ways
81659   ** that it has not been previously stressed...  (SQLite ticket #2172)
81660   */
81661   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
81662   yygotominor = yyzerominor;
81663
81664
81665   switch( yyruleno ){
81666   /* Beginning here are the reduction cases.  A typical example
81667   ** follows:
81668   **   case 0:
81669   **  #line <lineno> <grammarfile>
81670   **     { ... }           // User supplied code
81671   **  #line <lineno> <thisfile>
81672   **     break;
81673   */
81674       case 0: /* input ::= cmdlist */
81675       case 1: /* cmdlist ::= cmdlist ecmd */
81676       case 2: /* cmdlist ::= ecmd */
81677       case 3: /* ecmd ::= SEMI */
81678       case 4: /* ecmd ::= explain cmdx SEMI */
81679       case 10: /* trans_opt ::= */
81680       case 11: /* trans_opt ::= TRANSACTION */
81681       case 12: /* trans_opt ::= TRANSACTION nm */
81682       case 20: /* cmd ::= create_table create_table_args */
81683       case 28: /* columnlist ::= columnlist COMMA column */
81684       case 29: /* columnlist ::= column */
81685       case 37: /* type ::= */
81686       case 44: /* signed ::= plus_num */
81687       case 45: /* signed ::= minus_num */
81688       case 46: /* carglist ::= carglist carg */
81689       case 47: /* carglist ::= */
81690       case 48: /* carg ::= CONSTRAINT nm ccons */
81691       case 49: /* carg ::= ccons */
81692       case 55: /* ccons ::= NULL onconf */
81693       case 82: /* conslist ::= conslist COMMA tcons */
81694       case 83: /* conslist ::= conslist tcons */
81695       case 84: /* conslist ::= tcons */
81696       case 85: /* tcons ::= CONSTRAINT nm */
81697       case 260: /* plus_opt ::= PLUS */
81698       case 261: /* plus_opt ::= */
81699       case 271: /* foreach_clause ::= */
81700       case 272: /* foreach_clause ::= FOR EACH ROW */
81701       case 292: /* database_kw_opt ::= DATABASE */
81702       case 293: /* database_kw_opt ::= */
81703       case 301: /* kwcolumn_opt ::= */
81704       case 302: /* kwcolumn_opt ::= COLUMNKW */
81705       case 306: /* vtabarglist ::= vtabarg */
81706       case 307: /* vtabarglist ::= vtabarglist COMMA vtabarg */
81707       case 309: /* vtabarg ::= vtabarg vtabargtoken */
81708       case 313: /* anylist ::= */
81709 {
81710 }
81711         break;
81712       case 5: /* explain ::= */
81713 { sqlite3BeginParse(pParse, 0); }
81714         break;
81715       case 6: /* explain ::= EXPLAIN */
81716 { sqlite3BeginParse(pParse, 1); }
81717         break;
81718       case 7: /* explain ::= EXPLAIN QUERY PLAN */
81719 { sqlite3BeginParse(pParse, 2); }
81720         break;
81721       case 8: /* cmdx ::= cmd */
81722 { sqlite3FinishCoding(pParse); }
81723         break;
81724       case 9: /* cmd ::= BEGIN transtype trans_opt */
81725 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy316);}
81726         break;
81727       case 13: /* transtype ::= */
81728 {yygotominor.yy316 = TK_DEFERRED;}
81729         break;
81730       case 14: /* transtype ::= DEFERRED */
81731       case 15: /* transtype ::= IMMEDIATE */
81732       case 16: /* transtype ::= EXCLUSIVE */
81733       case 107: /* multiselect_op ::= UNION */
81734       case 109: /* multiselect_op ::= EXCEPT|INTERSECT */
81735 {yygotominor.yy316 = yymsp[0].major;}
81736         break;
81737       case 17: /* cmd ::= COMMIT trans_opt */
81738       case 18: /* cmd ::= END trans_opt */
81739 {sqlite3CommitTransaction(pParse);}
81740         break;
81741       case 19: /* cmd ::= ROLLBACK trans_opt */
81742 {sqlite3RollbackTransaction(pParse);}
81743         break;
81744       case 21: /* create_table ::= CREATE temp TABLE ifnotexists nm dbnm */
81745 {
81746    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy316,0,0,yymsp[-2].minor.yy316);
81747 }
81748         break;
81749       case 22: /* ifnotexists ::= */
81750       case 25: /* temp ::= */
81751       case 63: /* autoinc ::= */
81752       case 77: /* init_deferred_pred_opt ::= */
81753       case 79: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
81754       case 90: /* defer_subclause_opt ::= */
81755       case 101: /* ifexists ::= */
81756       case 112: /* distinct ::= ALL */
81757       case 113: /* distinct ::= */
81758       case 216: /* between_op ::= BETWEEN */
81759       case 219: /* in_op ::= IN */
81760 {yygotominor.yy316 = 0;}
81761         break;
81762       case 23: /* ifnotexists ::= IF NOT EXISTS */
81763       case 24: /* temp ::= TEMP */
81764       case 64: /* autoinc ::= AUTOINCR */
81765       case 78: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
81766       case 100: /* ifexists ::= IF EXISTS */
81767       case 111: /* distinct ::= DISTINCT */
81768       case 217: /* between_op ::= NOT BETWEEN */
81769       case 220: /* in_op ::= NOT IN */
81770 {yygotominor.yy316 = 1;}
81771         break;
81772       case 26: /* create_table_args ::= LP columnlist conslist_opt RP */
81773 {
81774   sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
81775 }
81776         break;
81777       case 27: /* create_table_args ::= AS select */
81778 {
81779   sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy43);
81780   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy43);
81781 }
81782         break;
81783       case 30: /* column ::= columnid type carglist */
81784 {
81785   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
81786   yygotominor.yy0.n = (pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
81787 }
81788         break;
81789       case 31: /* columnid ::= nm */
81790 {
81791   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
81792   yygotominor.yy0 = yymsp[0].minor.yy0;
81793 }
81794         break;
81795       case 32: /* id ::= ID */
81796       case 33: /* ids ::= ID|STRING */
81797       case 34: /* nm ::= ID */
81798       case 35: /* nm ::= STRING */
81799       case 36: /* nm ::= JOIN_KW */
81800       case 39: /* typetoken ::= typename */
81801       case 42: /* typename ::= ids */
81802       case 119: /* as ::= AS nm */
81803       case 120: /* as ::= ids */
81804       case 131: /* dbnm ::= DOT nm */
81805       case 140: /* indexed_opt ::= INDEXED BY nm */
81806       case 245: /* collate ::= COLLATE ids */
81807       case 255: /* nmnum ::= plus_num */
81808       case 256: /* nmnum ::= nm */
81809       case 257: /* plus_num ::= plus_opt number */
81810       case 258: /* minus_num ::= MINUS number */
81811       case 259: /* number ::= INTEGER|FLOAT */
81812 {yygotominor.yy0 = yymsp[0].minor.yy0;}
81813         break;
81814       case 38: /* type ::= typetoken */
81815 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
81816         break;
81817       case 40: /* typetoken ::= typename LP signed RP */
81818 {
81819   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
81820   yygotominor.yy0.n = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z;
81821 }
81822         break;
81823       case 41: /* typetoken ::= typename LP signed COMMA signed RP */
81824 {
81825   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
81826   yygotominor.yy0.n = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z;
81827 }
81828         break;
81829       case 43: /* typename ::= typename ids */
81830 {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);}
81831         break;
81832       case 50: /* ccons ::= DEFAULT term */
81833       case 52: /* ccons ::= DEFAULT PLUS term */
81834 {sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy450);}
81835         break;
81836       case 51: /* ccons ::= DEFAULT LP expr RP */
81837 {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy450);}
81838         break;
81839       case 53: /* ccons ::= DEFAULT MINUS term */
81840 {
81841   Expr *p = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy450, 0, 0);
81842   sqlite3ExprSpan(p,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy450->span);
81843   sqlite3AddDefaultValue(pParse,p);
81844 }
81845         break;
81846       case 54: /* ccons ::= DEFAULT id */
81847 {
81848   Expr *p = sqlite3PExpr(pParse, TK_STRING, 0, 0, &yymsp[0].minor.yy0);
81849   sqlite3AddDefaultValue(pParse,p);
81850 }
81851         break;
81852       case 56: /* ccons ::= NOT NULL onconf */
81853 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy316);}
81854         break;
81855       case 57: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
81856 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy316,yymsp[0].minor.yy316,yymsp[-2].minor.yy316);}
81857         break;
81858       case 58: /* ccons ::= UNIQUE onconf */
81859 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy316,0,0,0,0);}
81860         break;
81861       case 59: /* ccons ::= CHECK LP expr RP */
81862 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy450);}
81863         break;
81864       case 60: /* ccons ::= REFERENCES nm idxlist_opt refargs */
81865 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy242,yymsp[0].minor.yy316);}
81866         break;
81867       case 61: /* ccons ::= defer_subclause */
81868 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy316);}
81869         break;
81870       case 62: /* ccons ::= COLLATE ids */
81871 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
81872         break;
81873       case 65: /* refargs ::= */
81874 { yygotominor.yy316 = OE_Restrict * 0x010101; }
81875         break;
81876       case 66: /* refargs ::= refargs refarg */
81877 { yygotominor.yy316 = (yymsp[-1].minor.yy316 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; }
81878         break;
81879       case 67: /* refarg ::= MATCH nm */
81880 { yygotominor.yy207.value = 0;     yygotominor.yy207.mask = 0x000000; }
81881         break;
81882       case 68: /* refarg ::= ON DELETE refact */
81883 { yygotominor.yy207.value = yymsp[0].minor.yy316;     yygotominor.yy207.mask = 0x0000ff; }
81884         break;
81885       case 69: /* refarg ::= ON UPDATE refact */
81886 { yygotominor.yy207.value = yymsp[0].minor.yy316<<8;  yygotominor.yy207.mask = 0x00ff00; }
81887         break;
81888       case 70: /* refarg ::= ON INSERT refact */
81889 { yygotominor.yy207.value = yymsp[0].minor.yy316<<16; yygotominor.yy207.mask = 0xff0000; }
81890         break;
81891       case 71: /* refact ::= SET NULL */
81892 { yygotominor.yy316 = OE_SetNull; }
81893         break;
81894       case 72: /* refact ::= SET DEFAULT */
81895 { yygotominor.yy316 = OE_SetDflt; }
81896         break;
81897       case 73: /* refact ::= CASCADE */
81898 { yygotominor.yy316 = OE_Cascade; }
81899         break;
81900       case 74: /* refact ::= RESTRICT */
81901 { yygotominor.yy316 = OE_Restrict; }
81902         break;
81903       case 75: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
81904       case 76: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
81905       case 91: /* defer_subclause_opt ::= defer_subclause */
81906       case 93: /* onconf ::= ON CONFLICT resolvetype */
81907       case 95: /* orconf ::= OR resolvetype */
81908       case 96: /* resolvetype ::= raisetype */
81909       case 169: /* insert_cmd ::= INSERT orconf */
81910 {yygotominor.yy316 = yymsp[0].minor.yy316;}
81911         break;
81912       case 80: /* conslist_opt ::= */
81913 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
81914         break;
81915       case 81: /* conslist_opt ::= COMMA conslist */
81916 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
81917         break;
81918       case 86: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
81919 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy242,yymsp[0].minor.yy316,yymsp[-2].minor.yy316,0);}
81920         break;
81921       case 87: /* tcons ::= UNIQUE LP idxlist RP onconf */
81922 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy242,yymsp[0].minor.yy316,0,0,0,0);}
81923         break;
81924       case 88: /* tcons ::= CHECK LP expr RP onconf */
81925 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy450);}
81926         break;
81927       case 89: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
81928 {
81929     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy242, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy242, yymsp[-1].minor.yy316);
81930     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy316);
81931 }
81932         break;
81933       case 92: /* onconf ::= */
81934       case 94: /* orconf ::= */
81935 {yygotominor.yy316 = OE_Default;}
81936         break;
81937       case 97: /* resolvetype ::= IGNORE */
81938 {yygotominor.yy316 = OE_Ignore;}
81939         break;
81940       case 98: /* resolvetype ::= REPLACE */
81941       case 170: /* insert_cmd ::= REPLACE */
81942 {yygotominor.yy316 = OE_Replace;}
81943         break;
81944       case 99: /* cmd ::= DROP TABLE ifexists fullname */
81945 {
81946   sqlite3DropTable(pParse, yymsp[0].minor.yy419, 0, yymsp[-1].minor.yy316);
81947 }
81948         break;
81949       case 102: /* cmd ::= CREATE temp VIEW ifnotexists nm dbnm AS select */
81950 {
81951   sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy43, yymsp[-6].minor.yy316, yymsp[-4].minor.yy316);
81952 }
81953         break;
81954       case 103: /* cmd ::= DROP VIEW ifexists fullname */
81955 {
81956   sqlite3DropTable(pParse, yymsp[0].minor.yy419, 1, yymsp[-1].minor.yy316);
81957 }
81958         break;
81959       case 104: /* cmd ::= select */
81960 {
81961   SelectDest dest = {SRT_Output, 0, 0, 0, 0};
81962   sqlite3Select(pParse, yymsp[0].minor.yy43, &dest);
81963   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy43);
81964 }
81965         break;
81966       case 105: /* select ::= oneselect */
81967       case 128: /* seltablist_paren ::= select */
81968 {yygotominor.yy43 = yymsp[0].minor.yy43;}
81969         break;
81970       case 106: /* select ::= select multiselect_op oneselect */
81971 {
81972   if( yymsp[0].minor.yy43 ){
81973     yymsp[0].minor.yy43->op = yymsp[-1].minor.yy316;
81974     yymsp[0].minor.yy43->pPrior = yymsp[-2].minor.yy43;
81975   }else{
81976     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy43);
81977   }
81978   yygotominor.yy43 = yymsp[0].minor.yy43;
81979 }
81980         break;
81981       case 108: /* multiselect_op ::= UNION ALL */
81982 {yygotominor.yy316 = TK_ALL;}
81983         break;
81984       case 110: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
81985 {
81986   yygotominor.yy43 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy242,yymsp[-5].minor.yy419,yymsp[-4].minor.yy450,yymsp[-3].minor.yy242,yymsp[-2].minor.yy450,yymsp[-1].minor.yy242,yymsp[-7].minor.yy316,yymsp[0].minor.yy84.pLimit,yymsp[0].minor.yy84.pOffset);
81987 }
81988         break;
81989       case 114: /* sclp ::= selcollist COMMA */
81990       case 241: /* idxlist_opt ::= LP idxlist RP */
81991 {yygotominor.yy242 = yymsp[-1].minor.yy242;}
81992         break;
81993       case 115: /* sclp ::= */
81994       case 144: /* orderby_opt ::= */
81995       case 152: /* groupby_opt ::= */
81996       case 234: /* exprlist ::= */
81997       case 240: /* idxlist_opt ::= */
81998 {yygotominor.yy242 = 0;}
81999         break;
82000       case 116: /* selcollist ::= sclp expr as */
82001 {
82002    yygotominor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy242,yymsp[-1].minor.yy450,yymsp[0].minor.yy0.n?&yymsp[0].minor.yy0:0);
82003 }
82004         break;
82005       case 117: /* selcollist ::= sclp STAR */
82006 {
82007   Expr *p = sqlite3PExpr(pParse, TK_ALL, 0, 0, 0);
82008   yygotominor.yy242 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy242, p, 0);
82009 }
82010         break;
82011       case 118: /* selcollist ::= sclp nm DOT STAR */
82012 {
82013   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
82014   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
82015   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
82016   yygotominor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy242, pDot, 0);
82017 }
82018         break;
82019       case 121: /* as ::= */
82020 {yygotominor.yy0.n = 0;}
82021         break;
82022       case 122: /* from ::= */
82023 {yygotominor.yy419 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy419));}
82024         break;
82025       case 123: /* from ::= FROM seltablist */
82026 {
82027   yygotominor.yy419 = yymsp[0].minor.yy419;
82028   sqlite3SrcListShiftJoinType(yygotominor.yy419);
82029 }
82030         break;
82031       case 124: /* stl_prefix ::= seltablist joinop */
82032 {
82033    yygotominor.yy419 = yymsp[-1].minor.yy419;
82034    if( yygotominor.yy419 && yygotominor.yy419->nSrc>0 ) yygotominor.yy419->a[yygotominor.yy419->nSrc-1].jointype = yymsp[0].minor.yy316;
82035 }
82036         break;
82037       case 125: /* stl_prefix ::= */
82038 {yygotominor.yy419 = 0;}
82039         break;
82040       case 126: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
82041 {
82042   yygotominor.yy419 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy419,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy450,yymsp[0].minor.yy352);
82043   sqlite3SrcListIndexedBy(pParse, yygotominor.yy419, &yymsp[-2].minor.yy0);
82044 }
82045         break;
82046       case 127: /* seltablist ::= stl_prefix LP seltablist_paren RP as on_opt using_opt */
82047 {
82048     yygotominor.yy419 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy419,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy43,yymsp[-1].minor.yy450,yymsp[0].minor.yy352);
82049   }
82050         break;
82051       case 129: /* seltablist_paren ::= seltablist */
82052 {
82053      sqlite3SrcListShiftJoinType(yymsp[0].minor.yy419);
82054      yygotominor.yy43 = sqlite3SelectNew(pParse,0,yymsp[0].minor.yy419,0,0,0,0,0,0,0);
82055   }
82056         break;
82057       case 130: /* dbnm ::= */
82058       case 139: /* indexed_opt ::= */
82059 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
82060         break;
82061       case 132: /* fullname ::= nm dbnm */
82062 {yygotominor.yy419 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
82063         break;
82064       case 133: /* joinop ::= COMMA|JOIN */
82065 { yygotominor.yy316 = JT_INNER; }
82066         break;
82067       case 134: /* joinop ::= JOIN_KW JOIN */
82068 { yygotominor.yy316 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
82069         break;
82070       case 135: /* joinop ::= JOIN_KW nm JOIN */
82071 { yygotominor.yy316 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
82072         break;
82073       case 136: /* joinop ::= JOIN_KW nm nm JOIN */
82074 { yygotominor.yy316 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
82075         break;
82076       case 137: /* on_opt ::= ON expr */
82077       case 148: /* sortitem ::= expr */
82078       case 155: /* having_opt ::= HAVING expr */
82079       case 162: /* where_opt ::= WHERE expr */
82080       case 177: /* expr ::= term */
82081       case 205: /* escape ::= ESCAPE expr */
82082       case 229: /* case_else ::= ELSE expr */
82083       case 231: /* case_operand ::= expr */
82084 {yygotominor.yy450 = yymsp[0].minor.yy450;}
82085         break;
82086       case 138: /* on_opt ::= */
82087       case 154: /* having_opt ::= */
82088       case 161: /* where_opt ::= */
82089       case 206: /* escape ::= */
82090       case 230: /* case_else ::= */
82091       case 232: /* case_operand ::= */
82092 {yygotominor.yy450 = 0;}
82093         break;
82094       case 141: /* indexed_opt ::= NOT INDEXED */
82095 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
82096         break;
82097       case 142: /* using_opt ::= USING LP inscollist RP */
82098       case 174: /* inscollist_opt ::= LP inscollist RP */
82099 {yygotominor.yy352 = yymsp[-1].minor.yy352;}
82100         break;
82101       case 143: /* using_opt ::= */
82102       case 173: /* inscollist_opt ::= */
82103 {yygotominor.yy352 = 0;}
82104         break;
82105       case 145: /* orderby_opt ::= ORDER BY sortlist */
82106       case 153: /* groupby_opt ::= GROUP BY nexprlist */
82107       case 233: /* exprlist ::= nexprlist */
82108 {yygotominor.yy242 = yymsp[0].minor.yy242;}
82109         break;
82110       case 146: /* sortlist ::= sortlist COMMA sortitem sortorder */
82111 {
82112   yygotominor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy242,yymsp[-1].minor.yy450,0);
82113   if( yygotominor.yy242 ) yygotominor.yy242->a[yygotominor.yy242->nExpr-1].sortOrder = yymsp[0].minor.yy316;
82114 }
82115         break;
82116       case 147: /* sortlist ::= sortitem sortorder */
82117 {
82118   yygotominor.yy242 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy450,0);
82119   if( yygotominor.yy242 && yygotominor.yy242->a ) yygotominor.yy242->a[0].sortOrder = yymsp[0].minor.yy316;
82120 }
82121         break;
82122       case 149: /* sortorder ::= ASC */
82123       case 151: /* sortorder ::= */
82124 {yygotominor.yy316 = SQLITE_SO_ASC;}
82125         break;
82126       case 150: /* sortorder ::= DESC */
82127 {yygotominor.yy316 = SQLITE_SO_DESC;}
82128         break;
82129       case 156: /* limit_opt ::= */
82130 {yygotominor.yy84.pLimit = 0; yygotominor.yy84.pOffset = 0;}
82131         break;
82132       case 157: /* limit_opt ::= LIMIT expr */
82133 {yygotominor.yy84.pLimit = yymsp[0].minor.yy450; yygotominor.yy84.pOffset = 0;}
82134         break;
82135       case 158: /* limit_opt ::= LIMIT expr OFFSET expr */
82136 {yygotominor.yy84.pLimit = yymsp[-2].minor.yy450; yygotominor.yy84.pOffset = yymsp[0].minor.yy450;}
82137         break;
82138       case 159: /* limit_opt ::= LIMIT expr COMMA expr */
82139 {yygotominor.yy84.pOffset = yymsp[-2].minor.yy450; yygotominor.yy84.pLimit = yymsp[0].minor.yy450;}
82140         break;
82141       case 160: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
82142 {
82143   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy419, &yymsp[-1].minor.yy0);
82144   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy419,yymsp[0].minor.yy450);
82145 }
82146         break;
82147       case 163: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
82148 {
82149   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy419, &yymsp[-3].minor.yy0);
82150   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy242,"set list"); 
82151   sqlite3Update(pParse,yymsp[-4].minor.yy419,yymsp[-1].minor.yy242,yymsp[0].minor.yy450,yymsp[-5].minor.yy316);
82152 }
82153         break;
82154       case 164: /* setlist ::= setlist COMMA nm EQ expr */
82155 {yygotominor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy242,yymsp[0].minor.yy450,&yymsp[-2].minor.yy0);}
82156         break;
82157       case 165: /* setlist ::= nm EQ expr */
82158 {yygotominor.yy242 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy450,&yymsp[-2].minor.yy0);}
82159         break;
82160       case 166: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
82161 {sqlite3Insert(pParse, yymsp[-5].minor.yy419, yymsp[-1].minor.yy242, 0, yymsp[-4].minor.yy352, yymsp[-7].minor.yy316);}
82162         break;
82163       case 167: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
82164 {sqlite3Insert(pParse, yymsp[-2].minor.yy419, 0, yymsp[0].minor.yy43, yymsp[-1].minor.yy352, yymsp[-4].minor.yy316);}
82165         break;
82166       case 168: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
82167 {sqlite3Insert(pParse, yymsp[-3].minor.yy419, 0, 0, yymsp[-2].minor.yy352, yymsp[-5].minor.yy316);}
82168         break;
82169       case 171: /* itemlist ::= itemlist COMMA expr */
82170       case 235: /* nexprlist ::= nexprlist COMMA expr */
82171 {yygotominor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy242,yymsp[0].minor.yy450,0);}
82172         break;
82173       case 172: /* itemlist ::= expr */
82174       case 236: /* nexprlist ::= expr */
82175 {yygotominor.yy242 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy450,0);}
82176         break;
82177       case 175: /* inscollist ::= inscollist COMMA nm */
82178 {yygotominor.yy352 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy352,&yymsp[0].minor.yy0);}
82179         break;
82180       case 176: /* inscollist ::= nm */
82181 {yygotominor.yy352 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
82182         break;
82183       case 178: /* expr ::= LP expr RP */
82184 {yygotominor.yy450 = yymsp[-1].minor.yy450; sqlite3ExprSpan(yygotominor.yy450,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); }
82185         break;
82186       case 179: /* term ::= NULL */
82187       case 184: /* term ::= INTEGER|FLOAT|BLOB */
82188       case 185: /* term ::= STRING */
82189 {yygotominor.yy450 = sqlite3PExpr(pParse, yymsp[0].major, 0, 0, &yymsp[0].minor.yy0);}
82190         break;
82191       case 180: /* expr ::= ID */
82192       case 181: /* expr ::= JOIN_KW */
82193 {yygotominor.yy450 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);}
82194         break;
82195       case 182: /* expr ::= nm DOT nm */
82196 {
82197   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
82198   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
82199   yygotominor.yy450 = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
82200 }
82201         break;
82202       case 183: /* expr ::= nm DOT nm DOT nm */
82203 {
82204   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
82205   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
82206   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
82207   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
82208   yygotominor.yy450 = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
82209 }
82210         break;
82211       case 186: /* expr ::= REGISTER */
82212 {yygotominor.yy450 = sqlite3RegisterExpr(pParse, &yymsp[0].minor.yy0);}
82213         break;
82214       case 187: /* expr ::= VARIABLE */
82215 {
82216   Token *pToken = &yymsp[0].minor.yy0;
82217   Expr *pExpr = yygotominor.yy450 = sqlite3PExpr(pParse, TK_VARIABLE, 0, 0, pToken);
82218   sqlite3ExprAssignVarNumber(pParse, pExpr);
82219 }
82220         break;
82221       case 188: /* expr ::= expr COLLATE ids */
82222 {
82223   yygotominor.yy450 = sqlite3ExprSetColl(pParse, yymsp[-2].minor.yy450, &yymsp[0].minor.yy0);
82224 }
82225         break;
82226       case 189: /* expr ::= CAST LP expr AS typetoken RP */
82227 {
82228   yygotominor.yy450 = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy450, 0, &yymsp[-1].minor.yy0);
82229   sqlite3ExprSpan(yygotominor.yy450,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
82230 }
82231         break;
82232       case 190: /* expr ::= ID LP distinct exprlist RP */
82233 {
82234   if( yymsp[-1].minor.yy242 && yymsp[-1].minor.yy242->nExpr>SQLITE_MAX_FUNCTION_ARG ){
82235     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
82236   }
82237   yygotominor.yy450 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy242, &yymsp[-4].minor.yy0);
82238   sqlite3ExprSpan(yygotominor.yy450,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
82239   if( yymsp[-2].minor.yy316 && yygotominor.yy450 ){
82240     yygotominor.yy450->flags |= EP_Distinct;
82241   }
82242 }
82243         break;
82244       case 191: /* expr ::= ID LP STAR RP */
82245 {
82246   yygotominor.yy450 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
82247   sqlite3ExprSpan(yygotominor.yy450,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
82248 }
82249         break;
82250       case 192: /* term ::= CTIME_KW */
82251 {
82252   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
82253   ** treated as functions that return constants */
82254   yygotominor.yy450 = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
82255   if( yygotominor.yy450 ){
82256     yygotominor.yy450->op = TK_CONST_FUNC;  
82257     yygotominor.yy450->span = yymsp[0].minor.yy0;
82258   }
82259 }
82260         break;
82261       case 193: /* expr ::= expr AND expr */
82262       case 194: /* expr ::= expr OR expr */
82263       case 195: /* expr ::= expr LT|GT|GE|LE expr */
82264       case 196: /* expr ::= expr EQ|NE expr */
82265       case 197: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
82266       case 198: /* expr ::= expr PLUS|MINUS expr */
82267       case 199: /* expr ::= expr STAR|SLASH|REM expr */
82268       case 200: /* expr ::= expr CONCAT expr */
82269 {yygotominor.yy450 = sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy450,yymsp[0].minor.yy450,0);}
82270         break;
82271       case 201: /* likeop ::= LIKE_KW */
82272       case 203: /* likeop ::= MATCH */
82273 {yygotominor.yy86.eOperator = yymsp[0].minor.yy0; yygotominor.yy86.not = 0;}
82274         break;
82275       case 202: /* likeop ::= NOT LIKE_KW */
82276       case 204: /* likeop ::= NOT MATCH */
82277 {yygotominor.yy86.eOperator = yymsp[0].minor.yy0; yygotominor.yy86.not = 1;}
82278         break;
82279       case 207: /* expr ::= expr likeop expr escape */
82280 {
82281   ExprList *pList;
82282   pList = sqlite3ExprListAppend(pParse,0, yymsp[-1].minor.yy450, 0);
82283   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-3].minor.yy450, 0);
82284   if( yymsp[0].minor.yy450 ){
82285     pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy450, 0);
82286   }
82287   yygotominor.yy450 = sqlite3ExprFunction(pParse, pList, &yymsp[-2].minor.yy86.eOperator);
82288   if( yymsp[-2].minor.yy86.not ) yygotominor.yy450 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy450, 0, 0);
82289   sqlite3ExprSpan(yygotominor.yy450, &yymsp[-3].minor.yy450->span, &yymsp[-1].minor.yy450->span);
82290   if( yygotominor.yy450 ) yygotominor.yy450->flags |= EP_InfixFunc;
82291 }
82292         break;
82293       case 208: /* expr ::= expr ISNULL|NOTNULL */
82294 {
82295   yygotominor.yy450 = sqlite3PExpr(pParse, yymsp[0].major, yymsp[-1].minor.yy450, 0, 0);
82296   sqlite3ExprSpan(yygotominor.yy450,&yymsp[-1].minor.yy450->span,&yymsp[0].minor.yy0);
82297 }
82298         break;
82299       case 209: /* expr ::= expr IS NULL */
82300 {
82301   yygotominor.yy450 = sqlite3PExpr(pParse, TK_ISNULL, yymsp[-2].minor.yy450, 0, 0);
82302   sqlite3ExprSpan(yygotominor.yy450,&yymsp[-2].minor.yy450->span,&yymsp[0].minor.yy0);
82303 }
82304         break;
82305       case 210: /* expr ::= expr NOT NULL */
82306 {
82307   yygotominor.yy450 = sqlite3PExpr(pParse, TK_NOTNULL, yymsp[-2].minor.yy450, 0, 0);
82308   sqlite3ExprSpan(yygotominor.yy450,&yymsp[-2].minor.yy450->span,&yymsp[0].minor.yy0);
82309 }
82310         break;
82311       case 211: /* expr ::= expr IS NOT NULL */
82312 {
82313   yygotominor.yy450 = sqlite3PExpr(pParse, TK_NOTNULL, yymsp[-3].minor.yy450, 0, 0);
82314   sqlite3ExprSpan(yygotominor.yy450,&yymsp[-3].minor.yy450->span,&yymsp[0].minor.yy0);
82315 }
82316         break;
82317       case 212: /* expr ::= NOT expr */
82318       case 213: /* expr ::= BITNOT expr */
82319 {
82320   yygotominor.yy450 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy450, 0, 0);
82321   sqlite3ExprSpan(yygotominor.yy450,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy450->span);
82322 }
82323         break;
82324       case 214: /* expr ::= MINUS expr */
82325 {
82326   yygotominor.yy450 = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy450, 0, 0);
82327   sqlite3ExprSpan(yygotominor.yy450,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy450->span);
82328 }
82329         break;
82330       case 215: /* expr ::= PLUS expr */
82331 {
82332   yygotominor.yy450 = sqlite3PExpr(pParse, TK_UPLUS, yymsp[0].minor.yy450, 0, 0);
82333   sqlite3ExprSpan(yygotominor.yy450,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy450->span);
82334 }
82335         break;
82336       case 218: /* expr ::= expr between_op expr AND expr */
82337 {
82338   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy450, 0);
82339   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy450, 0);
82340   yygotominor.yy450 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy450, 0, 0);
82341   if( yygotominor.yy450 ){
82342     yygotominor.yy450->pList = pList;
82343   }else{
82344     sqlite3ExprListDelete(pParse->db, pList);
82345   } 
82346   if( yymsp[-3].minor.yy316 ) yygotominor.yy450 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy450, 0, 0);
82347   sqlite3ExprSpan(yygotominor.yy450,&yymsp[-4].minor.yy450->span,&yymsp[0].minor.yy450->span);
82348 }
82349         break;
82350       case 221: /* expr ::= expr in_op LP exprlist RP */
82351 {
82352     yygotominor.yy450 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy450, 0, 0);
82353     if( yygotominor.yy450 ){
82354       yygotominor.yy450->pList = yymsp[-1].minor.yy242;
82355       sqlite3ExprSetHeight(pParse, yygotominor.yy450);
82356     }else{
82357       sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy242);
82358     }
82359     if( yymsp[-3].minor.yy316 ) yygotominor.yy450 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy450, 0, 0);
82360     sqlite3ExprSpan(yygotominor.yy450,&yymsp[-4].minor.yy450->span,&yymsp[0].minor.yy0);
82361   }
82362         break;
82363       case 222: /* expr ::= LP select RP */
82364 {
82365     yygotominor.yy450 = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
82366     if( yygotominor.yy450 ){
82367       yygotominor.yy450->pSelect = yymsp[-1].minor.yy43;
82368       sqlite3ExprSetHeight(pParse, yygotominor.yy450);
82369     }else{
82370       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy43);
82371     }
82372     sqlite3ExprSpan(yygotominor.yy450,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
82373   }
82374         break;
82375       case 223: /* expr ::= expr in_op LP select RP */
82376 {
82377     yygotominor.yy450 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy450, 0, 0);
82378     if( yygotominor.yy450 ){
82379       yygotominor.yy450->pSelect = yymsp[-1].minor.yy43;
82380       sqlite3ExprSetHeight(pParse, yygotominor.yy450);
82381     }else{
82382       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy43);
82383     }
82384     if( yymsp[-3].minor.yy316 ) yygotominor.yy450 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy450, 0, 0);
82385     sqlite3ExprSpan(yygotominor.yy450,&yymsp[-4].minor.yy450->span,&yymsp[0].minor.yy0);
82386   }
82387         break;
82388       case 224: /* expr ::= expr in_op nm dbnm */
82389 {
82390     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
82391     yygotominor.yy450 = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy450, 0, 0);
82392     if( yygotominor.yy450 ){
82393       yygotominor.yy450->pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
82394       sqlite3ExprSetHeight(pParse, yygotominor.yy450);
82395     }else{
82396       sqlite3SrcListDelete(pParse->db, pSrc);
82397     }
82398     if( yymsp[-2].minor.yy316 ) yygotominor.yy450 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy450, 0, 0);
82399     sqlite3ExprSpan(yygotominor.yy450,&yymsp[-3].minor.yy450->span,yymsp[0].minor.yy0.z?&yymsp[0].minor.yy0:&yymsp[-1].minor.yy0);
82400   }
82401         break;
82402       case 225: /* expr ::= EXISTS LP select RP */
82403 {
82404     Expr *p = yygotominor.yy450 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
82405     if( p ){
82406       p->pSelect = yymsp[-1].minor.yy43;
82407       sqlite3ExprSpan(p,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
82408       sqlite3ExprSetHeight(pParse, yygotominor.yy450);
82409     }else{
82410       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy43);
82411     }
82412   }
82413         break;
82414       case 226: /* expr ::= CASE case_operand case_exprlist case_else END */
82415 {
82416   yygotominor.yy450 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy450, yymsp[-1].minor.yy450, 0);
82417   if( yygotominor.yy450 ){
82418     yygotominor.yy450->pList = yymsp[-2].minor.yy242;
82419     sqlite3ExprSetHeight(pParse, yygotominor.yy450);
82420   }else{
82421     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy242);
82422   }
82423   sqlite3ExprSpan(yygotominor.yy450, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0);
82424 }
82425         break;
82426       case 227: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
82427 {
82428   yygotominor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy242, yymsp[-2].minor.yy450, 0);
82429   yygotominor.yy242 = sqlite3ExprListAppend(pParse,yygotominor.yy242, yymsp[0].minor.yy450, 0);
82430 }
82431         break;
82432       case 228: /* case_exprlist ::= WHEN expr THEN expr */
82433 {
82434   yygotominor.yy242 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy450, 0);
82435   yygotominor.yy242 = sqlite3ExprListAppend(pParse,yygotominor.yy242, yymsp[0].minor.yy450, 0);
82436 }
82437         break;
82438       case 237: /* cmd ::= CREATE uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
82439 {
82440   sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0, 
82441                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy242, yymsp[-9].minor.yy316,
82442                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy316);
82443 }
82444         break;
82445       case 238: /* uniqueflag ::= UNIQUE */
82446       case 285: /* raisetype ::= ABORT */
82447 {yygotominor.yy316 = OE_Abort;}
82448         break;
82449       case 239: /* uniqueflag ::= */
82450 {yygotominor.yy316 = OE_None;}
82451         break;
82452       case 242: /* idxlist ::= idxlist COMMA nm collate sortorder */
82453 {
82454   Expr *p = 0;
82455   if( yymsp[-1].minor.yy0.n>0 ){
82456     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
82457     sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
82458   }
82459   yygotominor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy242, p, &yymsp[-2].minor.yy0);
82460   sqlite3ExprListCheckLength(pParse, yygotominor.yy242, "index");
82461   if( yygotominor.yy242 ) yygotominor.yy242->a[yygotominor.yy242->nExpr-1].sortOrder = yymsp[0].minor.yy316;
82462 }
82463         break;
82464       case 243: /* idxlist ::= nm collate sortorder */
82465 {
82466   Expr *p = 0;
82467   if( yymsp[-1].minor.yy0.n>0 ){
82468     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
82469     sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
82470   }
82471   yygotominor.yy242 = sqlite3ExprListAppend(pParse,0, p, &yymsp[-2].minor.yy0);
82472   sqlite3ExprListCheckLength(pParse, yygotominor.yy242, "index");
82473   if( yygotominor.yy242 ) yygotominor.yy242->a[yygotominor.yy242->nExpr-1].sortOrder = yymsp[0].minor.yy316;
82474 }
82475         break;
82476       case 244: /* collate ::= */
82477 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
82478         break;
82479       case 246: /* cmd ::= DROP INDEX ifexists fullname */
82480 {sqlite3DropIndex(pParse, yymsp[0].minor.yy419, yymsp[-1].minor.yy316);}
82481         break;
82482       case 247: /* cmd ::= VACUUM */
82483       case 248: /* cmd ::= VACUUM nm */
82484 {sqlite3Vacuum(pParse);}
82485         break;
82486       case 249: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
82487       case 250: /* cmd ::= PRAGMA nm dbnm EQ ON */
82488       case 251: /* cmd ::= PRAGMA nm dbnm EQ DELETE */
82489 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
82490         break;
82491       case 252: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
82492 {
82493   sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);
82494 }
82495         break;
82496       case 253: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
82497 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
82498         break;
82499       case 254: /* cmd ::= PRAGMA nm dbnm */
82500 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
82501         break;
82502       case 262: /* cmd ::= CREATE trigger_decl BEGIN trigger_cmd_list END */
82503 {
82504   Token all;
82505   all.z = yymsp[-3].minor.yy0.z;
82506   all.n = (yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
82507   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy75, &all);
82508 }
82509         break;
82510       case 263: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
82511 {
82512   sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy316, yymsp[-4].minor.yy354.a, yymsp[-4].minor.yy354.b, yymsp[-2].minor.yy419, yymsp[0].minor.yy450, yymsp[-10].minor.yy316, yymsp[-8].minor.yy316);
82513   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
82514 }
82515         break;
82516       case 264: /* trigger_time ::= BEFORE */
82517       case 267: /* trigger_time ::= */
82518 { yygotominor.yy316 = TK_BEFORE; }
82519         break;
82520       case 265: /* trigger_time ::= AFTER */
82521 { yygotominor.yy316 = TK_AFTER;  }
82522         break;
82523       case 266: /* trigger_time ::= INSTEAD OF */
82524 { yygotominor.yy316 = TK_INSTEAD;}
82525         break;
82526       case 268: /* trigger_event ::= DELETE|INSERT */
82527       case 269: /* trigger_event ::= UPDATE */
82528 {yygotominor.yy354.a = yymsp[0].major; yygotominor.yy354.b = 0;}
82529         break;
82530       case 270: /* trigger_event ::= UPDATE OF inscollist */
82531 {yygotominor.yy354.a = TK_UPDATE; yygotominor.yy354.b = yymsp[0].minor.yy352;}
82532         break;
82533       case 273: /* when_clause ::= */
82534       case 290: /* key_opt ::= */
82535 { yygotominor.yy450 = 0; }
82536         break;
82537       case 274: /* when_clause ::= WHEN expr */
82538       case 291: /* key_opt ::= KEY expr */
82539 { yygotominor.yy450 = yymsp[0].minor.yy450; }
82540         break;
82541       case 275: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
82542 {
82543 /*
82544   if( yymsp[-2].minor.yy75 ){
82545     yymsp[-2].minor.yy75->pLast->pNext = yymsp[-1].minor.yy75;
82546   }else{
82547     yymsp[-2].minor.yy75 = yymsp[-1].minor.yy75;
82548   }
82549 */
82550   assert( yymsp[-2].minor.yy75!=0 );
82551   yymsp[-2].minor.yy75->pLast->pNext = yymsp[-1].minor.yy75;
82552   yymsp[-2].minor.yy75->pLast = yymsp[-1].minor.yy75;
82553   yygotominor.yy75 = yymsp[-2].minor.yy75;
82554 }
82555         break;
82556       case 276: /* trigger_cmd_list ::= trigger_cmd SEMI */
82557
82558   /* if( yymsp[-1].minor.yy75 ) */
82559   assert( yymsp[-1].minor.yy75!=0 );
82560   yymsp[-1].minor.yy75->pLast = yymsp[-1].minor.yy75;
82561   yygotominor.yy75 = yymsp[-1].minor.yy75;
82562 }
82563         break;
82564       case 277: /* trigger_cmd ::= UPDATE orconf nm SET setlist where_opt */
82565 { yygotominor.yy75 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy242, yymsp[0].minor.yy450, yymsp[-4].minor.yy316); }
82566         break;
82567       case 278: /* trigger_cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP */
82568 {yygotominor.yy75 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy352, yymsp[-1].minor.yy242, 0, yymsp[-7].minor.yy316);}
82569         break;
82570       case 279: /* trigger_cmd ::= insert_cmd INTO nm inscollist_opt select */
82571 {yygotominor.yy75 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy352, 0, yymsp[0].minor.yy43, yymsp[-4].minor.yy316);}
82572         break;
82573       case 280: /* trigger_cmd ::= DELETE FROM nm where_opt */
82574 {yygotominor.yy75 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-1].minor.yy0, yymsp[0].minor.yy450);}
82575         break;
82576       case 281: /* trigger_cmd ::= select */
82577 {yygotominor.yy75 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy43); }
82578         break;
82579       case 282: /* expr ::= RAISE LP IGNORE RP */
82580 {
82581   yygotominor.yy450 = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); 
82582   if( yygotominor.yy450 ){
82583     yygotominor.yy450->iColumn = OE_Ignore;
82584     sqlite3ExprSpan(yygotominor.yy450, &yymsp[-3].minor.yy0, &yymsp[0].minor.yy0);
82585   }
82586 }
82587         break;
82588       case 283: /* expr ::= RAISE LP raisetype COMMA nm RP */
82589 {
82590   yygotominor.yy450 = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); 
82591   if( yygotominor.yy450 ) {
82592     yygotominor.yy450->iColumn = yymsp[-3].minor.yy316;
82593     sqlite3ExprSpan(yygotominor.yy450, &yymsp[-5].minor.yy0, &yymsp[0].minor.yy0);
82594   }
82595 }
82596         break;
82597       case 284: /* raisetype ::= ROLLBACK */
82598 {yygotominor.yy316 = OE_Rollback;}
82599         break;
82600       case 286: /* raisetype ::= FAIL */
82601 {yygotominor.yy316 = OE_Fail;}
82602         break;
82603       case 287: /* cmd ::= DROP TRIGGER ifexists fullname */
82604 {
82605   sqlite3DropTrigger(pParse,yymsp[0].minor.yy419,yymsp[-1].minor.yy316);
82606 }
82607         break;
82608       case 288: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
82609 {
82610   sqlite3Attach(pParse, yymsp[-3].minor.yy450, yymsp[-1].minor.yy450, yymsp[0].minor.yy450);
82611 }
82612         break;
82613       case 289: /* cmd ::= DETACH database_kw_opt expr */
82614 {
82615   sqlite3Detach(pParse, yymsp[0].minor.yy450);
82616 }
82617         break;
82618       case 294: /* cmd ::= REINDEX */
82619 {sqlite3Reindex(pParse, 0, 0);}
82620         break;
82621       case 295: /* cmd ::= REINDEX nm dbnm */
82622 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
82623         break;
82624       case 296: /* cmd ::= ANALYZE */
82625 {sqlite3Analyze(pParse, 0, 0);}
82626         break;
82627       case 297: /* cmd ::= ANALYZE nm dbnm */
82628 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
82629         break;
82630       case 298: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
82631 {
82632   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy419,&yymsp[0].minor.yy0);
82633 }
82634         break;
82635       case 299: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
82636 {
82637   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
82638 }
82639         break;
82640       case 300: /* add_column_fullname ::= fullname */
82641 {
82642   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy419);
82643 }
82644         break;
82645       case 303: /* cmd ::= create_vtab */
82646 {sqlite3VtabFinishParse(pParse,0);}
82647         break;
82648       case 304: /* cmd ::= create_vtab LP vtabarglist RP */
82649 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
82650         break;
82651       case 305: /* create_vtab ::= CREATE VIRTUAL TABLE nm dbnm USING nm */
82652 {
82653     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
82654 }
82655         break;
82656       case 308: /* vtabarg ::= */
82657 {sqlite3VtabArgInit(pParse);}
82658         break;
82659       case 310: /* vtabargtoken ::= ANY */
82660       case 311: /* vtabargtoken ::= lp anylist RP */
82661       case 312: /* lp ::= LP */
82662       case 314: /* anylist ::= anylist ANY */
82663 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
82664         break;
82665   };
82666   yygoto = yyRuleInfo[yyruleno].lhs;
82667   yysize = yyRuleInfo[yyruleno].nrhs;
82668   yypParser->yyidx -= yysize;
82669   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,yygoto);
82670   if( yyact < YYNSTATE ){
82671 #ifdef NDEBUG
82672     /* If we are not debugging and the reduce action popped at least
82673     ** one element off the stack, then we can push the new element back
82674     ** onto the stack here, and skip the stack overflow test in yy_shift().
82675     ** That gives a significant speed improvement. */
82676     if( yysize ){
82677       yypParser->yyidx++;
82678       yymsp -= yysize-1;
82679       yymsp->stateno = yyact;
82680       yymsp->major = yygoto;
82681       yymsp->minor = yygotominor;
82682     }else
82683 #endif
82684     {
82685       yy_shift(yypParser,yyact,yygoto,&yygotominor);
82686     }
82687   }else{
82688     assert( yyact == YYNSTATE + YYNRULE + 1 );
82689     yy_accept(yypParser);
82690   }
82691 }
82692
82693 /*
82694 ** The following code executes when the parse fails
82695 */
82696 static void yy_parse_failed(
82697   yyParser *yypParser           /* The parser */
82698 ){
82699   sqlite3ParserARG_FETCH;
82700 #ifndef NDEBUG
82701   if( yyTraceFILE ){
82702     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
82703   }
82704 #endif
82705   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
82706   /* Here code is inserted which will be executed whenever the
82707   ** parser fails */
82708   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
82709 }
82710
82711 /*
82712 ** The following code executes when a syntax error first occurs.
82713 */
82714 static void yy_syntax_error(
82715   yyParser *yypParser,           /* The parser */
82716   int yymajor,                   /* The major type of the error token */
82717   YYMINORTYPE yyminor            /* The minor type of the error token */
82718 ){
82719   sqlite3ParserARG_FETCH;
82720 #define TOKEN (yyminor.yy0)
82721
82722   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
82723   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
82724   pParse->parseError = 1;
82725   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
82726 }
82727
82728 /*
82729 ** The following is executed when the parser accepts
82730 */
82731 static void yy_accept(
82732   yyParser *yypParser           /* The parser */
82733 ){
82734   sqlite3ParserARG_FETCH;
82735 #ifndef NDEBUG
82736   if( yyTraceFILE ){
82737     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
82738   }
82739 #endif
82740   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
82741   /* Here code is inserted which will be executed whenever the
82742   ** parser accepts */
82743   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
82744 }
82745
82746 /* The main parser program.
82747 ** The first argument is a pointer to a structure obtained from
82748 ** "sqlite3ParserAlloc" which describes the current state of the parser.
82749 ** The second argument is the major token number.  The third is
82750 ** the minor token.  The fourth optional argument is whatever the
82751 ** user wants (and specified in the grammar) and is available for
82752 ** use by the action routines.
82753 **
82754 ** Inputs:
82755 ** <ul>
82756 ** <li> A pointer to the parser (an opaque structure.)
82757 ** <li> The major token number.
82758 ** <li> The minor token number.
82759 ** <li> An option argument of a grammar-specified type.
82760 ** </ul>
82761 **
82762 ** Outputs:
82763 ** None.
82764 */
82765 SQLITE_PRIVATE void sqlite3Parser(
82766   void *yyp,                   /* The parser */
82767   int yymajor,                 /* The major token code number */
82768   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
82769   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
82770 ){
82771   YYMINORTYPE yyminorunion;
82772   int yyact;            /* The parser action. */
82773   int yyendofinput;     /* True if we are at the end of input */
82774 #ifdef YYERRORSYMBOL
82775   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
82776 #endif
82777   yyParser *yypParser;  /* The parser */
82778
82779   /* (re)initialize the parser, if necessary */
82780   yypParser = (yyParser*)yyp;
82781   if( yypParser->yyidx<0 ){
82782 #if YYSTACKDEPTH<=0
82783     if( yypParser->yystksz <=0 ){
82784       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
82785       yyminorunion = yyzerominor;
82786       yyStackOverflow(yypParser, &yyminorunion);
82787       return;
82788     }
82789 #endif
82790     yypParser->yyidx = 0;
82791     yypParser->yyerrcnt = -1;
82792     yypParser->yystack[0].stateno = 0;
82793     yypParser->yystack[0].major = 0;
82794   }
82795   yyminorunion.yy0 = yyminor;
82796   yyendofinput = (yymajor==0);
82797   sqlite3ParserARG_STORE;
82798
82799 #ifndef NDEBUG
82800   if( yyTraceFILE ){
82801     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
82802   }
82803 #endif
82804
82805   do{
82806     yyact = yy_find_shift_action(yypParser,yymajor);
82807     if( yyact<YYNSTATE ){
82808       assert( !yyendofinput );  /* Impossible to shift the $ token */
82809       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
82810       yypParser->yyerrcnt--;
82811       yymajor = YYNOCODE;
82812     }else if( yyact < YYNSTATE + YYNRULE ){
82813       yy_reduce(yypParser,yyact-YYNSTATE);
82814     }else{
82815       assert( yyact == YY_ERROR_ACTION );
82816 #ifdef YYERRORSYMBOL
82817       int yymx;
82818 #endif
82819 #ifndef NDEBUG
82820       if( yyTraceFILE ){
82821         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
82822       }
82823 #endif
82824 #ifdef YYERRORSYMBOL
82825       /* A syntax error has occurred.
82826       ** The response to an error depends upon whether or not the
82827       ** grammar defines an error token "ERROR".  
82828       **
82829       ** This is what we do if the grammar does define ERROR:
82830       **
82831       **  * Call the %syntax_error function.
82832       **
82833       **  * Begin popping the stack until we enter a state where
82834       **    it is legal to shift the error symbol, then shift
82835       **    the error symbol.
82836       **
82837       **  * Set the error count to three.
82838       **
82839       **  * Begin accepting and shifting new tokens.  No new error
82840       **    processing will occur until three tokens have been
82841       **    shifted successfully.
82842       **
82843       */
82844       if( yypParser->yyerrcnt<0 ){
82845         yy_syntax_error(yypParser,yymajor,yyminorunion);
82846       }
82847       yymx = yypParser->yystack[yypParser->yyidx].major;
82848       if( yymx==YYERRORSYMBOL || yyerrorhit ){
82849 #ifndef NDEBUG
82850         if( yyTraceFILE ){
82851           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
82852              yyTracePrompt,yyTokenName[yymajor]);
82853         }
82854 #endif
82855         yy_destructor(yypParser, yymajor,&yyminorunion);
82856         yymajor = YYNOCODE;
82857       }else{
82858          while(
82859           yypParser->yyidx >= 0 &&
82860           yymx != YYERRORSYMBOL &&
82861           (yyact = yy_find_reduce_action(
82862                         yypParser->yystack[yypParser->yyidx].stateno,
82863                         YYERRORSYMBOL)) >= YYNSTATE
82864         ){
82865           yy_pop_parser_stack(yypParser);
82866         }
82867         if( yypParser->yyidx < 0 || yymajor==0 ){
82868           yy_destructor(yypParser,yymajor,&yyminorunion);
82869           yy_parse_failed(yypParser);
82870           yymajor = YYNOCODE;
82871         }else if( yymx!=YYERRORSYMBOL ){
82872           YYMINORTYPE u2;
82873           u2.YYERRSYMDT = 0;
82874           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
82875         }
82876       }
82877       yypParser->yyerrcnt = 3;
82878       yyerrorhit = 1;
82879 #else  /* YYERRORSYMBOL is not defined */
82880       /* This is what we do if the grammar does not define ERROR:
82881       **
82882       **  * Report an error message, and throw away the input token.
82883       **
82884       **  * If the input token is $, then fail the parse.
82885       **
82886       ** As before, subsequent error messages are suppressed until
82887       ** three input tokens have been successfully shifted.
82888       */
82889       if( yypParser->yyerrcnt<=0 ){
82890         yy_syntax_error(yypParser,yymajor,yyminorunion);
82891       }
82892       yypParser->yyerrcnt = 3;
82893       yy_destructor(yypParser,yymajor,&yyminorunion);
82894       if( yyendofinput ){
82895         yy_parse_failed(yypParser);
82896       }
82897       yymajor = YYNOCODE;
82898 #endif
82899     }
82900   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
82901   return;
82902 }
82903
82904 /************** End of parse.c ***********************************************/
82905 /************** Begin file tokenize.c ****************************************/
82906 /*
82907 ** 2001 September 15
82908 **
82909 ** The author disclaims copyright to this source code.  In place of
82910 ** a legal notice, here is a blessing:
82911 **
82912 **    May you do good and not evil.
82913 **    May you find forgiveness for yourself and forgive others.
82914 **    May you share freely, never taking more than you give.
82915 **
82916 *************************************************************************
82917 ** An tokenizer for SQL
82918 **
82919 ** This file contains C code that splits an SQL input string up into
82920 ** individual tokens and sends those tokens one-by-one over to the
82921 ** parser for analysis.
82922 **
82923 ** $Id: tokenize.c,v 1.152 2008/09/01 15:52:11 drh Exp $
82924 */
82925
82926 /*
82927 ** The charMap() macro maps alphabetic characters into their
82928 ** lower-case ASCII equivalent.  On ASCII machines, this is just
82929 ** an upper-to-lower case map.  On EBCDIC machines we also need
82930 ** to adjust the encoding.  Only alphabetic characters and underscores
82931 ** need to be translated.
82932 */
82933 #ifdef SQLITE_ASCII
82934 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
82935 #endif
82936 #ifdef SQLITE_EBCDIC
82937 # define charMap(X) ebcdicToAscii[(unsigned char)X]
82938 const unsigned char ebcdicToAscii[] = {
82939 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
82940    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
82941    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
82942    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
82943    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
82944    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
82945    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
82946    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
82947    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
82948    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
82949    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
82950    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
82951    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
82952    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
82953    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
82954    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
82955    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
82956 };
82957 #endif
82958
82959 /*
82960 ** The sqlite3KeywordCode function looks up an identifier to determine if
82961 ** it is a keyword.  If it is a keyword, the token code of that keyword is 
82962 ** returned.  If the input is not a keyword, TK_ID is returned.
82963 **
82964 ** The implementation of this routine was generated by a program,
82965 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
82966 ** The output of the mkkeywordhash.c program is written into a file
82967 ** named keywordhash.h and then included into this source file by
82968 ** the #include below.
82969 */
82970 /************** Include keywordhash.h in the middle of tokenize.c ************/
82971 /************** Begin file keywordhash.h *************************************/
82972 /***** This file contains automatically generated code ******
82973 **
82974 ** The code in this file has been automatically generated by
82975 **
82976 **     $Header: /sqlite/sqlite/tool/mkkeywordhash.c,v 1.32 2008/10/06 05:32:19 danielk1977 Exp $
82977 **
82978 ** The code in this file implements a function that determines whether
82979 ** or not a given identifier is really an SQL keyword.  The same thing
82980 ** might be implemented more directly using a hand-written hash table.
82981 ** But by using this automatically generated code, the size of the code
82982 ** is substantially reduced.  This is important for embedded applications
82983 ** on platforms with limited memory.
82984 */
82985 /* Hash score: 167 */
82986 static int keywordCode(const char *z, int n){
82987   /* zText[] encodes 783 bytes of keywords in 528 bytes */
82988   static const char zText[528] =
82989     "REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECTABLE"
82990     "FTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVEXISTSCONSTRAINT"
82991     "ERSECTRIGGEREFERENCESUNIQUERYATTACHAVINGROUPDATEMPORARYBEGINNER"
82992     "ENAMEBETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATE"
82993     "DETACHIMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMIT"
82994     "WHENWHEREPLACEAFTERESTRICTANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT"
82995     "CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROM"
82996     "FULLGLOBYIFINTOFFSETISNULLORDERIGHTOUTEROLLBACKROWUNIONUSINGVACUUM"
82997     "VIEWINITIALLY";
82998   static const unsigned char aHash[127] = {
82999       65,  94, 110,  63,   0,  44,   0,   0,  71,   0,  66,   0,   0,
83000      104,  12,  67,  15,   0, 108,  74, 105, 101,   0,  19,   0,   0,
83001      114,   0, 112,  78,   0,  22,  82,   0,   9,   0,   0,  59,  60,
83002        0,  58,   6,   0,  39,  79,  91,   0, 111,  90,   0,   0,  45,
83003        0,  92,  24,   0,  17,   0, 115,  40,  23,   0,   5,  99,  25,
83004       85,   0,   0, 117,  95,  50, 116,  47,   7,  42,   0,  80,   0,
83005       89,  26,   0,  88,   0,   0,   0,  84,  81,  86,  77,  98,  14,
83006       34,  97,   0,  70,   0,  18,  76, 100,  31,   0, 113,  69, 106,
83007       52,  46,  73,   0,   0,  83, 102,   0, 109,   0,  35,   0,   0,
83008       28,   0,  75,  48,  53,   0,  20,  51,   0,  43,
83009   };
83010   static const unsigned char aNext[117] = {
83011        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
83012        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
83013        0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
83014        0,   0,   3,  38,   0,  32,  21,   0,   0,   0,   0,  29,   0,
83015        0,  37,   0,   0,   0,   1,  55,   0,   0,  56,   0,   0,   0,
83016        0,   0,   0,   0,   0,   0,  54,   0,   0,   0,   0,  30,   0,
83017       16,  33,  10,   0,   0,   0,   0,   0,   0,   0,  11,  61,  68,
83018        0,   8,   0,  93,  87,   0,  96,   0,  49,   0,   0,  64,   0,
83019       41, 103,   0,  27, 107,  36,  62,  72,   0,   0,  57,   0,   0,
83020   };
83021   static const unsigned char aLen[117] = {
83022        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
83023        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
83024       11,   2,   7,   5,   5,   9,   6,  10,   9,   7,  10,   6,   5,
83025        6,   6,   5,   6,   4,   9,   2,   5,   5,   6,   7,   7,   3,
83026        4,   4,   7,   3,   6,   4,   7,   6,  12,   6,   9,   4,   6,
83027        5,   4,   7,   6,   5,   6,   7,   5,   4,   5,   7,   5,   8,
83028        3,   7,  13,   2,   2,   4,   6,   6,   8,   5,  17,  12,   7,
83029        8,   8,   2,   4,   4,   4,   4,   4,   2,   2,   4,   6,   2,
83030        3,   6,   5,   5,   5,   8,   3,   5,   5,   6,   4,   9,   3,
83031   };
83032   static const unsigned short int aOffset[117] = {
83033        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
83034       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
83035       86,  95,  96, 101, 105, 109, 117, 123, 130, 138, 144, 154, 157,
83036      162, 167, 172, 175, 179, 179, 183, 188, 191, 195, 201, 207, 207,
83037      210, 213, 217, 218, 222, 228, 232, 239, 245, 257, 263, 272, 274,
83038      280, 285, 287, 294, 299, 304, 310, 316, 321, 325, 328, 335, 339,
83039      347, 349, 356, 358, 360, 369, 373, 379, 385, 393, 398, 398, 414,
83040      421, 428, 429, 436, 440, 444, 448, 452, 455, 457, 459, 462, 462,
83041      465, 468, 474, 478, 483, 487, 495, 498, 503, 508, 514, 518, 523,
83042   };
83043   static const unsigned char aCode[117] = {
83044     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,     
83045     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,    
83046     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,    
83047     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,      
83048     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,       
83049     TK_EXCEPT,     TK_TRANSACTION,TK_ON,         TK_JOIN_KW,    TK_ALTER,      
83050     TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_CONSTRAINT, TK_INTERSECT,  
83051     TK_TRIGGER,    TK_REFERENCES, TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     
83052     TK_HAVING,     TK_GROUP,      TK_UPDATE,     TK_TEMP,       TK_TEMP,       
83053     TK_OR,         TK_BEGIN,      TK_JOIN_KW,    TK_RENAME,     TK_BETWEEN,    
83054     TK_NOTNULL,    TK_NOT,        TK_NULL,       TK_LIKE_KW,    TK_CASCADE,    
83055     TK_ASC,        TK_DELETE,     TK_CASE,       TK_COLLATE,    TK_CREATE,     
83056     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  TK_JOIN,       TK_INSERT,     
83057     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    TK_PRAGMA,     TK_ABORT,      
83058     TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      TK_WHEN,       TK_WHERE,      
83059     TK_REPLACE,    TK_AFTER,      TK_RESTRICT,   TK_AND,        TK_DEFAULT,    
83060     TK_AUTOINCR,   TK_TO,         TK_IN,         TK_CAST,       TK_COLUMNKW,   
83061     TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    TK_CTIME_KW,   TK_CTIME_KW,   
83062     TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   TK_IS,         TK_DROP,       
83063     TK_FAIL,       TK_FROM,       TK_JOIN_KW,    TK_LIKE_KW,    TK_BY,         
83064     TK_IF,         TK_INTO,       TK_OFFSET,     TK_OF,         TK_SET,        
83065     TK_ISNULL,     TK_ORDER,      TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   
83066     TK_ROW,        TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       
83067     TK_INITIALLY,  TK_ALL,        
83068   };
83069   int h, i;
83070   if( n<2 ) return TK_ID;
83071   h = ((charMap(z[0])*4) ^
83072       (charMap(z[n-1])*3) ^
83073       n) % 127;
83074   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
83075     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
83076       return aCode[i];
83077     }
83078   }
83079   return TK_ID;
83080 }
83081 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
83082   return keywordCode((char*)z, n);
83083 }
83084
83085 /************** End of keywordhash.h *****************************************/
83086 /************** Continuing where we left off in tokenize.c *******************/
83087
83088
83089 /*
83090 ** If X is a character that can be used in an identifier then
83091 ** IdChar(X) will be true.  Otherwise it is false.
83092 **
83093 ** For ASCII, any character with the high-order bit set is
83094 ** allowed in an identifier.  For 7-bit characters, 
83095 ** sqlite3IsIdChar[X] must be 1.
83096 **
83097 ** For EBCDIC, the rules are more complex but have the same
83098 ** end result.
83099 **
83100 ** Ticket #1066.  the SQL standard does not allow '$' in the
83101 ** middle of identfiers.  But many SQL implementations do. 
83102 ** SQLite will allow '$' in identifiers for compatibility.
83103 ** But the feature is undocumented.
83104 */
83105 #ifdef SQLITE_ASCII
83106 SQLITE_PRIVATE const char sqlite3IsAsciiIdChar[] = {
83107 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
83108     0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
83109     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
83110     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
83111     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
83112     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
83113     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
83114 };
83115 #define IdChar(C)  (((c=C)&0x80)!=0 || (c>0x1f && sqlite3IsAsciiIdChar[c-0x20]))
83116 #endif
83117 #ifdef SQLITE_EBCDIC
83118 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
83119 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
83120     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
83121     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
83122     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
83123     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
83124     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
83125     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
83126     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
83127     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
83128     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
83129     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
83130     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
83131     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
83132 };
83133 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
83134 #endif
83135
83136
83137 /*
83138 ** Return the length of the token that begins at z[0]. 
83139 ** Store the token type in *tokenType before returning.
83140 */
83141 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
83142   int i, c;
83143   switch( *z ){
83144     case ' ': case '\t': case '\n': case '\f': case '\r': {
83145       for(i=1; isspace(z[i]); i++){}
83146       *tokenType = TK_SPACE;
83147       return i;
83148     }
83149     case '-': {
83150       if( z[1]=='-' ){
83151         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
83152         *tokenType = TK_SPACE;
83153         return i;
83154       }
83155       *tokenType = TK_MINUS;
83156       return 1;
83157     }
83158     case '(': {
83159       *tokenType = TK_LP;
83160       return 1;
83161     }
83162     case ')': {
83163       *tokenType = TK_RP;
83164       return 1;
83165     }
83166     case ';': {
83167       *tokenType = TK_SEMI;
83168       return 1;
83169     }
83170     case '+': {
83171       *tokenType = TK_PLUS;
83172       return 1;
83173     }
83174     case '*': {
83175       *tokenType = TK_STAR;
83176       return 1;
83177     }
83178     case '/': {
83179       if( z[1]!='*' || z[2]==0 ){
83180         *tokenType = TK_SLASH;
83181         return 1;
83182       }
83183       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
83184       if( c ) i++;
83185       *tokenType = TK_SPACE;
83186       return i;
83187     }
83188     case '%': {
83189       *tokenType = TK_REM;
83190       return 1;
83191     }
83192     case '=': {
83193       *tokenType = TK_EQ;
83194       return 1 + (z[1]=='=');
83195     }
83196     case '<': {
83197       if( (c=z[1])=='=' ){
83198         *tokenType = TK_LE;
83199         return 2;
83200       }else if( c=='>' ){
83201         *tokenType = TK_NE;
83202         return 2;
83203       }else if( c=='<' ){
83204         *tokenType = TK_LSHIFT;
83205         return 2;
83206       }else{
83207         *tokenType = TK_LT;
83208         return 1;
83209       }
83210     }
83211     case '>': {
83212       if( (c=z[1])=='=' ){
83213         *tokenType = TK_GE;
83214         return 2;
83215       }else if( c=='>' ){
83216         *tokenType = TK_RSHIFT;
83217         return 2;
83218       }else{
83219         *tokenType = TK_GT;
83220         return 1;
83221       }
83222     }
83223     case '!': {
83224       if( z[1]!='=' ){
83225         *tokenType = TK_ILLEGAL;
83226         return 2;
83227       }else{
83228         *tokenType = TK_NE;
83229         return 2;
83230       }
83231     }
83232     case '|': {
83233       if( z[1]!='|' ){
83234         *tokenType = TK_BITOR;
83235         return 1;
83236       }else{
83237         *tokenType = TK_CONCAT;
83238         return 2;
83239       }
83240     }
83241     case ',': {
83242       *tokenType = TK_COMMA;
83243       return 1;
83244     }
83245     case '&': {
83246       *tokenType = TK_BITAND;
83247       return 1;
83248     }
83249     case '~': {
83250       *tokenType = TK_BITNOT;
83251       return 1;
83252     }
83253     case '`':
83254     case '\'':
83255     case '"': {
83256       int delim = z[0];
83257       for(i=1; (c=z[i])!=0; i++){
83258         if( c==delim ){
83259           if( z[i+1]==delim ){
83260             i++;
83261           }else{
83262             break;
83263           }
83264         }
83265       }
83266       if( c=='\'' ){
83267         *tokenType = TK_STRING;
83268         return i+1;
83269       }else if( c!=0 ){
83270         *tokenType = TK_ID;
83271         return i+1;
83272       }else{
83273         *tokenType = TK_ILLEGAL;
83274         return i;
83275       }
83276     }
83277     case '.': {
83278 #ifndef SQLITE_OMIT_FLOATING_POINT
83279       if( !isdigit(z[1]) )
83280 #endif
83281       {
83282         *tokenType = TK_DOT;
83283         return 1;
83284       }
83285       /* If the next character is a digit, this is a floating point
83286       ** number that begins with ".".  Fall thru into the next case */
83287     }
83288     case '0': case '1': case '2': case '3': case '4':
83289     case '5': case '6': case '7': case '8': case '9': {
83290       *tokenType = TK_INTEGER;
83291       for(i=0; isdigit(z[i]); i++){}
83292 #ifndef SQLITE_OMIT_FLOATING_POINT
83293       if( z[i]=='.' ){
83294         i++;
83295         while( isdigit(z[i]) ){ i++; }
83296         *tokenType = TK_FLOAT;
83297       }
83298       if( (z[i]=='e' || z[i]=='E') &&
83299            ( isdigit(z[i+1]) 
83300             || ((z[i+1]=='+' || z[i+1]=='-') && isdigit(z[i+2]))
83301            )
83302       ){
83303         i += 2;
83304         while( isdigit(z[i]) ){ i++; }
83305         *tokenType = TK_FLOAT;
83306       }
83307 #endif
83308       while( IdChar(z[i]) ){
83309         *tokenType = TK_ILLEGAL;
83310         i++;
83311       }
83312       return i;
83313     }
83314     case '[': {
83315       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
83316       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
83317       return i;
83318     }
83319     case '?': {
83320       *tokenType = TK_VARIABLE;
83321       for(i=1; isdigit(z[i]); i++){}
83322       return i;
83323     }
83324     case '#': {
83325       for(i=1; isdigit(z[i]); i++){}
83326       if( i>1 ){
83327         /* Parameters of the form #NNN (where NNN is a number) are used
83328         ** internally by sqlite3NestedParse.  */
83329         *tokenType = TK_REGISTER;
83330         return i;
83331       }
83332       /* Fall through into the next case if the '#' is not followed by
83333       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
83334     }
83335 #ifndef SQLITE_OMIT_TCL_VARIABLE
83336     case '$':
83337 #endif
83338     case '@':  /* For compatibility with MS SQL Server */
83339     case ':': {
83340       int n = 0;
83341       *tokenType = TK_VARIABLE;
83342       for(i=1; (c=z[i])!=0; i++){
83343         if( IdChar(c) ){
83344           n++;
83345 #ifndef SQLITE_OMIT_TCL_VARIABLE
83346         }else if( c=='(' && n>0 ){
83347           do{
83348             i++;
83349           }while( (c=z[i])!=0 && !isspace(c) && c!=')' );
83350           if( c==')' ){
83351             i++;
83352           }else{
83353             *tokenType = TK_ILLEGAL;
83354           }
83355           break;
83356         }else if( c==':' && z[i+1]==':' ){
83357           i++;
83358 #endif
83359         }else{
83360           break;
83361         }
83362       }
83363       if( n==0 ) *tokenType = TK_ILLEGAL;
83364       return i;
83365     }
83366 #ifndef SQLITE_OMIT_BLOB_LITERAL
83367     case 'x': case 'X': {
83368       if( z[1]=='\'' ){
83369         *tokenType = TK_BLOB;
83370         for(i=2; (c=z[i])!=0 && c!='\''; i++){
83371           if( !isxdigit(c) ){
83372             *tokenType = TK_ILLEGAL;
83373           }
83374         }
83375         if( i%2 || !c ) *tokenType = TK_ILLEGAL;
83376         if( c ) i++;
83377         return i;
83378       }
83379       /* Otherwise fall through to the next case */
83380     }
83381 #endif
83382     default: {
83383       if( !IdChar(*z) ){
83384         break;
83385       }
83386       for(i=1; IdChar(z[i]); i++){}
83387       *tokenType = keywordCode((char*)z, i);
83388       return i;
83389     }
83390   }
83391   *tokenType = TK_ILLEGAL;
83392   return 1;
83393 }
83394
83395 /*
83396 ** Run the parser on the given SQL string.  The parser structure is
83397 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
83398 ** then an and attempt is made to write an error message into 
83399 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
83400 ** error message.
83401 */
83402 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
83403   int nErr = 0;
83404   int i;
83405   void *pEngine;
83406   int tokenType;
83407   int lastTokenParsed = -1;
83408   sqlite3 *db = pParse->db;
83409   int mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
83410
83411   if( db->activeVdbeCnt==0 ){
83412     db->u1.isInterrupted = 0;
83413   }
83414   pParse->rc = SQLITE_OK;
83415   pParse->zTail = pParse->zSql = zSql;
83416   i = 0;
83417   assert( pzErrMsg!=0 );
83418   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
83419   if( pEngine==0 ){
83420     db->mallocFailed = 1;
83421     return SQLITE_NOMEM;
83422   }
83423   assert( pParse->sLastToken.dyn==0 );
83424   assert( pParse->pNewTable==0 );
83425   assert( pParse->pNewTrigger==0 );
83426   assert( pParse->nVar==0 );
83427   assert( pParse->nVarExpr==0 );
83428   assert( pParse->nVarExprAlloc==0 );
83429   assert( pParse->apVarExpr==0 );
83430   while( !db->mallocFailed && zSql[i]!=0 ){
83431     assert( i>=0 );
83432     pParse->sLastToken.z = (u8*)&zSql[i];
83433     assert( pParse->sLastToken.dyn==0 );
83434     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
83435     i += pParse->sLastToken.n;
83436     if( i>mxSqlLen ){
83437       pParse->rc = SQLITE_TOOBIG;
83438       break;
83439     }
83440     switch( tokenType ){
83441       case TK_SPACE: {
83442         if( db->u1.isInterrupted ){
83443           pParse->rc = SQLITE_INTERRUPT;
83444           sqlite3SetString(pzErrMsg, db, "interrupt");
83445           goto abort_parse;
83446         }
83447         break;
83448       }
83449       case TK_ILLEGAL: {
83450         sqlite3DbFree(db, *pzErrMsg);
83451         *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
83452                         &pParse->sLastToken);
83453         nErr++;
83454         goto abort_parse;
83455       }
83456       case TK_SEMI: {
83457         pParse->zTail = &zSql[i];
83458         /* Fall thru into the default case */
83459       }
83460       default: {
83461         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
83462         lastTokenParsed = tokenType;
83463         if( pParse->rc!=SQLITE_OK ){
83464           goto abort_parse;
83465         }
83466         break;
83467       }
83468     }
83469   }
83470 abort_parse:
83471   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
83472     if( lastTokenParsed!=TK_SEMI ){
83473       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
83474       pParse->zTail = &zSql[i];
83475     }
83476     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
83477   }
83478 #ifdef YYTRACKMAXSTACKDEPTH
83479   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
83480       sqlite3ParserStackPeak(pEngine)
83481   );
83482 #endif /* YYDEBUG */
83483   sqlite3ParserFree(pEngine, sqlite3_free);
83484   if( db->mallocFailed ){
83485     pParse->rc = SQLITE_NOMEM;
83486   }
83487   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
83488     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
83489   }
83490   if( pParse->zErrMsg ){
83491     if( *pzErrMsg==0 ){
83492       *pzErrMsg = pParse->zErrMsg;
83493     }else{
83494       sqlite3DbFree(db, pParse->zErrMsg);
83495     }
83496     pParse->zErrMsg = 0;
83497     nErr++;
83498   }
83499   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
83500     sqlite3VdbeDelete(pParse->pVdbe);
83501     pParse->pVdbe = 0;
83502   }
83503 #ifndef SQLITE_OMIT_SHARED_CACHE
83504   if( pParse->nested==0 ){
83505     sqlite3DbFree(db, pParse->aTableLock);
83506     pParse->aTableLock = 0;
83507     pParse->nTableLock = 0;
83508   }
83509 #endif
83510 #ifndef SQLITE_OMIT_VIRTUALTABLE
83511   sqlite3DbFree(db, pParse->apVtabLock);
83512 #endif
83513
83514   if( !IN_DECLARE_VTAB ){
83515     /* If the pParse->declareVtab flag is set, do not delete any table 
83516     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
83517     ** will take responsibility for freeing the Table structure.
83518     */
83519     sqlite3DeleteTable(pParse->pNewTable);
83520   }
83521
83522   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
83523   sqlite3DbFree(db, pParse->apVarExpr);
83524   sqlite3DbFree(db, pParse->aAlias);
83525   while( pParse->pZombieTab ){
83526     Table *p = pParse->pZombieTab;
83527     pParse->pZombieTab = p->pNextZombie;
83528     sqlite3DeleteTable(p);
83529   }
83530   if( nErr>0 && (pParse->rc==SQLITE_OK || pParse->rc==SQLITE_DONE) ){
83531     pParse->rc = SQLITE_ERROR;
83532   }
83533   return nErr;
83534 }
83535
83536 /************** End of tokenize.c ********************************************/
83537 /************** Begin file complete.c ****************************************/
83538 /*
83539 ** 2001 September 15
83540 **
83541 ** The author disclaims copyright to this source code.  In place of
83542 ** a legal notice, here is a blessing:
83543 **
83544 **    May you do good and not evil.
83545 **    May you find forgiveness for yourself and forgive others.
83546 **    May you share freely, never taking more than you give.
83547 **
83548 *************************************************************************
83549 ** An tokenizer for SQL
83550 **
83551 ** This file contains C code that implements the sqlite3_complete() API.
83552 ** This code used to be part of the tokenizer.c source file.  But by
83553 ** separating it out, the code will be automatically omitted from
83554 ** static links that do not use it.
83555 **
83556 ** $Id: complete.c,v 1.7 2008/06/13 18:24:27 drh Exp $
83557 */
83558 #ifndef SQLITE_OMIT_COMPLETE
83559
83560 /*
83561 ** This is defined in tokenize.c.  We just have to import the definition.
83562 */
83563 #ifndef SQLITE_AMALGAMATION
83564 #ifdef SQLITE_ASCII
83565 SQLITE_PRIVATE const char sqlite3IsAsciiIdChar[];
83566 #define IdChar(C)  (((c=C)&0x80)!=0 || (c>0x1f && sqlite3IsAsciiIdChar[c-0x20]))
83567 #endif
83568 #ifdef SQLITE_EBCDIC
83569 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
83570 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
83571 #endif
83572 #endif /* SQLITE_AMALGAMATION */
83573
83574
83575 /*
83576 ** Token types used by the sqlite3_complete() routine.  See the header
83577 ** comments on that procedure for additional information.
83578 */
83579 #define tkSEMI    0
83580 #define tkWS      1
83581 #define tkOTHER   2
83582 #define tkEXPLAIN 3
83583 #define tkCREATE  4
83584 #define tkTEMP    5
83585 #define tkTRIGGER 6
83586 #define tkEND     7
83587
83588 /*
83589 ** Return TRUE if the given SQL string ends in a semicolon.
83590 **
83591 ** Special handling is require for CREATE TRIGGER statements.
83592 ** Whenever the CREATE TRIGGER keywords are seen, the statement
83593 ** must end with ";END;".
83594 **
83595 ** This implementation uses a state machine with 7 states:
83596 **
83597 **   (0) START     At the beginning or end of an SQL statement.  This routine
83598 **                 returns 1 if it ends in the START state and 0 if it ends
83599 **                 in any other state.
83600 **
83601 **   (1) NORMAL    We are in the middle of statement which ends with a single
83602 **                 semicolon.
83603 **
83604 **   (2) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
83605 **                 a statement.
83606 **
83607 **   (3) CREATE    The keyword CREATE has been seen at the beginning of a
83608 **                 statement, possibly preceeded by EXPLAIN and/or followed by
83609 **                 TEMP or TEMPORARY
83610 **
83611 **   (4) TRIGGER   We are in the middle of a trigger definition that must be
83612 **                 ended by a semicolon, the keyword END, and another semicolon.
83613 **
83614 **   (5) SEMI      We've seen the first semicolon in the ";END;" that occurs at
83615 **                 the end of a trigger definition.
83616 **
83617 **   (6) END       We've seen the ";END" of the ";END;" that occurs at the end
83618 **                 of a trigger difinition.
83619 **
83620 ** Transitions between states above are determined by tokens extracted
83621 ** from the input.  The following tokens are significant:
83622 **
83623 **   (0) tkSEMI      A semicolon.
83624 **   (1) tkWS        Whitespace
83625 **   (2) tkOTHER     Any other SQL token.
83626 **   (3) tkEXPLAIN   The "explain" keyword.
83627 **   (4) tkCREATE    The "create" keyword.
83628 **   (5) tkTEMP      The "temp" or "temporary" keyword.
83629 **   (6) tkTRIGGER   The "trigger" keyword.
83630 **   (7) tkEND       The "end" keyword.
83631 **
83632 ** Whitespace never causes a state transition and is always ignored.
83633 **
83634 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
83635 ** to recognize the end of a trigger can be omitted.  All we have to do
83636 ** is look for a semicolon that is not part of an string or comment.
83637 */
83638 SQLITE_API int sqlite3_complete(const char *zSql){
83639   u8 state = 0;   /* Current state, using numbers defined in header comment */
83640   u8 token;       /* Value of the next token */
83641
83642 #ifndef SQLITE_OMIT_TRIGGER
83643   /* A complex statement machine used to detect the end of a CREATE TRIGGER
83644   ** statement.  This is the normal case.
83645   */
83646   static const u8 trans[7][8] = {
83647                      /* Token:                                                */
83648      /* State:       **  SEMI  WS  OTHER EXPLAIN  CREATE  TEMP  TRIGGER  END  */
83649      /* 0   START: */ {    0,  0,     1,      2,      3,    1,       1,   1,  },
83650      /* 1  NORMAL: */ {    0,  1,     1,      1,      1,    1,       1,   1,  },
83651      /* 2 EXPLAIN: */ {    0,  2,     1,      1,      3,    1,       1,   1,  },
83652      /* 3  CREATE: */ {    0,  3,     1,      1,      1,    3,       4,   1,  },
83653      /* 4 TRIGGER: */ {    5,  4,     4,      4,      4,    4,       4,   4,  },
83654      /* 5    SEMI: */ {    5,  5,     4,      4,      4,    4,       4,   6,  },
83655      /* 6     END: */ {    0,  6,     4,      4,      4,    4,       4,   4,  },
83656   };
83657 #else
83658   /* If triggers are not suppored by this compile then the statement machine
83659   ** used to detect the end of a statement is much simplier
83660   */
83661   static const u8 trans[2][3] = {
83662                      /* Token:           */
83663      /* State:       **  SEMI  WS  OTHER */
83664      /* 0   START: */ {    0,  0,     1, },
83665      /* 1  NORMAL: */ {    0,  1,     1, },
83666   };
83667 #endif /* SQLITE_OMIT_TRIGGER */
83668
83669   while( *zSql ){
83670     switch( *zSql ){
83671       case ';': {  /* A semicolon */
83672         token = tkSEMI;
83673         break;
83674       }
83675       case ' ':
83676       case '\r':
83677       case '\t':
83678       case '\n':
83679       case '\f': {  /* White space is ignored */
83680         token = tkWS;
83681         break;
83682       }
83683       case '/': {   /* C-style comments */
83684         if( zSql[1]!='*' ){
83685           token = tkOTHER;
83686           break;
83687         }
83688         zSql += 2;
83689         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
83690         if( zSql[0]==0 ) return 0;
83691         zSql++;
83692         token = tkWS;
83693         break;
83694       }
83695       case '-': {   /* SQL-style comments from "--" to end of line */
83696         if( zSql[1]!='-' ){
83697           token = tkOTHER;
83698           break;
83699         }
83700         while( *zSql && *zSql!='\n' ){ zSql++; }
83701         if( *zSql==0 ) return state==0;
83702         token = tkWS;
83703         break;
83704       }
83705       case '[': {   /* Microsoft-style identifiers in [...] */
83706         zSql++;
83707         while( *zSql && *zSql!=']' ){ zSql++; }
83708         if( *zSql==0 ) return 0;
83709         token = tkOTHER;
83710         break;
83711       }
83712       case '`':     /* Grave-accent quoted symbols used by MySQL */
83713       case '"':     /* single- and double-quoted strings */
83714       case '\'': {
83715         int c = *zSql;
83716         zSql++;
83717         while( *zSql && *zSql!=c ){ zSql++; }
83718         if( *zSql==0 ) return 0;
83719         token = tkOTHER;
83720         break;
83721       }
83722       default: {
83723         int c;
83724         if( IdChar((u8)*zSql) ){
83725           /* Keywords and unquoted identifiers */
83726           int nId;
83727           for(nId=1; IdChar(zSql[nId]); nId++){}
83728 #ifdef SQLITE_OMIT_TRIGGER
83729           token = tkOTHER;
83730 #else
83731           switch( *zSql ){
83732             case 'c': case 'C': {
83733               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
83734                 token = tkCREATE;
83735               }else{
83736                 token = tkOTHER;
83737               }
83738               break;
83739             }
83740             case 't': case 'T': {
83741               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
83742                 token = tkTRIGGER;
83743               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
83744                 token = tkTEMP;
83745               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
83746                 token = tkTEMP;
83747               }else{
83748                 token = tkOTHER;
83749               }
83750               break;
83751             }
83752             case 'e':  case 'E': {
83753               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
83754                 token = tkEND;
83755               }else
83756 #ifndef SQLITE_OMIT_EXPLAIN
83757               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
83758                 token = tkEXPLAIN;
83759               }else
83760 #endif
83761               {
83762                 token = tkOTHER;
83763               }
83764               break;
83765             }
83766             default: {
83767               token = tkOTHER;
83768               break;
83769             }
83770           }
83771 #endif /* SQLITE_OMIT_TRIGGER */
83772           zSql += nId-1;
83773         }else{
83774           /* Operators and special symbols */
83775           token = tkOTHER;
83776         }
83777         break;
83778       }
83779     }
83780     state = trans[state][token];
83781     zSql++;
83782   }
83783   return state==0;
83784 }
83785
83786 #ifndef SQLITE_OMIT_UTF16
83787 /*
83788 ** This routine is the same as the sqlite3_complete() routine described
83789 ** above, except that the parameter is required to be UTF-16 encoded, not
83790 ** UTF-8.
83791 */
83792 SQLITE_API int sqlite3_complete16(const void *zSql){
83793   sqlite3_value *pVal;
83794   char const *zSql8;
83795   int rc = SQLITE_NOMEM;
83796
83797 #ifndef SQLITE_OMIT_AUTOINIT
83798   rc = sqlite3_initialize();
83799   if( rc ) return rc;
83800 #endif
83801   pVal = sqlite3ValueNew(0);
83802   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
83803   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
83804   if( zSql8 ){
83805     rc = sqlite3_complete(zSql8);
83806   }else{
83807     rc = SQLITE_NOMEM;
83808   }
83809   sqlite3ValueFree(pVal);
83810   return sqlite3ApiExit(0, rc);
83811 }
83812 #endif /* SQLITE_OMIT_UTF16 */
83813 #endif /* SQLITE_OMIT_COMPLETE */
83814
83815 /************** End of complete.c ********************************************/
83816 /************** Begin file main.c ********************************************/
83817 /*
83818 ** 2001 September 15
83819 **
83820 ** The author disclaims copyright to this source code.  In place of
83821 ** a legal notice, here is a blessing:
83822 **
83823 **    May you do good and not evil.
83824 **    May you find forgiveness for yourself and forgive others.
83825 **    May you share freely, never taking more than you give.
83826 **
83827 *************************************************************************
83828 ** Main file for the SQLite library.  The routines in this file
83829 ** implement the programmer interface to the library.  Routines in
83830 ** other files are for internal use by SQLite and should not be
83831 ** accessed by users of the library.
83832 **
83833 ** $Id: main.c,v 1.514 2008/11/19 09:05:27 danielk1977 Exp $
83834 */
83835
83836 #ifdef SQLITE_ENABLE_FTS3
83837 /************** Include fts3.h in the middle of main.c ***********************/
83838 /************** Begin file fts3.h ********************************************/
83839 /*
83840 ** 2006 Oct 10
83841 **
83842 ** The author disclaims copyright to this source code.  In place of
83843 ** a legal notice, here is a blessing:
83844 **
83845 **    May you do good and not evil.
83846 **    May you find forgiveness for yourself and forgive others.
83847 **    May you share freely, never taking more than you give.
83848 **
83849 ******************************************************************************
83850 **
83851 ** This header file is used by programs that want to link against the
83852 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
83853 */
83854
83855 #if 0
83856 extern "C" {
83857 #endif  /* __cplusplus */
83858
83859 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
83860
83861 #if 0
83862 }  /* extern "C" */
83863 #endif  /* __cplusplus */
83864
83865 /************** End of fts3.h ************************************************/
83866 /************** Continuing where we left off in main.c ***********************/
83867 #endif
83868 #ifdef SQLITE_ENABLE_RTREE
83869 /************** Include rtree.h in the middle of main.c **********************/
83870 /************** Begin file rtree.h *******************************************/
83871 /*
83872 ** 2008 May 26
83873 **
83874 ** The author disclaims copyright to this source code.  In place of
83875 ** a legal notice, here is a blessing:
83876 **
83877 **    May you do good and not evil.
83878 **    May you find forgiveness for yourself and forgive others.
83879 **    May you share freely, never taking more than you give.
83880 **
83881 ******************************************************************************
83882 **
83883 ** This header file is used by programs that want to link against the
83884 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
83885 */
83886
83887 #if 0
83888 extern "C" {
83889 #endif  /* __cplusplus */
83890
83891 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
83892
83893 #if 0
83894 }  /* extern "C" */
83895 #endif  /* __cplusplus */
83896
83897 /************** End of rtree.h ***********************************************/
83898 /************** Continuing where we left off in main.c ***********************/
83899 #endif
83900 #ifdef SQLITE_ENABLE_ICU
83901 /************** Include sqliteicu.h in the middle of main.c ******************/
83902 /************** Begin file sqliteicu.h ***************************************/
83903 /*
83904 ** 2008 May 26
83905 **
83906 ** The author disclaims copyright to this source code.  In place of
83907 ** a legal notice, here is a blessing:
83908 **
83909 **    May you do good and not evil.
83910 **    May you find forgiveness for yourself and forgive others.
83911 **    May you share freely, never taking more than you give.
83912 **
83913 ******************************************************************************
83914 **
83915 ** This header file is used by programs that want to link against the
83916 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
83917 */
83918
83919 #if 0
83920 extern "C" {
83921 #endif  /* __cplusplus */
83922
83923 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
83924
83925 #if 0
83926 }  /* extern "C" */
83927 #endif  /* __cplusplus */
83928
83929
83930 /************** End of sqliteicu.h *******************************************/
83931 /************** Continuing where we left off in main.c ***********************/
83932 #endif
83933
83934 /*
83935 ** The version of the library
83936 */
83937 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
83938 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
83939 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
83940 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
83941
83942 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
83943 /*
83944 ** If the following function pointer is not NULL and if
83945 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
83946 ** I/O active are written using this function.  These messages
83947 ** are intended for debugging activity only.
83948 */
83949 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
83950 #endif
83951
83952 /*
83953 ** If the following global variable points to a string which is the
83954 ** name of a directory, then that directory will be used to store
83955 ** temporary files.
83956 **
83957 ** See also the "PRAGMA temp_store_directory" SQL command.
83958 */
83959 SQLITE_API char *sqlite3_temp_directory = 0;
83960
83961 /*
83962 ** Initialize SQLite.  
83963 **
83964 ** This routine must be called to initialize the memory allocation,
83965 ** VFS, and mutex subsystems prior to doing any serious work with
83966 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
83967 ** this routine will be called automatically by key routines such as
83968 ** sqlite3_open().  
83969 **
83970 ** This routine is a no-op except on its very first call for the process,
83971 ** or for the first call after a call to sqlite3_shutdown.
83972 **
83973 ** The first thread to call this routine runs the initialization to
83974 ** completion.  If subsequent threads call this routine before the first
83975 ** thread has finished the initialization process, then the subsequent
83976 ** threads must block until the first thread finishes with the initialization.
83977 **
83978 ** The first thread might call this routine recursively.  Recursive
83979 ** calls to this routine should not block, of course.  Otherwise the
83980 ** initialization process would never complete.
83981 **
83982 ** Let X be the first thread to enter this routine.  Let Y be some other
83983 ** thread.  Then while the initial invocation of this routine by X is
83984 ** incomplete, it is required that:
83985 **
83986 **    *  Calls to this routine from Y must block until the outer-most
83987 **       call by X completes.
83988 **
83989 **    *  Recursive calls to this routine from thread X return immediately
83990 **       without blocking.
83991 */
83992 SQLITE_API int sqlite3_initialize(void){
83993   sqlite3_mutex *pMaster;                      /* The main static mutex */
83994   int rc;                                      /* Result code */
83995
83996 #ifdef SQLITE_OMIT_WSD
83997   rc = sqlite3_wsd_init(4096, 24);
83998   if( rc!=SQLITE_OK ){
83999     return rc;
84000   }
84001 #endif
84002
84003   /* If SQLite is already completely initialized, then this call
84004   ** to sqlite3_initialize() should be a no-op.  But the initialization
84005   ** must be complete.  So isInit must not be set until the very end
84006   ** of this routine.
84007   */
84008   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
84009
84010   /* Make sure the mutex subsystem is initialized.  If unable to 
84011   ** initialize the mutex subsystem, return early with the error.
84012   ** If the system is so sick that we are unable to allocate a mutex,
84013   ** there is not much SQLite is going to be able to do.
84014   **
84015   ** The mutex subsystem must take care of serializing its own
84016   ** initialization.
84017   */
84018   rc = sqlite3MutexInit();
84019   if( rc ) return rc;
84020
84021   /* Initialize the malloc() system and the recursive pInitMutex mutex.
84022   ** This operation is protected by the STATIC_MASTER mutex.  Note that
84023   ** MutexAlloc() is called for a static mutex prior to initializing the
84024   ** malloc subsystem - this implies that the allocation of a static
84025   ** mutex must not require support from the malloc subsystem.
84026   */
84027   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
84028   sqlite3_mutex_enter(pMaster);
84029   if( !sqlite3GlobalConfig.isMallocInit ){
84030     rc = sqlite3MallocInit();
84031   }
84032   if( rc==SQLITE_OK ){
84033     sqlite3GlobalConfig.isMallocInit = 1;
84034     if( !sqlite3GlobalConfig.pInitMutex ){
84035       sqlite3GlobalConfig.pInitMutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
84036       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
84037         rc = SQLITE_NOMEM;
84038       }
84039     }
84040   }
84041   if( rc==SQLITE_OK ){
84042     sqlite3GlobalConfig.nRefInitMutex++;
84043   }
84044   sqlite3_mutex_leave(pMaster);
84045
84046   /* If unable to initialize the malloc subsystem, then return early.
84047   ** There is little hope of getting SQLite to run if the malloc
84048   ** subsystem cannot be initialized.
84049   */
84050   if( rc!=SQLITE_OK ){
84051     return rc;
84052   }
84053
84054   /* Do the rest of the initialization under the recursive mutex so
84055   ** that we will be able to handle recursive calls into
84056   ** sqlite3_initialize().  The recursive calls normally come through
84057   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
84058   ** recursive calls might also be possible.
84059   */
84060   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
84061   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
84062     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
84063     sqlite3GlobalConfig.inProgress = 1;
84064     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
84065     sqlite3RegisterGlobalFunctions();
84066     rc = sqlite3_os_init();
84067     if( rc==SQLITE_OK ){
84068       rc = sqlite3PcacheInitialize();
84069       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, 
84070           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
84071     }
84072     sqlite3GlobalConfig.inProgress = 0;
84073     sqlite3GlobalConfig.isInit = (rc==SQLITE_OK ? 1 : 0);
84074   }
84075   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
84076
84077   /* Go back under the static mutex and clean up the recursive
84078   ** mutex to prevent a resource leak.
84079   */
84080   sqlite3_mutex_enter(pMaster);
84081   sqlite3GlobalConfig.nRefInitMutex--;
84082   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
84083     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
84084     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
84085     sqlite3GlobalConfig.pInitMutex = 0;
84086   }
84087   sqlite3_mutex_leave(pMaster);
84088
84089   /* The following is just a sanity check to make sure SQLite has
84090   ** been compiled correctly.  It is important to run this code, but
84091   ** we don't want to run it too often and soak up CPU cycles for no
84092   ** reason.  So we run it once during initialization.
84093   */
84094 #ifndef NDEBUG
84095   /* This section of code's only "output" is via assert() statements. */
84096   if ( rc==SQLITE_OK ){
84097     u64 x = (((u64)1)<<63)-1;
84098     double y;
84099     assert(sizeof(x)==8);
84100     assert(sizeof(x)==sizeof(y));
84101     memcpy(&y, &x, 8);
84102     assert( sqlite3IsNaN(y) );
84103   }
84104 #endif
84105
84106   return rc;
84107 }
84108
84109 /*
84110 ** Undo the effects of sqlite3_initialize().  Must not be called while
84111 ** there are outstanding database connections or memory allocations or
84112 ** while any part of SQLite is otherwise in use in any thread.  This
84113 ** routine is not threadsafe.  Not by a long shot.
84114 */
84115 SQLITE_API int sqlite3_shutdown(void){
84116   sqlite3GlobalConfig.isMallocInit = 0;
84117   sqlite3PcacheShutdown();
84118   if( sqlite3GlobalConfig.isInit ){
84119     sqlite3_os_end();
84120   }
84121   sqlite3MallocEnd();
84122   sqlite3MutexEnd();
84123   sqlite3GlobalConfig.isInit = 0;
84124   return SQLITE_OK;
84125 }
84126
84127 /*
84128 ** This API allows applications to modify the global configuration of
84129 ** the SQLite library at run-time.
84130 **
84131 ** This routine should only be called when there are no outstanding
84132 ** database connections or memory allocations.  This routine is not
84133 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
84134 ** behavior.
84135 */
84136 SQLITE_API int sqlite3_config(int op, ...){
84137   va_list ap;
84138   int rc = SQLITE_OK;
84139
84140   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
84141   ** the SQLite library is in use. */
84142   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE;
84143
84144   va_start(ap, op);
84145   switch( op ){
84146
84147     /* Mutex configuration options are only available in a threadsafe
84148     ** compile. 
84149     */
84150 #if SQLITE_THREADSAFE
84151     case SQLITE_CONFIG_SINGLETHREAD: {
84152       /* Disable all mutexing */
84153       sqlite3GlobalConfig.bCoreMutex = 0;
84154       sqlite3GlobalConfig.bFullMutex = 0;
84155       break;
84156     }
84157     case SQLITE_CONFIG_MULTITHREAD: {
84158       /* Disable mutexing of database connections */
84159       /* Enable mutexing of core data structures */
84160       sqlite3GlobalConfig.bCoreMutex = 1;
84161       sqlite3GlobalConfig.bFullMutex = 0;
84162       break;
84163     }
84164     case SQLITE_CONFIG_SERIALIZED: {
84165       /* Enable all mutexing */
84166       sqlite3GlobalConfig.bCoreMutex = 1;
84167       sqlite3GlobalConfig.bFullMutex = 1;
84168       break;
84169     }
84170     case SQLITE_CONFIG_MUTEX: {
84171       /* Specify an alternative mutex implementation */
84172       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
84173       break;
84174     }
84175     case SQLITE_CONFIG_GETMUTEX: {
84176       /* Retrieve the current mutex implementation */
84177       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
84178       break;
84179     }
84180 #endif
84181
84182
84183     case SQLITE_CONFIG_MALLOC: {
84184       /* Specify an alternative malloc implementation */
84185       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
84186       break;
84187     }
84188     case SQLITE_CONFIG_GETMALLOC: {
84189       /* Retrieve the current malloc() implementation */
84190       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
84191       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
84192       break;
84193     }
84194     case SQLITE_CONFIG_MEMSTATUS: {
84195       /* Enable or disable the malloc status collection */
84196       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
84197       break;
84198     }
84199     case SQLITE_CONFIG_SCRATCH: {
84200       /* Designate a buffer for scratch memory space */
84201       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
84202       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
84203       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
84204       break;
84205     }
84206     case SQLITE_CONFIG_PAGECACHE: {
84207       /* Designate a buffer for scratch memory space */
84208       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
84209       sqlite3GlobalConfig.szPage = va_arg(ap, int);
84210       sqlite3GlobalConfig.nPage = va_arg(ap, int);
84211       break;
84212     }
84213
84214     case SQLITE_CONFIG_PCACHE: {
84215       /* Specify an alternative malloc implementation */
84216       sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
84217       break;
84218     }
84219
84220     case SQLITE_CONFIG_GETPCACHE: {
84221       if( sqlite3GlobalConfig.pcache.xInit==0 ){
84222         sqlite3PCacheSetDefault();
84223       }
84224       *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
84225       break;
84226     }
84227
84228 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
84229     case SQLITE_CONFIG_HEAP: {
84230       /* Designate a buffer for heap memory space */
84231       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
84232       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
84233       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
84234
84235       if( sqlite3GlobalConfig.pHeap==0 ){
84236         /* If the heap pointer is NULL, then restore the malloc implementation
84237         ** back to NULL pointers too.  This will cause the malloc to go
84238         ** back to its default implementation when sqlite3_initialize() is
84239         ** run.
84240         */
84241         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
84242       }else{
84243         /* The heap pointer is not NULL, then install one of the
84244         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
84245         ** ENABLE_MEMSYS5 is defined, return an error.
84246         ** the default case and return an error.
84247         */
84248 #ifdef SQLITE_ENABLE_MEMSYS3
84249         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
84250 #endif
84251 #ifdef SQLITE_ENABLE_MEMSYS5
84252         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
84253 #endif
84254       }
84255       break;
84256     }
84257 #endif
84258
84259     case SQLITE_CONFIG_LOOKASIDE: {
84260       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
84261       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
84262       break;
84263     }
84264
84265     default: {
84266       rc = SQLITE_ERROR;
84267       break;
84268     }
84269   }
84270   va_end(ap);
84271   return rc;
84272 }
84273
84274 /*
84275 ** Set up the lookaside buffers for a database connection.
84276 ** Return SQLITE_OK on success.  
84277 ** If lookaside is already active, return SQLITE_BUSY.
84278 **
84279 ** The sz parameter is the number of bytes in each lookaside slot.
84280 ** The cnt parameter is the number of slots.  If pStart is NULL the
84281 ** space for the lookaside memory is obtained from sqlite3_malloc().
84282 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
84283 ** the lookaside memory.
84284 */
84285 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
84286   void *pStart;
84287   if( db->lookaside.nOut ){
84288     return SQLITE_BUSY;
84289   }
84290   if( sz<0 ) sz = 0;
84291   if( cnt<0 ) cnt = 0;
84292   if( pBuf==0 ){
84293     sz = (sz + 7)&~7;
84294     sqlite3BeginBenignMalloc();
84295     pStart = sqlite3Malloc( sz*cnt );
84296     sqlite3EndBenignMalloc();
84297   }else{
84298     sz = sz&~7;
84299     pStart = pBuf;
84300   }
84301   if( db->lookaside.bMalloced ){
84302     sqlite3_free(db->lookaside.pStart);
84303   }
84304   db->lookaside.pStart = pStart;
84305   db->lookaside.pFree = 0;
84306   db->lookaside.sz = sz;
84307   db->lookaside.bMalloced = pBuf==0;
84308   if( pStart ){
84309     int i;
84310     LookasideSlot *p;
84311     p = (LookasideSlot*)pStart;
84312     for(i=cnt-1; i>=0; i--){
84313       p->pNext = db->lookaside.pFree;
84314       db->lookaside.pFree = p;
84315       p = (LookasideSlot*)&((u8*)p)[sz];
84316     }
84317     db->lookaside.pEnd = p;
84318     db->lookaside.bEnabled = 1;
84319   }else{
84320     db->lookaside.pEnd = 0;
84321     db->lookaside.bEnabled = 0;
84322   }
84323   return SQLITE_OK;
84324 }
84325
84326 /*
84327 ** Return the mutex associated with a database connection.
84328 */
84329 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
84330   return db->mutex;
84331 }
84332
84333 /*
84334 ** Configuration settings for an individual database connection
84335 */
84336 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
84337   va_list ap;
84338   int rc;
84339   va_start(ap, op);
84340   switch( op ){
84341     case SQLITE_DBCONFIG_LOOKASIDE: {
84342       void *pBuf = va_arg(ap, void*);
84343       int sz = va_arg(ap, int);
84344       int cnt = va_arg(ap, int);
84345       rc = setupLookaside(db, pBuf, sz, cnt);
84346       break;
84347     }
84348     default: {
84349       rc = SQLITE_ERROR;
84350       break;
84351     }
84352   }
84353   va_end(ap);
84354   return rc;
84355 }
84356
84357 /*
84358 ** Routine needed to support the testcase() macro.
84359 */
84360 #ifdef SQLITE_COVERAGE_TEST
84361 SQLITE_PRIVATE void sqlite3Coverage(int x){
84362   static int dummy = 0;
84363   dummy += x;
84364 }
84365 #endif
84366
84367
84368 /*
84369 ** Return true if the buffer z[0..n-1] contains all spaces.
84370 */
84371 static int allSpaces(const char *z, int n){
84372   while( n>0 && z[n-1]==' ' ){ n--; }
84373   return n==0;
84374 }
84375
84376 /*
84377 ** This is the default collating function named "BINARY" which is always
84378 ** available.
84379 **
84380 ** If the padFlag argument is not NULL then space padding at the end
84381 ** of strings is ignored.  This implements the RTRIM collation.
84382 */
84383 static int binCollFunc(
84384   void *padFlag,
84385   int nKey1, const void *pKey1,
84386   int nKey2, const void *pKey2
84387 ){
84388   int rc, n;
84389   n = nKey1<nKey2 ? nKey1 : nKey2;
84390   rc = memcmp(pKey1, pKey2, n);
84391   if( rc==0 ){
84392     if( padFlag
84393      && allSpaces(((char*)pKey1)+n, nKey1-n)
84394      && allSpaces(((char*)pKey2)+n, nKey2-n)
84395     ){
84396       /* Leave rc unchanged at 0 */
84397     }else{
84398       rc = nKey1 - nKey2;
84399     }
84400   }
84401   return rc;
84402 }
84403
84404 /*
84405 ** Another built-in collating sequence: NOCASE. 
84406 **
84407 ** This collating sequence is intended to be used for "case independant
84408 ** comparison". SQLite's knowledge of upper and lower case equivalents
84409 ** extends only to the 26 characters used in the English language.
84410 **
84411 ** At the moment there is only a UTF-8 implementation.
84412 */
84413 static int nocaseCollatingFunc(
84414   void *NotUsed,
84415   int nKey1, const void *pKey1,
84416   int nKey2, const void *pKey2
84417 ){
84418   int r = sqlite3StrNICmp(
84419       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
84420   UNUSED_PARAMETER(NotUsed);
84421   if( 0==r ){
84422     r = nKey1-nKey2;
84423   }
84424   return r;
84425 }
84426
84427 /*
84428 ** Return the ROWID of the most recent insert
84429 */
84430 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
84431   return db->lastRowid;
84432 }
84433
84434 /*
84435 ** Return the number of changes in the most recent call to sqlite3_exec().
84436 */
84437 SQLITE_API int sqlite3_changes(sqlite3 *db){
84438   return db->nChange;
84439 }
84440
84441 /*
84442 ** Return the number of changes since the database handle was opened.
84443 */
84444 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
84445   return db->nTotalChange;
84446 }
84447
84448 /*
84449 ** Close an existing SQLite database
84450 */
84451 SQLITE_API int sqlite3_close(sqlite3 *db){
84452   HashElem *i;
84453   int j;
84454
84455   if( !db ){
84456     return SQLITE_OK;
84457   }
84458   if( !sqlite3SafetyCheckSickOrOk(db) ){
84459     return SQLITE_MISUSE;
84460   }
84461   sqlite3_mutex_enter(db->mutex);
84462
84463 #ifdef SQLITE_SSE
84464   {
84465     extern void sqlite3SseCleanup(sqlite3*);
84466     sqlite3SseCleanup(db);
84467   }
84468 #endif 
84469
84470   sqlite3ResetInternalSchema(db, 0);
84471
84472   /* If a transaction is open, the ResetInternalSchema() call above
84473   ** will not have called the xDisconnect() method on any virtual
84474   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
84475   ** call will do so. We need to do this before the check for active
84476   ** SQL statements below, as the v-table implementation may be storing
84477   ** some prepared statements internally.
84478   */
84479   sqlite3VtabRollback(db);
84480
84481   /* If there are any outstanding VMs, return SQLITE_BUSY. */
84482   if( db->pVdbe ){
84483     sqlite3Error(db, SQLITE_BUSY, 
84484         "Unable to close due to unfinalised statements");
84485     sqlite3_mutex_leave(db->mutex);
84486     return SQLITE_BUSY;
84487   }
84488   assert( sqlite3SafetyCheckSickOrOk(db) );
84489
84490   for(j=0; j<db->nDb; j++){
84491     struct Db *pDb = &db->aDb[j];
84492     if( pDb->pBt ){
84493       sqlite3BtreeClose(pDb->pBt);
84494       pDb->pBt = 0;
84495       if( j!=1 ){
84496         pDb->pSchema = 0;
84497       }
84498     }
84499   }
84500   sqlite3ResetInternalSchema(db, 0);
84501   assert( db->nDb<=2 );
84502   assert( db->aDb==db->aDbStatic );
84503   for(j=0; j<ArraySize(db->aFunc.a); j++){
84504     FuncDef *pNext, *pHash, *p;
84505     for(p=db->aFunc.a[j]; p; p=pHash){
84506       pHash = p->pHash;
84507       while( p ){
84508         pNext = p->pNext;
84509         sqlite3DbFree(db, p);
84510         p = pNext;
84511       }
84512     }
84513   }
84514   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
84515     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
84516     /* Invoke any destructors registered for collation sequence user data. */
84517     for(j=0; j<3; j++){
84518       if( pColl[j].xDel ){
84519         pColl[j].xDel(pColl[j].pUser);
84520       }
84521     }
84522     sqlite3DbFree(db, pColl);
84523   }
84524   sqlite3HashClear(&db->aCollSeq);
84525 #ifndef SQLITE_OMIT_VIRTUALTABLE
84526   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
84527     Module *pMod = (Module *)sqliteHashData(i);
84528     if( pMod->xDestroy ){
84529       pMod->xDestroy(pMod->pAux);
84530     }
84531     sqlite3DbFree(db, pMod);
84532   }
84533   sqlite3HashClear(&db->aModule);
84534 #endif
84535
84536   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
84537   if( db->pErr ){
84538     sqlite3ValueFree(db->pErr);
84539   }
84540   sqlite3CloseExtensions(db);
84541
84542   db->magic = SQLITE_MAGIC_ERROR;
84543
84544   /* The temp-database schema is allocated differently from the other schema
84545   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
84546   ** So it needs to be freed here. Todo: Why not roll the temp schema into
84547   ** the same sqliteMalloc() as the one that allocates the database 
84548   ** structure?
84549   */
84550   sqlite3DbFree(db, db->aDb[1].pSchema);
84551   sqlite3_mutex_leave(db->mutex);
84552   db->magic = SQLITE_MAGIC_CLOSED;
84553   sqlite3_mutex_free(db->mutex);
84554   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
84555   if( db->lookaside.bMalloced ){
84556     sqlite3_free(db->lookaside.pStart);
84557   }
84558   sqlite3_free(db);
84559   return SQLITE_OK;
84560 }
84561
84562 /*
84563 ** Rollback all database files.
84564 */
84565 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
84566   int i;
84567   int inTrans = 0;
84568   assert( sqlite3_mutex_held(db->mutex) );
84569   sqlite3BeginBenignMalloc();
84570   for(i=0; i<db->nDb; i++){
84571     if( db->aDb[i].pBt ){
84572       if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
84573         inTrans = 1;
84574       }
84575       sqlite3BtreeRollback(db->aDb[i].pBt);
84576       db->aDb[i].inTrans = 0;
84577     }
84578   }
84579   sqlite3VtabRollback(db);
84580   sqlite3EndBenignMalloc();
84581
84582   if( db->flags&SQLITE_InternChanges ){
84583     sqlite3ExpirePreparedStatements(db);
84584     sqlite3ResetInternalSchema(db, 0);
84585   }
84586
84587   /* If one has been configured, invoke the rollback-hook callback */
84588   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
84589     db->xRollbackCallback(db->pRollbackArg);
84590   }
84591 }
84592
84593 /*
84594 ** Return a static string that describes the kind of error specified in the
84595 ** argument.
84596 */
84597 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
84598   const char *z;
84599   switch( rc & 0xff ){
84600     case SQLITE_ROW:
84601     case SQLITE_DONE:
84602     case SQLITE_OK:         z = "not an error";                          break;
84603     case SQLITE_ERROR:      z = "SQL logic error or missing database";   break;
84604     case SQLITE_PERM:       z = "access permission denied";              break;
84605     case SQLITE_ABORT:      z = "callback requested query abort";        break;
84606     case SQLITE_BUSY:       z = "database is locked";                    break;
84607     case SQLITE_LOCKED:     z = "database table is locked";              break;
84608     case SQLITE_NOMEM:      z = "out of memory";                         break;
84609     case SQLITE_READONLY:   z = "attempt to write a readonly database";  break;
84610     case SQLITE_INTERRUPT:  z = "interrupted";                           break;
84611     case SQLITE_IOERR:      z = "disk I/O error";                        break;
84612     case SQLITE_CORRUPT:    z = "database disk image is malformed";      break;
84613     case SQLITE_FULL:       z = "database or disk is full";              break;
84614     case SQLITE_CANTOPEN:   z = "unable to open database file";          break;
84615     case SQLITE_EMPTY:      z = "table contains no data";                break;
84616     case SQLITE_SCHEMA:     z = "database schema has changed";           break;
84617     case SQLITE_TOOBIG:     z = "String or BLOB exceeded size limit";    break;
84618     case SQLITE_CONSTRAINT: z = "constraint failed";                     break;
84619     case SQLITE_MISMATCH:   z = "datatype mismatch";                     break;
84620     case SQLITE_MISUSE:     z = "library routine called out of sequence";break;
84621     case SQLITE_NOLFS:      z = "large file support is disabled";        break;
84622     case SQLITE_AUTH:       z = "authorization denied";                  break;
84623     case SQLITE_FORMAT:     z = "auxiliary database format error";       break;
84624     case SQLITE_RANGE:      z = "bind or column index out of range";     break;
84625     case SQLITE_NOTADB:     z = "file is encrypted or is not a database";break;
84626     default:                z = "unknown error";                         break;
84627   }
84628   return z;
84629 }
84630
84631 /*
84632 ** This routine implements a busy callback that sleeps and tries
84633 ** again until a timeout value is reached.  The timeout value is
84634 ** an integer number of milliseconds passed in as the first
84635 ** argument.
84636 */
84637 static int sqliteDefaultBusyCallback(
84638  void *ptr,               /* Database connection */
84639  int count                /* Number of times table has been busy */
84640 ){
84641 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
84642   static const u8 delays[] =
84643      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
84644   static const u8 totals[] =
84645      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
84646 # define NDELAY (sizeof(delays)/sizeof(delays[0]))
84647   sqlite3 *db = (sqlite3 *)ptr;
84648   int timeout = db->busyTimeout;
84649   int delay, prior;
84650
84651   assert( count>=0 );
84652   if( count < NDELAY ){
84653     delay = delays[count];
84654     prior = totals[count];
84655   }else{
84656     delay = delays[NDELAY-1];
84657     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
84658   }
84659   if( prior + delay > timeout ){
84660     delay = timeout - prior;
84661     if( delay<=0 ) return 0;
84662   }
84663   sqlite3OsSleep(db->pVfs, delay*1000);
84664   return 1;
84665 #else
84666   sqlite3 *db = (sqlite3 *)ptr;
84667   int timeout = ((sqlite3 *)ptr)->busyTimeout;
84668   if( (count+1)*1000 > timeout ){
84669     return 0;
84670   }
84671   sqlite3OsSleep(db->pVfs, 1000000);
84672   return 1;
84673 #endif
84674 }
84675
84676 /*
84677 ** Invoke the given busy handler.
84678 **
84679 ** This routine is called when an operation failed with a lock.
84680 ** If this routine returns non-zero, the lock is retried.  If it
84681 ** returns 0, the operation aborts with an SQLITE_BUSY error.
84682 */
84683 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
84684   int rc;
84685   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
84686   rc = p->xFunc(p->pArg, p->nBusy);
84687   if( rc==0 ){
84688     p->nBusy = -1;
84689   }else{
84690     p->nBusy++;
84691   }
84692   return rc; 
84693 }
84694
84695 /*
84696 ** This routine sets the busy callback for an Sqlite database to the
84697 ** given callback function with the given argument.
84698 */
84699 SQLITE_API int sqlite3_busy_handler(
84700   sqlite3 *db,
84701   int (*xBusy)(void*,int),
84702   void *pArg
84703 ){
84704   sqlite3_mutex_enter(db->mutex);
84705   db->busyHandler.xFunc = xBusy;
84706   db->busyHandler.pArg = pArg;
84707   db->busyHandler.nBusy = 0;
84708   sqlite3_mutex_leave(db->mutex);
84709   return SQLITE_OK;
84710 }
84711
84712 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
84713 /*
84714 ** This routine sets the progress callback for an Sqlite database to the
84715 ** given callback function with the given argument. The progress callback will
84716 ** be invoked every nOps opcodes.
84717 */
84718 SQLITE_API void sqlite3_progress_handler(
84719   sqlite3 *db, 
84720   int nOps,
84721   int (*xProgress)(void*), 
84722   void *pArg
84723 ){
84724   sqlite3_mutex_enter(db->mutex);
84725   if( nOps>0 ){
84726     db->xProgress = xProgress;
84727     db->nProgressOps = nOps;
84728     db->pProgressArg = pArg;
84729   }else{
84730     db->xProgress = 0;
84731     db->nProgressOps = 0;
84732     db->pProgressArg = 0;
84733   }
84734   sqlite3_mutex_leave(db->mutex);
84735 }
84736 #endif
84737
84738
84739 /*
84740 ** This routine installs a default busy handler that waits for the
84741 ** specified number of milliseconds before returning 0.
84742 */
84743 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
84744   if( ms>0 ){
84745     db->busyTimeout = ms;
84746     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
84747   }else{
84748     sqlite3_busy_handler(db, 0, 0);
84749   }
84750   return SQLITE_OK;
84751 }
84752
84753 /*
84754 ** Cause any pending operation to stop at its earliest opportunity.
84755 */
84756 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
84757   db->u1.isInterrupted = 1;
84758 }
84759
84760
84761 /*
84762 ** This function is exactly the same as sqlite3_create_function(), except
84763 ** that it is designed to be called by internal code. The difference is
84764 ** that if a malloc() fails in sqlite3_create_function(), an error code
84765 ** is returned and the mallocFailed flag cleared. 
84766 */
84767 SQLITE_PRIVATE int sqlite3CreateFunc(
84768   sqlite3 *db,
84769   const char *zFunctionName,
84770   int nArg,
84771   int enc,
84772   void *pUserData,
84773   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
84774   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
84775   void (*xFinal)(sqlite3_context*)
84776 ){
84777   FuncDef *p;
84778   int nName;
84779
84780   assert( sqlite3_mutex_held(db->mutex) );
84781   if( zFunctionName==0 ||
84782       (xFunc && (xFinal || xStep)) || 
84783       (!xFunc && (xFinal && !xStep)) ||
84784       (!xFunc && (!xFinal && xStep)) ||
84785       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
84786       (255<(nName = sqlite3Strlen(db, zFunctionName))) ){
84787     sqlite3Error(db, SQLITE_ERROR, "bad parameters");
84788     return SQLITE_ERROR;
84789   }
84790   
84791 #ifndef SQLITE_OMIT_UTF16
84792   /* If SQLITE_UTF16 is specified as the encoding type, transform this
84793   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
84794   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
84795   **
84796   ** If SQLITE_ANY is specified, add three versions of the function
84797   ** to the hash table.
84798   */
84799   if( enc==SQLITE_UTF16 ){
84800     enc = SQLITE_UTF16NATIVE;
84801   }else if( enc==SQLITE_ANY ){
84802     int rc;
84803     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
84804          pUserData, xFunc, xStep, xFinal);
84805     if( rc==SQLITE_OK ){
84806       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
84807           pUserData, xFunc, xStep, xFinal);
84808     }
84809     if( rc!=SQLITE_OK ){
84810       return rc;
84811     }
84812     enc = SQLITE_UTF16BE;
84813   }
84814 #else
84815   enc = SQLITE_UTF8;
84816 #endif
84817   
84818   /* Check if an existing function is being overridden or deleted. If so,
84819   ** and there are active VMs, then return SQLITE_BUSY. If a function
84820   ** is being overridden/deleted but there are no active VMs, allow the
84821   ** operation to continue but invalidate all precompiled statements.
84822   */
84823   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 0);
84824   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
84825     if( db->activeVdbeCnt ){
84826       sqlite3Error(db, SQLITE_BUSY, 
84827         "Unable to delete/modify user-function due to active statements");
84828       assert( !db->mallocFailed );
84829       return SQLITE_BUSY;
84830     }else{
84831       sqlite3ExpirePreparedStatements(db);
84832     }
84833   }
84834
84835   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 1);
84836   assert(p || db->mallocFailed);
84837   if( !p ){
84838     return SQLITE_NOMEM;
84839   }
84840   p->flags = 0;
84841   p->xFunc = xFunc;
84842   p->xStep = xStep;
84843   p->xFinalize = xFinal;
84844   p->pUserData = pUserData;
84845   p->nArg = nArg;
84846   return SQLITE_OK;
84847 }
84848
84849 /*
84850 ** Create new user functions.
84851 */
84852 SQLITE_API int sqlite3_create_function(
84853   sqlite3 *db,
84854   const char *zFunctionName,
84855   int nArg,
84856   int enc,
84857   void *p,
84858   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
84859   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
84860   void (*xFinal)(sqlite3_context*)
84861 ){
84862   int rc;
84863   sqlite3_mutex_enter(db->mutex);
84864   rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
84865   rc = sqlite3ApiExit(db, rc);
84866   sqlite3_mutex_leave(db->mutex);
84867   return rc;
84868 }
84869
84870 #ifndef SQLITE_OMIT_UTF16
84871 SQLITE_API int sqlite3_create_function16(
84872   sqlite3 *db,
84873   const void *zFunctionName,
84874   int nArg,
84875   int eTextRep,
84876   void *p,
84877   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
84878   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
84879   void (*xFinal)(sqlite3_context*)
84880 ){
84881   int rc;
84882   char *zFunc8;
84883   sqlite3_mutex_enter(db->mutex);
84884   assert( !db->mallocFailed );
84885   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1);
84886   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
84887   sqlite3DbFree(db, zFunc8);
84888   rc = sqlite3ApiExit(db, rc);
84889   sqlite3_mutex_leave(db->mutex);
84890   return rc;
84891 }
84892 #endif
84893
84894
84895 /*
84896 ** Declare that a function has been overloaded by a virtual table.
84897 **
84898 ** If the function already exists as a regular global function, then
84899 ** this routine is a no-op.  If the function does not exist, then create
84900 ** a new one that always throws a run-time error.  
84901 **
84902 ** When virtual tables intend to provide an overloaded function, they
84903 ** should call this routine to make sure the global function exists.
84904 ** A global function must exist in order for name resolution to work
84905 ** properly.
84906 */
84907 SQLITE_API int sqlite3_overload_function(
84908   sqlite3 *db,
84909   const char *zName,
84910   int nArg
84911 ){
84912   int nName = sqlite3Strlen(db, zName);
84913   int rc;
84914   sqlite3_mutex_enter(db->mutex);
84915   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
84916     sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
84917                       0, sqlite3InvalidFunction, 0, 0);
84918   }
84919   rc = sqlite3ApiExit(db, SQLITE_OK);
84920   sqlite3_mutex_leave(db->mutex);
84921   return rc;
84922 }
84923
84924 #ifndef SQLITE_OMIT_TRACE
84925 /*
84926 ** Register a trace function.  The pArg from the previously registered trace
84927 ** is returned.  
84928 **
84929 ** A NULL trace function means that no tracing is executes.  A non-NULL
84930 ** trace is a pointer to a function that is invoked at the start of each
84931 ** SQL statement.
84932 */
84933 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
84934   void *pOld;
84935   sqlite3_mutex_enter(db->mutex);
84936   pOld = db->pTraceArg;
84937   db->xTrace = xTrace;
84938   db->pTraceArg = pArg;
84939   sqlite3_mutex_leave(db->mutex);
84940   return pOld;
84941 }
84942 /*
84943 ** Register a profile function.  The pArg from the previously registered 
84944 ** profile function is returned.  
84945 **
84946 ** A NULL profile function means that no profiling is executes.  A non-NULL
84947 ** profile is a pointer to a function that is invoked at the conclusion of
84948 ** each SQL statement that is run.
84949 */
84950 SQLITE_API void *sqlite3_profile(
84951   sqlite3 *db,
84952   void (*xProfile)(void*,const char*,sqlite_uint64),
84953   void *pArg
84954 ){
84955   void *pOld;
84956   sqlite3_mutex_enter(db->mutex);
84957   pOld = db->pProfileArg;
84958   db->xProfile = xProfile;
84959   db->pProfileArg = pArg;
84960   sqlite3_mutex_leave(db->mutex);
84961   return pOld;
84962 }
84963 #endif /* SQLITE_OMIT_TRACE */
84964
84965 /*** EXPERIMENTAL ***
84966 **
84967 ** Register a function to be invoked when a transaction comments.
84968 ** If the invoked function returns non-zero, then the commit becomes a
84969 ** rollback.
84970 */
84971 SQLITE_API void *sqlite3_commit_hook(
84972   sqlite3 *db,              /* Attach the hook to this database */
84973   int (*xCallback)(void*),  /* Function to invoke on each commit */
84974   void *pArg                /* Argument to the function */
84975 ){
84976   void *pOld;
84977   sqlite3_mutex_enter(db->mutex);
84978   pOld = db->pCommitArg;
84979   db->xCommitCallback = xCallback;
84980   db->pCommitArg = pArg;
84981   sqlite3_mutex_leave(db->mutex);
84982   return pOld;
84983 }
84984
84985 /*
84986 ** Register a callback to be invoked each time a row is updated,
84987 ** inserted or deleted using this database connection.
84988 */
84989 SQLITE_API void *sqlite3_update_hook(
84990   sqlite3 *db,              /* Attach the hook to this database */
84991   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
84992   void *pArg                /* Argument to the function */
84993 ){
84994   void *pRet;
84995   sqlite3_mutex_enter(db->mutex);
84996   pRet = db->pUpdateArg;
84997   db->xUpdateCallback = xCallback;
84998   db->pUpdateArg = pArg;
84999   sqlite3_mutex_leave(db->mutex);
85000   return pRet;
85001 }
85002
85003 /*
85004 ** Register a callback to be invoked each time a transaction is rolled
85005 ** back by this database connection.
85006 */
85007 SQLITE_API void *sqlite3_rollback_hook(
85008   sqlite3 *db,              /* Attach the hook to this database */
85009   void (*xCallback)(void*), /* Callback function */
85010   void *pArg                /* Argument to the function */
85011 ){
85012   void *pRet;
85013   sqlite3_mutex_enter(db->mutex);
85014   pRet = db->pRollbackArg;
85015   db->xRollbackCallback = xCallback;
85016   db->pRollbackArg = pArg;
85017   sqlite3_mutex_leave(db->mutex);
85018   return pRet;
85019 }
85020
85021 /*
85022 ** This routine is called to create a connection to a database BTree
85023 ** driver.  If zFilename is the name of a file, then that file is
85024 ** opened and used.  If zFilename is the magic name ":memory:" then
85025 ** the database is stored in memory (and is thus forgotten as soon as
85026 ** the connection is closed.)  If zFilename is NULL then the database
85027 ** is a "virtual" database for transient use only and is deleted as
85028 ** soon as the connection is closed.
85029 **
85030 ** A virtual database can be either a disk file (that is automatically
85031 ** deleted when the file is closed) or it an be held entirely in memory,
85032 ** depending on the values of the SQLITE_TEMP_STORE compile-time macro and the
85033 ** db->temp_store variable, according to the following chart:
85034 **
85035 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
85036 **   -----------------     --------------     ------------------------------
85037 **   0                     any                file
85038 **   1                     1                  file
85039 **   1                     2                  memory
85040 **   1                     0                  file
85041 **   2                     1                  file
85042 **   2                     2                  memory
85043 **   2                     0                  memory
85044 **   3                     any                memory
85045 */
85046 SQLITE_PRIVATE int sqlite3BtreeFactory(
85047   const sqlite3 *db,        /* Main database when opening aux otherwise 0 */
85048   const char *zFilename,    /* Name of the file containing the BTree database */
85049   int omitJournal,          /* if TRUE then do not journal this file */
85050   int nCache,               /* How many pages in the page cache */
85051   int vfsFlags,             /* Flags passed through to vfsOpen */
85052   Btree **ppBtree           /* Pointer to new Btree object written here */
85053 ){
85054   int btFlags = 0;
85055   int rc;
85056   
85057   assert( sqlite3_mutex_held(db->mutex) );
85058   assert( ppBtree != 0);
85059   if( omitJournal ){
85060     btFlags |= BTREE_OMIT_JOURNAL;
85061   }
85062   if( db->flags & SQLITE_NoReadlock ){
85063     btFlags |= BTREE_NO_READLOCK;
85064   }
85065   if( zFilename==0 ){
85066 #if SQLITE_TEMP_STORE==0
85067     /* Do nothing */
85068 #endif
85069 #ifndef SQLITE_OMIT_MEMORYDB
85070 #if SQLITE_TEMP_STORE==1
85071     if( db->temp_store==2 ) zFilename = ":memory:";
85072 #endif
85073 #if SQLITE_TEMP_STORE==2
85074     if( db->temp_store!=1 ) zFilename = ":memory:";
85075 #endif
85076 #if SQLITE_TEMP_STORE==3
85077     zFilename = ":memory:";
85078 #endif
85079 #endif /* SQLITE_OMIT_MEMORYDB */
85080   }
85081
85082   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
85083     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
85084   }
85085   rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
85086
85087   /* If the B-Tree was successfully opened, set the pager-cache size to the
85088   ** default value. Except, if the call to BtreeOpen() returned a handle
85089   ** open on an existing shared pager-cache, do not change the pager-cache 
85090   ** size.
85091   */
85092   if( rc==SQLITE_OK && 0==sqlite3BtreeSchema(*ppBtree, 0, 0) ){
85093     sqlite3BtreeSetCacheSize(*ppBtree, nCache);
85094   }
85095   return rc;
85096 }
85097
85098 /*
85099 ** Return UTF-8 encoded English language explanation of the most recent
85100 ** error.
85101 */
85102 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
85103   const char *z;
85104   if( !db ){
85105     return sqlite3ErrStr(SQLITE_NOMEM);
85106   }
85107   if( !sqlite3SafetyCheckSickOrOk(db) ){
85108     return sqlite3ErrStr(SQLITE_MISUSE);
85109   }
85110   sqlite3_mutex_enter(db->mutex);
85111   assert( !db->mallocFailed );
85112   z = (char*)sqlite3_value_text(db->pErr);
85113   assert( !db->mallocFailed );
85114   if( z==0 ){
85115     z = sqlite3ErrStr(db->errCode);
85116   }
85117   sqlite3_mutex_leave(db->mutex);
85118   return z;
85119 }
85120
85121 #ifndef SQLITE_OMIT_UTF16
85122 /*
85123 ** Return UTF-16 encoded English language explanation of the most recent
85124 ** error.
85125 */
85126 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
85127   /* Because all the characters in the string are in the unicode
85128   ** range 0x00-0xFF, if we pad the big-endian string with a 
85129   ** zero byte, we can obtain the little-endian string with
85130   ** &big_endian[1].
85131   */
85132   static const char outOfMemBe[] = {
85133     0, 'o', 0, 'u', 0, 't', 0, ' ', 
85134     0, 'o', 0, 'f', 0, ' ', 
85135     0, 'm', 0, 'e', 0, 'm', 0, 'o', 0, 'r', 0, 'y', 0, 0, 0
85136   };
85137   static const char misuseBe [] = {
85138     0, 'l', 0, 'i', 0, 'b', 0, 'r', 0, 'a', 0, 'r', 0, 'y', 0, ' ', 
85139     0, 'r', 0, 'o', 0, 'u', 0, 't', 0, 'i', 0, 'n', 0, 'e', 0, ' ', 
85140     0, 'c', 0, 'a', 0, 'l', 0, 'l', 0, 'e', 0, 'd', 0, ' ', 
85141     0, 'o', 0, 'u', 0, 't', 0, ' ', 
85142     0, 'o', 0, 'f', 0, ' ', 
85143     0, 's', 0, 'e', 0, 'q', 0, 'u', 0, 'e', 0, 'n', 0, 'c', 0, 'e', 0, 0, 0
85144   };
85145
85146   const void *z;
85147   if( !db ){
85148     return (void *)(&outOfMemBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
85149   }
85150   if( !sqlite3SafetyCheckSickOrOk(db) ){
85151     return (void *)(&misuseBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
85152   }
85153   sqlite3_mutex_enter(db->mutex);
85154   assert( !db->mallocFailed );
85155   z = sqlite3_value_text16(db->pErr);
85156   if( z==0 ){
85157     sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
85158          SQLITE_UTF8, SQLITE_STATIC);
85159     z = sqlite3_value_text16(db->pErr);
85160   }
85161   /* A malloc() may have failed within the call to sqlite3_value_text16()
85162   ** above. If this is the case, then the db->mallocFailed flag needs to
85163   ** be cleared before returning. Do this directly, instead of via
85164   ** sqlite3ApiExit(), to avoid setting the database handle error message.
85165   */
85166   db->mallocFailed = 0;
85167   sqlite3_mutex_leave(db->mutex);
85168   return z;
85169 }
85170 #endif /* SQLITE_OMIT_UTF16 */
85171
85172 /*
85173 ** Return the most recent error code generated by an SQLite routine. If NULL is
85174 ** passed to this function, we assume a malloc() failed during sqlite3_open().
85175 */
85176 SQLITE_API int sqlite3_errcode(sqlite3 *db){
85177   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
85178     return SQLITE_MISUSE;
85179   }
85180   if( !db || db->mallocFailed ){
85181     return SQLITE_NOMEM;
85182   }
85183   return db->errCode & db->errMask;
85184 }
85185 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
85186   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
85187     return SQLITE_MISUSE;
85188   }
85189   if( !db || db->mallocFailed ){
85190     return SQLITE_NOMEM;
85191   }
85192   return db->errCode;
85193 }
85194
85195 /*
85196 ** Create a new collating function for database "db".  The name is zName
85197 ** and the encoding is enc.
85198 */
85199 static int createCollation(
85200   sqlite3* db, 
85201   const char *zName, 
85202   int enc, 
85203   void* pCtx,
85204   int(*xCompare)(void*,int,const void*,int,const void*),
85205   void(*xDel)(void*)
85206 ){
85207   CollSeq *pColl;
85208   int enc2;
85209   int nName;
85210   
85211   assert( sqlite3_mutex_held(db->mutex) );
85212
85213   /* If SQLITE_UTF16 is specified as the encoding type, transform this
85214   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
85215   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
85216   */
85217   enc2 = enc & ~SQLITE_UTF16_ALIGNED;
85218   if( enc2==SQLITE_UTF16 ){
85219     enc2 = SQLITE_UTF16NATIVE;
85220   }
85221   if( (enc2&~3)!=0 ){
85222     return SQLITE_MISUSE;
85223   }
85224
85225   /* Check if this call is removing or replacing an existing collation 
85226   ** sequence. If so, and there are active VMs, return busy. If there
85227   ** are no active VMs, invalidate any pre-compiled statements.
85228   */
85229   nName = sqlite3Strlen(db, zName);
85230   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, nName, 0);
85231   if( pColl && pColl->xCmp ){
85232     if( db->activeVdbeCnt ){
85233       sqlite3Error(db, SQLITE_BUSY, 
85234         "Unable to delete/modify collation sequence due to active statements");
85235       return SQLITE_BUSY;
85236     }
85237     sqlite3ExpirePreparedStatements(db);
85238
85239     /* If collation sequence pColl was created directly by a call to
85240     ** sqlite3_create_collation, and not generated by synthCollSeq(),
85241     ** then any copies made by synthCollSeq() need to be invalidated.
85242     ** Also, collation destructor - CollSeq.xDel() - function may need
85243     ** to be called.
85244     */ 
85245     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
85246       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
85247       int j;
85248       for(j=0; j<3; j++){
85249         CollSeq *p = &aColl[j];
85250         if( p->enc==pColl->enc ){
85251           if( p->xDel ){
85252             p->xDel(p->pUser);
85253           }
85254           p->xCmp = 0;
85255         }
85256       }
85257     }
85258   }
85259
85260   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, nName, 1);
85261   if( pColl ){
85262     pColl->xCmp = xCompare;
85263     pColl->pUser = pCtx;
85264     pColl->xDel = xDel;
85265     pColl->enc = enc2 | (enc & SQLITE_UTF16_ALIGNED);
85266   }
85267   sqlite3Error(db, SQLITE_OK, 0);
85268   return SQLITE_OK;
85269 }
85270
85271
85272 /*
85273 ** This array defines hard upper bounds on limit values.  The
85274 ** initializer must be kept in sync with the SQLITE_LIMIT_*
85275 ** #defines in sqlite3.h.
85276 */
85277 static const int aHardLimit[] = {
85278   SQLITE_MAX_LENGTH,
85279   SQLITE_MAX_SQL_LENGTH,
85280   SQLITE_MAX_COLUMN,
85281   SQLITE_MAX_EXPR_DEPTH,
85282   SQLITE_MAX_COMPOUND_SELECT,
85283   SQLITE_MAX_VDBE_OP,
85284   SQLITE_MAX_FUNCTION_ARG,
85285   SQLITE_MAX_ATTACHED,
85286   SQLITE_MAX_LIKE_PATTERN_LENGTH,
85287   SQLITE_MAX_VARIABLE_NUMBER,
85288 };
85289
85290 /*
85291 ** Make sure the hard limits are set to reasonable values
85292 */
85293 #if SQLITE_MAX_LENGTH<100
85294 # error SQLITE_MAX_LENGTH must be at least 100
85295 #endif
85296 #if SQLITE_MAX_SQL_LENGTH<100
85297 # error SQLITE_MAX_SQL_LENGTH must be at least 100
85298 #endif
85299 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
85300 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
85301 #endif
85302 #if SQLITE_MAX_COMPOUND_SELECT<2
85303 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
85304 #endif
85305 #if SQLITE_MAX_VDBE_OP<40
85306 # error SQLITE_MAX_VDBE_OP must be at least 40
85307 #endif
85308 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
85309 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
85310 #endif
85311 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>30
85312 # error SQLITE_MAX_ATTACHED must be between 0 and 30
85313 #endif
85314 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
85315 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
85316 #endif
85317 #if SQLITE_MAX_VARIABLE_NUMBER<1
85318 # error SQLITE_MAX_VARIABLE_NUMBER must be at least 1
85319 #endif
85320 #if SQLITE_MAX_COLUMN>32767
85321 # error SQLITE_MAX_COLUMN must not exceed 32767
85322 #endif
85323
85324
85325 /*
85326 ** Change the value of a limit.  Report the old value.
85327 ** If an invalid limit index is supplied, report -1.
85328 ** Make no changes but still report the old value if the
85329 ** new limit is negative.
85330 **
85331 ** A new lower limit does not shrink existing constructs.
85332 ** It merely prevents new constructs that exceed the limit
85333 ** from forming.
85334 */
85335 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
85336   int oldLimit;
85337   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
85338     return -1;
85339   }
85340   oldLimit = db->aLimit[limitId];
85341   if( newLimit>=0 ){
85342     if( newLimit>aHardLimit[limitId] ){
85343       newLimit = aHardLimit[limitId];
85344     }
85345     db->aLimit[limitId] = newLimit;
85346   }
85347   return oldLimit;
85348 }
85349
85350 /*
85351 ** This routine does the work of opening a database on behalf of
85352 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
85353 ** is UTF-8 encoded.
85354 */
85355 static int openDatabase(
85356   const char *zFilename, /* Database filename UTF-8 encoded */
85357   sqlite3 **ppDb,        /* OUT: Returned database handle */
85358   unsigned flags,        /* Operational flags */
85359   const char *zVfs       /* Name of the VFS to use */
85360 ){
85361   sqlite3 *db;
85362   int rc;
85363   CollSeq *pColl;
85364   int isThreadsafe;
85365
85366 #ifndef SQLITE_OMIT_AUTOINIT
85367   rc = sqlite3_initialize();
85368   if( rc ) return rc;
85369 #endif
85370
85371   if( sqlite3GlobalConfig.bCoreMutex==0 ){
85372     isThreadsafe = 0;
85373   }else if( flags & SQLITE_OPEN_NOMUTEX ){
85374     isThreadsafe = 0;
85375   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
85376     isThreadsafe = 1;
85377   }else{
85378     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
85379   }
85380
85381   /* Remove harmful bits from the flags parameter */
85382   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
85383                SQLITE_OPEN_MAIN_DB |
85384                SQLITE_OPEN_TEMP_DB | 
85385                SQLITE_OPEN_TRANSIENT_DB | 
85386                SQLITE_OPEN_MAIN_JOURNAL | 
85387                SQLITE_OPEN_TEMP_JOURNAL | 
85388                SQLITE_OPEN_SUBJOURNAL | 
85389                SQLITE_OPEN_MASTER_JOURNAL |
85390                SQLITE_OPEN_NOMUTEX |
85391                SQLITE_OPEN_FULLMUTEX
85392              );
85393
85394   /* Allocate the sqlite data structure */
85395   db = sqlite3MallocZero( sizeof(sqlite3) );
85396   if( db==0 ) goto opendb_out;
85397   if( isThreadsafe ){
85398     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
85399     if( db->mutex==0 ){
85400       sqlite3_free(db);
85401       db = 0;
85402       goto opendb_out;
85403     }
85404   }
85405   sqlite3_mutex_enter(db->mutex);
85406   db->errMask = 0xff;
85407   db->priorNewRowid = 0;
85408   db->nDb = 2;
85409   db->magic = SQLITE_MAGIC_BUSY;
85410   db->aDb = db->aDbStatic;
85411
85412   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
85413   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
85414   db->autoCommit = 1;
85415   db->nextAutovac = -1;
85416   db->nextPagesize = 0;
85417   db->flags |= SQLITE_ShortColNames
85418 #if SQLITE_DEFAULT_FILE_FORMAT<4
85419                  | SQLITE_LegacyFileFmt
85420 #endif
85421 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
85422                  | SQLITE_LoadExtension
85423 #endif
85424       ;
85425   sqlite3HashInit(&db->aCollSeq, 0);
85426 #ifndef SQLITE_OMIT_VIRTUALTABLE
85427   sqlite3HashInit(&db->aModule, 0);
85428 #endif
85429
85430   db->pVfs = sqlite3_vfs_find(zVfs);
85431   if( !db->pVfs ){
85432     rc = SQLITE_ERROR;
85433     sqlite3Error(db, rc, "no such vfs: %s", zVfs);
85434     goto opendb_out;
85435   }
85436
85437   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
85438   ** and UTF-16, so add a version for each to avoid any unnecessary
85439   ** conversions. The only error that can occur here is a malloc() failure.
85440   */
85441   createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
85442   createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
85443   createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
85444   createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
85445   if( db->mallocFailed ){
85446     goto opendb_out;
85447   }
85448   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0);
85449   assert( db->pDfltColl!=0 );
85450
85451   /* Also add a UTF-8 case-insensitive collation sequence. */
85452   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
85453
85454   /* Set flags on the built-in collating sequences */
85455   db->pDfltColl->type = SQLITE_COLL_BINARY;
85456   pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "NOCASE", 6, 0);
85457   if( pColl ){
85458     pColl->type = SQLITE_COLL_NOCASE;
85459   }
85460
85461   /* Open the backend database driver */
85462   db->openFlags = flags;
85463   rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE, 
85464                            flags | SQLITE_OPEN_MAIN_DB,
85465                            &db->aDb[0].pBt);
85466   if( rc!=SQLITE_OK ){
85467     if( rc==SQLITE_IOERR_NOMEM ){
85468       rc = SQLITE_NOMEM;
85469     }
85470     sqlite3Error(db, rc, 0);
85471     goto opendb_out;
85472   }
85473   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
85474   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
85475
85476
85477   /* The default safety_level for the main database is 'full'; for the temp
85478   ** database it is 'NONE'. This matches the pager layer defaults.  
85479   */
85480   db->aDb[0].zName = "main";
85481   db->aDb[0].safety_level = 3;
85482 #ifndef SQLITE_OMIT_TEMPDB
85483   db->aDb[1].zName = "temp";
85484   db->aDb[1].safety_level = 1;
85485 #endif
85486
85487   db->magic = SQLITE_MAGIC_OPEN;
85488   if( db->mallocFailed ){
85489     goto opendb_out;
85490   }
85491
85492   /* Register all built-in functions, but do not attempt to read the
85493   ** database schema yet. This is delayed until the first time the database
85494   ** is accessed.
85495   */
85496   sqlite3Error(db, SQLITE_OK, 0);
85497   sqlite3RegisterBuiltinFunctions(db);
85498
85499   /* Load automatic extensions - extensions that have been registered
85500   ** using the sqlite3_automatic_extension() API.
85501   */
85502   (void)sqlite3AutoLoadExtensions(db);
85503   if( sqlite3_errcode(db)!=SQLITE_OK ){
85504     goto opendb_out;
85505   }
85506
85507 #ifdef SQLITE_ENABLE_FTS1
85508   if( !db->mallocFailed ){
85509     extern int sqlite3Fts1Init(sqlite3*);
85510     rc = sqlite3Fts1Init(db);
85511   }
85512 #endif
85513
85514 #ifdef SQLITE_ENABLE_FTS2
85515   if( !db->mallocFailed && rc==SQLITE_OK ){
85516     extern int sqlite3Fts2Init(sqlite3*);
85517     rc = sqlite3Fts2Init(db);
85518   }
85519 #endif
85520
85521 #ifdef SQLITE_ENABLE_FTS3
85522   if( !db->mallocFailed && rc==SQLITE_OK ){
85523     rc = sqlite3Fts3Init(db);
85524   }
85525 #endif
85526
85527 #ifdef SQLITE_ENABLE_ICU
85528   if( !db->mallocFailed && rc==SQLITE_OK ){
85529     rc = sqlite3IcuInit(db);
85530   }
85531 #endif
85532
85533 #ifdef SQLITE_ENABLE_RTREE
85534   if( !db->mallocFailed && rc==SQLITE_OK){
85535     rc = sqlite3RtreeInit(db);
85536   }
85537 #endif
85538
85539   sqlite3Error(db, rc, 0);
85540
85541   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
85542   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
85543   ** mode.  Doing nothing at all also makes NORMAL the default.
85544   */
85545 #ifdef SQLITE_DEFAULT_LOCKING_MODE
85546   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
85547   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
85548                           SQLITE_DEFAULT_LOCKING_MODE);
85549 #endif
85550
85551   /* Enable the lookaside-malloc subsystem */
85552   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
85553                         sqlite3GlobalConfig.nLookaside);
85554
85555 opendb_out:
85556   if( db ){
85557     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
85558     sqlite3_mutex_leave(db->mutex);
85559   }
85560   rc = sqlite3_errcode(db);
85561   if( rc==SQLITE_NOMEM ){
85562     sqlite3_close(db);
85563     db = 0;
85564   }else if( rc!=SQLITE_OK ){
85565     db->magic = SQLITE_MAGIC_SICK;
85566   }
85567   *ppDb = db;
85568   return sqlite3ApiExit(0, rc);
85569 }
85570
85571 /*
85572 ** Open a new database handle.
85573 */
85574 SQLITE_API int sqlite3_open(
85575   const char *zFilename, 
85576   sqlite3 **ppDb 
85577 ){
85578   return openDatabase(zFilename, ppDb,
85579                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
85580 }
85581 SQLITE_API int sqlite3_open_v2(
85582   const char *filename,   /* Database filename (UTF-8) */
85583   sqlite3 **ppDb,         /* OUT: SQLite db handle */
85584   int flags,              /* Flags */
85585   const char *zVfs        /* Name of VFS module to use */
85586 ){
85587   return openDatabase(filename, ppDb, flags, zVfs);
85588 }
85589
85590 #ifndef SQLITE_OMIT_UTF16
85591 /*
85592 ** Open a new database handle.
85593 */
85594 SQLITE_API int sqlite3_open16(
85595   const void *zFilename, 
85596   sqlite3 **ppDb
85597 ){
85598   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
85599   sqlite3_value *pVal;
85600   int rc;
85601
85602   assert( zFilename );
85603   assert( ppDb );
85604   *ppDb = 0;
85605 #ifndef SQLITE_OMIT_AUTOINIT
85606   rc = sqlite3_initialize();
85607   if( rc ) return rc;
85608 #endif
85609   pVal = sqlite3ValueNew(0);
85610   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
85611   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
85612   if( zFilename8 ){
85613     rc = openDatabase(zFilename8, ppDb,
85614                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
85615     assert( *ppDb || rc==SQLITE_NOMEM );
85616     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
85617       ENC(*ppDb) = SQLITE_UTF16NATIVE;
85618     }
85619   }else{
85620     rc = SQLITE_NOMEM;
85621   }
85622   sqlite3ValueFree(pVal);
85623
85624   return sqlite3ApiExit(0, rc);
85625 }
85626 #endif /* SQLITE_OMIT_UTF16 */
85627
85628 /*
85629 ** Register a new collation sequence with the database handle db.
85630 */
85631 SQLITE_API int sqlite3_create_collation(
85632   sqlite3* db, 
85633   const char *zName, 
85634   int enc, 
85635   void* pCtx,
85636   int(*xCompare)(void*,int,const void*,int,const void*)
85637 ){
85638   int rc;
85639   sqlite3_mutex_enter(db->mutex);
85640   assert( !db->mallocFailed );
85641   rc = createCollation(db, zName, enc, pCtx, xCompare, 0);
85642   rc = sqlite3ApiExit(db, rc);
85643   sqlite3_mutex_leave(db->mutex);
85644   return rc;
85645 }
85646
85647 /*
85648 ** Register a new collation sequence with the database handle db.
85649 */
85650 SQLITE_API int sqlite3_create_collation_v2(
85651   sqlite3* db, 
85652   const char *zName, 
85653   int enc, 
85654   void* pCtx,
85655   int(*xCompare)(void*,int,const void*,int,const void*),
85656   void(*xDel)(void*)
85657 ){
85658   int rc;
85659   sqlite3_mutex_enter(db->mutex);
85660   assert( !db->mallocFailed );
85661   rc = createCollation(db, zName, enc, pCtx, xCompare, xDel);
85662   rc = sqlite3ApiExit(db, rc);
85663   sqlite3_mutex_leave(db->mutex);
85664   return rc;
85665 }
85666
85667 #ifndef SQLITE_OMIT_UTF16
85668 /*
85669 ** Register a new collation sequence with the database handle db.
85670 */
85671 SQLITE_API int sqlite3_create_collation16(
85672   sqlite3* db, 
85673   const void *zName,
85674   int enc, 
85675   void* pCtx,
85676   int(*xCompare)(void*,int,const void*,int,const void*)
85677 ){
85678   int rc = SQLITE_OK;
85679   char *zName8;
85680   sqlite3_mutex_enter(db->mutex);
85681   assert( !db->mallocFailed );
85682   zName8 = sqlite3Utf16to8(db, zName, -1);
85683   if( zName8 ){
85684     rc = createCollation(db, zName8, enc, pCtx, xCompare, 0);
85685     sqlite3DbFree(db, zName8);
85686   }
85687   rc = sqlite3ApiExit(db, rc);
85688   sqlite3_mutex_leave(db->mutex);
85689   return rc;
85690 }
85691 #endif /* SQLITE_OMIT_UTF16 */
85692
85693 /*
85694 ** Register a collation sequence factory callback with the database handle
85695 ** db. Replace any previously installed collation sequence factory.
85696 */
85697 SQLITE_API int sqlite3_collation_needed(
85698   sqlite3 *db, 
85699   void *pCollNeededArg, 
85700   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
85701 ){
85702   sqlite3_mutex_enter(db->mutex);
85703   db->xCollNeeded = xCollNeeded;
85704   db->xCollNeeded16 = 0;
85705   db->pCollNeededArg = pCollNeededArg;
85706   sqlite3_mutex_leave(db->mutex);
85707   return SQLITE_OK;
85708 }
85709
85710 #ifndef SQLITE_OMIT_UTF16
85711 /*
85712 ** Register a collation sequence factory callback with the database handle
85713 ** db. Replace any previously installed collation sequence factory.
85714 */
85715 SQLITE_API int sqlite3_collation_needed16(
85716   sqlite3 *db, 
85717   void *pCollNeededArg, 
85718   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
85719 ){
85720   sqlite3_mutex_enter(db->mutex);
85721   db->xCollNeeded = 0;
85722   db->xCollNeeded16 = xCollNeeded16;
85723   db->pCollNeededArg = pCollNeededArg;
85724   sqlite3_mutex_leave(db->mutex);
85725   return SQLITE_OK;
85726 }
85727 #endif /* SQLITE_OMIT_UTF16 */
85728
85729 #ifndef SQLITE_OMIT_GLOBALRECOVER
85730 #ifndef SQLITE_OMIT_DEPRECATED
85731 /*
85732 ** This function is now an anachronism. It used to be used to recover from a
85733 ** malloc() failure, but SQLite now does this automatically.
85734 */
85735 SQLITE_API int sqlite3_global_recover(void){
85736   return SQLITE_OK;
85737 }
85738 #endif
85739 #endif
85740
85741 /*
85742 ** Test to see whether or not the database connection is in autocommit
85743 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
85744 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
85745 ** by the next COMMIT or ROLLBACK.
85746 **
85747 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
85748 */
85749 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
85750   return db->autoCommit;
85751 }
85752
85753 #ifdef SQLITE_DEBUG
85754 /*
85755 ** The following routine is subtituted for constant SQLITE_CORRUPT in
85756 ** debugging builds.  This provides a way to set a breakpoint for when
85757 ** corruption is first detected.
85758 */
85759 SQLITE_PRIVATE int sqlite3Corrupt(void){
85760   return SQLITE_CORRUPT;
85761 }
85762 #endif
85763
85764 #ifndef SQLITE_OMIT_DEPRECATED
85765 /*
85766 ** This is a convenience routine that makes sure that all thread-specific
85767 ** data for this thread has been deallocated.
85768 **
85769 ** SQLite no longer uses thread-specific data so this routine is now a
85770 ** no-op.  It is retained for historical compatibility.
85771 */
85772 SQLITE_API void sqlite3_thread_cleanup(void){
85773 }
85774 #endif
85775
85776 /*
85777 ** Return meta information about a specific column of a database table.
85778 ** See comment in sqlite3.h (sqlite.h.in) for details.
85779 */
85780 #ifdef SQLITE_ENABLE_COLUMN_METADATA
85781 SQLITE_API int sqlite3_table_column_metadata(
85782   sqlite3 *db,                /* Connection handle */
85783   const char *zDbName,        /* Database name or NULL */
85784   const char *zTableName,     /* Table name */
85785   const char *zColumnName,    /* Column name */
85786   char const **pzDataType,    /* OUTPUT: Declared data type */
85787   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
85788   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
85789   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
85790   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
85791 ){
85792   int rc;
85793   char *zErrMsg = 0;
85794   Table *pTab = 0;
85795   Column *pCol = 0;
85796   int iCol;
85797
85798   char const *zDataType = 0;
85799   char const *zCollSeq = 0;
85800   int notnull = 0;
85801   int primarykey = 0;
85802   int autoinc = 0;
85803
85804   /* Ensure the database schema has been loaded */
85805   sqlite3_mutex_enter(db->mutex);
85806   (void)sqlite3SafetyOn(db);
85807   sqlite3BtreeEnterAll(db);
85808   rc = sqlite3Init(db, &zErrMsg);
85809   sqlite3BtreeLeaveAll(db);
85810   if( SQLITE_OK!=rc ){
85811     goto error_out;
85812   }
85813
85814   /* Locate the table in question */
85815   pTab = sqlite3FindTable(db, zTableName, zDbName);
85816   if( !pTab || pTab->pSelect ){
85817     pTab = 0;
85818     goto error_out;
85819   }
85820
85821   /* Find the column for which info is requested */
85822   if( sqlite3IsRowid(zColumnName) ){
85823     iCol = pTab->iPKey;
85824     if( iCol>=0 ){
85825       pCol = &pTab->aCol[iCol];
85826     }
85827   }else{
85828     for(iCol=0; iCol<pTab->nCol; iCol++){
85829       pCol = &pTab->aCol[iCol];
85830       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
85831         break;
85832       }
85833     }
85834     if( iCol==pTab->nCol ){
85835       pTab = 0;
85836       goto error_out;
85837     }
85838   }
85839
85840   /* The following block stores the meta information that will be returned
85841   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
85842   ** and autoinc. At this point there are two possibilities:
85843   ** 
85844   **     1. The specified column name was rowid", "oid" or "_rowid_" 
85845   **        and there is no explicitly declared IPK column. 
85846   **
85847   **     2. The table is not a view and the column name identified an 
85848   **        explicitly declared column. Copy meta information from *pCol.
85849   */ 
85850   if( pCol ){
85851     zDataType = pCol->zType;
85852     zCollSeq = pCol->zColl;
85853     notnull = pCol->notNull!=0;
85854     primarykey  = pCol->isPrimKey!=0;
85855     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
85856   }else{
85857     zDataType = "INTEGER";
85858     primarykey = 1;
85859   }
85860   if( !zCollSeq ){
85861     zCollSeq = "BINARY";
85862   }
85863
85864 error_out:
85865   (void)sqlite3SafetyOff(db);
85866
85867   /* Whether the function call succeeded or failed, set the output parameters
85868   ** to whatever their local counterparts contain. If an error did occur,
85869   ** this has the effect of zeroing all output parameters.
85870   */
85871   if( pzDataType ) *pzDataType = zDataType;
85872   if( pzCollSeq ) *pzCollSeq = zCollSeq;
85873   if( pNotNull ) *pNotNull = notnull;
85874   if( pPrimaryKey ) *pPrimaryKey = primarykey;
85875   if( pAutoinc ) *pAutoinc = autoinc;
85876
85877   if( SQLITE_OK==rc && !pTab ){
85878     sqlite3DbFree(db, zErrMsg);
85879     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
85880         zColumnName);
85881     rc = SQLITE_ERROR;
85882   }
85883   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
85884   sqlite3DbFree(db, zErrMsg);
85885   rc = sqlite3ApiExit(db, rc);
85886   sqlite3_mutex_leave(db->mutex);
85887   return rc;
85888 }
85889 #endif
85890
85891 /*
85892 ** Sleep for a little while.  Return the amount of time slept.
85893 */
85894 SQLITE_API int sqlite3_sleep(int ms){
85895   sqlite3_vfs *pVfs;
85896   int rc;
85897   pVfs = sqlite3_vfs_find(0);
85898   if( pVfs==0 ) return 0;
85899
85900   /* This function works in milliseconds, but the underlying OsSleep() 
85901   ** API uses microseconds. Hence the 1000's.
85902   */
85903   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
85904   return rc;
85905 }
85906
85907 /*
85908 ** Enable or disable the extended result codes.
85909 */
85910 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
85911   sqlite3_mutex_enter(db->mutex);
85912   db->errMask = onoff ? 0xffffffff : 0xff;
85913   sqlite3_mutex_leave(db->mutex);
85914   return SQLITE_OK;
85915 }
85916
85917 /*
85918 ** Invoke the xFileControl method on a particular database.
85919 */
85920 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
85921   int rc = SQLITE_ERROR;
85922   int iDb;
85923   sqlite3_mutex_enter(db->mutex);
85924   if( zDbName==0 ){
85925     iDb = 0;
85926   }else{
85927     for(iDb=0; iDb<db->nDb; iDb++){
85928       if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
85929     }
85930   }
85931   if( iDb<db->nDb ){
85932     Btree *pBtree = db->aDb[iDb].pBt;
85933     if( pBtree ){
85934       Pager *pPager;
85935       sqlite3_file *fd;
85936       sqlite3BtreeEnter(pBtree);
85937       pPager = sqlite3BtreePager(pBtree);
85938       assert( pPager!=0 );
85939       fd = sqlite3PagerFile(pPager);
85940       assert( fd!=0 );
85941       if( fd->pMethods ){
85942         rc = sqlite3OsFileControl(fd, op, pArg);
85943       }
85944       sqlite3BtreeLeave(pBtree);
85945     }
85946   }
85947   sqlite3_mutex_leave(db->mutex);
85948   return rc;   
85949 }
85950
85951 /*
85952 ** Interface to the testing logic.
85953 */
85954 SQLITE_API int sqlite3_test_control(int op, ...){
85955   int rc = 0;
85956 #ifndef SQLITE_OMIT_BUILTIN_TEST
85957   va_list ap;
85958   va_start(ap, op);
85959   switch( op ){
85960
85961     /*
85962     ** Save the current state of the PRNG.
85963     */
85964     case SQLITE_TESTCTRL_PRNG_SAVE: {
85965       sqlite3PrngSaveState();
85966       break;
85967     }
85968
85969     /*
85970     ** Restore the state of the PRNG to the last state saved using
85971     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
85972     ** this verb acts like PRNG_RESET.
85973     */
85974     case SQLITE_TESTCTRL_PRNG_RESTORE: {
85975       sqlite3PrngRestoreState();
85976       break;
85977     }
85978
85979     /*
85980     ** Reset the PRNG back to its uninitialized state.  The next call
85981     ** to sqlite3_randomness() will reseed the PRNG using a single call
85982     ** to the xRandomness method of the default VFS.
85983     */
85984     case SQLITE_TESTCTRL_PRNG_RESET: {
85985       sqlite3PrngResetState();
85986       break;
85987     }
85988
85989     /*
85990     **  sqlite3_test_control(BITVEC_TEST, size, program)
85991     **
85992     ** Run a test against a Bitvec object of size.  The program argument
85993     ** is an array of integers that defines the test.  Return -1 on a
85994     ** memory allocation error, 0 on success, or non-zero for an error.
85995     ** See the sqlite3BitvecBuiltinTest() for additional information.
85996     */
85997     case SQLITE_TESTCTRL_BITVEC_TEST: {
85998       int sz = va_arg(ap, int);
85999       int *aProg = va_arg(ap, int*);
86000       rc = sqlite3BitvecBuiltinTest(sz, aProg);
86001       break;
86002     }
86003
86004     /*
86005     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
86006     **
86007     ** Register hooks to call to indicate which malloc() failures 
86008     ** are benign.
86009     */
86010     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
86011       typedef void (*void_function)(void);
86012       void_function xBenignBegin;
86013       void_function xBenignEnd;
86014       xBenignBegin = va_arg(ap, void_function);
86015       xBenignEnd = va_arg(ap, void_function);
86016       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
86017       break;
86018     }
86019   }
86020   va_end(ap);
86021 #endif /* SQLITE_OMIT_BUILTIN_TEST */
86022   return rc;
86023 }
86024
86025 /************** End of main.c ************************************************/
86026 /************** Begin file fts3.c ********************************************/
86027 /*
86028 ** 2006 Oct 10
86029 **
86030 ** The author disclaims copyright to this source code.  In place of
86031 ** a legal notice, here is a blessing:
86032 **
86033 **    May you do good and not evil.
86034 **    May you find forgiveness for yourself and forgive others.
86035 **    May you share freely, never taking more than you give.
86036 **
86037 ******************************************************************************
86038 **
86039 ** This is an SQLite module implementing full-text search.
86040 */
86041
86042 /*
86043 ** The code in this file is only compiled if:
86044 **
86045 **     * The FTS3 module is being built as an extension
86046 **       (in which case SQLITE_CORE is not defined), or
86047 **
86048 **     * The FTS3 module is being built into the core of
86049 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
86050 */
86051
86052 /* TODO(shess) Consider exporting this comment to an HTML file or the
86053 ** wiki.
86054 */
86055 /* The full-text index is stored in a series of b+tree (-like)
86056 ** structures called segments which map terms to doclists.  The
86057 ** structures are like b+trees in layout, but are constructed from the
86058 ** bottom up in optimal fashion and are not updatable.  Since trees
86059 ** are built from the bottom up, things will be described from the
86060 ** bottom up.
86061 **
86062 **
86063 **** Varints ****
86064 ** The basic unit of encoding is a variable-length integer called a
86065 ** varint.  We encode variable-length integers in little-endian order
86066 ** using seven bits * per byte as follows:
86067 **
86068 ** KEY:
86069 **         A = 0xxxxxxx    7 bits of data and one flag bit
86070 **         B = 1xxxxxxx    7 bits of data and one flag bit
86071 **
86072 **  7 bits - A
86073 ** 14 bits - BA
86074 ** 21 bits - BBA
86075 ** and so on.
86076 **
86077 ** This is identical to how sqlite encodes varints (see util.c).
86078 **
86079 **
86080 **** Document lists ****
86081 ** A doclist (document list) holds a docid-sorted list of hits for a
86082 ** given term.  Doclists hold docids, and can optionally associate
86083 ** token positions and offsets with docids.
86084 **
86085 ** A DL_POSITIONS_OFFSETS doclist is stored like this:
86086 **
86087 ** array {
86088 **   varint docid;
86089 **   array {                (position list for column 0)
86090 **     varint position;     (delta from previous position plus POS_BASE)
86091 **     varint startOffset;  (delta from previous startOffset)
86092 **     varint endOffset;    (delta from startOffset)
86093 **   }
86094 **   array {
86095 **     varint POS_COLUMN;   (marks start of position list for new column)
86096 **     varint column;       (index of new column)
86097 **     array {
86098 **       varint position;   (delta from previous position plus POS_BASE)
86099 **       varint startOffset;(delta from previous startOffset)
86100 **       varint endOffset;  (delta from startOffset)
86101 **     }
86102 **   }
86103 **   varint POS_END;        (marks end of positions for this document.
86104 ** }
86105 **
86106 ** Here, array { X } means zero or more occurrences of X, adjacent in
86107 ** memory.  A "position" is an index of a token in the token stream
86108 ** generated by the tokenizer, while an "offset" is a byte offset,
86109 ** both based at 0.  Note that POS_END and POS_COLUMN occur in the
86110 ** same logical place as the position element, and act as sentinals
86111 ** ending a position list array.
86112 **
86113 ** A DL_POSITIONS doclist omits the startOffset and endOffset
86114 ** information.  A DL_DOCIDS doclist omits both the position and
86115 ** offset information, becoming an array of varint-encoded docids.
86116 **
86117 ** On-disk data is stored as type DL_DEFAULT, so we don't serialize
86118 ** the type.  Due to how deletion is implemented in the segmentation
86119 ** system, on-disk doclists MUST store at least positions.
86120 **
86121 **
86122 **** Segment leaf nodes ****
86123 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
86124 ** nodes are written using LeafWriter, and read using LeafReader (to
86125 ** iterate through a single leaf node's data) and LeavesReader (to
86126 ** iterate through a segment's entire leaf layer).  Leaf nodes have
86127 ** the format:
86128 **
86129 ** varint iHeight;             (height from leaf level, always 0)
86130 ** varint nTerm;               (length of first term)
86131 ** char pTerm[nTerm];          (content of first term)
86132 ** varint nDoclist;            (length of term's associated doclist)
86133 ** char pDoclist[nDoclist];    (content of doclist)
86134 ** array {
86135 **                             (further terms are delta-encoded)
86136 **   varint nPrefix;           (length of prefix shared with previous term)
86137 **   varint nSuffix;           (length of unshared suffix)
86138 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
86139 **   varint nDoclist;          (length of term's associated doclist)
86140 **   char pDoclist[nDoclist];  (content of doclist)
86141 ** }
86142 **
86143 ** Here, array { X } means zero or more occurrences of X, adjacent in
86144 ** memory.
86145 **
86146 ** Leaf nodes are broken into blocks which are stored contiguously in
86147 ** the %_segments table in sorted order.  This means that when the end
86148 ** of a node is reached, the next term is in the node with the next
86149 ** greater node id.
86150 **
86151 ** New data is spilled to a new leaf node when the current node
86152 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
86153 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
86154 ** node (a leaf node with a single term and doclist).  The goal of
86155 ** these settings is to pack together groups of small doclists while
86156 ** making it efficient to directly access large doclists.  The
86157 ** assumption is that large doclists represent terms which are more
86158 ** likely to be query targets.
86159 **
86160 ** TODO(shess) It may be useful for blocking decisions to be more
86161 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
86162 ** node rather than splitting into 2k and .5k nodes.  My intuition is
86163 ** that this might extend through 2x or 4x the pagesize.
86164 **
86165 **
86166 **** Segment interior nodes ****
86167 ** Segment interior nodes store blockids for subtree nodes and terms
86168 ** to describe what data is stored by the each subtree.  Interior
86169 ** nodes are written using InteriorWriter, and read using
86170 ** InteriorReader.  InteriorWriters are created as needed when
86171 ** SegmentWriter creates new leaf nodes, or when an interior node
86172 ** itself grows too big and must be split.  The format of interior
86173 ** nodes:
86174 **
86175 ** varint iHeight;           (height from leaf level, always >0)
86176 ** varint iBlockid;          (block id of node's leftmost subtree)
86177 ** optional {
86178 **   varint nTerm;           (length of first term)
86179 **   char pTerm[nTerm];      (content of first term)
86180 **   array {
86181 **                                (further terms are delta-encoded)
86182 **     varint nPrefix;            (length of shared prefix with previous term)
86183 **     varint nSuffix;            (length of unshared suffix)
86184 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
86185 **   }
86186 ** }
86187 **
86188 ** Here, optional { X } means an optional element, while array { X }
86189 ** means zero or more occurrences of X, adjacent in memory.
86190 **
86191 ** An interior node encodes n terms separating n+1 subtrees.  The
86192 ** subtree blocks are contiguous, so only the first subtree's blockid
86193 ** is encoded.  The subtree at iBlockid will contain all terms less
86194 ** than the first term encoded (or all terms if no term is encoded).
86195 ** Otherwise, for terms greater than or equal to pTerm[i] but less
86196 ** than pTerm[i+1], the subtree for that term will be rooted at
86197 ** iBlockid+i.  Interior nodes only store enough term data to
86198 ** distinguish adjacent children (if the rightmost term of the left
86199 ** child is "something", and the leftmost term of the right child is
86200 ** "wicked", only "w" is stored).
86201 **
86202 ** New data is spilled to a new interior node at the same height when
86203 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
86204 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
86205 ** interior nodes and making the tree too skinny.  The interior nodes
86206 ** at a given height are naturally tracked by interior nodes at
86207 ** height+1, and so on.
86208 **
86209 **
86210 **** Segment directory ****
86211 ** The segment directory in table %_segdir stores meta-information for
86212 ** merging and deleting segments, and also the root node of the
86213 ** segment's tree.
86214 **
86215 ** The root node is the top node of the segment's tree after encoding
86216 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
86217 ** This could be either a leaf node or an interior node.  If the top
86218 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
86219 ** and a new root interior node is generated (which should always fit
86220 ** within ROOT_MAX because it only needs space for 2 varints, the
86221 ** height and the blockid of the previous root).
86222 **
86223 ** The meta-information in the segment directory is:
86224 **   level               - segment level (see below)
86225 **   idx                 - index within level
86226 **                       - (level,idx uniquely identify a segment)
86227 **   start_block         - first leaf node
86228 **   leaves_end_block    - last leaf node
86229 **   end_block           - last block (including interior nodes)
86230 **   root                - contents of root node
86231 **
86232 ** If the root node is a leaf node, then start_block,
86233 ** leaves_end_block, and end_block are all 0.
86234 **
86235 **
86236 **** Segment merging ****
86237 ** To amortize update costs, segments are groups into levels and
86238 ** merged in matches.  Each increase in level represents exponentially
86239 ** more documents.
86240 **
86241 ** New documents (actually, document updates) are tokenized and
86242 ** written individually (using LeafWriter) to a level 0 segment, with
86243 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
86244 ** level 0 segments are merged into a single level 1 segment.  Level 1
86245 ** is populated like level 0, and eventually MERGE_COUNT level 1
86246 ** segments are merged to a single level 2 segment (representing
86247 ** MERGE_COUNT^2 updates), and so on.
86248 **
86249 ** A segment merge traverses all segments at a given level in
86250 ** parallel, performing a straightforward sorted merge.  Since segment
86251 ** leaf nodes are written in to the %_segments table in order, this
86252 ** merge traverses the underlying sqlite disk structures efficiently.
86253 ** After the merge, all segment blocks from the merged level are
86254 ** deleted.
86255 **
86256 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
86257 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
86258 ** very similar performance numbers to 16 on insertion, though they're
86259 ** a tiny bit slower (perhaps due to more overhead in merge-time
86260 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
86261 ** 16, 2 about 66% slower than 16.
86262 **
86263 ** At query time, high MERGE_COUNT increases the number of segments
86264 ** which need to be scanned and merged.  For instance, with 100k docs
86265 ** inserted:
86266 **
86267 **    MERGE_COUNT   segments
86268 **       16           25
86269 **        8           12
86270 **        4           10
86271 **        2            6
86272 **
86273 ** This appears to have only a moderate impact on queries for very
86274 ** frequent terms (which are somewhat dominated by segment merge
86275 ** costs), and infrequent and non-existent terms still seem to be fast
86276 ** even with many segments.
86277 **
86278 ** TODO(shess) That said, it would be nice to have a better query-side
86279 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
86280 ** optimizations to things like doclist merging will swing the sweet
86281 ** spot around.
86282 **
86283 **
86284 **
86285 **** Handling of deletions and updates ****
86286 ** Since we're using a segmented structure, with no docid-oriented
86287 ** index into the term index, we clearly cannot simply update the term
86288 ** index when a document is deleted or updated.  For deletions, we
86289 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
86290 ** we simply write the new doclist.  Segment merges overwrite older
86291 ** data for a particular docid with newer data, so deletes or updates
86292 ** will eventually overtake the earlier data and knock it out.  The
86293 ** query logic likewise merges doclists so that newer data knocks out
86294 ** older data.
86295 **
86296 ** TODO(shess) Provide a VACUUM type operation to clear out all
86297 ** deletions and duplications.  This would basically be a forced merge
86298 ** into a single segment.
86299 */
86300
86301 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
86302
86303 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
86304 # define SQLITE_CORE 1
86305 #endif
86306
86307
86308 /************** Include fts3_hash.h in the middle of fts3.c ******************/
86309 /************** Begin file fts3_hash.h ***************************************/
86310 /*
86311 ** 2001 September 22
86312 **
86313 ** The author disclaims copyright to this source code.  In place of
86314 ** a legal notice, here is a blessing:
86315 **
86316 **    May you do good and not evil.
86317 **    May you find forgiveness for yourself and forgive others.
86318 **    May you share freely, never taking more than you give.
86319 **
86320 *************************************************************************
86321 ** This is the header file for the generic hash-table implemenation
86322 ** used in SQLite.  We've modified it slightly to serve as a standalone
86323 ** hash table implementation for the full-text indexing module.
86324 **
86325 */
86326 #ifndef _FTS3_HASH_H_
86327 #define _FTS3_HASH_H_
86328
86329 /* Forward declarations of structures. */
86330 typedef struct fts3Hash fts3Hash;
86331 typedef struct fts3HashElem fts3HashElem;
86332
86333 /* A complete hash table is an instance of the following structure.
86334 ** The internals of this structure are intended to be opaque -- client
86335 ** code should not attempt to access or modify the fields of this structure
86336 ** directly.  Change this structure only by using the routines below.
86337 ** However, many of the "procedures" and "functions" for modifying and
86338 ** accessing this structure are really macros, so we can't really make
86339 ** this structure opaque.
86340 */
86341 struct fts3Hash {
86342   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
86343   char copyKey;           /* True if copy of key made on insert */
86344   int count;              /* Number of entries in this table */
86345   fts3HashElem *first;    /* The first element of the array */
86346   int htsize;             /* Number of buckets in the hash table */
86347   struct _fts3ht {        /* the hash table */
86348     int count;               /* Number of entries with this hash */
86349     fts3HashElem *chain;     /* Pointer to first entry with this hash */
86350   } *ht;
86351 };
86352
86353 /* Each element in the hash table is an instance of the following 
86354 ** structure.  All elements are stored on a single doubly-linked list.
86355 **
86356 ** Again, this structure is intended to be opaque, but it can't really
86357 ** be opaque because it is used by macros.
86358 */
86359 struct fts3HashElem {
86360   fts3HashElem *next, *prev; /* Next and previous elements in the table */
86361   void *data;                /* Data associated with this element */
86362   void *pKey; int nKey;      /* Key associated with this element */
86363 };
86364
86365 /*
86366 ** There are 2 different modes of operation for a hash table:
86367 **
86368 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
86369 **                           (including the null-terminator, if any).  Case
86370 **                           is respected in comparisons.
86371 **
86372 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
86373 **                           memcmp() is used to compare keys.
86374 **
86375 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
86376 */
86377 #define FTS3_HASH_STRING    1
86378 #define FTS3_HASH_BINARY    2
86379
86380 /*
86381 ** Access routines.  To delete, insert a NULL pointer.
86382 */
86383 SQLITE_PRIVATE void sqlite3Fts3HashInit(fts3Hash*, int keytype, int copyKey);
86384 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(fts3Hash*, const void *pKey, int nKey, void *pData);
86385 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const fts3Hash*, const void *pKey, int nKey);
86386 SQLITE_PRIVATE void sqlite3Fts3HashClear(fts3Hash*);
86387
86388 /*
86389 ** Shorthand for the functions above
86390 */
86391 #define fts3HashInit   sqlite3Fts3HashInit
86392 #define fts3HashInsert sqlite3Fts3HashInsert
86393 #define fts3HashFind   sqlite3Fts3HashFind
86394 #define fts3HashClear  sqlite3Fts3HashClear
86395
86396 /*
86397 ** Macros for looping over all elements of a hash table.  The idiom is
86398 ** like this:
86399 **
86400 **   fts3Hash h;
86401 **   fts3HashElem *p;
86402 **   ...
86403 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
86404 **     SomeStructure *pData = fts3HashData(p);
86405 **     // do something with pData
86406 **   }
86407 */
86408 #define fts3HashFirst(H)  ((H)->first)
86409 #define fts3HashNext(E)   ((E)->next)
86410 #define fts3HashData(E)   ((E)->data)
86411 #define fts3HashKey(E)    ((E)->pKey)
86412 #define fts3HashKeysize(E) ((E)->nKey)
86413
86414 /*
86415 ** Number of entries in a hash table
86416 */
86417 #define fts3HashCount(H)  ((H)->count)
86418
86419 #endif /* _FTS3_HASH_H_ */
86420
86421 /************** End of fts3_hash.h *******************************************/
86422 /************** Continuing where we left off in fts3.c ***********************/
86423 /************** Include fts3_tokenizer.h in the middle of fts3.c *************/
86424 /************** Begin file fts3_tokenizer.h **********************************/
86425 /*
86426 ** 2006 July 10
86427 **
86428 ** The author disclaims copyright to this source code.
86429 **
86430 *************************************************************************
86431 ** Defines the interface to tokenizers used by fulltext-search.  There
86432 ** are three basic components:
86433 **
86434 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
86435 ** interface functions.  This is essentially the class structure for
86436 ** tokenizers.
86437 **
86438 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
86439 ** including customization information defined at creation time.
86440 **
86441 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
86442 ** tokens from a particular input.
86443 */
86444 #ifndef _FTS3_TOKENIZER_H_
86445 #define _FTS3_TOKENIZER_H_
86446
86447 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
86448 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
86449 ** we will need a way to register the API consistently.
86450 */
86451
86452 /*
86453 ** Structures used by the tokenizer interface. When a new tokenizer
86454 ** implementation is registered, the caller provides a pointer to
86455 ** an sqlite3_tokenizer_module containing pointers to the callback
86456 ** functions that make up an implementation.
86457 **
86458 ** When an fts3 table is created, it passes any arguments passed to
86459 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
86460 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
86461 ** implementation. The xCreate() function in turn returns an 
86462 ** sqlite3_tokenizer structure representing the specific tokenizer to
86463 ** be used for the fts3 table (customized by the tokenizer clause arguments).
86464 **
86465 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
86466 ** method is called. It returns an sqlite3_tokenizer_cursor object
86467 ** that may be used to tokenize a specific input buffer based on
86468 ** the tokenization rules supplied by a specific sqlite3_tokenizer
86469 ** object.
86470 */
86471 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
86472 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
86473 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
86474
86475 struct sqlite3_tokenizer_module {
86476
86477   /*
86478   ** Structure version. Should always be set to 0.
86479   */
86480   int iVersion;
86481
86482   /*
86483   ** Create a new tokenizer. The values in the argv[] array are the
86484   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
86485   ** TABLE statement that created the fts3 table. For example, if
86486   ** the following SQL is executed:
86487   **
86488   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
86489   **
86490   ** then argc is set to 2, and the argv[] array contains pointers
86491   ** to the strings "arg1" and "arg2".
86492   **
86493   ** This method should return either SQLITE_OK (0), or an SQLite error 
86494   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
86495   ** to point at the newly created tokenizer structure. The generic
86496   ** sqlite3_tokenizer.pModule variable should not be initialised by
86497   ** this callback. The caller will do so.
86498   */
86499   int (*xCreate)(
86500     int argc,                           /* Size of argv array */
86501     const char *const*argv,             /* Tokenizer argument strings */
86502     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
86503   );
86504
86505   /*
86506   ** Destroy an existing tokenizer. The fts3 module calls this method
86507   ** exactly once for each successful call to xCreate().
86508   */
86509   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
86510
86511   /*
86512   ** Create a tokenizer cursor to tokenize an input buffer. The caller
86513   ** is responsible for ensuring that the input buffer remains valid
86514   ** until the cursor is closed (using the xClose() method). 
86515   */
86516   int (*xOpen)(
86517     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
86518     const char *pInput, int nBytes,      /* Input buffer */
86519     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
86520   );
86521
86522   /*
86523   ** Destroy an existing tokenizer cursor. The fts3 module calls this 
86524   ** method exactly once for each successful call to xOpen().
86525   */
86526   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
86527
86528   /*
86529   ** Retrieve the next token from the tokenizer cursor pCursor. This
86530   ** method should either return SQLITE_OK and set the values of the
86531   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
86532   ** the end of the buffer has been reached, or an SQLite error code.
86533   **
86534   ** *ppToken should be set to point at a buffer containing the 
86535   ** normalized version of the token (i.e. after any case-folding and/or
86536   ** stemming has been performed). *pnBytes should be set to the length
86537   ** of this buffer in bytes. The input text that generated the token is
86538   ** identified by the byte offsets returned in *piStartOffset and
86539   ** *piEndOffset.
86540   **
86541   ** The buffer *ppToken is set to point at is managed by the tokenizer
86542   ** implementation. It is only required to be valid until the next call
86543   ** to xNext() or xClose(). 
86544   */
86545   /* TODO(shess) current implementation requires pInput to be
86546   ** nul-terminated.  This should either be fixed, or pInput/nBytes
86547   ** should be converted to zInput.
86548   */
86549   int (*xNext)(
86550     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
86551     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
86552     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
86553     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
86554     int *piPosition      /* OUT: Number of tokens returned before this one */
86555   );
86556 };
86557
86558 struct sqlite3_tokenizer {
86559   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
86560   /* Tokenizer implementations will typically add additional fields */
86561 };
86562
86563 struct sqlite3_tokenizer_cursor {
86564   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
86565   /* Tokenizer implementations will typically add additional fields */
86566 };
86567
86568 #endif /* _FTS3_TOKENIZER_H_ */
86569
86570 /************** End of fts3_tokenizer.h **************************************/
86571 /************** Continuing where we left off in fts3.c ***********************/
86572 #ifndef SQLITE_CORE 
86573   SQLITE_EXTENSION_INIT1
86574 #endif
86575
86576
86577 /* TODO(shess) MAN, this thing needs some refactoring.  At minimum, it
86578 ** would be nice to order the file better, perhaps something along the
86579 ** lines of:
86580 **
86581 **  - utility functions
86582 **  - table setup functions
86583 **  - table update functions
86584 **  - table query functions
86585 **
86586 ** Put the query functions last because they're likely to reference
86587 ** typedefs or functions from the table update section.
86588 */
86589
86590 #if 0
86591 # define FTSTRACE(A)  printf A; fflush(stdout)
86592 #else
86593 # define FTSTRACE(A)
86594 #endif
86595
86596 /*
86597 ** Default span for NEAR operators.
86598 */
86599 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
86600
86601 /* It is not safe to call isspace(), tolower(), or isalnum() on
86602 ** hi-bit-set characters.  This is the same solution used in the
86603 ** tokenizer.
86604 */
86605 /* TODO(shess) The snippet-generation code should be using the
86606 ** tokenizer-generated tokens rather than doing its own local
86607 ** tokenization.
86608 */
86609 /* TODO(shess) Is __isascii() a portable version of (c&0x80)==0? */
86610 static int safe_isspace(char c){
86611   return (c&0x80)==0 ? isspace(c) : 0;
86612 }
86613 static int safe_tolower(char c){
86614   return (c&0x80)==0 ? tolower(c) : c;
86615 }
86616 static int safe_isalnum(char c){
86617   return (c&0x80)==0 ? isalnum(c) : 0;
86618 }
86619
86620 typedef enum DocListType {
86621   DL_DOCIDS,              /* docids only */
86622   DL_POSITIONS,           /* docids + positions */
86623   DL_POSITIONS_OFFSETS    /* docids + positions + offsets */
86624 } DocListType;
86625
86626 /*
86627 ** By default, only positions and not offsets are stored in the doclists.
86628 ** To change this so that offsets are stored too, compile with
86629 **
86630 **          -DDL_DEFAULT=DL_POSITIONS_OFFSETS
86631 **
86632 ** If DL_DEFAULT is set to DL_DOCIDS, your table can only be inserted
86633 ** into (no deletes or updates).
86634 */
86635 #ifndef DL_DEFAULT
86636 # define DL_DEFAULT DL_POSITIONS
86637 #endif
86638
86639 enum {
86640   POS_END = 0,        /* end of this position list */
86641   POS_COLUMN,         /* followed by new column number */
86642   POS_BASE
86643 };
86644
86645 /* MERGE_COUNT controls how often we merge segments (see comment at
86646 ** top of file).
86647 */
86648 #define MERGE_COUNT 16
86649
86650 /* utility functions */
86651
86652 /* CLEAR() and SCRAMBLE() abstract memset() on a pointer to a single
86653 ** record to prevent errors of the form:
86654 **
86655 ** my_function(SomeType *b){
86656 **   memset(b, '\0', sizeof(b));  // sizeof(b)!=sizeof(*b)
86657 ** }
86658 */
86659 /* TODO(shess) Obvious candidates for a header file. */
86660 #define CLEAR(b) memset(b, '\0', sizeof(*(b)))
86661
86662 #ifndef NDEBUG
86663 #  define SCRAMBLE(b) memset(b, 0x55, sizeof(*(b)))
86664 #else
86665 #  define SCRAMBLE(b)
86666 #endif
86667
86668 /* We may need up to VARINT_MAX bytes to store an encoded 64-bit integer. */
86669 #define VARINT_MAX 10
86670
86671 /* Write a 64-bit variable-length integer to memory starting at p[0].
86672  * The length of data written will be between 1 and VARINT_MAX bytes.
86673  * The number of bytes written is returned. */
86674 static int fts3PutVarint(char *p, sqlite_int64 v){
86675   unsigned char *q = (unsigned char *) p;
86676   sqlite_uint64 vu = v;
86677   do{
86678     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
86679     vu >>= 7;
86680   }while( vu!=0 );
86681   q[-1] &= 0x7f;  /* turn off high bit in final byte */
86682   assert( q - (unsigned char *)p <= VARINT_MAX );
86683   return (int) (q - (unsigned char *)p);
86684 }
86685
86686 /* Read a 64-bit variable-length integer from memory starting at p[0].
86687  * Return the number of bytes read, or 0 on error.
86688  * The value is stored in *v. */
86689 static int fts3GetVarint(const char *p, sqlite_int64 *v){
86690   const unsigned char *q = (const unsigned char *) p;
86691   sqlite_uint64 x = 0, y = 1;
86692   while( (*q & 0x80) == 0x80 ){
86693     x += y * (*q++ & 0x7f);
86694     y <<= 7;
86695     if( q - (unsigned char *)p >= VARINT_MAX ){  /* bad data */
86696       assert( 0 );
86697       return 0;
86698     }
86699   }
86700   x += y * (*q++);
86701   *v = (sqlite_int64) x;
86702   return (int) (q - (unsigned char *)p);
86703 }
86704
86705 static int fts3GetVarint32(const char *p, int *pi){
86706  sqlite_int64 i;
86707  int ret = fts3GetVarint(p, &i);
86708  *pi = (int) i;
86709  assert( *pi==i );
86710  return ret;
86711 }
86712
86713 /*******************************************************************/
86714 /* DataBuffer is used to collect data into a buffer in piecemeal
86715 ** fashion.  It implements the usual distinction between amount of
86716 ** data currently stored (nData) and buffer capacity (nCapacity).
86717 **
86718 ** dataBufferInit - create a buffer with given initial capacity.
86719 ** dataBufferReset - forget buffer's data, retaining capacity.
86720 ** dataBufferDestroy - free buffer's data.
86721 ** dataBufferSwap - swap contents of two buffers.
86722 ** dataBufferExpand - expand capacity without adding data.
86723 ** dataBufferAppend - append data.
86724 ** dataBufferAppend2 - append two pieces of data at once.
86725 ** dataBufferReplace - replace buffer's data.
86726 */
86727 typedef struct DataBuffer {
86728   char *pData;          /* Pointer to malloc'ed buffer. */
86729   int nCapacity;        /* Size of pData buffer. */
86730   int nData;            /* End of data loaded into pData. */
86731 } DataBuffer;
86732
86733 static void dataBufferInit(DataBuffer *pBuffer, int nCapacity){
86734   assert( nCapacity>=0 );
86735   pBuffer->nData = 0;
86736   pBuffer->nCapacity = nCapacity;
86737   pBuffer->pData = nCapacity==0 ? NULL : sqlite3_malloc(nCapacity);
86738 }
86739 static void dataBufferReset(DataBuffer *pBuffer){
86740   pBuffer->nData = 0;
86741 }
86742 static void dataBufferDestroy(DataBuffer *pBuffer){
86743   if( pBuffer->pData!=NULL ) sqlite3_free(pBuffer->pData);
86744   SCRAMBLE(pBuffer);
86745 }
86746 static void dataBufferSwap(DataBuffer *pBuffer1, DataBuffer *pBuffer2){
86747   DataBuffer tmp = *pBuffer1;
86748   *pBuffer1 = *pBuffer2;
86749   *pBuffer2 = tmp;
86750 }
86751 static void dataBufferExpand(DataBuffer *pBuffer, int nAddCapacity){
86752   assert( nAddCapacity>0 );
86753   /* TODO(shess) Consider expanding more aggressively.  Note that the
86754   ** underlying malloc implementation may take care of such things for
86755   ** us already.
86756   */
86757   if( pBuffer->nData+nAddCapacity>pBuffer->nCapacity ){
86758     pBuffer->nCapacity = pBuffer->nData+nAddCapacity;
86759     pBuffer->pData = sqlite3_realloc(pBuffer->pData, pBuffer->nCapacity);
86760   }
86761 }
86762 static void dataBufferAppend(DataBuffer *pBuffer,
86763                              const char *pSource, int nSource){
86764   assert( nSource>0 && pSource!=NULL );
86765   dataBufferExpand(pBuffer, nSource);
86766   memcpy(pBuffer->pData+pBuffer->nData, pSource, nSource);
86767   pBuffer->nData += nSource;
86768 }
86769 static void dataBufferAppend2(DataBuffer *pBuffer,
86770                               const char *pSource1, int nSource1,
86771                               const char *pSource2, int nSource2){
86772   assert( nSource1>0 && pSource1!=NULL );
86773   assert( nSource2>0 && pSource2!=NULL );
86774   dataBufferExpand(pBuffer, nSource1+nSource2);
86775   memcpy(pBuffer->pData+pBuffer->nData, pSource1, nSource1);
86776   memcpy(pBuffer->pData+pBuffer->nData+nSource1, pSource2, nSource2);
86777   pBuffer->nData += nSource1+nSource2;
86778 }
86779 static void dataBufferReplace(DataBuffer *pBuffer,
86780                               const char *pSource, int nSource){
86781   dataBufferReset(pBuffer);
86782   dataBufferAppend(pBuffer, pSource, nSource);
86783 }
86784
86785 /* StringBuffer is a null-terminated version of DataBuffer. */
86786 typedef struct StringBuffer {
86787   DataBuffer b;            /* Includes null terminator. */
86788 } StringBuffer;
86789
86790 static void initStringBuffer(StringBuffer *sb){
86791   dataBufferInit(&sb->b, 100);
86792   dataBufferReplace(&sb->b, "", 1);
86793 }
86794 static int stringBufferLength(StringBuffer *sb){
86795   return sb->b.nData-1;
86796 }
86797 static char *stringBufferData(StringBuffer *sb){
86798   return sb->b.pData;
86799 }
86800 static void stringBufferDestroy(StringBuffer *sb){
86801   dataBufferDestroy(&sb->b);
86802 }
86803
86804 static void nappend(StringBuffer *sb, const char *zFrom, int nFrom){
86805   assert( sb->b.nData>0 );
86806   if( nFrom>0 ){
86807     sb->b.nData--;
86808     dataBufferAppend2(&sb->b, zFrom, nFrom, "", 1);
86809   }
86810 }
86811 static void append(StringBuffer *sb, const char *zFrom){
86812   nappend(sb, zFrom, strlen(zFrom));
86813 }
86814
86815 /* Append a list of strings separated by commas. */
86816 static void appendList(StringBuffer *sb, int nString, char **azString){
86817   int i;
86818   for(i=0; i<nString; ++i){
86819     if( i>0 ) append(sb, ", ");
86820     append(sb, azString[i]);
86821   }
86822 }
86823
86824 static int endsInWhiteSpace(StringBuffer *p){
86825   return stringBufferLength(p)>0 &&
86826     safe_isspace(stringBufferData(p)[stringBufferLength(p)-1]);
86827 }
86828
86829 /* If the StringBuffer ends in something other than white space, add a
86830 ** single space character to the end.
86831 */
86832 static void appendWhiteSpace(StringBuffer *p){
86833   if( stringBufferLength(p)==0 ) return;
86834   if( !endsInWhiteSpace(p) ) append(p, " ");
86835 }
86836
86837 /* Remove white space from the end of the StringBuffer */
86838 static void trimWhiteSpace(StringBuffer *p){
86839   while( endsInWhiteSpace(p) ){
86840     p->b.pData[--p->b.nData-1] = '\0';
86841   }
86842 }
86843
86844 /*******************************************************************/
86845 /* DLReader is used to read document elements from a doclist.  The
86846 ** current docid is cached, so dlrDocid() is fast.  DLReader does not
86847 ** own the doclist buffer.
86848 **
86849 ** dlrAtEnd - true if there's no more data to read.
86850 ** dlrDocid - docid of current document.
86851 ** dlrDocData - doclist data for current document (including docid).
86852 ** dlrDocDataBytes - length of same.
86853 ** dlrAllDataBytes - length of all remaining data.
86854 ** dlrPosData - position data for current document.
86855 ** dlrPosDataLen - length of pos data for current document (incl POS_END).
86856 ** dlrStep - step to current document.
86857 ** dlrInit - initial for doclist of given type against given data.
86858 ** dlrDestroy - clean up.
86859 **
86860 ** Expected usage is something like:
86861 **
86862 **   DLReader reader;
86863 **   dlrInit(&reader, pData, nData);
86864 **   while( !dlrAtEnd(&reader) ){
86865 **     // calls to dlrDocid() and kin.
86866 **     dlrStep(&reader);
86867 **   }
86868 **   dlrDestroy(&reader);
86869 */
86870 typedef struct DLReader {
86871   DocListType iType;
86872   const char *pData;
86873   int nData;
86874
86875   sqlite_int64 iDocid;
86876   int nElement;
86877 } DLReader;
86878
86879 static int dlrAtEnd(DLReader *pReader){
86880   assert( pReader->nData>=0 );
86881   return pReader->nData==0;
86882 }
86883 static sqlite_int64 dlrDocid(DLReader *pReader){
86884   assert( !dlrAtEnd(pReader) );
86885   return pReader->iDocid;
86886 }
86887 static const char *dlrDocData(DLReader *pReader){
86888   assert( !dlrAtEnd(pReader) );
86889   return pReader->pData;
86890 }
86891 static int dlrDocDataBytes(DLReader *pReader){
86892   assert( !dlrAtEnd(pReader) );
86893   return pReader->nElement;
86894 }
86895 static int dlrAllDataBytes(DLReader *pReader){
86896   assert( !dlrAtEnd(pReader) );
86897   return pReader->nData;
86898 }
86899 /* TODO(shess) Consider adding a field to track iDocid varint length
86900 ** to make these two functions faster.  This might matter (a tiny bit)
86901 ** for queries.
86902 */
86903 static const char *dlrPosData(DLReader *pReader){
86904   sqlite_int64 iDummy;
86905   int n = fts3GetVarint(pReader->pData, &iDummy);
86906   assert( !dlrAtEnd(pReader) );
86907   return pReader->pData+n;
86908 }
86909 static int dlrPosDataLen(DLReader *pReader){
86910   sqlite_int64 iDummy;
86911   int n = fts3GetVarint(pReader->pData, &iDummy);
86912   assert( !dlrAtEnd(pReader) );
86913   return pReader->nElement-n;
86914 }
86915 static void dlrStep(DLReader *pReader){
86916   assert( !dlrAtEnd(pReader) );
86917
86918   /* Skip past current doclist element. */
86919   assert( pReader->nElement<=pReader->nData );
86920   pReader->pData += pReader->nElement;
86921   pReader->nData -= pReader->nElement;
86922
86923   /* If there is more data, read the next doclist element. */
86924   if( pReader->nData!=0 ){
86925     sqlite_int64 iDocidDelta;
86926     int iDummy, n = fts3GetVarint(pReader->pData, &iDocidDelta);
86927     pReader->iDocid += iDocidDelta;
86928     if( pReader->iType>=DL_POSITIONS ){
86929       assert( n<pReader->nData );
86930       while( 1 ){
86931         n += fts3GetVarint32(pReader->pData+n, &iDummy);
86932         assert( n<=pReader->nData );
86933         if( iDummy==POS_END ) break;
86934         if( iDummy==POS_COLUMN ){
86935           n += fts3GetVarint32(pReader->pData+n, &iDummy);
86936           assert( n<pReader->nData );
86937         }else if( pReader->iType==DL_POSITIONS_OFFSETS ){
86938           n += fts3GetVarint32(pReader->pData+n, &iDummy);
86939           n += fts3GetVarint32(pReader->pData+n, &iDummy);
86940           assert( n<pReader->nData );
86941         }
86942       }
86943     }
86944     pReader->nElement = n;
86945     assert( pReader->nElement<=pReader->nData );
86946   }
86947 }
86948 static void dlrInit(DLReader *pReader, DocListType iType,
86949                     const char *pData, int nData){
86950   assert( pData!=NULL && nData!=0 );
86951   pReader->iType = iType;
86952   pReader->pData = pData;
86953   pReader->nData = nData;
86954   pReader->nElement = 0;
86955   pReader->iDocid = 0;
86956
86957   /* Load the first element's data.  There must be a first element. */
86958   dlrStep(pReader);
86959 }
86960 static void dlrDestroy(DLReader *pReader){
86961   SCRAMBLE(pReader);
86962 }
86963
86964 #ifndef NDEBUG
86965 /* Verify that the doclist can be validly decoded.  Also returns the
86966 ** last docid found because it is convenient in other assertions for
86967 ** DLWriter.
86968 */
86969 static void docListValidate(DocListType iType, const char *pData, int nData,
86970                             sqlite_int64 *pLastDocid){
86971   sqlite_int64 iPrevDocid = 0;
86972   assert( nData>0 );
86973   assert( pData!=0 );
86974   assert( pData+nData>pData );
86975   while( nData!=0 ){
86976     sqlite_int64 iDocidDelta;
86977     int n = fts3GetVarint(pData, &iDocidDelta);
86978     iPrevDocid += iDocidDelta;
86979     if( iType>DL_DOCIDS ){
86980       int iDummy;
86981       while( 1 ){
86982         n += fts3GetVarint32(pData+n, &iDummy);
86983         if( iDummy==POS_END ) break;
86984         if( iDummy==POS_COLUMN ){
86985           n += fts3GetVarint32(pData+n, &iDummy);
86986         }else if( iType>DL_POSITIONS ){
86987           n += fts3GetVarint32(pData+n, &iDummy);
86988           n += fts3GetVarint32(pData+n, &iDummy);
86989         }
86990         assert( n<=nData );
86991       }
86992     }
86993     assert( n<=nData );
86994     pData += n;
86995     nData -= n;
86996   }
86997   if( pLastDocid ) *pLastDocid = iPrevDocid;
86998 }
86999 #define ASSERT_VALID_DOCLIST(i, p, n, o) docListValidate(i, p, n, o)
87000 #else
87001 #define ASSERT_VALID_DOCLIST(i, p, n, o) assert( 1 )
87002 #endif
87003
87004 /*******************************************************************/
87005 /* DLWriter is used to write doclist data to a DataBuffer.  DLWriter
87006 ** always appends to the buffer and does not own it.
87007 **
87008 ** dlwInit - initialize to write a given type doclistto a buffer.
87009 ** dlwDestroy - clear the writer's memory.  Does not free buffer.
87010 ** dlwAppend - append raw doclist data to buffer.
87011 ** dlwCopy - copy next doclist from reader to writer.
87012 ** dlwAdd - construct doclist element and append to buffer.
87013 **    Only apply dlwAdd() to DL_DOCIDS doclists (else use PLWriter).
87014 */
87015 typedef struct DLWriter {
87016   DocListType iType;
87017   DataBuffer *b;
87018   sqlite_int64 iPrevDocid;
87019 #ifndef NDEBUG
87020   int has_iPrevDocid;
87021 #endif
87022 } DLWriter;
87023
87024 static void dlwInit(DLWriter *pWriter, DocListType iType, DataBuffer *b){
87025   pWriter->b = b;
87026   pWriter->iType = iType;
87027   pWriter->iPrevDocid = 0;
87028 #ifndef NDEBUG
87029   pWriter->has_iPrevDocid = 0;
87030 #endif
87031 }
87032 static void dlwDestroy(DLWriter *pWriter){
87033   SCRAMBLE(pWriter);
87034 }
87035 /* iFirstDocid is the first docid in the doclist in pData.  It is
87036 ** needed because pData may point within a larger doclist, in which
87037 ** case the first item would be delta-encoded.
87038 **
87039 ** iLastDocid is the final docid in the doclist in pData.  It is
87040 ** needed to create the new iPrevDocid for future delta-encoding.  The
87041 ** code could decode the passed doclist to recreate iLastDocid, but
87042 ** the only current user (docListMerge) already has decoded this
87043 ** information.
87044 */
87045 /* TODO(shess) This has become just a helper for docListMerge.
87046 ** Consider a refactor to make this cleaner.
87047 */
87048 static void dlwAppend(DLWriter *pWriter,
87049                       const char *pData, int nData,
87050                       sqlite_int64 iFirstDocid, sqlite_int64 iLastDocid){
87051   sqlite_int64 iDocid = 0;
87052   char c[VARINT_MAX];
87053   int nFirstOld, nFirstNew;     /* Old and new varint len of first docid. */
87054 #ifndef NDEBUG
87055   sqlite_int64 iLastDocidDelta;
87056 #endif
87057
87058   /* Recode the initial docid as delta from iPrevDocid. */
87059   nFirstOld = fts3GetVarint(pData, &iDocid);
87060   assert( nFirstOld<nData || (nFirstOld==nData && pWriter->iType==DL_DOCIDS) );
87061   nFirstNew = fts3PutVarint(c, iFirstDocid-pWriter->iPrevDocid);
87062
87063   /* Verify that the incoming doclist is valid AND that it ends with
87064   ** the expected docid.  This is essential because we'll trust this
87065   ** docid in future delta-encoding.
87066   */
87067   ASSERT_VALID_DOCLIST(pWriter->iType, pData, nData, &iLastDocidDelta);
87068   assert( iLastDocid==iFirstDocid-iDocid+iLastDocidDelta );
87069
87070   /* Append recoded initial docid and everything else.  Rest of docids
87071   ** should have been delta-encoded from previous initial docid.
87072   */
87073   if( nFirstOld<nData ){
87074     dataBufferAppend2(pWriter->b, c, nFirstNew,
87075                       pData+nFirstOld, nData-nFirstOld);
87076   }else{
87077     dataBufferAppend(pWriter->b, c, nFirstNew);
87078   }
87079   pWriter->iPrevDocid = iLastDocid;
87080 }
87081 static void dlwCopy(DLWriter *pWriter, DLReader *pReader){
87082   dlwAppend(pWriter, dlrDocData(pReader), dlrDocDataBytes(pReader),
87083             dlrDocid(pReader), dlrDocid(pReader));
87084 }
87085 static void dlwAdd(DLWriter *pWriter, sqlite_int64 iDocid){
87086   char c[VARINT_MAX];
87087   int n = fts3PutVarint(c, iDocid-pWriter->iPrevDocid);
87088
87089   /* Docids must ascend. */
87090   assert( !pWriter->has_iPrevDocid || iDocid>pWriter->iPrevDocid );
87091   assert( pWriter->iType==DL_DOCIDS );
87092
87093   dataBufferAppend(pWriter->b, c, n);
87094   pWriter->iPrevDocid = iDocid;
87095 #ifndef NDEBUG
87096   pWriter->has_iPrevDocid = 1;
87097 #endif
87098 }
87099
87100 /*******************************************************************/
87101 /* PLReader is used to read data from a document's position list.  As
87102 ** the caller steps through the list, data is cached so that varints
87103 ** only need to be decoded once.
87104 **
87105 ** plrInit, plrDestroy - create/destroy a reader.
87106 ** plrColumn, plrPosition, plrStartOffset, plrEndOffset - accessors
87107 ** plrAtEnd - at end of stream, only call plrDestroy once true.
87108 ** plrStep - step to the next element.
87109 */
87110 typedef struct PLReader {
87111   /* These refer to the next position's data.  nData will reach 0 when
87112   ** reading the last position, so plrStep() signals EOF by setting
87113   ** pData to NULL.
87114   */
87115   const char *pData;
87116   int nData;
87117
87118   DocListType iType;
87119   int iColumn;         /* the last column read */
87120   int iPosition;       /* the last position read */
87121   int iStartOffset;    /* the last start offset read */
87122   int iEndOffset;      /* the last end offset read */
87123 } PLReader;
87124
87125 static int plrAtEnd(PLReader *pReader){
87126   return pReader->pData==NULL;
87127 }
87128 static int plrColumn(PLReader *pReader){
87129   assert( !plrAtEnd(pReader) );
87130   return pReader->iColumn;
87131 }
87132 static int plrPosition(PLReader *pReader){
87133   assert( !plrAtEnd(pReader) );
87134   return pReader->iPosition;
87135 }
87136 static int plrStartOffset(PLReader *pReader){
87137   assert( !plrAtEnd(pReader) );
87138   return pReader->iStartOffset;
87139 }
87140 static int plrEndOffset(PLReader *pReader){
87141   assert( !plrAtEnd(pReader) );
87142   return pReader->iEndOffset;
87143 }
87144 static void plrStep(PLReader *pReader){
87145   int i, n;
87146
87147   assert( !plrAtEnd(pReader) );
87148
87149   if( pReader->nData==0 ){
87150     pReader->pData = NULL;
87151     return;
87152   }
87153
87154   n = fts3GetVarint32(pReader->pData, &i);
87155   if( i==POS_COLUMN ){
87156     n += fts3GetVarint32(pReader->pData+n, &pReader->iColumn);
87157     pReader->iPosition = 0;
87158     pReader->iStartOffset = 0;
87159     n += fts3GetVarint32(pReader->pData+n, &i);
87160   }
87161   /* Should never see adjacent column changes. */
87162   assert( i!=POS_COLUMN );
87163
87164   if( i==POS_END ){
87165     pReader->nData = 0;
87166     pReader->pData = NULL;
87167     return;
87168   }
87169
87170   pReader->iPosition += i-POS_BASE;
87171   if( pReader->iType==DL_POSITIONS_OFFSETS ){
87172     n += fts3GetVarint32(pReader->pData+n, &i);
87173     pReader->iStartOffset += i;
87174     n += fts3GetVarint32(pReader->pData+n, &i);
87175     pReader->iEndOffset = pReader->iStartOffset+i;
87176   }
87177   assert( n<=pReader->nData );
87178   pReader->pData += n;
87179   pReader->nData -= n;
87180 }
87181
87182 static void plrInit(PLReader *pReader, DLReader *pDLReader){
87183   pReader->pData = dlrPosData(pDLReader);
87184   pReader->nData = dlrPosDataLen(pDLReader);
87185   pReader->iType = pDLReader->iType;
87186   pReader->iColumn = 0;
87187   pReader->iPosition = 0;
87188   pReader->iStartOffset = 0;
87189   pReader->iEndOffset = 0;
87190   plrStep(pReader);
87191 }
87192 static void plrDestroy(PLReader *pReader){
87193   SCRAMBLE(pReader);
87194 }
87195
87196 /*******************************************************************/
87197 /* PLWriter is used in constructing a document's position list.  As a
87198 ** convenience, if iType is DL_DOCIDS, PLWriter becomes a no-op.
87199 ** PLWriter writes to the associated DLWriter's buffer.
87200 **
87201 ** plwInit - init for writing a document's poslist.
87202 ** plwDestroy - clear a writer.
87203 ** plwAdd - append position and offset information.
87204 ** plwCopy - copy next position's data from reader to writer.
87205 ** plwTerminate - add any necessary doclist terminator.
87206 **
87207 ** Calling plwAdd() after plwTerminate() may result in a corrupt
87208 ** doclist.
87209 */
87210 /* TODO(shess) Until we've written the second item, we can cache the
87211 ** first item's information.  Then we'd have three states:
87212 **
87213 ** - initialized with docid, no positions.
87214 ** - docid and one position.
87215 ** - docid and multiple positions.
87216 **
87217 ** Only the last state needs to actually write to dlw->b, which would
87218 ** be an improvement in the DLCollector case.
87219 */
87220 typedef struct PLWriter {
87221   DLWriter *dlw;
87222
87223   int iColumn;    /* the last column written */
87224   int iPos;       /* the last position written */
87225   int iOffset;    /* the last start offset written */
87226 } PLWriter;
87227
87228 /* TODO(shess) In the case where the parent is reading these values
87229 ** from a PLReader, we could optimize to a copy if that PLReader has
87230 ** the same type as pWriter.
87231 */
87232 static void plwAdd(PLWriter *pWriter, int iColumn, int iPos,
87233                    int iStartOffset, int iEndOffset){
87234   /* Worst-case space for POS_COLUMN, iColumn, iPosDelta,
87235   ** iStartOffsetDelta, and iEndOffsetDelta.
87236   */
87237   char c[5*VARINT_MAX];
87238   int n = 0;
87239
87240   /* Ban plwAdd() after plwTerminate(). */
87241   assert( pWriter->iPos!=-1 );
87242
87243   if( pWriter->dlw->iType==DL_DOCIDS ) return;
87244
87245   if( iColumn!=pWriter->iColumn ){
87246     n += fts3PutVarint(c+n, POS_COLUMN);
87247     n += fts3PutVarint(c+n, iColumn);
87248     pWriter->iColumn = iColumn;
87249     pWriter->iPos = 0;
87250     pWriter->iOffset = 0;
87251   }
87252   assert( iPos>=pWriter->iPos );
87253   n += fts3PutVarint(c+n, POS_BASE+(iPos-pWriter->iPos));
87254   pWriter->iPos = iPos;
87255   if( pWriter->dlw->iType==DL_POSITIONS_OFFSETS ){
87256     assert( iStartOffset>=pWriter->iOffset );
87257     n += fts3PutVarint(c+n, iStartOffset-pWriter->iOffset);
87258     pWriter->iOffset = iStartOffset;
87259     assert( iEndOffset>=iStartOffset );
87260     n += fts3PutVarint(c+n, iEndOffset-iStartOffset);
87261   }
87262   dataBufferAppend(pWriter->dlw->b, c, n);
87263 }
87264 static void plwCopy(PLWriter *pWriter, PLReader *pReader){
87265   plwAdd(pWriter, plrColumn(pReader), plrPosition(pReader),
87266          plrStartOffset(pReader), plrEndOffset(pReader));
87267 }
87268 static void plwInit(PLWriter *pWriter, DLWriter *dlw, sqlite_int64 iDocid){
87269   char c[VARINT_MAX];
87270   int n;
87271
87272   pWriter->dlw = dlw;
87273
87274   /* Docids must ascend. */
87275   assert( !pWriter->dlw->has_iPrevDocid || iDocid>pWriter->dlw->iPrevDocid );
87276   n = fts3PutVarint(c, iDocid-pWriter->dlw->iPrevDocid);
87277   dataBufferAppend(pWriter->dlw->b, c, n);
87278   pWriter->dlw->iPrevDocid = iDocid;
87279 #ifndef NDEBUG
87280   pWriter->dlw->has_iPrevDocid = 1;
87281 #endif
87282
87283   pWriter->iColumn = 0;
87284   pWriter->iPos = 0;
87285   pWriter->iOffset = 0;
87286 }
87287 /* TODO(shess) Should plwDestroy() also terminate the doclist?  But
87288 ** then plwDestroy() would no longer be just a destructor, it would
87289 ** also be doing work, which isn't consistent with the overall idiom.
87290 ** Another option would be for plwAdd() to always append any necessary
87291 ** terminator, so that the output is always correct.  But that would
87292 ** add incremental work to the common case with the only benefit being
87293 ** API elegance.  Punt for now.
87294 */
87295 static void plwTerminate(PLWriter *pWriter){
87296   if( pWriter->dlw->iType>DL_DOCIDS ){
87297     char c[VARINT_MAX];
87298     int n = fts3PutVarint(c, POS_END);
87299     dataBufferAppend(pWriter->dlw->b, c, n);
87300   }
87301 #ifndef NDEBUG
87302   /* Mark as terminated for assert in plwAdd(). */
87303   pWriter->iPos = -1;
87304 #endif
87305 }
87306 static void plwDestroy(PLWriter *pWriter){
87307   SCRAMBLE(pWriter);
87308 }
87309
87310 /*******************************************************************/
87311 /* DLCollector wraps PLWriter and DLWriter to provide a
87312 ** dynamically-allocated doclist area to use during tokenization.
87313 **
87314 ** dlcNew - malloc up and initialize a collector.
87315 ** dlcDelete - destroy a collector and all contained items.
87316 ** dlcAddPos - append position and offset information.
87317 ** dlcAddDoclist - add the collected doclist to the given buffer.
87318 ** dlcNext - terminate the current document and open another.
87319 */
87320 typedef struct DLCollector {
87321   DataBuffer b;
87322   DLWriter dlw;
87323   PLWriter plw;
87324 } DLCollector;
87325
87326 /* TODO(shess) This could also be done by calling plwTerminate() and
87327 ** dataBufferAppend().  I tried that, expecting nominal performance
87328 ** differences, but it seemed to pretty reliably be worth 1% to code
87329 ** it this way.  I suspect it is the incremental malloc overhead (some
87330 ** percentage of the plwTerminate() calls will cause a realloc), so
87331 ** this might be worth revisiting if the DataBuffer implementation
87332 ** changes.
87333 */
87334 static void dlcAddDoclist(DLCollector *pCollector, DataBuffer *b){
87335   if( pCollector->dlw.iType>DL_DOCIDS ){
87336     char c[VARINT_MAX];
87337     int n = fts3PutVarint(c, POS_END);
87338     dataBufferAppend2(b, pCollector->b.pData, pCollector->b.nData, c, n);
87339   }else{
87340     dataBufferAppend(b, pCollector->b.pData, pCollector->b.nData);
87341   }
87342 }
87343 static void dlcNext(DLCollector *pCollector, sqlite_int64 iDocid){
87344   plwTerminate(&pCollector->plw);
87345   plwDestroy(&pCollector->plw);
87346   plwInit(&pCollector->plw, &pCollector->dlw, iDocid);
87347 }
87348 static void dlcAddPos(DLCollector *pCollector, int iColumn, int iPos,
87349                       int iStartOffset, int iEndOffset){
87350   plwAdd(&pCollector->plw, iColumn, iPos, iStartOffset, iEndOffset);
87351 }
87352
87353 static DLCollector *dlcNew(sqlite_int64 iDocid, DocListType iType){
87354   DLCollector *pCollector = sqlite3_malloc(sizeof(DLCollector));
87355   dataBufferInit(&pCollector->b, 0);
87356   dlwInit(&pCollector->dlw, iType, &pCollector->b);
87357   plwInit(&pCollector->plw, &pCollector->dlw, iDocid);
87358   return pCollector;
87359 }
87360 static void dlcDelete(DLCollector *pCollector){
87361   plwDestroy(&pCollector->plw);
87362   dlwDestroy(&pCollector->dlw);
87363   dataBufferDestroy(&pCollector->b);
87364   SCRAMBLE(pCollector);
87365   sqlite3_free(pCollector);
87366 }
87367
87368
87369 /* Copy the doclist data of iType in pData/nData into *out, trimming
87370 ** unnecessary data as we go.  Only columns matching iColumn are
87371 ** copied, all columns copied if iColumn is -1.  Elements with no
87372 ** matching columns are dropped.  The output is an iOutType doclist.
87373 */
87374 /* NOTE(shess) This code is only valid after all doclists are merged.
87375 ** If this is run before merges, then doclist items which represent
87376 ** deletion will be trimmed, and will thus not effect a deletion
87377 ** during the merge.
87378 */
87379 static void docListTrim(DocListType iType, const char *pData, int nData,
87380                         int iColumn, DocListType iOutType, DataBuffer *out){
87381   DLReader dlReader;
87382   DLWriter dlWriter;
87383
87384   assert( iOutType<=iType );
87385
87386   dlrInit(&dlReader, iType, pData, nData);
87387   dlwInit(&dlWriter, iOutType, out);
87388
87389   while( !dlrAtEnd(&dlReader) ){
87390     PLReader plReader;
87391     PLWriter plWriter;
87392     int match = 0;
87393
87394     plrInit(&plReader, &dlReader);
87395
87396     while( !plrAtEnd(&plReader) ){
87397       if( iColumn==-1 || plrColumn(&plReader)==iColumn ){
87398         if( !match ){
87399           plwInit(&plWriter, &dlWriter, dlrDocid(&dlReader));
87400           match = 1;
87401         }
87402         plwAdd(&plWriter, plrColumn(&plReader), plrPosition(&plReader),
87403                plrStartOffset(&plReader), plrEndOffset(&plReader));
87404       }
87405       plrStep(&plReader);
87406     }
87407     if( match ){
87408       plwTerminate(&plWriter);
87409       plwDestroy(&plWriter);
87410     }
87411
87412     plrDestroy(&plReader);
87413     dlrStep(&dlReader);
87414   }
87415   dlwDestroy(&dlWriter);
87416   dlrDestroy(&dlReader);
87417 }
87418
87419 /* Used by docListMerge() to keep doclists in the ascending order by
87420 ** docid, then ascending order by age (so the newest comes first).
87421 */
87422 typedef struct OrderedDLReader {
87423   DLReader *pReader;
87424
87425   /* TODO(shess) If we assume that docListMerge pReaders is ordered by
87426   ** age (which we do), then we could use pReader comparisons to break
87427   ** ties.
87428   */
87429   int idx;
87430 } OrderedDLReader;
87431
87432 /* Order eof to end, then by docid asc, idx desc. */
87433 static int orderedDLReaderCmp(OrderedDLReader *r1, OrderedDLReader *r2){
87434   if( dlrAtEnd(r1->pReader) ){
87435     if( dlrAtEnd(r2->pReader) ) return 0;  /* Both atEnd(). */
87436     return 1;                              /* Only r1 atEnd(). */
87437   }
87438   if( dlrAtEnd(r2->pReader) ) return -1;   /* Only r2 atEnd(). */
87439
87440   if( dlrDocid(r1->pReader)<dlrDocid(r2->pReader) ) return -1;
87441   if( dlrDocid(r1->pReader)>dlrDocid(r2->pReader) ) return 1;
87442
87443   /* Descending on idx. */
87444   return r2->idx-r1->idx;
87445 }
87446
87447 /* Bubble p[0] to appropriate place in p[1..n-1].  Assumes that
87448 ** p[1..n-1] is already sorted.
87449 */
87450 /* TODO(shess) Is this frequent enough to warrant a binary search?
87451 ** Before implementing that, instrument the code to check.  In most
87452 ** current usage, I expect that p[0] will be less than p[1] a very
87453 ** high proportion of the time.
87454 */
87455 static void orderedDLReaderReorder(OrderedDLReader *p, int n){
87456   while( n>1 && orderedDLReaderCmp(p, p+1)>0 ){
87457     OrderedDLReader tmp = p[0];
87458     p[0] = p[1];
87459     p[1] = tmp;
87460     n--;
87461     p++;
87462   }
87463 }
87464
87465 /* Given an array of doclist readers, merge their doclist elements
87466 ** into out in sorted order (by docid), dropping elements from older
87467 ** readers when there is a duplicate docid.  pReaders is assumed to be
87468 ** ordered by age, oldest first.
87469 */
87470 /* TODO(shess) nReaders must be <= MERGE_COUNT.  This should probably
87471 ** be fixed.
87472 */
87473 static void docListMerge(DataBuffer *out,
87474                          DLReader *pReaders, int nReaders){
87475   OrderedDLReader readers[MERGE_COUNT];
87476   DLWriter writer;
87477   int i, n;
87478   const char *pStart = 0;
87479   int nStart = 0;
87480   sqlite_int64 iFirstDocid = 0, iLastDocid = 0;
87481
87482   assert( nReaders>0 );
87483   if( nReaders==1 ){
87484     dataBufferAppend(out, dlrDocData(pReaders), dlrAllDataBytes(pReaders));
87485     return;
87486   }
87487
87488   assert( nReaders<=MERGE_COUNT );
87489   n = 0;
87490   for(i=0; i<nReaders; i++){
87491     assert( pReaders[i].iType==pReaders[0].iType );
87492     readers[i].pReader = pReaders+i;
87493     readers[i].idx = i;
87494     n += dlrAllDataBytes(&pReaders[i]);
87495   }
87496   /* Conservatively size output to sum of inputs.  Output should end
87497   ** up strictly smaller than input.
87498   */
87499   dataBufferExpand(out, n);
87500
87501   /* Get the readers into sorted order. */
87502   while( i-->0 ){
87503     orderedDLReaderReorder(readers+i, nReaders-i);
87504   }
87505
87506   dlwInit(&writer, pReaders[0].iType, out);
87507   while( !dlrAtEnd(readers[0].pReader) ){
87508     sqlite_int64 iDocid = dlrDocid(readers[0].pReader);
87509
87510     /* If this is a continuation of the current buffer to copy, extend
87511     ** that buffer.  memcpy() seems to be more efficient if it has a
87512     ** lots of data to copy.
87513     */
87514     if( dlrDocData(readers[0].pReader)==pStart+nStart ){
87515       nStart += dlrDocDataBytes(readers[0].pReader);
87516     }else{
87517       if( pStart!=0 ){
87518         dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid);
87519       }
87520       pStart = dlrDocData(readers[0].pReader);
87521       nStart = dlrDocDataBytes(readers[0].pReader);
87522       iFirstDocid = iDocid;
87523     }
87524     iLastDocid = iDocid;
87525     dlrStep(readers[0].pReader);
87526
87527     /* Drop all of the older elements with the same docid. */
87528     for(i=1; i<nReaders &&
87529              !dlrAtEnd(readers[i].pReader) &&
87530              dlrDocid(readers[i].pReader)==iDocid; i++){
87531       dlrStep(readers[i].pReader);
87532     }
87533
87534     /* Get the readers back into order. */
87535     while( i-->0 ){
87536       orderedDLReaderReorder(readers+i, nReaders-i);
87537     }
87538   }
87539
87540   /* Copy over any remaining elements. */
87541   if( nStart>0 ) dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid);
87542   dlwDestroy(&writer);
87543 }
87544
87545 /* Helper function for posListUnion().  Compares the current position
87546 ** between left and right, returning as standard C idiom of <0 if
87547 ** left<right, >0 if left>right, and 0 if left==right.  "End" always
87548 ** compares greater.
87549 */
87550 static int posListCmp(PLReader *pLeft, PLReader *pRight){
87551   assert( pLeft->iType==pRight->iType );
87552   if( pLeft->iType==DL_DOCIDS ) return 0;
87553
87554   if( plrAtEnd(pLeft) ) return plrAtEnd(pRight) ? 0 : 1;
87555   if( plrAtEnd(pRight) ) return -1;
87556
87557   if( plrColumn(pLeft)<plrColumn(pRight) ) return -1;
87558   if( plrColumn(pLeft)>plrColumn(pRight) ) return 1;
87559
87560   if( plrPosition(pLeft)<plrPosition(pRight) ) return -1;
87561   if( plrPosition(pLeft)>plrPosition(pRight) ) return 1;
87562   if( pLeft->iType==DL_POSITIONS ) return 0;
87563
87564   if( plrStartOffset(pLeft)<plrStartOffset(pRight) ) return -1;
87565   if( plrStartOffset(pLeft)>plrStartOffset(pRight) ) return 1;
87566
87567   if( plrEndOffset(pLeft)<plrEndOffset(pRight) ) return -1;
87568   if( plrEndOffset(pLeft)>plrEndOffset(pRight) ) return 1;
87569
87570   return 0;
87571 }
87572
87573 /* Write the union of position lists in pLeft and pRight to pOut.
87574 ** "Union" in this case meaning "All unique position tuples".  Should
87575 ** work with any doclist type, though both inputs and the output
87576 ** should be the same type.
87577 */
87578 static void posListUnion(DLReader *pLeft, DLReader *pRight, DLWriter *pOut){
87579   PLReader left, right;
87580   PLWriter writer;
87581
87582   assert( dlrDocid(pLeft)==dlrDocid(pRight) );
87583   assert( pLeft->iType==pRight->iType );
87584   assert( pLeft->iType==pOut->iType );
87585
87586   plrInit(&left, pLeft);
87587   plrInit(&right, pRight);
87588   plwInit(&writer, pOut, dlrDocid(pLeft));
87589
87590   while( !plrAtEnd(&left) || !plrAtEnd(&right) ){
87591     int c = posListCmp(&left, &right);
87592     if( c<0 ){
87593       plwCopy(&writer, &left);
87594       plrStep(&left);
87595     }else if( c>0 ){
87596       plwCopy(&writer, &right);
87597       plrStep(&right);
87598     }else{
87599       plwCopy(&writer, &left);
87600       plrStep(&left);
87601       plrStep(&right);
87602     }
87603   }
87604
87605   plwTerminate(&writer);
87606   plwDestroy(&writer);
87607   plrDestroy(&left);
87608   plrDestroy(&right);
87609 }
87610
87611 /* Write the union of doclists in pLeft and pRight to pOut.  For
87612 ** docids in common between the inputs, the union of the position
87613 ** lists is written.  Inputs and outputs are always type DL_DEFAULT.
87614 */
87615 static void docListUnion(
87616   const char *pLeft, int nLeft,
87617   const char *pRight, int nRight,
87618   DataBuffer *pOut      /* Write the combined doclist here */
87619 ){
87620   DLReader left, right;
87621   DLWriter writer;
87622
87623   if( nLeft==0 ){
87624     if( nRight!=0) dataBufferAppend(pOut, pRight, nRight);
87625     return;
87626   }
87627   if( nRight==0 ){
87628     dataBufferAppend(pOut, pLeft, nLeft);
87629     return;
87630   }
87631
87632   dlrInit(&left, DL_DEFAULT, pLeft, nLeft);
87633   dlrInit(&right, DL_DEFAULT, pRight, nRight);
87634   dlwInit(&writer, DL_DEFAULT, pOut);
87635
87636   while( !dlrAtEnd(&left) || !dlrAtEnd(&right) ){
87637     if( dlrAtEnd(&right) ){
87638       dlwCopy(&writer, &left);
87639       dlrStep(&left);
87640     }else if( dlrAtEnd(&left) ){
87641       dlwCopy(&writer, &right);
87642       dlrStep(&right);
87643     }else if( dlrDocid(&left)<dlrDocid(&right) ){
87644       dlwCopy(&writer, &left);
87645       dlrStep(&left);
87646     }else if( dlrDocid(&left)>dlrDocid(&right) ){
87647       dlwCopy(&writer, &right);
87648       dlrStep(&right);
87649     }else{
87650       posListUnion(&left, &right, &writer);
87651       dlrStep(&left);
87652       dlrStep(&right);
87653     }
87654   }
87655
87656   dlrDestroy(&left);
87657   dlrDestroy(&right);
87658   dlwDestroy(&writer);
87659 }
87660
87661 /* 
87662 ** This function is used as part of the implementation of phrase and
87663 ** NEAR matching.
87664 **
87665 ** pLeft and pRight are DLReaders positioned to the same docid in
87666 ** lists of type DL_POSITION. This function writes an entry to the
87667 ** DLWriter pOut for each position in pRight that is less than
87668 ** (nNear+1) greater (but not equal to or smaller) than a position 
87669 ** in pLeft. For example, if nNear is 0, and the positions contained
87670 ** by pLeft and pRight are:
87671 **
87672 **    pLeft:  5 10 15 20
87673 **    pRight: 6  9 17 21
87674 **
87675 ** then the docid is added to pOut. If pOut is of type DL_POSITIONS,
87676 ** then a positionids "6" and "21" are also added to pOut.
87677 **
87678 ** If boolean argument isSaveLeft is true, then positionids are copied
87679 ** from pLeft instead of pRight. In the example above, the positions "5"
87680 ** and "20" would be added instead of "6" and "21".
87681 */
87682 static void posListPhraseMerge(
87683   DLReader *pLeft, 
87684   DLReader *pRight,
87685   int nNear,
87686   int isSaveLeft,
87687   DLWriter *pOut
87688 ){
87689   PLReader left, right;
87690   PLWriter writer;
87691   int match = 0;
87692
87693   assert( dlrDocid(pLeft)==dlrDocid(pRight) );
87694   assert( pOut->iType!=DL_POSITIONS_OFFSETS );
87695
87696   plrInit(&left, pLeft);
87697   plrInit(&right, pRight);
87698
87699   while( !plrAtEnd(&left) && !plrAtEnd(&right) ){
87700     if( plrColumn(&left)<plrColumn(&right) ){
87701       plrStep(&left);
87702     }else if( plrColumn(&left)>plrColumn(&right) ){
87703       plrStep(&right);
87704     }else if( plrPosition(&left)>=plrPosition(&right) ){
87705       plrStep(&right);
87706     }else{
87707       if( (plrPosition(&right)-plrPosition(&left))<=(nNear+1) ){
87708         if( !match ){
87709           plwInit(&writer, pOut, dlrDocid(pLeft));
87710           match = 1;
87711         }
87712         if( !isSaveLeft ){
87713           plwAdd(&writer, plrColumn(&right), plrPosition(&right), 0, 0);
87714         }else{
87715           plwAdd(&writer, plrColumn(&left), plrPosition(&left), 0, 0);
87716         }
87717         plrStep(&right);
87718       }else{
87719         plrStep(&left);
87720       }
87721     }
87722   }
87723
87724   if( match ){
87725     plwTerminate(&writer);
87726     plwDestroy(&writer);
87727   }
87728
87729   plrDestroy(&left);
87730   plrDestroy(&right);
87731 }
87732
87733 /*
87734 ** Compare the values pointed to by the PLReaders passed as arguments. 
87735 ** Return -1 if the value pointed to by pLeft is considered less than
87736 ** the value pointed to by pRight, +1 if it is considered greater
87737 ** than it, or 0 if it is equal. i.e.
87738 **
87739 **     (*pLeft - *pRight)
87740 **
87741 ** A PLReader that is in the EOF condition is considered greater than
87742 ** any other. If neither argument is in EOF state, the return value of
87743 ** plrColumn() is used. If the plrColumn() values are equal, the
87744 ** comparison is on the basis of plrPosition().
87745 */
87746 static int plrCompare(PLReader *pLeft, PLReader *pRight){
87747   assert(!plrAtEnd(pLeft) || !plrAtEnd(pRight));
87748
87749   if( plrAtEnd(pRight) || plrAtEnd(pLeft) ){
87750     return (plrAtEnd(pRight) ? -1 : 1);
87751   }
87752   if( plrColumn(pLeft)!=plrColumn(pRight) ){
87753     return ((plrColumn(pLeft)<plrColumn(pRight)) ? -1 : 1);
87754   }
87755   if( plrPosition(pLeft)!=plrPosition(pRight) ){
87756     return ((plrPosition(pLeft)<plrPosition(pRight)) ? -1 : 1);
87757   }
87758   return 0;
87759 }
87760
87761 /* We have two doclists with positions:  pLeft and pRight. Depending
87762 ** on the value of the nNear parameter, perform either a phrase
87763 ** intersection (if nNear==0) or a NEAR intersection (if nNear>0)
87764 ** and write the results into pOut.
87765 **
87766 ** A phrase intersection means that two documents only match
87767 ** if pLeft.iPos+1==pRight.iPos.
87768 **
87769 ** A NEAR intersection means that two documents only match if 
87770 ** (abs(pLeft.iPos-pRight.iPos)<nNear).
87771 **
87772 ** If a NEAR intersection is requested, then the nPhrase argument should
87773 ** be passed the number of tokens in the two operands to the NEAR operator
87774 ** combined. For example:
87775 **
87776 **       Query syntax               nPhrase
87777 **      ------------------------------------
87778 **       "A B C" NEAR "D E"         5
87779 **       A NEAR B                   2
87780 **
87781 ** iType controls the type of data written to pOut.  If iType is
87782 ** DL_POSITIONS, the positions are those from pRight.
87783 */
87784 static void docListPhraseMerge(
87785   const char *pLeft, int nLeft,
87786   const char *pRight, int nRight,
87787   int nNear,            /* 0 for a phrase merge, non-zero for a NEAR merge */
87788   int nPhrase,          /* Number of tokens in left+right operands to NEAR */
87789   DocListType iType,    /* Type of doclist to write to pOut */
87790   DataBuffer *pOut      /* Write the combined doclist here */
87791 ){
87792   DLReader left, right;
87793   DLWriter writer;
87794
87795   if( nLeft==0 || nRight==0 ) return;
87796
87797   assert( iType!=DL_POSITIONS_OFFSETS );
87798
87799   dlrInit(&left, DL_POSITIONS, pLeft, nLeft);
87800   dlrInit(&right, DL_POSITIONS, pRight, nRight);
87801   dlwInit(&writer, iType, pOut);
87802
87803   while( !dlrAtEnd(&left) && !dlrAtEnd(&right) ){
87804     if( dlrDocid(&left)<dlrDocid(&right) ){
87805       dlrStep(&left);
87806     }else if( dlrDocid(&right)<dlrDocid(&left) ){
87807       dlrStep(&right);
87808     }else{
87809       if( nNear==0 ){
87810         posListPhraseMerge(&left, &right, 0, 0, &writer);
87811       }else{
87812         /* This case occurs when two terms (simple terms or phrases) are
87813          * connected by a NEAR operator, span (nNear+1). i.e.
87814          *
87815          *     '"terrible company" NEAR widget'
87816          */
87817         DataBuffer one = {0, 0, 0};
87818         DataBuffer two = {0, 0, 0};
87819
87820         DLWriter dlwriter2;
87821         DLReader dr1 = {0, 0, 0, 0, 0}; 
87822         DLReader dr2 = {0, 0, 0, 0, 0};
87823
87824         dlwInit(&dlwriter2, iType, &one);
87825         posListPhraseMerge(&right, &left, nNear-3+nPhrase, 1, &dlwriter2);
87826         dlwInit(&dlwriter2, iType, &two);
87827         posListPhraseMerge(&left, &right, nNear-1, 0, &dlwriter2);
87828
87829         if( one.nData) dlrInit(&dr1, iType, one.pData, one.nData);
87830         if( two.nData) dlrInit(&dr2, iType, two.pData, two.nData);
87831
87832         if( !dlrAtEnd(&dr1) || !dlrAtEnd(&dr2) ){
87833           PLReader pr1 = {0};
87834           PLReader pr2 = {0};
87835
87836           PLWriter plwriter;
87837           plwInit(&plwriter, &writer, dlrDocid(dlrAtEnd(&dr1)?&dr2:&dr1));
87838
87839           if( one.nData ) plrInit(&pr1, &dr1);
87840           if( two.nData ) plrInit(&pr2, &dr2);
87841           while( !plrAtEnd(&pr1) || !plrAtEnd(&pr2) ){
87842             int iCompare = plrCompare(&pr1, &pr2);
87843             switch( iCompare ){
87844               case -1:
87845                 plwCopy(&plwriter, &pr1);
87846                 plrStep(&pr1);
87847                 break;
87848               case 1:
87849                 plwCopy(&plwriter, &pr2);
87850                 plrStep(&pr2);
87851                 break;
87852               case 0:
87853                 plwCopy(&plwriter, &pr1);
87854                 plrStep(&pr1);
87855                 plrStep(&pr2);
87856                 break;
87857             }
87858           }
87859           plwTerminate(&plwriter);
87860         }
87861         dataBufferDestroy(&one);
87862         dataBufferDestroy(&two);
87863       }
87864       dlrStep(&left);
87865       dlrStep(&right);
87866     }
87867   }
87868
87869   dlrDestroy(&left);
87870   dlrDestroy(&right);
87871   dlwDestroy(&writer);
87872 }
87873
87874 /* We have two DL_DOCIDS doclists:  pLeft and pRight.
87875 ** Write the intersection of these two doclists into pOut as a
87876 ** DL_DOCIDS doclist.
87877 */
87878 static void docListAndMerge(
87879   const char *pLeft, int nLeft,
87880   const char *pRight, int nRight,
87881   DataBuffer *pOut      /* Write the combined doclist here */
87882 ){
87883   DLReader left, right;
87884   DLWriter writer;
87885
87886   if( nLeft==0 || nRight==0 ) return;
87887
87888   dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
87889   dlrInit(&right, DL_DOCIDS, pRight, nRight);
87890   dlwInit(&writer, DL_DOCIDS, pOut);
87891
87892   while( !dlrAtEnd(&left) && !dlrAtEnd(&right) ){
87893     if( dlrDocid(&left)<dlrDocid(&right) ){
87894       dlrStep(&left);
87895     }else if( dlrDocid(&right)<dlrDocid(&left) ){
87896       dlrStep(&right);
87897     }else{
87898       dlwAdd(&writer, dlrDocid(&left));
87899       dlrStep(&left);
87900       dlrStep(&right);
87901     }
87902   }
87903
87904   dlrDestroy(&left);
87905   dlrDestroy(&right);
87906   dlwDestroy(&writer);
87907 }
87908
87909 /* We have two DL_DOCIDS doclists:  pLeft and pRight.
87910 ** Write the union of these two doclists into pOut as a
87911 ** DL_DOCIDS doclist.
87912 */
87913 static void docListOrMerge(
87914   const char *pLeft, int nLeft,
87915   const char *pRight, int nRight,
87916   DataBuffer *pOut      /* Write the combined doclist here */
87917 ){
87918   DLReader left, right;
87919   DLWriter writer;
87920
87921   if( nLeft==0 ){
87922     if( nRight!=0 ) dataBufferAppend(pOut, pRight, nRight);
87923     return;
87924   }
87925   if( nRight==0 ){
87926     dataBufferAppend(pOut, pLeft, nLeft);
87927     return;
87928   }
87929
87930   dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
87931   dlrInit(&right, DL_DOCIDS, pRight, nRight);
87932   dlwInit(&writer, DL_DOCIDS, pOut);
87933
87934   while( !dlrAtEnd(&left) || !dlrAtEnd(&right) ){
87935     if( dlrAtEnd(&right) ){
87936       dlwAdd(&writer, dlrDocid(&left));
87937       dlrStep(&left);
87938     }else if( dlrAtEnd(&left) ){
87939       dlwAdd(&writer, dlrDocid(&right));
87940       dlrStep(&right);
87941     }else if( dlrDocid(&left)<dlrDocid(&right) ){
87942       dlwAdd(&writer, dlrDocid(&left));
87943       dlrStep(&left);
87944     }else if( dlrDocid(&right)<dlrDocid(&left) ){
87945       dlwAdd(&writer, dlrDocid(&right));
87946       dlrStep(&right);
87947     }else{
87948       dlwAdd(&writer, dlrDocid(&left));
87949       dlrStep(&left);
87950       dlrStep(&right);
87951     }
87952   }
87953
87954   dlrDestroy(&left);
87955   dlrDestroy(&right);
87956   dlwDestroy(&writer);
87957 }
87958
87959 /* We have two DL_DOCIDS doclists:  pLeft and pRight.
87960 ** Write into pOut as DL_DOCIDS doclist containing all documents that
87961 ** occur in pLeft but not in pRight.
87962 */
87963 static void docListExceptMerge(
87964   const char *pLeft, int nLeft,
87965   const char *pRight, int nRight,
87966   DataBuffer *pOut      /* Write the combined doclist here */
87967 ){
87968   DLReader left, right;
87969   DLWriter writer;
87970
87971   if( nLeft==0 ) return;
87972   if( nRight==0 ){
87973     dataBufferAppend(pOut, pLeft, nLeft);
87974     return;
87975   }
87976
87977   dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
87978   dlrInit(&right, DL_DOCIDS, pRight, nRight);
87979   dlwInit(&writer, DL_DOCIDS, pOut);
87980
87981   while( !dlrAtEnd(&left) ){
87982     while( !dlrAtEnd(&right) && dlrDocid(&right)<dlrDocid(&left) ){
87983       dlrStep(&right);
87984     }
87985     if( dlrAtEnd(&right) || dlrDocid(&left)<dlrDocid(&right) ){
87986       dlwAdd(&writer, dlrDocid(&left));
87987     }
87988     dlrStep(&left);
87989   }
87990
87991   dlrDestroy(&left);
87992   dlrDestroy(&right);
87993   dlwDestroy(&writer);
87994 }
87995
87996 static char *string_dup_n(const char *s, int n){
87997   char *str = sqlite3_malloc(n + 1);
87998   memcpy(str, s, n);
87999   str[n] = '\0';
88000   return str;
88001 }
88002
88003 /* Duplicate a string; the caller must free() the returned string.
88004  * (We don't use strdup() since it is not part of the standard C library and
88005  * may not be available everywhere.) */
88006 static char *string_dup(const char *s){
88007   return string_dup_n(s, strlen(s));
88008 }
88009
88010 /* Format a string, replacing each occurrence of the % character with
88011  * zDb.zName.  This may be more convenient than sqlite_mprintf()
88012  * when one string is used repeatedly in a format string.
88013  * The caller must free() the returned string. */
88014 static char *string_format(const char *zFormat,
88015                            const char *zDb, const char *zName){
88016   const char *p;
88017   size_t len = 0;
88018   size_t nDb = strlen(zDb);
88019   size_t nName = strlen(zName);
88020   size_t nFullTableName = nDb+1+nName;
88021   char *result;
88022   char *r;
88023
88024   /* first compute length needed */
88025   for(p = zFormat ; *p ; ++p){
88026     len += (*p=='%' ? nFullTableName : 1);
88027   }
88028   len += 1;  /* for null terminator */
88029
88030   r = result = sqlite3_malloc(len);
88031   for(p = zFormat; *p; ++p){
88032     if( *p=='%' ){
88033       memcpy(r, zDb, nDb);
88034       r += nDb;
88035       *r++ = '.';
88036       memcpy(r, zName, nName);
88037       r += nName;
88038     } else {
88039       *r++ = *p;
88040     }
88041   }
88042   *r++ = '\0';
88043   assert( r == result + len );
88044   return result;
88045 }
88046
88047 static int sql_exec(sqlite3 *db, const char *zDb, const char *zName,
88048                     const char *zFormat){
88049   char *zCommand = string_format(zFormat, zDb, zName);
88050   int rc;
88051   FTSTRACE(("FTS3 sql: %s\n", zCommand));
88052   rc = sqlite3_exec(db, zCommand, NULL, 0, NULL);
88053   sqlite3_free(zCommand);
88054   return rc;
88055 }
88056
88057 static int sql_prepare(sqlite3 *db, const char *zDb, const char *zName,
88058                        sqlite3_stmt **ppStmt, const char *zFormat){
88059   char *zCommand = string_format(zFormat, zDb, zName);
88060   int rc;
88061   FTSTRACE(("FTS3 prepare: %s\n", zCommand));
88062   rc = sqlite3_prepare_v2(db, zCommand, -1, ppStmt, NULL);
88063   sqlite3_free(zCommand);
88064   return rc;
88065 }
88066
88067 /* end utility functions */
88068
88069 /* Forward reference */
88070 typedef struct fulltext_vtab fulltext_vtab;
88071
88072 /* A single term in a query is represented by an instances of
88073 ** the following structure. Each word which may match against
88074 ** document content is a term. Operators, like NEAR or OR, are
88075 ** not terms. Query terms are organized as a flat list stored
88076 ** in the Query.pTerms array.
88077 **
88078 ** If the QueryTerm.nPhrase variable is non-zero, then the QueryTerm
88079 ** is the first in a contiguous string of terms that are either part
88080 ** of the same phrase, or connected by the NEAR operator.
88081 **
88082 ** If the QueryTerm.nNear variable is non-zero, then the token is followed 
88083 ** by a NEAR operator with span set to (nNear-1). For example, the 
88084 ** following query:
88085 **
88086 ** The QueryTerm.iPhrase variable stores the index of the token within
88087 ** its phrase, indexed starting at 1, or 1 if the token is not part 
88088 ** of any phrase.
88089 **
88090 ** For example, the data structure used to represent the following query:
88091 **
88092 **     ... MATCH 'sqlite NEAR/5 google NEAR/2 "search engine"'
88093 **
88094 ** is:
88095 **
88096 **     {nPhrase=4, iPhrase=1, nNear=6, pTerm="sqlite"},
88097 **     {nPhrase=0, iPhrase=1, nNear=3, pTerm="google"},
88098 **     {nPhrase=0, iPhrase=1, nNear=0, pTerm="search"},
88099 **     {nPhrase=0, iPhrase=2, nNear=0, pTerm="engine"},
88100 **
88101 ** compiling the FTS3 syntax to Query structures is done by the parseQuery()
88102 ** function.
88103 */
88104 typedef struct QueryTerm {
88105   short int nPhrase; /* How many following terms are part of the same phrase */
88106   short int iPhrase; /* This is the i-th term of a phrase. */
88107   short int iColumn; /* Column of the index that must match this term */
88108   short int nNear;   /* term followed by a NEAR operator with span=(nNear-1) */
88109   signed char isOr;  /* this term is preceded by "OR" */
88110   signed char isNot; /* this term is preceded by "-" */
88111   signed char isPrefix; /* this term is followed by "*" */
88112   char *pTerm;       /* text of the term.  '\000' terminated.  malloced */
88113   int nTerm;         /* Number of bytes in pTerm[] */
88114 } QueryTerm;
88115
88116
88117 /* A query string is parsed into a Query structure.
88118  *
88119  * We could, in theory, allow query strings to be complicated
88120  * nested expressions with precedence determined by parentheses.
88121  * But none of the major search engines do this.  (Perhaps the
88122  * feeling is that an parenthesized expression is two complex of
88123  * an idea for the average user to grasp.)  Taking our lead from
88124  * the major search engines, we will allow queries to be a list
88125  * of terms (with an implied AND operator) or phrases in double-quotes,
88126  * with a single optional "-" before each non-phrase term to designate
88127  * negation and an optional OR connector.
88128  *
88129  * OR binds more tightly than the implied AND, which is what the
88130  * major search engines seem to do.  So, for example:
88131  * 
88132  *    [one two OR three]     ==>    one AND (two OR three)
88133  *    [one OR two three]     ==>    (one OR two) AND three
88134  *
88135  * A "-" before a term matches all entries that lack that term.
88136  * The "-" must occur immediately before the term with in intervening
88137  * space.  This is how the search engines do it.
88138  *
88139  * A NOT term cannot be the right-hand operand of an OR.  If this
88140  * occurs in the query string, the NOT is ignored:
88141  *
88142  *    [one OR -two]          ==>    one OR two
88143  *
88144  */
88145 typedef struct Query {
88146   fulltext_vtab *pFts;  /* The full text index */
88147   int nTerms;           /* Number of terms in the query */
88148   QueryTerm *pTerms;    /* Array of terms.  Space obtained from malloc() */
88149   int nextIsOr;         /* Set the isOr flag on the next inserted term */
88150   int nextIsNear;       /* Set the isOr flag on the next inserted term */
88151   int nextColumn;       /* Next word parsed must be in this column */
88152   int dfltColumn;       /* The default column */
88153 } Query;
88154
88155
88156 /*
88157 ** An instance of the following structure keeps track of generated
88158 ** matching-word offset information and snippets.
88159 */
88160 typedef struct Snippet {
88161   int nMatch;     /* Total number of matches */
88162   int nAlloc;     /* Space allocated for aMatch[] */
88163   struct snippetMatch { /* One entry for each matching term */
88164     char snStatus;       /* Status flag for use while constructing snippets */
88165     short int iCol;      /* The column that contains the match */
88166     short int iTerm;     /* The index in Query.pTerms[] of the matching term */
88167     int iToken;          /* The index of the matching document token */
88168     short int nByte;     /* Number of bytes in the term */
88169     int iStart;          /* The offset to the first character of the term */
88170   } *aMatch;      /* Points to space obtained from malloc */
88171   char *zOffset;  /* Text rendering of aMatch[] */
88172   int nOffset;    /* strlen(zOffset) */
88173   char *zSnippet; /* Snippet text */
88174   int nSnippet;   /* strlen(zSnippet) */
88175 } Snippet;
88176
88177
88178 typedef enum QueryType {
88179   QUERY_GENERIC,   /* table scan */
88180   QUERY_DOCID,     /* lookup by docid */
88181   QUERY_FULLTEXT   /* QUERY_FULLTEXT + [i] is a full-text search for column i*/
88182 } QueryType;
88183
88184 typedef enum fulltext_statement {
88185   CONTENT_INSERT_STMT,
88186   CONTENT_SELECT_STMT,
88187   CONTENT_UPDATE_STMT,
88188   CONTENT_DELETE_STMT,
88189   CONTENT_EXISTS_STMT,
88190
88191   BLOCK_INSERT_STMT,
88192   BLOCK_SELECT_STMT,
88193   BLOCK_DELETE_STMT,
88194   BLOCK_DELETE_ALL_STMT,
88195
88196   SEGDIR_MAX_INDEX_STMT,
88197   SEGDIR_SET_STMT,
88198   SEGDIR_SELECT_LEVEL_STMT,
88199   SEGDIR_SPAN_STMT,
88200   SEGDIR_DELETE_STMT,
88201   SEGDIR_SELECT_SEGMENT_STMT,
88202   SEGDIR_SELECT_ALL_STMT,
88203   SEGDIR_DELETE_ALL_STMT,
88204   SEGDIR_COUNT_STMT,
88205
88206   MAX_STMT                     /* Always at end! */
88207 } fulltext_statement;
88208
88209 /* These must exactly match the enum above. */
88210 /* TODO(shess): Is there some risk that a statement will be used in two
88211 ** cursors at once, e.g.  if a query joins a virtual table to itself?
88212 ** If so perhaps we should move some of these to the cursor object.
88213 */
88214 static const char *const fulltext_zStatement[MAX_STMT] = {
88215   /* CONTENT_INSERT */ NULL,  /* generated in contentInsertStatement() */
88216   /* CONTENT_SELECT */ NULL,  /* generated in contentSelectStatement() */
88217   /* CONTENT_UPDATE */ NULL,  /* generated in contentUpdateStatement() */
88218   /* CONTENT_DELETE */ "delete from %_content where docid = ?",
88219   /* CONTENT_EXISTS */ "select docid from %_content limit 1",
88220
88221   /* BLOCK_INSERT */
88222   "insert into %_segments (blockid, block) values (null, ?)",
88223   /* BLOCK_SELECT */ "select block from %_segments where blockid = ?",
88224   /* BLOCK_DELETE */ "delete from %_segments where blockid between ? and ?",
88225   /* BLOCK_DELETE_ALL */ "delete from %_segments",
88226
88227   /* SEGDIR_MAX_INDEX */ "select max(idx) from %_segdir where level = ?",
88228   /* SEGDIR_SET */ "insert into %_segdir values (?, ?, ?, ?, ?, ?)",
88229   /* SEGDIR_SELECT_LEVEL */
88230   "select start_block, leaves_end_block, root from %_segdir "
88231   " where level = ? order by idx",
88232   /* SEGDIR_SPAN */
88233   "select min(start_block), max(end_block) from %_segdir "
88234   " where level = ? and start_block <> 0",
88235   /* SEGDIR_DELETE */ "delete from %_segdir where level = ?",
88236
88237   /* NOTE(shess): The first three results of the following two
88238   ** statements must match.
88239   */
88240   /* SEGDIR_SELECT_SEGMENT */
88241   "select start_block, leaves_end_block, root from %_segdir "
88242   " where level = ? and idx = ?",
88243   /* SEGDIR_SELECT_ALL */
88244   "select start_block, leaves_end_block, root from %_segdir "
88245   " order by level desc, idx asc",
88246   /* SEGDIR_DELETE_ALL */ "delete from %_segdir",
88247   /* SEGDIR_COUNT */ "select count(*), ifnull(max(level),0) from %_segdir",
88248 };
88249
88250 /*
88251 ** A connection to a fulltext index is an instance of the following
88252 ** structure.  The xCreate and xConnect methods create an instance
88253 ** of this structure and xDestroy and xDisconnect free that instance.
88254 ** All other methods receive a pointer to the structure as one of their
88255 ** arguments.
88256 */
88257 struct fulltext_vtab {
88258   sqlite3_vtab base;               /* Base class used by SQLite core */
88259   sqlite3 *db;                     /* The database connection */
88260   const char *zDb;                 /* logical database name */
88261   const char *zName;               /* virtual table name */
88262   int nColumn;                     /* number of columns in virtual table */
88263   char **azColumn;                 /* column names.  malloced */
88264   char **azContentColumn;          /* column names in content table; malloced */
88265   sqlite3_tokenizer *pTokenizer;   /* tokenizer for inserts and queries */
88266
88267   /* Precompiled statements which we keep as long as the table is
88268   ** open.
88269   */
88270   sqlite3_stmt *pFulltextStatements[MAX_STMT];
88271
88272   /* Precompiled statements used for segment merges.  We run a
88273   ** separate select across the leaf level of each tree being merged.
88274   */
88275   sqlite3_stmt *pLeafSelectStmts[MERGE_COUNT];
88276   /* The statement used to prepare pLeafSelectStmts. */
88277 #define LEAF_SELECT \
88278   "select block from %_segments where blockid between ? and ? order by blockid"
88279
88280   /* These buffer pending index updates during transactions.
88281   ** nPendingData estimates the memory size of the pending data.  It
88282   ** doesn't include the hash-bucket overhead, nor any malloc
88283   ** overhead.  When nPendingData exceeds kPendingThreshold, the
88284   ** buffer is flushed even before the transaction closes.
88285   ** pendingTerms stores the data, and is only valid when nPendingData
88286   ** is >=0 (nPendingData<0 means pendingTerms has not been
88287   ** initialized).  iPrevDocid is the last docid written, used to make
88288   ** certain we're inserting in sorted order.
88289   */
88290   int nPendingData;
88291 #define kPendingThreshold (1*1024*1024)
88292   sqlite_int64 iPrevDocid;
88293   fts3Hash pendingTerms;
88294 };
88295
88296 /*
88297 ** When the core wants to do a query, it create a cursor using a
88298 ** call to xOpen.  This structure is an instance of a cursor.  It
88299 ** is destroyed by xClose.
88300 */
88301 typedef struct fulltext_cursor {
88302   sqlite3_vtab_cursor base;        /* Base class used by SQLite core */
88303   QueryType iCursorType;           /* Copy of sqlite3_index_info.idxNum */
88304   sqlite3_stmt *pStmt;             /* Prepared statement in use by the cursor */
88305   int eof;                         /* True if at End Of Results */
88306   Query q;                         /* Parsed query string */
88307   Snippet snippet;                 /* Cached snippet for the current row */
88308   int iColumn;                     /* Column being searched */
88309   DataBuffer result;               /* Doclist results from fulltextQuery */
88310   DLReader reader;                 /* Result reader if result not empty */
88311 } fulltext_cursor;
88312
88313 static struct fulltext_vtab *cursor_vtab(fulltext_cursor *c){
88314   return (fulltext_vtab *) c->base.pVtab;
88315 }
88316
88317 static const sqlite3_module fts3Module;   /* forward declaration */
88318
88319 /* Return a dynamically generated statement of the form
88320  *   insert into %_content (docid, ...) values (?, ...)
88321  */
88322 static const char *contentInsertStatement(fulltext_vtab *v){
88323   StringBuffer sb;
88324   int i;
88325
88326   initStringBuffer(&sb);
88327   append(&sb, "insert into %_content (docid, ");
88328   appendList(&sb, v->nColumn, v->azContentColumn);
88329   append(&sb, ") values (?");
88330   for(i=0; i<v->nColumn; ++i)
88331     append(&sb, ", ?");
88332   append(&sb, ")");
88333   return stringBufferData(&sb);
88334 }
88335
88336 /* Return a dynamically generated statement of the form
88337  *   select <content columns> from %_content where docid = ?
88338  */
88339 static const char *contentSelectStatement(fulltext_vtab *v){
88340   StringBuffer sb;
88341   initStringBuffer(&sb);
88342   append(&sb, "SELECT ");
88343   appendList(&sb, v->nColumn, v->azContentColumn);
88344   append(&sb, " FROM %_content WHERE docid = ?");
88345   return stringBufferData(&sb);
88346 }
88347
88348 /* Return a dynamically generated statement of the form
88349  *   update %_content set [col_0] = ?, [col_1] = ?, ...
88350  *                    where docid = ?
88351  */
88352 static const char *contentUpdateStatement(fulltext_vtab *v){
88353   StringBuffer sb;
88354   int i;
88355
88356   initStringBuffer(&sb);
88357   append(&sb, "update %_content set ");
88358   for(i=0; i<v->nColumn; ++i) {
88359     if( i>0 ){
88360       append(&sb, ", ");
88361     }
88362     append(&sb, v->azContentColumn[i]);
88363     append(&sb, " = ?");
88364   }
88365   append(&sb, " where docid = ?");
88366   return stringBufferData(&sb);
88367 }
88368
88369 /* Puts a freshly-prepared statement determined by iStmt in *ppStmt.
88370 ** If the indicated statement has never been prepared, it is prepared
88371 ** and cached, otherwise the cached version is reset.
88372 */
88373 static int sql_get_statement(fulltext_vtab *v, fulltext_statement iStmt,
88374                              sqlite3_stmt **ppStmt){
88375   assert( iStmt<MAX_STMT );
88376   if( v->pFulltextStatements[iStmt]==NULL ){
88377     const char *zStmt;
88378     int rc;
88379     switch( iStmt ){
88380       case CONTENT_INSERT_STMT:
88381         zStmt = contentInsertStatement(v); break;
88382       case CONTENT_SELECT_STMT:
88383         zStmt = contentSelectStatement(v); break;
88384       case CONTENT_UPDATE_STMT:
88385         zStmt = contentUpdateStatement(v); break;
88386       default:
88387         zStmt = fulltext_zStatement[iStmt];
88388     }
88389     rc = sql_prepare(v->db, v->zDb, v->zName, &v->pFulltextStatements[iStmt],
88390                          zStmt);
88391     if( zStmt != fulltext_zStatement[iStmt]) sqlite3_free((void *) zStmt);
88392     if( rc!=SQLITE_OK ) return rc;
88393   } else {
88394     int rc = sqlite3_reset(v->pFulltextStatements[iStmt]);
88395     if( rc!=SQLITE_OK ) return rc;
88396   }
88397
88398   *ppStmt = v->pFulltextStatements[iStmt];
88399   return SQLITE_OK;
88400 }
88401
88402 /* Like sqlite3_step(), but convert SQLITE_DONE to SQLITE_OK and
88403 ** SQLITE_ROW to SQLITE_ERROR.  Useful for statements like UPDATE,
88404 ** where we expect no results.
88405 */
88406 static int sql_single_step(sqlite3_stmt *s){
88407   int rc = sqlite3_step(s);
88408   return (rc==SQLITE_DONE) ? SQLITE_OK : rc;
88409 }
88410
88411 /* Like sql_get_statement(), but for special replicated LEAF_SELECT
88412 ** statements.  idx -1 is a special case for an uncached version of
88413 ** the statement (used in the optimize implementation).
88414 */
88415 /* TODO(shess) Write version for generic statements and then share
88416 ** that between the cached-statement functions.
88417 */
88418 static int sql_get_leaf_statement(fulltext_vtab *v, int idx,
88419                                   sqlite3_stmt **ppStmt){
88420   assert( idx>=-1 && idx<MERGE_COUNT );
88421   if( idx==-1 ){
88422     return sql_prepare(v->db, v->zDb, v->zName, ppStmt, LEAF_SELECT);
88423   }else if( v->pLeafSelectStmts[idx]==NULL ){
88424     int rc = sql_prepare(v->db, v->zDb, v->zName, &v->pLeafSelectStmts[idx],
88425                          LEAF_SELECT);
88426     if( rc!=SQLITE_OK ) return rc;
88427   }else{
88428     int rc = sqlite3_reset(v->pLeafSelectStmts[idx]);
88429     if( rc!=SQLITE_OK ) return rc;
88430   }
88431
88432   *ppStmt = v->pLeafSelectStmts[idx];
88433   return SQLITE_OK;
88434 }
88435
88436 /* insert into %_content (docid, ...) values ([docid], [pValues])
88437 ** If the docid contains SQL NULL, then a unique docid will be
88438 ** generated.
88439 */
88440 static int content_insert(fulltext_vtab *v, sqlite3_value *docid,
88441                           sqlite3_value **pValues){
88442   sqlite3_stmt *s;
88443   int i;
88444   int rc = sql_get_statement(v, CONTENT_INSERT_STMT, &s);
88445   if( rc!=SQLITE_OK ) return rc;
88446
88447   rc = sqlite3_bind_value(s, 1, docid);
88448   if( rc!=SQLITE_OK ) return rc;
88449
88450   for(i=0; i<v->nColumn; ++i){
88451     rc = sqlite3_bind_value(s, 2+i, pValues[i]);
88452     if( rc!=SQLITE_OK ) return rc;
88453   }
88454
88455   return sql_single_step(s);
88456 }
88457
88458 /* update %_content set col0 = pValues[0], col1 = pValues[1], ...
88459  *                  where docid = [iDocid] */
88460 static int content_update(fulltext_vtab *v, sqlite3_value **pValues,
88461                           sqlite_int64 iDocid){
88462   sqlite3_stmt *s;
88463   int i;
88464   int rc = sql_get_statement(v, CONTENT_UPDATE_STMT, &s);
88465   if( rc!=SQLITE_OK ) return rc;
88466
88467   for(i=0; i<v->nColumn; ++i){
88468     rc = sqlite3_bind_value(s, 1+i, pValues[i]);
88469     if( rc!=SQLITE_OK ) return rc;
88470   }
88471
88472   rc = sqlite3_bind_int64(s, 1+v->nColumn, iDocid);
88473   if( rc!=SQLITE_OK ) return rc;
88474
88475   return sql_single_step(s);
88476 }
88477
88478 static void freeStringArray(int nString, const char **pString){
88479   int i;
88480
88481   for (i=0 ; i < nString ; ++i) {
88482     if( pString[i]!=NULL ) sqlite3_free((void *) pString[i]);
88483   }
88484   sqlite3_free((void *) pString);
88485 }
88486
88487 /* select * from %_content where docid = [iDocid]
88488  * The caller must delete the returned array and all strings in it.
88489  * null fields will be NULL in the returned array.
88490  *
88491  * TODO: Perhaps we should return pointer/length strings here for consistency
88492  * with other code which uses pointer/length. */
88493 static int content_select(fulltext_vtab *v, sqlite_int64 iDocid,
88494                           const char ***pValues){
88495   sqlite3_stmt *s;
88496   const char **values;
88497   int i;
88498   int rc;
88499
88500   *pValues = NULL;
88501
88502   rc = sql_get_statement(v, CONTENT_SELECT_STMT, &s);
88503   if( rc!=SQLITE_OK ) return rc;
88504
88505   rc = sqlite3_bind_int64(s, 1, iDocid);
88506   if( rc!=SQLITE_OK ) return rc;
88507
88508   rc = sqlite3_step(s);
88509   if( rc!=SQLITE_ROW ) return rc;
88510
88511   values = (const char **) sqlite3_malloc(v->nColumn * sizeof(const char *));
88512   for(i=0; i<v->nColumn; ++i){
88513     if( sqlite3_column_type(s, i)==SQLITE_NULL ){
88514       values[i] = NULL;
88515     }else{
88516       values[i] = string_dup((char*)sqlite3_column_text(s, i));
88517     }
88518   }
88519
88520   /* We expect only one row.  We must execute another sqlite3_step()
88521    * to complete the iteration; otherwise the table will remain locked. */
88522   rc = sqlite3_step(s);
88523   if( rc==SQLITE_DONE ){
88524     *pValues = values;
88525     return SQLITE_OK;
88526   }
88527
88528   freeStringArray(v->nColumn, values);
88529   return rc;
88530 }
88531
88532 /* delete from %_content where docid = [iDocid ] */
88533 static int content_delete(fulltext_vtab *v, sqlite_int64 iDocid){
88534   sqlite3_stmt *s;
88535   int rc = sql_get_statement(v, CONTENT_DELETE_STMT, &s);
88536   if( rc!=SQLITE_OK ) return rc;
88537
88538   rc = sqlite3_bind_int64(s, 1, iDocid);
88539   if( rc!=SQLITE_OK ) return rc;
88540
88541   return sql_single_step(s);
88542 }
88543
88544 /* Returns SQLITE_ROW if any rows exist in %_content, SQLITE_DONE if
88545 ** no rows exist, and any error in case of failure.
88546 */
88547 static int content_exists(fulltext_vtab *v){
88548   sqlite3_stmt *s;
88549   int rc = sql_get_statement(v, CONTENT_EXISTS_STMT, &s);
88550   if( rc!=SQLITE_OK ) return rc;
88551
88552   rc = sqlite3_step(s);
88553   if( rc!=SQLITE_ROW ) return rc;
88554
88555   /* We expect only one row.  We must execute another sqlite3_step()
88556    * to complete the iteration; otherwise the table will remain locked. */
88557   rc = sqlite3_step(s);
88558   if( rc==SQLITE_DONE ) return SQLITE_ROW;
88559   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
88560   return rc;
88561 }
88562
88563 /* insert into %_segments values ([pData])
88564 **   returns assigned blockid in *piBlockid
88565 */
88566 static int block_insert(fulltext_vtab *v, const char *pData, int nData,
88567                         sqlite_int64 *piBlockid){
88568   sqlite3_stmt *s;
88569   int rc = sql_get_statement(v, BLOCK_INSERT_STMT, &s);
88570   if( rc!=SQLITE_OK ) return rc;
88571
88572   rc = sqlite3_bind_blob(s, 1, pData, nData, SQLITE_STATIC);
88573   if( rc!=SQLITE_OK ) return rc;
88574
88575   rc = sqlite3_step(s);
88576   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
88577   if( rc!=SQLITE_DONE ) return rc;
88578
88579   /* blockid column is an alias for rowid. */
88580   *piBlockid = sqlite3_last_insert_rowid(v->db);
88581   return SQLITE_OK;
88582 }
88583
88584 /* delete from %_segments
88585 **   where blockid between [iStartBlockid] and [iEndBlockid]
88586 **
88587 ** Deletes the range of blocks, inclusive, used to delete the blocks
88588 ** which form a segment.
88589 */
88590 static int block_delete(fulltext_vtab *v,
88591                         sqlite_int64 iStartBlockid, sqlite_int64 iEndBlockid){
88592   sqlite3_stmt *s;
88593   int rc = sql_get_statement(v, BLOCK_DELETE_STMT, &s);
88594   if( rc!=SQLITE_OK ) return rc;
88595
88596   rc = sqlite3_bind_int64(s, 1, iStartBlockid);
88597   if( rc!=SQLITE_OK ) return rc;
88598
88599   rc = sqlite3_bind_int64(s, 2, iEndBlockid);
88600   if( rc!=SQLITE_OK ) return rc;
88601
88602   return sql_single_step(s);
88603 }
88604
88605 /* Returns SQLITE_ROW with *pidx set to the maximum segment idx found
88606 ** at iLevel.  Returns SQLITE_DONE if there are no segments at
88607 ** iLevel.  Otherwise returns an error.
88608 */
88609 static int segdir_max_index(fulltext_vtab *v, int iLevel, int *pidx){
88610   sqlite3_stmt *s;
88611   int rc = sql_get_statement(v, SEGDIR_MAX_INDEX_STMT, &s);
88612   if( rc!=SQLITE_OK ) return rc;
88613
88614   rc = sqlite3_bind_int(s, 1, iLevel);
88615   if( rc!=SQLITE_OK ) return rc;
88616
88617   rc = sqlite3_step(s);
88618   /* Should always get at least one row due to how max() works. */
88619   if( rc==SQLITE_DONE ) return SQLITE_DONE;
88620   if( rc!=SQLITE_ROW ) return rc;
88621
88622   /* NULL means that there were no inputs to max(). */
88623   if( SQLITE_NULL==sqlite3_column_type(s, 0) ){
88624     rc = sqlite3_step(s);
88625     if( rc==SQLITE_ROW ) return SQLITE_ERROR;
88626     return rc;
88627   }
88628
88629   *pidx = sqlite3_column_int(s, 0);
88630
88631   /* We expect only one row.  We must execute another sqlite3_step()
88632    * to complete the iteration; otherwise the table will remain locked. */
88633   rc = sqlite3_step(s);
88634   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
88635   if( rc!=SQLITE_DONE ) return rc;
88636   return SQLITE_ROW;
88637 }
88638
88639 /* insert into %_segdir values (
88640 **   [iLevel], [idx],
88641 **   [iStartBlockid], [iLeavesEndBlockid], [iEndBlockid],
88642 **   [pRootData]
88643 ** )
88644 */
88645 static int segdir_set(fulltext_vtab *v, int iLevel, int idx,
88646                       sqlite_int64 iStartBlockid,
88647                       sqlite_int64 iLeavesEndBlockid,
88648                       sqlite_int64 iEndBlockid,
88649                       const char *pRootData, int nRootData){
88650   sqlite3_stmt *s;
88651   int rc = sql_get_statement(v, SEGDIR_SET_STMT, &s);
88652   if( rc!=SQLITE_OK ) return rc;
88653
88654   rc = sqlite3_bind_int(s, 1, iLevel);
88655   if( rc!=SQLITE_OK ) return rc;
88656
88657   rc = sqlite3_bind_int(s, 2, idx);
88658   if( rc!=SQLITE_OK ) return rc;
88659
88660   rc = sqlite3_bind_int64(s, 3, iStartBlockid);
88661   if( rc!=SQLITE_OK ) return rc;
88662
88663   rc = sqlite3_bind_int64(s, 4, iLeavesEndBlockid);
88664   if( rc!=SQLITE_OK ) return rc;
88665
88666   rc = sqlite3_bind_int64(s, 5, iEndBlockid);
88667   if( rc!=SQLITE_OK ) return rc;
88668
88669   rc = sqlite3_bind_blob(s, 6, pRootData, nRootData, SQLITE_STATIC);
88670   if( rc!=SQLITE_OK ) return rc;
88671
88672   return sql_single_step(s);
88673 }
88674
88675 /* Queries %_segdir for the block span of the segments in level
88676 ** iLevel.  Returns SQLITE_DONE if there are no blocks for iLevel,
88677 ** SQLITE_ROW if there are blocks, else an error.
88678 */
88679 static int segdir_span(fulltext_vtab *v, int iLevel,
88680                        sqlite_int64 *piStartBlockid,
88681                        sqlite_int64 *piEndBlockid){
88682   sqlite3_stmt *s;
88683   int rc = sql_get_statement(v, SEGDIR_SPAN_STMT, &s);
88684   if( rc!=SQLITE_OK ) return rc;
88685
88686   rc = sqlite3_bind_int(s, 1, iLevel);
88687   if( rc!=SQLITE_OK ) return rc;
88688
88689   rc = sqlite3_step(s);
88690   if( rc==SQLITE_DONE ) return SQLITE_DONE;  /* Should never happen */
88691   if( rc!=SQLITE_ROW ) return rc;
88692
88693   /* This happens if all segments at this level are entirely inline. */
88694   if( SQLITE_NULL==sqlite3_column_type(s, 0) ){
88695     /* We expect only one row.  We must execute another sqlite3_step()
88696      * to complete the iteration; otherwise the table will remain locked. */
88697     int rc2 = sqlite3_step(s);
88698     if( rc2==SQLITE_ROW ) return SQLITE_ERROR;
88699     return rc2;
88700   }
88701
88702   *piStartBlockid = sqlite3_column_int64(s, 0);
88703   *piEndBlockid = sqlite3_column_int64(s, 1);
88704
88705   /* We expect only one row.  We must execute another sqlite3_step()
88706    * to complete the iteration; otherwise the table will remain locked. */
88707   rc = sqlite3_step(s);
88708   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
88709   if( rc!=SQLITE_DONE ) return rc;
88710   return SQLITE_ROW;
88711 }
88712
88713 /* Delete the segment blocks and segment directory records for all
88714 ** segments at iLevel.
88715 */
88716 static int segdir_delete(fulltext_vtab *v, int iLevel){
88717   sqlite3_stmt *s;
88718   sqlite_int64 iStartBlockid, iEndBlockid;
88719   int rc = segdir_span(v, iLevel, &iStartBlockid, &iEndBlockid);
88720   if( rc!=SQLITE_ROW && rc!=SQLITE_DONE ) return rc;
88721
88722   if( rc==SQLITE_ROW ){
88723     rc = block_delete(v, iStartBlockid, iEndBlockid);
88724     if( rc!=SQLITE_OK ) return rc;
88725   }
88726
88727   /* Delete the segment directory itself. */
88728   rc = sql_get_statement(v, SEGDIR_DELETE_STMT, &s);
88729   if( rc!=SQLITE_OK ) return rc;
88730
88731   rc = sqlite3_bind_int64(s, 1, iLevel);
88732   if( rc!=SQLITE_OK ) return rc;
88733
88734   return sql_single_step(s);
88735 }
88736
88737 /* Delete entire fts index, SQLITE_OK on success, relevant error on
88738 ** failure.
88739 */
88740 static int segdir_delete_all(fulltext_vtab *v){
88741   sqlite3_stmt *s;
88742   int rc = sql_get_statement(v, SEGDIR_DELETE_ALL_STMT, &s);
88743   if( rc!=SQLITE_OK ) return rc;
88744
88745   rc = sql_single_step(s);
88746   if( rc!=SQLITE_OK ) return rc;
88747
88748   rc = sql_get_statement(v, BLOCK_DELETE_ALL_STMT, &s);
88749   if( rc!=SQLITE_OK ) return rc;
88750
88751   return sql_single_step(s);
88752 }
88753
88754 /* Returns SQLITE_OK with *pnSegments set to the number of entries in
88755 ** %_segdir and *piMaxLevel set to the highest level which has a
88756 ** segment.  Otherwise returns the SQLite error which caused failure.
88757 */
88758 static int segdir_count(fulltext_vtab *v, int *pnSegments, int *piMaxLevel){
88759   sqlite3_stmt *s;
88760   int rc = sql_get_statement(v, SEGDIR_COUNT_STMT, &s);
88761   if( rc!=SQLITE_OK ) return rc;
88762
88763   rc = sqlite3_step(s);
88764   /* TODO(shess): This case should not be possible?  Should stronger
88765   ** measures be taken if it happens?
88766   */
88767   if( rc==SQLITE_DONE ){
88768     *pnSegments = 0;
88769     *piMaxLevel = 0;
88770     return SQLITE_OK;
88771   }
88772   if( rc!=SQLITE_ROW ) return rc;
88773
88774   *pnSegments = sqlite3_column_int(s, 0);
88775   *piMaxLevel = sqlite3_column_int(s, 1);
88776
88777   /* We expect only one row.  We must execute another sqlite3_step()
88778    * to complete the iteration; otherwise the table will remain locked. */
88779   rc = sqlite3_step(s);
88780   if( rc==SQLITE_DONE ) return SQLITE_OK;
88781   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
88782   return rc;
88783 }
88784
88785 /* TODO(shess) clearPendingTerms() is far down the file because
88786 ** writeZeroSegment() is far down the file because LeafWriter is far
88787 ** down the file.  Consider refactoring the code to move the non-vtab
88788 ** code above the vtab code so that we don't need this forward
88789 ** reference.
88790 */
88791 static int clearPendingTerms(fulltext_vtab *v);
88792
88793 /*
88794 ** Free the memory used to contain a fulltext_vtab structure.
88795 */
88796 static void fulltext_vtab_destroy(fulltext_vtab *v){
88797   int iStmt, i;
88798
88799   FTSTRACE(("FTS3 Destroy %p\n", v));
88800   for( iStmt=0; iStmt<MAX_STMT; iStmt++ ){
88801     if( v->pFulltextStatements[iStmt]!=NULL ){
88802       sqlite3_finalize(v->pFulltextStatements[iStmt]);
88803       v->pFulltextStatements[iStmt] = NULL;
88804     }
88805   }
88806
88807   for( i=0; i<MERGE_COUNT; i++ ){
88808     if( v->pLeafSelectStmts[i]!=NULL ){
88809       sqlite3_finalize(v->pLeafSelectStmts[i]);
88810       v->pLeafSelectStmts[i] = NULL;
88811     }
88812   }
88813
88814   if( v->pTokenizer!=NULL ){
88815     v->pTokenizer->pModule->xDestroy(v->pTokenizer);
88816     v->pTokenizer = NULL;
88817   }
88818
88819   clearPendingTerms(v);
88820
88821   sqlite3_free(v->azColumn);
88822   for(i = 0; i < v->nColumn; ++i) {
88823     sqlite3_free(v->azContentColumn[i]);
88824   }
88825   sqlite3_free(v->azContentColumn);
88826   sqlite3_free(v);
88827 }
88828
88829 /*
88830 ** Token types for parsing the arguments to xConnect or xCreate.
88831 */
88832 #define TOKEN_EOF         0    /* End of file */
88833 #define TOKEN_SPACE       1    /* Any kind of whitespace */
88834 #define TOKEN_ID          2    /* An identifier */
88835 #define TOKEN_STRING      3    /* A string literal */
88836 #define TOKEN_PUNCT       4    /* A single punctuation character */
88837
88838 /*
88839 ** If X is a character that can be used in an identifier then
88840 ** ftsIdChar(X) will be true.  Otherwise it is false.
88841 **
88842 ** For ASCII, any character with the high-order bit set is
88843 ** allowed in an identifier.  For 7-bit characters, 
88844 ** isFtsIdChar[X] must be 1.
88845 **
88846 ** Ticket #1066.  the SQL standard does not allow '$' in the
88847 ** middle of identfiers.  But many SQL implementations do. 
88848 ** SQLite will allow '$' in identifiers for compatibility.
88849 ** But the feature is undocumented.
88850 */
88851 static const char isFtsIdChar[] = {
88852 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
88853     0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
88854     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
88855     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
88856     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
88857     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
88858     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
88859 };
88860 #define ftsIdChar(C)  (((c=C)&0x80)!=0 || (c>0x1f && isFtsIdChar[c-0x20]))
88861
88862
88863 /*
88864 ** Return the length of the token that begins at z[0]. 
88865 ** Store the token type in *tokenType before returning.
88866 */
88867 static int ftsGetToken(const char *z, int *tokenType){
88868   int i, c;
88869   switch( *z ){
88870     case 0: {
88871       *tokenType = TOKEN_EOF;
88872       return 0;
88873     }
88874     case ' ': case '\t': case '\n': case '\f': case '\r': {
88875       for(i=1; safe_isspace(z[i]); i++){}
88876       *tokenType = TOKEN_SPACE;
88877       return i;
88878     }
88879     case '`':
88880     case '\'':
88881     case '"': {
88882       int delim = z[0];
88883       for(i=1; (c=z[i])!=0; i++){
88884         if( c==delim ){
88885           if( z[i+1]==delim ){
88886             i++;
88887           }else{
88888             break;
88889           }
88890         }
88891       }
88892       *tokenType = TOKEN_STRING;
88893       return i + (c!=0);
88894     }
88895     case '[': {
88896       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
88897       *tokenType = TOKEN_ID;
88898       return i;
88899     }
88900     default: {
88901       if( !ftsIdChar(*z) ){
88902         break;
88903       }
88904       for(i=1; ftsIdChar(z[i]); i++){}
88905       *tokenType = TOKEN_ID;
88906       return i;
88907     }
88908   }
88909   *tokenType = TOKEN_PUNCT;
88910   return 1;
88911 }
88912
88913 /*
88914 ** A token extracted from a string is an instance of the following
88915 ** structure.
88916 */
88917 typedef struct FtsToken {
88918   const char *z;       /* Pointer to token text.  Not '\000' terminated */
88919   short int n;         /* Length of the token text in bytes. */
88920 } FtsToken;
88921
88922 /*
88923 ** Given a input string (which is really one of the argv[] parameters
88924 ** passed into xConnect or xCreate) split the string up into tokens.
88925 ** Return an array of pointers to '\000' terminated strings, one string
88926 ** for each non-whitespace token.
88927 **
88928 ** The returned array is terminated by a single NULL pointer.
88929 **
88930 ** Space to hold the returned array is obtained from a single
88931 ** malloc and should be freed by passing the return value to free().
88932 ** The individual strings within the token list are all a part of
88933 ** the single memory allocation and will all be freed at once.
88934 */
88935 static char **tokenizeString(const char *z, int *pnToken){
88936   int nToken = 0;
88937   FtsToken *aToken = sqlite3_malloc( strlen(z) * sizeof(aToken[0]) );
88938   int n = 1;
88939   int e, i;
88940   int totalSize = 0;
88941   char **azToken;
88942   char *zCopy;
88943   while( n>0 ){
88944     n = ftsGetToken(z, &e);
88945     if( e!=TOKEN_SPACE ){
88946       aToken[nToken].z = z;
88947       aToken[nToken].n = n;
88948       nToken++;
88949       totalSize += n+1;
88950     }
88951     z += n;
88952   }
88953   azToken = (char**)sqlite3_malloc( nToken*sizeof(char*) + totalSize );
88954   zCopy = (char*)&azToken[nToken];
88955   nToken--;
88956   for(i=0; i<nToken; i++){
88957     azToken[i] = zCopy;
88958     n = aToken[i].n;
88959     memcpy(zCopy, aToken[i].z, n);
88960     zCopy[n] = 0;
88961     zCopy += n+1;
88962   }
88963   azToken[nToken] = 0;
88964   sqlite3_free(aToken);
88965   *pnToken = nToken;
88966   return azToken;
88967 }
88968
88969 /*
88970 ** Convert an SQL-style quoted string into a normal string by removing
88971 ** the quote characters.  The conversion is done in-place.  If the
88972 ** input does not begin with a quote character, then this routine
88973 ** is a no-op.
88974 **
88975 ** Examples:
88976 **
88977 **     "abc"   becomes   abc
88978 **     'xyz'   becomes   xyz
88979 **     [pqr]   becomes   pqr
88980 **     `mno`   becomes   mno
88981 */
88982 static void dequoteString(char *z){
88983   int quote;
88984   int i, j;
88985   if( z==0 ) return;
88986   quote = z[0];
88987   switch( quote ){
88988     case '\'':  break;
88989     case '"':   break;
88990     case '`':   break;                /* For MySQL compatibility */
88991     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
88992     default:    return;
88993   }
88994   for(i=1, j=0; z[i]; i++){
88995     if( z[i]==quote ){
88996       if( z[i+1]==quote ){
88997         z[j++] = quote;
88998         i++;
88999       }else{
89000         z[j++] = 0;
89001         break;
89002       }
89003     }else{
89004       z[j++] = z[i];
89005     }
89006   }
89007 }
89008
89009 /*
89010 ** The input azIn is a NULL-terminated list of tokens.  Remove the first
89011 ** token and all punctuation tokens.  Remove the quotes from
89012 ** around string literal tokens.
89013 **
89014 ** Example:
89015 **
89016 **     input:      tokenize chinese ( 'simplifed' , 'mixed' )
89017 **     output:     chinese simplifed mixed
89018 **
89019 ** Another example:
89020 **
89021 **     input:      delimiters ( '[' , ']' , '...' )
89022 **     output:     [ ] ...
89023 */
89024 static void tokenListToIdList(char **azIn){
89025   int i, j;
89026   if( azIn ){
89027     for(i=0, j=-1; azIn[i]; i++){
89028       if( safe_isalnum(azIn[i][0]) || azIn[i][1] ){
89029         dequoteString(azIn[i]);
89030         if( j>=0 ){
89031           azIn[j] = azIn[i];
89032         }
89033         j++;
89034       }
89035     }
89036     azIn[j] = 0;
89037   }
89038 }
89039
89040
89041 /*
89042 ** Find the first alphanumeric token in the string zIn.  Null-terminate
89043 ** this token.  Remove any quotation marks.  And return a pointer to
89044 ** the result.
89045 */
89046 static char *firstToken(char *zIn, char **pzTail){
89047   int n, ttype;
89048   while(1){
89049     n = ftsGetToken(zIn, &ttype);
89050     if( ttype==TOKEN_SPACE ){
89051       zIn += n;
89052     }else if( ttype==TOKEN_EOF ){
89053       *pzTail = zIn;
89054       return 0;
89055     }else{
89056       zIn[n] = 0;
89057       *pzTail = &zIn[1];
89058       dequoteString(zIn);
89059       return zIn;
89060     }
89061   }
89062   /*NOTREACHED*/
89063 }
89064
89065 /* Return true if...
89066 **
89067 **   *  s begins with the string t, ignoring case
89068 **   *  s is longer than t
89069 **   *  The first character of s beyond t is not a alphanumeric
89070 ** 
89071 ** Ignore leading space in *s.
89072 **
89073 ** To put it another way, return true if the first token of
89074 ** s[] is t[].
89075 */
89076 static int startsWith(const char *s, const char *t){
89077   while( safe_isspace(*s) ){ s++; }
89078   while( *t ){
89079     if( safe_tolower(*s++)!=safe_tolower(*t++) ) return 0;
89080   }
89081   return *s!='_' && !safe_isalnum(*s);
89082 }
89083
89084 /*
89085 ** An instance of this structure defines the "spec" of a
89086 ** full text index.  This structure is populated by parseSpec
89087 ** and use by fulltextConnect and fulltextCreate.
89088 */
89089 typedef struct TableSpec {
89090   const char *zDb;         /* Logical database name */
89091   const char *zName;       /* Name of the full-text index */
89092   int nColumn;             /* Number of columns to be indexed */
89093   char **azColumn;         /* Original names of columns to be indexed */
89094   char **azContentColumn;  /* Column names for %_content */
89095   char **azTokenizer;      /* Name of tokenizer and its arguments */
89096 } TableSpec;
89097
89098 /*
89099 ** Reclaim all of the memory used by a TableSpec
89100 */
89101 static void clearTableSpec(TableSpec *p) {
89102   sqlite3_free(p->azColumn);
89103   sqlite3_free(p->azContentColumn);
89104   sqlite3_free(p->azTokenizer);
89105 }
89106
89107 /* Parse a CREATE VIRTUAL TABLE statement, which looks like this:
89108  *
89109  * CREATE VIRTUAL TABLE email
89110  *        USING fts3(subject, body, tokenize mytokenizer(myarg))
89111  *
89112  * We return parsed information in a TableSpec structure.
89113  * 
89114  */
89115 static int parseSpec(TableSpec *pSpec, int argc, const char *const*argv,
89116                      char**pzErr){
89117   int i, n;
89118   char *z, *zDummy;
89119   char **azArg;
89120   const char *zTokenizer = 0;    /* argv[] entry describing the tokenizer */
89121
89122   assert( argc>=3 );
89123   /* Current interface:
89124   ** argv[0] - module name
89125   ** argv[1] - database name
89126   ** argv[2] - table name
89127   ** argv[3..] - columns, optionally followed by tokenizer specification
89128   **             and snippet delimiters specification.
89129   */
89130
89131   /* Make a copy of the complete argv[][] array in a single allocation.
89132   ** The argv[][] array is read-only and transient.  We can write to the
89133   ** copy in order to modify things and the copy is persistent.
89134   */
89135   CLEAR(pSpec);
89136   for(i=n=0; i<argc; i++){
89137     n += strlen(argv[i]) + 1;
89138   }
89139   azArg = sqlite3_malloc( sizeof(char*)*argc + n );
89140   if( azArg==0 ){
89141     return SQLITE_NOMEM;
89142   }
89143   z = (char*)&azArg[argc];
89144   for(i=0; i<argc; i++){
89145     azArg[i] = z;
89146     strcpy(z, argv[i]);
89147     z += strlen(z)+1;
89148   }
89149
89150   /* Identify the column names and the tokenizer and delimiter arguments
89151   ** in the argv[][] array.
89152   */
89153   pSpec->zDb = azArg[1];
89154   pSpec->zName = azArg[2];
89155   pSpec->nColumn = 0;
89156   pSpec->azColumn = azArg;
89157   zTokenizer = "tokenize simple";
89158   for(i=3; i<argc; ++i){
89159     if( startsWith(azArg[i],"tokenize") ){
89160       zTokenizer = azArg[i];
89161     }else{
89162       z = azArg[pSpec->nColumn] = firstToken(azArg[i], &zDummy);
89163       pSpec->nColumn++;
89164     }
89165   }
89166   if( pSpec->nColumn==0 ){
89167     azArg[0] = "content";
89168     pSpec->nColumn = 1;
89169   }
89170
89171   /*
89172   ** Construct the list of content column names.
89173   **
89174   ** Each content column name will be of the form cNNAAAA
89175   ** where NN is the column number and AAAA is the sanitized
89176   ** column name.  "sanitized" means that special characters are
89177   ** converted to "_".  The cNN prefix guarantees that all column
89178   ** names are unique.
89179   **
89180   ** The AAAA suffix is not strictly necessary.  It is included
89181   ** for the convenience of people who might examine the generated
89182   ** %_content table and wonder what the columns are used for.
89183   */
89184   pSpec->azContentColumn = sqlite3_malloc( pSpec->nColumn * sizeof(char *) );
89185   if( pSpec->azContentColumn==0 ){
89186     clearTableSpec(pSpec);
89187     return SQLITE_NOMEM;
89188   }
89189   for(i=0; i<pSpec->nColumn; i++){
89190     char *p;
89191     pSpec->azContentColumn[i] = sqlite3_mprintf("c%d%s", i, azArg[i]);
89192     for (p = pSpec->azContentColumn[i]; *p ; ++p) {
89193       if( !safe_isalnum(*p) ) *p = '_';
89194     }
89195   }
89196
89197   /*
89198   ** Parse the tokenizer specification string.
89199   */
89200   pSpec->azTokenizer = tokenizeString(zTokenizer, &n);
89201   tokenListToIdList(pSpec->azTokenizer);
89202
89203   return SQLITE_OK;
89204 }
89205
89206 /*
89207 ** Generate a CREATE TABLE statement that describes the schema of
89208 ** the virtual table.  Return a pointer to this schema string.
89209 **
89210 ** Space is obtained from sqlite3_mprintf() and should be freed
89211 ** using sqlite3_free().
89212 */
89213 static char *fulltextSchema(
89214   int nColumn,                  /* Number of columns */
89215   const char *const* azColumn,  /* List of columns */
89216   const char *zTableName        /* Name of the table */
89217 ){
89218   int i;
89219   char *zSchema, *zNext;
89220   const char *zSep = "(";
89221   zSchema = sqlite3_mprintf("CREATE TABLE x");
89222   for(i=0; i<nColumn; i++){
89223     zNext = sqlite3_mprintf("%s%s%Q", zSchema, zSep, azColumn[i]);
89224     sqlite3_free(zSchema);
89225     zSchema = zNext;
89226     zSep = ",";
89227   }
89228   zNext = sqlite3_mprintf("%s,%Q HIDDEN", zSchema, zTableName);
89229   sqlite3_free(zSchema);
89230   zSchema = zNext;
89231   zNext = sqlite3_mprintf("%s,docid HIDDEN)", zSchema);
89232   sqlite3_free(zSchema);
89233   return zNext;
89234 }
89235
89236 /*
89237 ** Build a new sqlite3_vtab structure that will describe the
89238 ** fulltext index defined by spec.
89239 */
89240 static int constructVtab(
89241   sqlite3 *db,              /* The SQLite database connection */
89242   fts3Hash *pHash,          /* Hash table containing tokenizers */
89243   TableSpec *spec,          /* Parsed spec information from parseSpec() */
89244   sqlite3_vtab **ppVTab,    /* Write the resulting vtab structure here */
89245   char **pzErr              /* Write any error message here */
89246 ){
89247   int rc;
89248   int n;
89249   fulltext_vtab *v = 0;
89250   const sqlite3_tokenizer_module *m = NULL;
89251   char *schema;
89252
89253   char const *zTok;         /* Name of tokenizer to use for this fts table */
89254   int nTok;                 /* Length of zTok, including nul terminator */
89255
89256   v = (fulltext_vtab *) sqlite3_malloc(sizeof(fulltext_vtab));
89257   if( v==0 ) return SQLITE_NOMEM;
89258   CLEAR(v);
89259   /* sqlite will initialize v->base */
89260   v->db = db;
89261   v->zDb = spec->zDb;       /* Freed when azColumn is freed */
89262   v->zName = spec->zName;   /* Freed when azColumn is freed */
89263   v->nColumn = spec->nColumn;
89264   v->azContentColumn = spec->azContentColumn;
89265   spec->azContentColumn = 0;
89266   v->azColumn = spec->azColumn;
89267   spec->azColumn = 0;
89268
89269   if( spec->azTokenizer==0 ){
89270     return SQLITE_NOMEM;
89271   }
89272
89273   zTok = spec->azTokenizer[0]; 
89274   if( !zTok ){
89275     zTok = "simple";
89276   }
89277   nTok = strlen(zTok)+1;
89278
89279   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zTok, nTok);
89280   if( !m ){
89281     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", spec->azTokenizer[0]);
89282     rc = SQLITE_ERROR;
89283     goto err;
89284   }
89285
89286   for(n=0; spec->azTokenizer[n]; n++){}
89287   if( n ){
89288     rc = m->xCreate(n-1, (const char*const*)&spec->azTokenizer[1],
89289                     &v->pTokenizer);
89290   }else{
89291     rc = m->xCreate(0, 0, &v->pTokenizer);
89292   }
89293   if( rc!=SQLITE_OK ) goto err;
89294   v->pTokenizer->pModule = m;
89295
89296   /* TODO: verify the existence of backing tables foo_content, foo_term */
89297
89298   schema = fulltextSchema(v->nColumn, (const char*const*)v->azColumn,
89299                           spec->zName);
89300   rc = sqlite3_declare_vtab(db, schema);
89301   sqlite3_free(schema);
89302   if( rc!=SQLITE_OK ) goto err;
89303
89304   memset(v->pFulltextStatements, 0, sizeof(v->pFulltextStatements));
89305
89306   /* Indicate that the buffer is not live. */
89307   v->nPendingData = -1;
89308
89309   *ppVTab = &v->base;
89310   FTSTRACE(("FTS3 Connect %p\n", v));
89311
89312   return rc;
89313
89314 err:
89315   fulltext_vtab_destroy(v);
89316   return rc;
89317 }
89318
89319 static int fulltextConnect(
89320   sqlite3 *db,
89321   void *pAux,
89322   int argc, const char *const*argv,
89323   sqlite3_vtab **ppVTab,
89324   char **pzErr
89325 ){
89326   TableSpec spec;
89327   int rc = parseSpec(&spec, argc, argv, pzErr);
89328   if( rc!=SQLITE_OK ) return rc;
89329
89330   rc = constructVtab(db, (fts3Hash *)pAux, &spec, ppVTab, pzErr);
89331   clearTableSpec(&spec);
89332   return rc;
89333 }
89334
89335 /* The %_content table holds the text of each document, with
89336 ** the docid column exposed as the SQLite rowid for the table.
89337 */
89338 /* TODO(shess) This comment needs elaboration to match the updated
89339 ** code.  Work it into the top-of-file comment at that time.
89340 */
89341 static int fulltextCreate(sqlite3 *db, void *pAux,
89342                           int argc, const char * const *argv,
89343                           sqlite3_vtab **ppVTab, char **pzErr){
89344   int rc;
89345   TableSpec spec;
89346   StringBuffer schema;
89347   FTSTRACE(("FTS3 Create\n"));
89348
89349   rc = parseSpec(&spec, argc, argv, pzErr);
89350   if( rc!=SQLITE_OK ) return rc;
89351
89352   initStringBuffer(&schema);
89353   append(&schema, "CREATE TABLE %_content(");
89354   append(&schema, "  docid INTEGER PRIMARY KEY,");
89355   appendList(&schema, spec.nColumn, spec.azContentColumn);
89356   append(&schema, ")");
89357   rc = sql_exec(db, spec.zDb, spec.zName, stringBufferData(&schema));
89358   stringBufferDestroy(&schema);
89359   if( rc!=SQLITE_OK ) goto out;
89360
89361   rc = sql_exec(db, spec.zDb, spec.zName,
89362                 "create table %_segments("
89363                 "  blockid INTEGER PRIMARY KEY,"
89364                 "  block blob"
89365                 ");"
89366                 );
89367   if( rc!=SQLITE_OK ) goto out;
89368
89369   rc = sql_exec(db, spec.zDb, spec.zName,
89370                 "create table %_segdir("
89371                 "  level integer,"
89372                 "  idx integer,"
89373                 "  start_block integer,"
89374                 "  leaves_end_block integer,"
89375                 "  end_block integer,"
89376                 "  root blob,"
89377                 "  primary key(level, idx)"
89378                 ");");
89379   if( rc!=SQLITE_OK ) goto out;
89380
89381   rc = constructVtab(db, (fts3Hash *)pAux, &spec, ppVTab, pzErr);
89382
89383 out:
89384   clearTableSpec(&spec);
89385   return rc;
89386 }
89387
89388 /* Decide how to handle an SQL query. */
89389 static int fulltextBestIndex(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
89390   fulltext_vtab *v = (fulltext_vtab *)pVTab;
89391   int i;
89392   FTSTRACE(("FTS3 BestIndex\n"));
89393
89394   for(i=0; i<pInfo->nConstraint; ++i){
89395     const struct sqlite3_index_constraint *pConstraint;
89396     pConstraint = &pInfo->aConstraint[i];
89397     if( pConstraint->usable ) {
89398       if( (pConstraint->iColumn==-1 || pConstraint->iColumn==v->nColumn+1) &&
89399           pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
89400         pInfo->idxNum = QUERY_DOCID;      /* lookup by docid */
89401         FTSTRACE(("FTS3 QUERY_DOCID\n"));
89402       } else if( pConstraint->iColumn>=0 && pConstraint->iColumn<=v->nColumn &&
89403                  pConstraint->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
89404         /* full-text search */
89405         pInfo->idxNum = QUERY_FULLTEXT + pConstraint->iColumn;
89406         FTSTRACE(("FTS3 QUERY_FULLTEXT %d\n", pConstraint->iColumn));
89407       } else continue;
89408
89409       pInfo->aConstraintUsage[i].argvIndex = 1;
89410       pInfo->aConstraintUsage[i].omit = 1;
89411
89412       /* An arbitrary value for now.
89413        * TODO: Perhaps docid matches should be considered cheaper than
89414        * full-text searches. */
89415       pInfo->estimatedCost = 1.0;   
89416
89417       return SQLITE_OK;
89418     }
89419   }
89420   pInfo->idxNum = QUERY_GENERIC;
89421   return SQLITE_OK;
89422 }
89423
89424 static int fulltextDisconnect(sqlite3_vtab *pVTab){
89425   FTSTRACE(("FTS3 Disconnect %p\n", pVTab));
89426   fulltext_vtab_destroy((fulltext_vtab *)pVTab);
89427   return SQLITE_OK;
89428 }
89429
89430 static int fulltextDestroy(sqlite3_vtab *pVTab){
89431   fulltext_vtab *v = (fulltext_vtab *)pVTab;
89432   int rc;
89433
89434   FTSTRACE(("FTS3 Destroy %p\n", pVTab));
89435   rc = sql_exec(v->db, v->zDb, v->zName,
89436                 "drop table if exists %_content;"
89437                 "drop table if exists %_segments;"
89438                 "drop table if exists %_segdir;"
89439                 );
89440   if( rc!=SQLITE_OK ) return rc;
89441
89442   fulltext_vtab_destroy((fulltext_vtab *)pVTab);
89443   return SQLITE_OK;
89444 }
89445
89446 static int fulltextOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
89447   fulltext_cursor *c;
89448
89449   c = (fulltext_cursor *) sqlite3_malloc(sizeof(fulltext_cursor));
89450   if( c ){
89451     memset(c, 0, sizeof(fulltext_cursor));
89452     /* sqlite will initialize c->base */
89453     *ppCursor = &c->base;
89454     FTSTRACE(("FTS3 Open %p: %p\n", pVTab, c));
89455     return SQLITE_OK;
89456   }else{
89457     return SQLITE_NOMEM;
89458   }
89459 }
89460
89461
89462 /* Free all of the dynamically allocated memory held by *q
89463 */
89464 static void queryClear(Query *q){
89465   int i;
89466   for(i = 0; i < q->nTerms; ++i){
89467     sqlite3_free(q->pTerms[i].pTerm);
89468   }
89469   sqlite3_free(q->pTerms);
89470   CLEAR(q);
89471 }
89472
89473 /* Free all of the dynamically allocated memory held by the
89474 ** Snippet
89475 */
89476 static void snippetClear(Snippet *p){
89477   sqlite3_free(p->aMatch);
89478   sqlite3_free(p->zOffset);
89479   sqlite3_free(p->zSnippet);
89480   CLEAR(p);
89481 }
89482 /*
89483 ** Append a single entry to the p->aMatch[] log.
89484 */
89485 static void snippetAppendMatch(
89486   Snippet *p,               /* Append the entry to this snippet */
89487   int iCol, int iTerm,      /* The column and query term */
89488   int iToken,               /* Matching token in document */
89489   int iStart, int nByte     /* Offset and size of the match */
89490 ){
89491   int i;
89492   struct snippetMatch *pMatch;
89493   if( p->nMatch+1>=p->nAlloc ){
89494     p->nAlloc = p->nAlloc*2 + 10;
89495     p->aMatch = sqlite3_realloc(p->aMatch, p->nAlloc*sizeof(p->aMatch[0]) );
89496     if( p->aMatch==0 ){
89497       p->nMatch = 0;
89498       p->nAlloc = 0;
89499       return;
89500     }
89501   }
89502   i = p->nMatch++;
89503   pMatch = &p->aMatch[i];
89504   pMatch->iCol = iCol;
89505   pMatch->iTerm = iTerm;
89506   pMatch->iToken = iToken;
89507   pMatch->iStart = iStart;
89508   pMatch->nByte = nByte;
89509 }
89510
89511 /*
89512 ** Sizing information for the circular buffer used in snippetOffsetsOfColumn()
89513 */
89514 #define FTS3_ROTOR_SZ   (32)
89515 #define FTS3_ROTOR_MASK (FTS3_ROTOR_SZ-1)
89516
89517 /*
89518 ** Add entries to pSnippet->aMatch[] for every match that occurs against
89519 ** document zDoc[0..nDoc-1] which is stored in column iColumn.
89520 */
89521 static void snippetOffsetsOfColumn(
89522   Query *pQuery,
89523   Snippet *pSnippet,
89524   int iColumn,
89525   const char *zDoc,
89526   int nDoc
89527 ){
89528   const sqlite3_tokenizer_module *pTModule;  /* The tokenizer module */
89529   sqlite3_tokenizer *pTokenizer;             /* The specific tokenizer */
89530   sqlite3_tokenizer_cursor *pTCursor;        /* Tokenizer cursor */
89531   fulltext_vtab *pVtab;                /* The full text index */
89532   int nColumn;                         /* Number of columns in the index */
89533   const QueryTerm *aTerm;              /* Query string terms */
89534   int nTerm;                           /* Number of query string terms */  
89535   int i, j;                            /* Loop counters */
89536   int rc;                              /* Return code */
89537   unsigned int match, prevMatch;       /* Phrase search bitmasks */
89538   const char *zToken;                  /* Next token from the tokenizer */
89539   int nToken;                          /* Size of zToken */
89540   int iBegin, iEnd, iPos;              /* Offsets of beginning and end */
89541
89542   /* The following variables keep a circular buffer of the last
89543   ** few tokens */
89544   unsigned int iRotor = 0;             /* Index of current token */
89545   int iRotorBegin[FTS3_ROTOR_SZ];      /* Beginning offset of token */
89546   int iRotorLen[FTS3_ROTOR_SZ];        /* Length of token */
89547
89548   pVtab = pQuery->pFts;
89549   nColumn = pVtab->nColumn;
89550   pTokenizer = pVtab->pTokenizer;
89551   pTModule = pTokenizer->pModule;
89552   rc = pTModule->xOpen(pTokenizer, zDoc, nDoc, &pTCursor);
89553   if( rc ) return;
89554   pTCursor->pTokenizer = pTokenizer;
89555   aTerm = pQuery->pTerms;
89556   nTerm = pQuery->nTerms;
89557   if( nTerm>=FTS3_ROTOR_SZ ){
89558     nTerm = FTS3_ROTOR_SZ - 1;
89559   }
89560   prevMatch = 0;
89561   while(1){
89562     rc = pTModule->xNext(pTCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
89563     if( rc ) break;
89564     iRotorBegin[iRotor&FTS3_ROTOR_MASK] = iBegin;
89565     iRotorLen[iRotor&FTS3_ROTOR_MASK] = iEnd-iBegin;
89566     match = 0;
89567     for(i=0; i<nTerm; i++){
89568       int iCol;
89569       iCol = aTerm[i].iColumn;
89570       if( iCol>=0 && iCol<nColumn && iCol!=iColumn ) continue;
89571       if( aTerm[i].nTerm>nToken ) continue;
89572       if( !aTerm[i].isPrefix && aTerm[i].nTerm<nToken ) continue;
89573       assert( aTerm[i].nTerm<=nToken );
89574       if( memcmp(aTerm[i].pTerm, zToken, aTerm[i].nTerm) ) continue;
89575       if( aTerm[i].iPhrase>1 && (prevMatch & (1<<i))==0 ) continue;
89576       match |= 1<<i;
89577       if( i==nTerm-1 || aTerm[i+1].iPhrase==1 ){
89578         for(j=aTerm[i].iPhrase-1; j>=0; j--){
89579           int k = (iRotor-j) & FTS3_ROTOR_MASK;
89580           snippetAppendMatch(pSnippet, iColumn, i-j, iPos-j,
89581                 iRotorBegin[k], iRotorLen[k]);
89582         }
89583       }
89584     }
89585     prevMatch = match<<1;
89586     iRotor++;
89587   }
89588   pTModule->xClose(pTCursor);  
89589 }
89590
89591 /*
89592 ** Remove entries from the pSnippet structure to account for the NEAR
89593 ** operator. When this is called, pSnippet contains the list of token 
89594 ** offsets produced by treating all NEAR operators as AND operators.
89595 ** This function removes any entries that should not be present after
89596 ** accounting for the NEAR restriction. For example, if the queried
89597 ** document is:
89598 **
89599 **     "A B C D E A"
89600 **
89601 ** and the query is:
89602 ** 
89603 **     A NEAR/0 E
89604 **
89605 ** then when this function is called the Snippet contains token offsets
89606 ** 0, 4 and 5. This function removes the "0" entry (because the first A
89607 ** is not near enough to an E).
89608 */
89609 static void trimSnippetOffsetsForNear(Query *pQuery, Snippet *pSnippet){
89610   int ii;
89611   int iDir = 1;
89612
89613   while(iDir>-2) {
89614     assert( iDir==1 || iDir==-1 );
89615     for(ii=0; ii<pSnippet->nMatch; ii++){
89616       int jj;
89617       int nNear;
89618       struct snippetMatch *pMatch = &pSnippet->aMatch[ii];
89619       QueryTerm *pQueryTerm = &pQuery->pTerms[pMatch->iTerm];
89620
89621       if( (pMatch->iTerm+iDir)<0 
89622        || (pMatch->iTerm+iDir)>=pQuery->nTerms
89623       ){
89624         continue;
89625       }
89626      
89627       nNear = pQueryTerm->nNear;
89628       if( iDir<0 ){
89629         nNear = pQueryTerm[-1].nNear;
89630       }
89631   
89632       if( pMatch->iTerm>=0 && nNear ){
89633         int isOk = 0;
89634         int iNextTerm = pMatch->iTerm+iDir;
89635         int iPrevTerm = iNextTerm;
89636
89637         int iEndToken;
89638         int iStartToken;
89639
89640         if( iDir<0 ){
89641           int nPhrase = 1;
89642           iStartToken = pMatch->iToken;
89643           while( (pMatch->iTerm+nPhrase)<pQuery->nTerms 
89644               && pQuery->pTerms[pMatch->iTerm+nPhrase].iPhrase>1 
89645           ){
89646             nPhrase++;
89647           }
89648           iEndToken = iStartToken + nPhrase - 1;
89649         }else{
89650           iEndToken   = pMatch->iToken;
89651           iStartToken = pMatch->iToken+1-pQueryTerm->iPhrase;
89652         }
89653
89654         while( pQuery->pTerms[iNextTerm].iPhrase>1 ){
89655           iNextTerm--;
89656         }
89657         while( (iPrevTerm+1)<pQuery->nTerms && 
89658                pQuery->pTerms[iPrevTerm+1].iPhrase>1 
89659         ){
89660           iPrevTerm++;
89661         }
89662   
89663         for(jj=0; isOk==0 && jj<pSnippet->nMatch; jj++){
89664           struct snippetMatch *p = &pSnippet->aMatch[jj];
89665           if( p->iCol==pMatch->iCol && ((
89666                p->iTerm==iNextTerm && 
89667                p->iToken>iEndToken && 
89668                p->iToken<=iEndToken+nNear
89669           ) || (
89670                p->iTerm==iPrevTerm && 
89671                p->iToken<iStartToken && 
89672                p->iToken>=iStartToken-nNear
89673           ))){
89674             isOk = 1;
89675           }
89676         }
89677         if( !isOk ){
89678           for(jj=1-pQueryTerm->iPhrase; jj<=0; jj++){
89679             pMatch[jj].iTerm = -1;
89680           }
89681           ii = -1;
89682           iDir = 1;
89683         }
89684       }
89685     }
89686     iDir -= 2;
89687   }
89688 }
89689
89690 /*
89691 ** Compute all offsets for the current row of the query.  
89692 ** If the offsets have already been computed, this routine is a no-op.
89693 */
89694 static void snippetAllOffsets(fulltext_cursor *p){
89695   int nColumn;
89696   int iColumn, i;
89697   int iFirst, iLast;
89698   fulltext_vtab *pFts;
89699
89700   if( p->snippet.nMatch ) return;
89701   if( p->q.nTerms==0 ) return;
89702   pFts = p->q.pFts;
89703   nColumn = pFts->nColumn;
89704   iColumn = (p->iCursorType - QUERY_FULLTEXT);
89705   if( iColumn<0 || iColumn>=nColumn ){
89706     iFirst = 0;
89707     iLast = nColumn-1;
89708   }else{
89709     iFirst = iColumn;
89710     iLast = iColumn;
89711   }
89712   for(i=iFirst; i<=iLast; i++){
89713     const char *zDoc;
89714     int nDoc;
89715     zDoc = (const char*)sqlite3_column_text(p->pStmt, i+1);
89716     nDoc = sqlite3_column_bytes(p->pStmt, i+1);
89717     snippetOffsetsOfColumn(&p->q, &p->snippet, i, zDoc, nDoc);
89718   }
89719
89720   trimSnippetOffsetsForNear(&p->q, &p->snippet);
89721 }
89722
89723 /*
89724 ** Convert the information in the aMatch[] array of the snippet
89725 ** into the string zOffset[0..nOffset-1].
89726 */
89727 static void snippetOffsetText(Snippet *p){
89728   int i;
89729   int cnt = 0;
89730   StringBuffer sb;
89731   char zBuf[200];
89732   if( p->zOffset ) return;
89733   initStringBuffer(&sb);
89734   for(i=0; i<p->nMatch; i++){
89735     struct snippetMatch *pMatch = &p->aMatch[i];
89736     if( pMatch->iTerm>=0 ){
89737       /* If snippetMatch.iTerm is less than 0, then the match was 
89738       ** discarded as part of processing the NEAR operator (see the 
89739       ** trimSnippetOffsetsForNear() function for details). Ignore 
89740       ** it in this case
89741       */
89742       zBuf[0] = ' ';
89743       sqlite3_snprintf(sizeof(zBuf)-1, &zBuf[cnt>0], "%d %d %d %d",
89744           pMatch->iCol, pMatch->iTerm, pMatch->iStart, pMatch->nByte);
89745       append(&sb, zBuf);
89746       cnt++;
89747     }
89748   }
89749   p->zOffset = stringBufferData(&sb);
89750   p->nOffset = stringBufferLength(&sb);
89751 }
89752
89753 /*
89754 ** zDoc[0..nDoc-1] is phrase of text.  aMatch[0..nMatch-1] are a set
89755 ** of matching words some of which might be in zDoc.  zDoc is column
89756 ** number iCol.
89757 **
89758 ** iBreak is suggested spot in zDoc where we could begin or end an
89759 ** excerpt.  Return a value similar to iBreak but possibly adjusted
89760 ** to be a little left or right so that the break point is better.
89761 */
89762 static int wordBoundary(
89763   int iBreak,                   /* The suggested break point */
89764   const char *zDoc,             /* Document text */
89765   int nDoc,                     /* Number of bytes in zDoc[] */
89766   struct snippetMatch *aMatch,  /* Matching words */
89767   int nMatch,                   /* Number of entries in aMatch[] */
89768   int iCol                      /* The column number for zDoc[] */
89769 ){
89770   int i;
89771   if( iBreak<=10 ){
89772     return 0;
89773   }
89774   if( iBreak>=nDoc-10 ){
89775     return nDoc;
89776   }
89777   for(i=0; i<nMatch && aMatch[i].iCol<iCol; i++){}
89778   while( i<nMatch && aMatch[i].iStart+aMatch[i].nByte<iBreak ){ i++; }
89779   if( i<nMatch ){
89780     if( aMatch[i].iStart<iBreak+10 ){
89781       return aMatch[i].iStart;
89782     }
89783     if( i>0 && aMatch[i-1].iStart+aMatch[i-1].nByte>=iBreak ){
89784       return aMatch[i-1].iStart;
89785     }
89786   }
89787   for(i=1; i<=10; i++){
89788     if( safe_isspace(zDoc[iBreak-i]) ){
89789       return iBreak - i + 1;
89790     }
89791     if( safe_isspace(zDoc[iBreak+i]) ){
89792       return iBreak + i + 1;
89793     }
89794   }
89795   return iBreak;
89796 }
89797
89798
89799
89800 /*
89801 ** Allowed values for Snippet.aMatch[].snStatus
89802 */
89803 #define SNIPPET_IGNORE  0   /* It is ok to omit this match from the snippet */
89804 #define SNIPPET_DESIRED 1   /* We want to include this match in the snippet */
89805
89806 /*
89807 ** Generate the text of a snippet.
89808 */
89809 static void snippetText(
89810   fulltext_cursor *pCursor,   /* The cursor we need the snippet for */
89811   const char *zStartMark,     /* Markup to appear before each match */
89812   const char *zEndMark,       /* Markup to appear after each match */
89813   const char *zEllipsis       /* Ellipsis mark */
89814 ){
89815   int i, j;
89816   struct snippetMatch *aMatch;
89817   int nMatch;
89818   int nDesired;
89819   StringBuffer sb;
89820   int tailCol;
89821   int tailOffset;
89822   int iCol;
89823   int nDoc;
89824   const char *zDoc;
89825   int iStart, iEnd;
89826   int tailEllipsis = 0;
89827   int iMatch;
89828   
89829
89830   sqlite3_free(pCursor->snippet.zSnippet);
89831   pCursor->snippet.zSnippet = 0;
89832   aMatch = pCursor->snippet.aMatch;
89833   nMatch = pCursor->snippet.nMatch;
89834   initStringBuffer(&sb);
89835
89836   for(i=0; i<nMatch; i++){
89837     aMatch[i].snStatus = SNIPPET_IGNORE;
89838   }
89839   nDesired = 0;
89840   for(i=0; i<pCursor->q.nTerms; i++){
89841     for(j=0; j<nMatch; j++){
89842       if( aMatch[j].iTerm==i ){
89843         aMatch[j].snStatus = SNIPPET_DESIRED;
89844         nDesired++;
89845         break;
89846       }
89847     }
89848   }
89849
89850   iMatch = 0;
89851   tailCol = -1;
89852   tailOffset = 0;
89853   for(i=0; i<nMatch && nDesired>0; i++){
89854     if( aMatch[i].snStatus!=SNIPPET_DESIRED ) continue;
89855     nDesired--;
89856     iCol = aMatch[i].iCol;
89857     zDoc = (const char*)sqlite3_column_text(pCursor->pStmt, iCol+1);
89858     nDoc = sqlite3_column_bytes(pCursor->pStmt, iCol+1);
89859     iStart = aMatch[i].iStart - 40;
89860     iStart = wordBoundary(iStart, zDoc, nDoc, aMatch, nMatch, iCol);
89861     if( iStart<=10 ){
89862       iStart = 0;
89863     }
89864     if( iCol==tailCol && iStart<=tailOffset+20 ){
89865       iStart = tailOffset;
89866     }
89867     if( (iCol!=tailCol && tailCol>=0) || iStart!=tailOffset ){
89868       trimWhiteSpace(&sb);
89869       appendWhiteSpace(&sb);
89870       append(&sb, zEllipsis);
89871       appendWhiteSpace(&sb);
89872     }
89873     iEnd = aMatch[i].iStart + aMatch[i].nByte + 40;
89874     iEnd = wordBoundary(iEnd, zDoc, nDoc, aMatch, nMatch, iCol);
89875     if( iEnd>=nDoc-10 ){
89876       iEnd = nDoc;
89877       tailEllipsis = 0;
89878     }else{
89879       tailEllipsis = 1;
89880     }
89881     while( iMatch<nMatch && aMatch[iMatch].iCol<iCol ){ iMatch++; }
89882     while( iStart<iEnd ){
89883       while( iMatch<nMatch && aMatch[iMatch].iStart<iStart
89884              && aMatch[iMatch].iCol<=iCol ){
89885         iMatch++;
89886       }
89887       if( iMatch<nMatch && aMatch[iMatch].iStart<iEnd
89888              && aMatch[iMatch].iCol==iCol ){
89889         nappend(&sb, &zDoc[iStart], aMatch[iMatch].iStart - iStart);
89890         iStart = aMatch[iMatch].iStart;
89891         append(&sb, zStartMark);
89892         nappend(&sb, &zDoc[iStart], aMatch[iMatch].nByte);
89893         append(&sb, zEndMark);
89894         iStart += aMatch[iMatch].nByte;
89895         for(j=iMatch+1; j<nMatch; j++){
89896           if( aMatch[j].iTerm==aMatch[iMatch].iTerm
89897               && aMatch[j].snStatus==SNIPPET_DESIRED ){
89898             nDesired--;
89899             aMatch[j].snStatus = SNIPPET_IGNORE;
89900           }
89901         }
89902       }else{
89903         nappend(&sb, &zDoc[iStart], iEnd - iStart);
89904         iStart = iEnd;
89905       }
89906     }
89907     tailCol = iCol;
89908     tailOffset = iEnd;
89909   }
89910   trimWhiteSpace(&sb);
89911   if( tailEllipsis ){
89912     appendWhiteSpace(&sb);
89913     append(&sb, zEllipsis);
89914   }
89915   pCursor->snippet.zSnippet = stringBufferData(&sb);
89916   pCursor->snippet.nSnippet = stringBufferLength(&sb);
89917 }
89918
89919
89920 /*
89921 ** Close the cursor.  For additional information see the documentation
89922 ** on the xClose method of the virtual table interface.
89923 */
89924 static int fulltextClose(sqlite3_vtab_cursor *pCursor){
89925   fulltext_cursor *c = (fulltext_cursor *) pCursor;
89926   FTSTRACE(("FTS3 Close %p\n", c));
89927   sqlite3_finalize(c->pStmt);
89928   queryClear(&c->q);
89929   snippetClear(&c->snippet);
89930   if( c->result.nData!=0 ) dlrDestroy(&c->reader);
89931   dataBufferDestroy(&c->result);
89932   sqlite3_free(c);
89933   return SQLITE_OK;
89934 }
89935
89936 static int fulltextNext(sqlite3_vtab_cursor *pCursor){
89937   fulltext_cursor *c = (fulltext_cursor *) pCursor;
89938   int rc;
89939
89940   FTSTRACE(("FTS3 Next %p\n", pCursor));
89941   snippetClear(&c->snippet);
89942   if( c->iCursorType < QUERY_FULLTEXT ){
89943     /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
89944     rc = sqlite3_step(c->pStmt);
89945     switch( rc ){
89946       case SQLITE_ROW:
89947         c->eof = 0;
89948         return SQLITE_OK;
89949       case SQLITE_DONE:
89950         c->eof = 1;
89951         return SQLITE_OK;
89952       default:
89953         c->eof = 1;
89954         return rc;
89955     }
89956   } else {  /* full-text query */
89957     rc = sqlite3_reset(c->pStmt);
89958     if( rc!=SQLITE_OK ) return rc;
89959
89960     if( c->result.nData==0 || dlrAtEnd(&c->reader) ){
89961       c->eof = 1;
89962       return SQLITE_OK;
89963     }
89964     rc = sqlite3_bind_int64(c->pStmt, 1, dlrDocid(&c->reader));
89965     dlrStep(&c->reader);
89966     if( rc!=SQLITE_OK ) return rc;
89967     /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
89968     rc = sqlite3_step(c->pStmt);
89969     if( rc==SQLITE_ROW ){   /* the case we expect */
89970       c->eof = 0;
89971       return SQLITE_OK;
89972     }
89973     /* an error occurred; abort */
89974     return rc==SQLITE_DONE ? SQLITE_ERROR : rc;
89975   }
89976 }
89977
89978
89979 /* TODO(shess) If we pushed LeafReader to the top of the file, or to
89980 ** another file, term_select() could be pushed above
89981 ** docListOfTerm().
89982 */
89983 static int termSelect(fulltext_vtab *v, int iColumn,
89984                       const char *pTerm, int nTerm, int isPrefix,
89985                       DocListType iType, DataBuffer *out);
89986
89987 /* Return a DocList corresponding to the query term *pTerm.  If *pTerm
89988 ** is the first term of a phrase query, go ahead and evaluate the phrase
89989 ** query and return the doclist for the entire phrase query.
89990 **
89991 ** The resulting DL_DOCIDS doclist is stored in pResult, which is
89992 ** overwritten.
89993 */
89994 static int docListOfTerm(
89995   fulltext_vtab *v,    /* The full text index */
89996   int iColumn,         /* column to restrict to.  No restriction if >=nColumn */
89997   QueryTerm *pQTerm,   /* Term we are looking for, or 1st term of a phrase */
89998   DataBuffer *pResult  /* Write the result here */
89999 ){
90000   DataBuffer left, right, new;
90001   int i, rc;
90002
90003   /* No phrase search if no position info. */
90004   assert( pQTerm->nPhrase==0 || DL_DEFAULT!=DL_DOCIDS );
90005
90006   /* This code should never be called with buffered updates. */
90007   assert( v->nPendingData<0 );
90008
90009   dataBufferInit(&left, 0);
90010   rc = termSelect(v, iColumn, pQTerm->pTerm, pQTerm->nTerm, pQTerm->isPrefix,
90011                   (0<pQTerm->nPhrase ? DL_POSITIONS : DL_DOCIDS), &left);
90012   if( rc ) return rc;
90013   for(i=1; i<=pQTerm->nPhrase && left.nData>0; i++){
90014     /* If this token is connected to the next by a NEAR operator, and
90015     ** the next token is the start of a phrase, then set nPhraseRight
90016     ** to the number of tokens in the phrase. Otherwise leave it at 1.
90017     */
90018     int nPhraseRight = 1;
90019     while( (i+nPhraseRight)<=pQTerm->nPhrase 
90020         && pQTerm[i+nPhraseRight].nNear==0 
90021     ){
90022       nPhraseRight++;
90023     }
90024
90025     dataBufferInit(&right, 0);
90026     rc = termSelect(v, iColumn, pQTerm[i].pTerm, pQTerm[i].nTerm,
90027                     pQTerm[i].isPrefix, DL_POSITIONS, &right);
90028     if( rc ){
90029       dataBufferDestroy(&left);
90030       return rc;
90031     }
90032     dataBufferInit(&new, 0);
90033     docListPhraseMerge(left.pData, left.nData, right.pData, right.nData,
90034                        pQTerm[i-1].nNear, pQTerm[i-1].iPhrase + nPhraseRight,
90035                        ((i<pQTerm->nPhrase) ? DL_POSITIONS : DL_DOCIDS),
90036                        &new);
90037     dataBufferDestroy(&left);
90038     dataBufferDestroy(&right);
90039     left = new;
90040   }
90041   *pResult = left;
90042   return SQLITE_OK;
90043 }
90044
90045 /* Add a new term pTerm[0..nTerm-1] to the query *q.
90046 */
90047 static void queryAdd(Query *q, const char *pTerm, int nTerm){
90048   QueryTerm *t;
90049   ++q->nTerms;
90050   q->pTerms = sqlite3_realloc(q->pTerms, q->nTerms * sizeof(q->pTerms[0]));
90051   if( q->pTerms==0 ){
90052     q->nTerms = 0;
90053     return;
90054   }
90055   t = &q->pTerms[q->nTerms - 1];
90056   CLEAR(t);
90057   t->pTerm = sqlite3_malloc(nTerm+1);
90058   memcpy(t->pTerm, pTerm, nTerm);
90059   t->pTerm[nTerm] = 0;
90060   t->nTerm = nTerm;
90061   t->isOr = q->nextIsOr;
90062   t->isPrefix = 0;
90063   q->nextIsOr = 0;
90064   t->iColumn = q->nextColumn;
90065   q->nextColumn = q->dfltColumn;
90066 }
90067
90068 /*
90069 ** Check to see if the string zToken[0...nToken-1] matches any
90070 ** column name in the virtual table.   If it does,
90071 ** return the zero-indexed column number.  If not, return -1.
90072 */
90073 static int checkColumnSpecifier(
90074   fulltext_vtab *pVtab,    /* The virtual table */
90075   const char *zToken,      /* Text of the token */
90076   int nToken               /* Number of characters in the token */
90077 ){
90078   int i;
90079   for(i=0; i<pVtab->nColumn; i++){
90080     if( memcmp(pVtab->azColumn[i], zToken, nToken)==0
90081         && pVtab->azColumn[i][nToken]==0 ){
90082       return i;
90083     }
90084   }
90085   return -1;
90086 }
90087
90088 /*
90089 ** Parse the text at zSegment[0..nSegment-1].  Add additional terms
90090 ** to the query being assemblied in pQuery.
90091 **
90092 ** inPhrase is true if zSegment[0..nSegement-1] is contained within
90093 ** double-quotes.  If inPhrase is true, then the first term
90094 ** is marked with the number of terms in the phrase less one and
90095 ** OR and "-" syntax is ignored.  If inPhrase is false, then every
90096 ** term found is marked with nPhrase=0 and OR and "-" syntax is significant.
90097 */
90098 static int tokenizeSegment(
90099   sqlite3_tokenizer *pTokenizer,          /* The tokenizer to use */
90100   const char *zSegment, int nSegment,     /* Query expression being parsed */
90101   int inPhrase,                           /* True if within "..." */
90102   Query *pQuery                           /* Append results here */
90103 ){
90104   const sqlite3_tokenizer_module *pModule = pTokenizer->pModule;
90105   sqlite3_tokenizer_cursor *pCursor;
90106   int firstIndex = pQuery->nTerms;
90107   int iCol;
90108   int nTerm = 1;
90109   
90110   int rc = pModule->xOpen(pTokenizer, zSegment, nSegment, &pCursor);
90111   if( rc!=SQLITE_OK ) return rc;
90112   pCursor->pTokenizer = pTokenizer;
90113
90114   while( 1 ){
90115     const char *zToken;
90116     int nToken, iBegin, iEnd, iPos;
90117
90118     rc = pModule->xNext(pCursor,
90119                         &zToken, &nToken,
90120                         &iBegin, &iEnd, &iPos);
90121     if( rc!=SQLITE_OK ) break;
90122     if( !inPhrase &&
90123         zSegment[iEnd]==':' &&
90124          (iCol = checkColumnSpecifier(pQuery->pFts, zToken, nToken))>=0 ){
90125       pQuery->nextColumn = iCol;
90126       continue;
90127     }
90128     if( !inPhrase && pQuery->nTerms>0 && nToken==2 
90129      && zSegment[iBegin+0]=='O'
90130      && zSegment[iBegin+1]=='R' 
90131     ){
90132       pQuery->nextIsOr = 1;
90133       continue;
90134     }
90135     if( !inPhrase && pQuery->nTerms>0 && !pQuery->nextIsOr && nToken==4 
90136       && memcmp(&zSegment[iBegin], "NEAR", 4)==0
90137     ){
90138       QueryTerm *pTerm = &pQuery->pTerms[pQuery->nTerms-1];
90139       if( (iBegin+6)<nSegment 
90140        && zSegment[iBegin+4] == '/'
90141        && isdigit(zSegment[iBegin+5])
90142       ){
90143         int k;
90144         pTerm->nNear = 0;
90145         for(k=5; (iBegin+k)<=nSegment && isdigit(zSegment[iBegin+k]); k++){
90146           pTerm->nNear = pTerm->nNear*10 + (zSegment[iBegin+k] - '0');
90147         }
90148         pModule->xNext(pCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
90149       } else {
90150         pTerm->nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
90151       }
90152       pTerm->nNear++;
90153       continue;
90154     }
90155
90156     queryAdd(pQuery, zToken, nToken);
90157     if( !inPhrase && iBegin>0 && zSegment[iBegin-1]=='-' ){
90158       pQuery->pTerms[pQuery->nTerms-1].isNot = 1;
90159     }
90160     if( iEnd<nSegment && zSegment[iEnd]=='*' ){
90161       pQuery->pTerms[pQuery->nTerms-1].isPrefix = 1;
90162     }
90163     pQuery->pTerms[pQuery->nTerms-1].iPhrase = nTerm;
90164     if( inPhrase ){
90165       nTerm++;
90166     }
90167   }
90168
90169   if( inPhrase && pQuery->nTerms>firstIndex ){
90170     pQuery->pTerms[firstIndex].nPhrase = pQuery->nTerms - firstIndex - 1;
90171   }
90172
90173   return pModule->xClose(pCursor);
90174 }
90175
90176 /* Parse a query string, yielding a Query object pQuery.
90177 **
90178 ** The calling function will need to queryClear() to clean up
90179 ** the dynamically allocated memory held by pQuery.
90180 */
90181 static int parseQuery(
90182   fulltext_vtab *v,        /* The fulltext index */
90183   const char *zInput,      /* Input text of the query string */
90184   int nInput,              /* Size of the input text */
90185   int dfltColumn,          /* Default column of the index to match against */
90186   Query *pQuery            /* Write the parse results here. */
90187 ){
90188   int iInput, inPhrase = 0;
90189   int ii;
90190   QueryTerm *aTerm;
90191
90192   if( zInput==0 ) nInput = 0;
90193   if( nInput<0 ) nInput = strlen(zInput);
90194   pQuery->nTerms = 0;
90195   pQuery->pTerms = NULL;
90196   pQuery->nextIsOr = 0;
90197   pQuery->nextColumn = dfltColumn;
90198   pQuery->dfltColumn = dfltColumn;
90199   pQuery->pFts = v;
90200
90201   for(iInput=0; iInput<nInput; ++iInput){
90202     int i;
90203     for(i=iInput; i<nInput && zInput[i]!='"'; ++i){}
90204     if( i>iInput ){
90205       tokenizeSegment(v->pTokenizer, zInput+iInput, i-iInput, inPhrase,
90206                        pQuery);
90207     }
90208     iInput = i;
90209     if( i<nInput ){
90210       assert( zInput[i]=='"' );
90211       inPhrase = !inPhrase;
90212     }
90213   }
90214
90215   if( inPhrase ){
90216     /* unmatched quote */
90217     queryClear(pQuery);
90218     return SQLITE_ERROR;
90219   }
90220
90221   /* Modify the values of the QueryTerm.nPhrase variables to account for
90222   ** the NEAR operator. For the purposes of QueryTerm.nPhrase, phrases
90223   ** and tokens connected by the NEAR operator are handled as a single
90224   ** phrase. See comments above the QueryTerm structure for details.
90225   */
90226   aTerm = pQuery->pTerms;
90227   for(ii=0; ii<pQuery->nTerms; ii++){
90228     if( aTerm[ii].nNear || aTerm[ii].nPhrase ){
90229       while (aTerm[ii+aTerm[ii].nPhrase].nNear) {
90230         aTerm[ii].nPhrase += (1 + aTerm[ii+aTerm[ii].nPhrase+1].nPhrase);
90231       }
90232     }
90233   }
90234
90235   return SQLITE_OK;
90236 }
90237
90238 /* TODO(shess) Refactor the code to remove this forward decl. */
90239 static int flushPendingTerms(fulltext_vtab *v);
90240
90241 /* Perform a full-text query using the search expression in
90242 ** zInput[0..nInput-1].  Return a list of matching documents
90243 ** in pResult.
90244 **
90245 ** Queries must match column iColumn.  Or if iColumn>=nColumn
90246 ** they are allowed to match against any column.
90247 */
90248 static int fulltextQuery(
90249   fulltext_vtab *v,      /* The full text index */
90250   int iColumn,           /* Match against this column by default */
90251   const char *zInput,    /* The query string */
90252   int nInput,            /* Number of bytes in zInput[] */
90253   DataBuffer *pResult,   /* Write the result doclist here */
90254   Query *pQuery          /* Put parsed query string here */
90255 ){
90256   int i, iNext, rc;
90257   DataBuffer left, right, or, new;
90258   int nNot = 0;
90259   QueryTerm *aTerm;
90260
90261   /* TODO(shess) Instead of flushing pendingTerms, we could query for
90262   ** the relevant term and merge the doclist into what we receive from
90263   ** the database.  Wait and see if this is a common issue, first.
90264   **
90265   ** A good reason not to flush is to not generate update-related
90266   ** error codes from here.
90267   */
90268
90269   /* Flush any buffered updates before executing the query. */
90270   rc = flushPendingTerms(v);
90271   if( rc!=SQLITE_OK ) return rc;
90272
90273   /* TODO(shess) I think that the queryClear() calls below are not
90274   ** necessary, because fulltextClose() already clears the query.
90275   */
90276   rc = parseQuery(v, zInput, nInput, iColumn, pQuery);
90277   if( rc!=SQLITE_OK ) return rc;
90278
90279   /* Empty or NULL queries return no results. */
90280   if( pQuery->nTerms==0 ){
90281     dataBufferInit(pResult, 0);
90282     return SQLITE_OK;
90283   }
90284
90285   /* Merge AND terms. */
90286   /* TODO(shess) I think we can early-exit if( i>nNot && left.nData==0 ). */
90287   aTerm = pQuery->pTerms;
90288   for(i = 0; i<pQuery->nTerms; i=iNext){
90289     if( aTerm[i].isNot ){
90290       /* Handle all NOT terms in a separate pass */
90291       nNot++;
90292       iNext = i + aTerm[i].nPhrase+1;
90293       continue;
90294     }
90295     iNext = i + aTerm[i].nPhrase + 1;
90296     rc = docListOfTerm(v, aTerm[i].iColumn, &aTerm[i], &right);
90297     if( rc ){
90298       if( i!=nNot ) dataBufferDestroy(&left);
90299       queryClear(pQuery);
90300       return rc;
90301     }
90302     while( iNext<pQuery->nTerms && aTerm[iNext].isOr ){
90303       rc = docListOfTerm(v, aTerm[iNext].iColumn, &aTerm[iNext], &or);
90304       iNext += aTerm[iNext].nPhrase + 1;
90305       if( rc ){
90306         if( i!=nNot ) dataBufferDestroy(&left);
90307         dataBufferDestroy(&right);
90308         queryClear(pQuery);
90309         return rc;
90310       }
90311       dataBufferInit(&new, 0);
90312       docListOrMerge(right.pData, right.nData, or.pData, or.nData, &new);
90313       dataBufferDestroy(&right);
90314       dataBufferDestroy(&or);
90315       right = new;
90316     }
90317     if( i==nNot ){           /* first term processed. */
90318       left = right;
90319     }else{
90320       dataBufferInit(&new, 0);
90321       docListAndMerge(left.pData, left.nData, right.pData, right.nData, &new);
90322       dataBufferDestroy(&right);
90323       dataBufferDestroy(&left);
90324       left = new;
90325     }
90326   }
90327
90328   if( nNot==pQuery->nTerms ){
90329     /* We do not yet know how to handle a query of only NOT terms */
90330     return SQLITE_ERROR;
90331   }
90332
90333   /* Do the EXCEPT terms */
90334   for(i=0; i<pQuery->nTerms;  i += aTerm[i].nPhrase + 1){
90335     if( !aTerm[i].isNot ) continue;
90336     rc = docListOfTerm(v, aTerm[i].iColumn, &aTerm[i], &right);
90337     if( rc ){
90338       queryClear(pQuery);
90339       dataBufferDestroy(&left);
90340       return rc;
90341     }
90342     dataBufferInit(&new, 0);
90343     docListExceptMerge(left.pData, left.nData, right.pData, right.nData, &new);
90344     dataBufferDestroy(&right);
90345     dataBufferDestroy(&left);
90346     left = new;
90347   }
90348
90349   *pResult = left;
90350   return rc;
90351 }
90352
90353 /*
90354 ** This is the xFilter interface for the virtual table.  See
90355 ** the virtual table xFilter method documentation for additional
90356 ** information.
90357 **
90358 ** If idxNum==QUERY_GENERIC then do a full table scan against
90359 ** the %_content table.
90360 **
90361 ** If idxNum==QUERY_DOCID then do a docid lookup for a single entry
90362 ** in the %_content table.
90363 **
90364 ** If idxNum>=QUERY_FULLTEXT then use the full text index.  The
90365 ** column on the left-hand side of the MATCH operator is column
90366 ** number idxNum-QUERY_FULLTEXT, 0 indexed.  argv[0] is the right-hand
90367 ** side of the MATCH operator.
90368 */
90369 /* TODO(shess) Upgrade the cursor initialization and destruction to
90370 ** account for fulltextFilter() being called multiple times on the
90371 ** same cursor.  The current solution is very fragile.  Apply fix to
90372 ** fts3 as appropriate.
90373 */
90374 static int fulltextFilter(
90375   sqlite3_vtab_cursor *pCursor,     /* The cursor used for this query */
90376   int idxNum, const char *idxStr,   /* Which indexing scheme to use */
90377   int argc, sqlite3_value **argv    /* Arguments for the indexing scheme */
90378 ){
90379   fulltext_cursor *c = (fulltext_cursor *) pCursor;
90380   fulltext_vtab *v = cursor_vtab(c);
90381   int rc;
90382
90383   FTSTRACE(("FTS3 Filter %p\n",pCursor));
90384
90385   /* If the cursor has a statement that was not prepared according to
90386   ** idxNum, clear it.  I believe all calls to fulltextFilter with a
90387   ** given cursor will have the same idxNum , but in this case it's
90388   ** easy to be safe.
90389   */
90390   if( c->pStmt && c->iCursorType!=idxNum ){
90391     sqlite3_finalize(c->pStmt);
90392     c->pStmt = NULL;
90393   }
90394
90395   /* Get a fresh statement appropriate to idxNum. */
90396   /* TODO(shess): Add a prepared-statement cache in the vt structure.
90397   ** The cache must handle multiple open cursors.  Easier to cache the
90398   ** statement variants at the vt to reduce malloc/realloc/free here.
90399   ** Or we could have a StringBuffer variant which allowed stack
90400   ** construction for small values.
90401   */
90402   if( !c->pStmt ){
90403     StringBuffer sb;
90404     initStringBuffer(&sb);
90405     append(&sb, "SELECT docid, ");
90406     appendList(&sb, v->nColumn, v->azContentColumn);
90407     append(&sb, " FROM %_content");
90408     if( idxNum!=QUERY_GENERIC ) append(&sb, " WHERE docid = ?");
90409     rc = sql_prepare(v->db, v->zDb, v->zName, &c->pStmt,
90410                      stringBufferData(&sb));
90411     stringBufferDestroy(&sb);
90412     if( rc!=SQLITE_OK ) return rc;
90413     c->iCursorType = idxNum;
90414   }else{
90415     sqlite3_reset(c->pStmt);
90416     assert( c->iCursorType==idxNum );
90417   }
90418
90419   switch( idxNum ){
90420     case QUERY_GENERIC:
90421       break;
90422
90423     case QUERY_DOCID:
90424       rc = sqlite3_bind_int64(c->pStmt, 1, sqlite3_value_int64(argv[0]));
90425       if( rc!=SQLITE_OK ) return rc;
90426       break;
90427
90428     default:   /* full-text search */
90429     {
90430       const char *zQuery = (const char *)sqlite3_value_text(argv[0]);
90431       assert( idxNum<=QUERY_FULLTEXT+v->nColumn);
90432       assert( argc==1 );
90433       queryClear(&c->q);
90434       if( c->result.nData!=0 ){
90435         /* This case happens if the same cursor is used repeatedly. */
90436         dlrDestroy(&c->reader);
90437         dataBufferReset(&c->result);
90438       }else{
90439         dataBufferInit(&c->result, 0);
90440       }
90441       rc = fulltextQuery(v, idxNum-QUERY_FULLTEXT, zQuery, -1, &c->result, &c->q);
90442       if( rc!=SQLITE_OK ) return rc;
90443       if( c->result.nData!=0 ){
90444         dlrInit(&c->reader, DL_DOCIDS, c->result.pData, c->result.nData);
90445       }
90446       break;
90447     }
90448   }
90449
90450   return fulltextNext(pCursor);
90451 }
90452
90453 /* This is the xEof method of the virtual table.  The SQLite core
90454 ** calls this routine to find out if it has reached the end of
90455 ** a query's results set.
90456 */
90457 static int fulltextEof(sqlite3_vtab_cursor *pCursor){
90458   fulltext_cursor *c = (fulltext_cursor *) pCursor;
90459   return c->eof;
90460 }
90461
90462 /* This is the xColumn method of the virtual table.  The SQLite
90463 ** core calls this method during a query when it needs the value
90464 ** of a column from the virtual table.  This method needs to use
90465 ** one of the sqlite3_result_*() routines to store the requested
90466 ** value back in the pContext.
90467 */
90468 static int fulltextColumn(sqlite3_vtab_cursor *pCursor,
90469                           sqlite3_context *pContext, int idxCol){
90470   fulltext_cursor *c = (fulltext_cursor *) pCursor;
90471   fulltext_vtab *v = cursor_vtab(c);
90472
90473   if( idxCol<v->nColumn ){
90474     sqlite3_value *pVal = sqlite3_column_value(c->pStmt, idxCol+1);
90475     sqlite3_result_value(pContext, pVal);
90476   }else if( idxCol==v->nColumn ){
90477     /* The extra column whose name is the same as the table.
90478     ** Return a blob which is a pointer to the cursor
90479     */
90480     sqlite3_result_blob(pContext, &c, sizeof(c), SQLITE_TRANSIENT);
90481   }else if( idxCol==v->nColumn+1 ){
90482     /* The docid column, which is an alias for rowid. */
90483     sqlite3_value *pVal = sqlite3_column_value(c->pStmt, 0);
90484     sqlite3_result_value(pContext, pVal);
90485   }
90486   return SQLITE_OK;
90487 }
90488
90489 /* This is the xRowid method.  The SQLite core calls this routine to
90490 ** retrieve the rowid for the current row of the result set.  fts3
90491 ** exposes %_content.docid as the rowid for the virtual table.  The
90492 ** rowid should be written to *pRowid.
90493 */
90494 static int fulltextRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
90495   fulltext_cursor *c = (fulltext_cursor *) pCursor;
90496
90497   *pRowid = sqlite3_column_int64(c->pStmt, 0);
90498   return SQLITE_OK;
90499 }
90500
90501 /* Add all terms in [zText] to pendingTerms table.  If [iColumn] > 0,
90502 ** we also store positions and offsets in the hash table using that
90503 ** column number.
90504 */
90505 static int buildTerms(fulltext_vtab *v, sqlite_int64 iDocid,
90506                       const char *zText, int iColumn){
90507   sqlite3_tokenizer *pTokenizer = v->pTokenizer;
90508   sqlite3_tokenizer_cursor *pCursor;
90509   const char *pToken;
90510   int nTokenBytes;
90511   int iStartOffset, iEndOffset, iPosition;
90512   int rc;
90513
90514   rc = pTokenizer->pModule->xOpen(pTokenizer, zText, -1, &pCursor);
90515   if( rc!=SQLITE_OK ) return rc;
90516
90517   pCursor->pTokenizer = pTokenizer;
90518   while( SQLITE_OK==(rc=pTokenizer->pModule->xNext(pCursor,
90519                                                    &pToken, &nTokenBytes,
90520                                                    &iStartOffset, &iEndOffset,
90521                                                    &iPosition)) ){
90522     DLCollector *p;
90523     int nData;                   /* Size of doclist before our update. */
90524
90525     /* Positions can't be negative; we use -1 as a terminator
90526      * internally.  Token can't be NULL or empty. */
90527     if( iPosition<0 || pToken == NULL || nTokenBytes == 0 ){
90528       rc = SQLITE_ERROR;
90529       break;
90530     }
90531
90532     p = fts3HashFind(&v->pendingTerms, pToken, nTokenBytes);
90533     if( p==NULL ){
90534       nData = 0;
90535       p = dlcNew(iDocid, DL_DEFAULT);
90536       fts3HashInsert(&v->pendingTerms, pToken, nTokenBytes, p);
90537
90538       /* Overhead for our hash table entry, the key, and the value. */
90539       v->nPendingData += sizeof(struct fts3HashElem)+sizeof(*p)+nTokenBytes;
90540     }else{
90541       nData = p->b.nData;
90542       if( p->dlw.iPrevDocid!=iDocid ) dlcNext(p, iDocid);
90543     }
90544     if( iColumn>=0 ){
90545       dlcAddPos(p, iColumn, iPosition, iStartOffset, iEndOffset);
90546     }
90547
90548     /* Accumulate data added by dlcNew or dlcNext, and dlcAddPos. */
90549     v->nPendingData += p->b.nData-nData;
90550   }
90551
90552   /* TODO(shess) Check return?  Should this be able to cause errors at
90553   ** this point?  Actually, same question about sqlite3_finalize(),
90554   ** though one could argue that failure there means that the data is
90555   ** not durable.  *ponder*
90556   */
90557   pTokenizer->pModule->xClose(pCursor);
90558   if( SQLITE_DONE == rc ) return SQLITE_OK;
90559   return rc;
90560 }
90561
90562 /* Add doclists for all terms in [pValues] to pendingTerms table. */
90563 static int insertTerms(fulltext_vtab *v, sqlite_int64 iDocid,
90564                        sqlite3_value **pValues){
90565   int i;
90566   for(i = 0; i < v->nColumn ; ++i){
90567     char *zText = (char*)sqlite3_value_text(pValues[i]);
90568     int rc = buildTerms(v, iDocid, zText, i);
90569     if( rc!=SQLITE_OK ) return rc;
90570   }
90571   return SQLITE_OK;
90572 }
90573
90574 /* Add empty doclists for all terms in the given row's content to
90575 ** pendingTerms.
90576 */
90577 static int deleteTerms(fulltext_vtab *v, sqlite_int64 iDocid){
90578   const char **pValues;
90579   int i, rc;
90580
90581   /* TODO(shess) Should we allow such tables at all? */
90582   if( DL_DEFAULT==DL_DOCIDS ) return SQLITE_ERROR;
90583
90584   rc = content_select(v, iDocid, &pValues);
90585   if( rc!=SQLITE_OK ) return rc;
90586
90587   for(i = 0 ; i < v->nColumn; ++i) {
90588     rc = buildTerms(v, iDocid, pValues[i], -1);
90589     if( rc!=SQLITE_OK ) break;
90590   }
90591
90592   freeStringArray(v->nColumn, pValues);
90593   return SQLITE_OK;
90594 }
90595
90596 /* TODO(shess) Refactor the code to remove this forward decl. */
90597 static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid);
90598
90599 /* Insert a row into the %_content table; set *piDocid to be the ID of the
90600 ** new row.  Add doclists for terms to pendingTerms.
90601 */
90602 static int index_insert(fulltext_vtab *v, sqlite3_value *pRequestDocid,
90603                         sqlite3_value **pValues, sqlite_int64 *piDocid){
90604   int rc;
90605
90606   rc = content_insert(v, pRequestDocid, pValues);  /* execute an SQL INSERT */
90607   if( rc!=SQLITE_OK ) return rc;
90608
90609   /* docid column is an alias for rowid. */
90610   *piDocid = sqlite3_last_insert_rowid(v->db);
90611   rc = initPendingTerms(v, *piDocid);
90612   if( rc!=SQLITE_OK ) return rc;
90613
90614   return insertTerms(v, *piDocid, pValues);
90615 }
90616
90617 /* Delete a row from the %_content table; add empty doclists for terms
90618 ** to pendingTerms.
90619 */
90620 static int index_delete(fulltext_vtab *v, sqlite_int64 iRow){
90621   int rc = initPendingTerms(v, iRow);
90622   if( rc!=SQLITE_OK ) return rc;
90623
90624   rc = deleteTerms(v, iRow);
90625   if( rc!=SQLITE_OK ) return rc;
90626
90627   return content_delete(v, iRow);  /* execute an SQL DELETE */
90628 }
90629
90630 /* Update a row in the %_content table; add delete doclists to
90631 ** pendingTerms for old terms not in the new data, add insert doclists
90632 ** to pendingTerms for terms in the new data.
90633 */
90634 static int index_update(fulltext_vtab *v, sqlite_int64 iRow,
90635                         sqlite3_value **pValues){
90636   int rc = initPendingTerms(v, iRow);
90637   if( rc!=SQLITE_OK ) return rc;
90638
90639   /* Generate an empty doclist for each term that previously appeared in this
90640    * row. */
90641   rc = deleteTerms(v, iRow);
90642   if( rc!=SQLITE_OK ) return rc;
90643
90644   rc = content_update(v, pValues, iRow);  /* execute an SQL UPDATE */
90645   if( rc!=SQLITE_OK ) return rc;
90646
90647   /* Now add positions for terms which appear in the updated row. */
90648   return insertTerms(v, iRow, pValues);
90649 }
90650
90651 /*******************************************************************/
90652 /* InteriorWriter is used to collect terms and block references into
90653 ** interior nodes in %_segments.  See commentary at top of file for
90654 ** format.
90655 */
90656
90657 /* How large interior nodes can grow. */
90658 #define INTERIOR_MAX 2048
90659
90660 /* Minimum number of terms per interior node (except the root). This
90661 ** prevents large terms from making the tree too skinny - must be >0
90662 ** so that the tree always makes progress.  Note that the min tree
90663 ** fanout will be INTERIOR_MIN_TERMS+1.
90664 */
90665 #define INTERIOR_MIN_TERMS 7
90666 #if INTERIOR_MIN_TERMS<1
90667 # error INTERIOR_MIN_TERMS must be greater than 0.
90668 #endif
90669
90670 /* ROOT_MAX controls how much data is stored inline in the segment
90671 ** directory.
90672 */
90673 /* TODO(shess) Push ROOT_MAX down to whoever is writing things.  It's
90674 ** only here so that interiorWriterRootInfo() and leafWriterRootInfo()
90675 ** can both see it, but if the caller passed it in, we wouldn't even
90676 ** need a define.
90677 */
90678 #define ROOT_MAX 1024
90679 #if ROOT_MAX<VARINT_MAX*2
90680 # error ROOT_MAX must have enough space for a header.
90681 #endif
90682
90683 /* InteriorBlock stores a linked-list of interior blocks while a lower
90684 ** layer is being constructed.
90685 */
90686 typedef struct InteriorBlock {
90687   DataBuffer term;           /* Leftmost term in block's subtree. */
90688   DataBuffer data;           /* Accumulated data for the block. */
90689   struct InteriorBlock *next;
90690 } InteriorBlock;
90691
90692 static InteriorBlock *interiorBlockNew(int iHeight, sqlite_int64 iChildBlock,
90693                                        const char *pTerm, int nTerm){
90694   InteriorBlock *block = sqlite3_malloc(sizeof(InteriorBlock));
90695   char c[VARINT_MAX+VARINT_MAX];
90696   int n;
90697
90698   if( block ){
90699     memset(block, 0, sizeof(*block));
90700     dataBufferInit(&block->term, 0);
90701     dataBufferReplace(&block->term, pTerm, nTerm);
90702
90703     n = fts3PutVarint(c, iHeight);
90704     n += fts3PutVarint(c+n, iChildBlock);
90705     dataBufferInit(&block->data, INTERIOR_MAX);
90706     dataBufferReplace(&block->data, c, n);
90707   }
90708   return block;
90709 }
90710
90711 #ifndef NDEBUG
90712 /* Verify that the data is readable as an interior node. */
90713 static void interiorBlockValidate(InteriorBlock *pBlock){
90714   const char *pData = pBlock->data.pData;
90715   int nData = pBlock->data.nData;
90716   int n, iDummy;
90717   sqlite_int64 iBlockid;
90718
90719   assert( nData>0 );
90720   assert( pData!=0 );
90721   assert( pData+nData>pData );
90722
90723   /* Must lead with height of node as a varint(n), n>0 */
90724   n = fts3GetVarint32(pData, &iDummy);
90725   assert( n>0 );
90726   assert( iDummy>0 );
90727   assert( n<nData );
90728   pData += n;
90729   nData -= n;
90730
90731   /* Must contain iBlockid. */
90732   n = fts3GetVarint(pData, &iBlockid);
90733   assert( n>0 );
90734   assert( n<=nData );
90735   pData += n;
90736   nData -= n;
90737
90738   /* Zero or more terms of positive length */
90739   if( nData!=0 ){
90740     /* First term is not delta-encoded. */
90741     n = fts3GetVarint32(pData, &iDummy);
90742     assert( n>0 );
90743     assert( iDummy>0 );
90744     assert( n+iDummy>0);
90745     assert( n+iDummy<=nData );
90746     pData += n+iDummy;
90747     nData -= n+iDummy;
90748
90749     /* Following terms delta-encoded. */
90750     while( nData!=0 ){
90751       /* Length of shared prefix. */
90752       n = fts3GetVarint32(pData, &iDummy);
90753       assert( n>0 );
90754       assert( iDummy>=0 );
90755       assert( n<nData );
90756       pData += n;
90757       nData -= n;
90758
90759       /* Length and data of distinct suffix. */
90760       n = fts3GetVarint32(pData, &iDummy);
90761       assert( n>0 );
90762       assert( iDummy>0 );
90763       assert( n+iDummy>0);
90764       assert( n+iDummy<=nData );
90765       pData += n+iDummy;
90766       nData -= n+iDummy;
90767     }
90768   }
90769 }
90770 #define ASSERT_VALID_INTERIOR_BLOCK(x) interiorBlockValidate(x)
90771 #else
90772 #define ASSERT_VALID_INTERIOR_BLOCK(x) assert( 1 )
90773 #endif
90774
90775 typedef struct InteriorWriter {
90776   int iHeight;                   /* from 0 at leaves. */
90777   InteriorBlock *first, *last;
90778   struct InteriorWriter *parentWriter;
90779
90780   DataBuffer term;               /* Last term written to block "last". */
90781   sqlite_int64 iOpeningChildBlock; /* First child block in block "last". */
90782 #ifndef NDEBUG
90783   sqlite_int64 iLastChildBlock;  /* for consistency checks. */
90784 #endif
90785 } InteriorWriter;
90786
90787 /* Initialize an interior node where pTerm[nTerm] marks the leftmost
90788 ** term in the tree.  iChildBlock is the leftmost child block at the
90789 ** next level down the tree.
90790 */
90791 static void interiorWriterInit(int iHeight, const char *pTerm, int nTerm,
90792                                sqlite_int64 iChildBlock,
90793                                InteriorWriter *pWriter){
90794   InteriorBlock *block;
90795   assert( iHeight>0 );
90796   CLEAR(pWriter);
90797
90798   pWriter->iHeight = iHeight;
90799   pWriter->iOpeningChildBlock = iChildBlock;
90800 #ifndef NDEBUG
90801   pWriter->iLastChildBlock = iChildBlock;
90802 #endif
90803   block = interiorBlockNew(iHeight, iChildBlock, pTerm, nTerm);
90804   pWriter->last = pWriter->first = block;
90805   ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
90806   dataBufferInit(&pWriter->term, 0);
90807 }
90808
90809 /* Append the child node rooted at iChildBlock to the interior node,
90810 ** with pTerm[nTerm] as the leftmost term in iChildBlock's subtree.
90811 */
90812 static void interiorWriterAppend(InteriorWriter *pWriter,
90813                                  const char *pTerm, int nTerm,
90814                                  sqlite_int64 iChildBlock){
90815   char c[VARINT_MAX+VARINT_MAX];
90816   int n, nPrefix = 0;
90817
90818   ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
90819
90820   /* The first term written into an interior node is actually
90821   ** associated with the second child added (the first child was added
90822   ** in interiorWriterInit, or in the if clause at the bottom of this
90823   ** function).  That term gets encoded straight up, with nPrefix left
90824   ** at 0.
90825   */
90826   if( pWriter->term.nData==0 ){
90827     n = fts3PutVarint(c, nTerm);
90828   }else{
90829     while( nPrefix<pWriter->term.nData &&
90830            pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){
90831       nPrefix++;
90832     }
90833
90834     n = fts3PutVarint(c, nPrefix);
90835     n += fts3PutVarint(c+n, nTerm-nPrefix);
90836   }
90837
90838 #ifndef NDEBUG
90839   pWriter->iLastChildBlock++;
90840 #endif
90841   assert( pWriter->iLastChildBlock==iChildBlock );
90842
90843   /* Overflow to a new block if the new term makes the current block
90844   ** too big, and the current block already has enough terms.
90845   */
90846   if( pWriter->last->data.nData+n+nTerm-nPrefix>INTERIOR_MAX &&
90847       iChildBlock-pWriter->iOpeningChildBlock>INTERIOR_MIN_TERMS ){
90848     pWriter->last->next = interiorBlockNew(pWriter->iHeight, iChildBlock,
90849                                            pTerm, nTerm);
90850     pWriter->last = pWriter->last->next;
90851     pWriter->iOpeningChildBlock = iChildBlock;
90852     dataBufferReset(&pWriter->term);
90853   }else{
90854     dataBufferAppend2(&pWriter->last->data, c, n,
90855                       pTerm+nPrefix, nTerm-nPrefix);
90856     dataBufferReplace(&pWriter->term, pTerm, nTerm);
90857   }
90858   ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
90859 }
90860
90861 /* Free the space used by pWriter, including the linked-list of
90862 ** InteriorBlocks, and parentWriter, if present.
90863 */
90864 static int interiorWriterDestroy(InteriorWriter *pWriter){
90865   InteriorBlock *block = pWriter->first;
90866
90867   while( block!=NULL ){
90868     InteriorBlock *b = block;
90869     block = block->next;
90870     dataBufferDestroy(&b->term);
90871     dataBufferDestroy(&b->data);
90872     sqlite3_free(b);
90873   }
90874   if( pWriter->parentWriter!=NULL ){
90875     interiorWriterDestroy(pWriter->parentWriter);
90876     sqlite3_free(pWriter->parentWriter);
90877   }
90878   dataBufferDestroy(&pWriter->term);
90879   SCRAMBLE(pWriter);
90880   return SQLITE_OK;
90881 }
90882
90883 /* If pWriter can fit entirely in ROOT_MAX, return it as the root info
90884 ** directly, leaving *piEndBlockid unchanged.  Otherwise, flush
90885 ** pWriter to %_segments, building a new layer of interior nodes, and
90886 ** recursively ask for their root into.
90887 */
90888 static int interiorWriterRootInfo(fulltext_vtab *v, InteriorWriter *pWriter,
90889                                   char **ppRootInfo, int *pnRootInfo,
90890                                   sqlite_int64 *piEndBlockid){
90891   InteriorBlock *block = pWriter->first;
90892   sqlite_int64 iBlockid = 0;
90893   int rc;
90894
90895   /* If we can fit the segment inline */
90896   if( block==pWriter->last && block->data.nData<ROOT_MAX ){
90897     *ppRootInfo = block->data.pData;
90898     *pnRootInfo = block->data.nData;
90899     return SQLITE_OK;
90900   }
90901
90902   /* Flush the first block to %_segments, and create a new level of
90903   ** interior node.
90904   */
90905   ASSERT_VALID_INTERIOR_BLOCK(block);
90906   rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid);
90907   if( rc!=SQLITE_OK ) return rc;
90908   *piEndBlockid = iBlockid;
90909
90910   pWriter->parentWriter = sqlite3_malloc(sizeof(*pWriter->parentWriter));
90911   interiorWriterInit(pWriter->iHeight+1,
90912                      block->term.pData, block->term.nData,
90913                      iBlockid, pWriter->parentWriter);
90914
90915   /* Flush additional blocks and append to the higher interior
90916   ** node.
90917   */
90918   for(block=block->next; block!=NULL; block=block->next){
90919     ASSERT_VALID_INTERIOR_BLOCK(block);
90920     rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid);
90921     if( rc!=SQLITE_OK ) return rc;
90922     *piEndBlockid = iBlockid;
90923
90924     interiorWriterAppend(pWriter->parentWriter,
90925                          block->term.pData, block->term.nData, iBlockid);
90926   }
90927
90928   /* Parent node gets the chance to be the root. */
90929   return interiorWriterRootInfo(v, pWriter->parentWriter,
90930                                 ppRootInfo, pnRootInfo, piEndBlockid);
90931 }
90932
90933 /****************************************************************/
90934 /* InteriorReader is used to read off the data from an interior node
90935 ** (see comment at top of file for the format).
90936 */
90937 typedef struct InteriorReader {
90938   const char *pData;
90939   int nData;
90940
90941   DataBuffer term;          /* previous term, for decoding term delta. */
90942
90943   sqlite_int64 iBlockid;
90944 } InteriorReader;
90945
90946 static void interiorReaderDestroy(InteriorReader *pReader){
90947   dataBufferDestroy(&pReader->term);
90948   SCRAMBLE(pReader);
90949 }
90950
90951 /* TODO(shess) The assertions are great, but what if we're in NDEBUG
90952 ** and the blob is empty or otherwise contains suspect data?
90953 */
90954 static void interiorReaderInit(const char *pData, int nData,
90955                                InteriorReader *pReader){
90956   int n, nTerm;
90957
90958   /* Require at least the leading flag byte */
90959   assert( nData>0 );
90960   assert( pData[0]!='\0' );
90961
90962   CLEAR(pReader);
90963
90964   /* Decode the base blockid, and set the cursor to the first term. */
90965   n = fts3GetVarint(pData+1, &pReader->iBlockid);
90966   assert( 1+n<=nData );
90967   pReader->pData = pData+1+n;
90968   pReader->nData = nData-(1+n);
90969
90970   /* A single-child interior node (such as when a leaf node was too
90971   ** large for the segment directory) won't have any terms.
90972   ** Otherwise, decode the first term.
90973   */
90974   if( pReader->nData==0 ){
90975     dataBufferInit(&pReader->term, 0);
90976   }else{
90977     n = fts3GetVarint32(pReader->pData, &nTerm);
90978     dataBufferInit(&pReader->term, nTerm);
90979     dataBufferReplace(&pReader->term, pReader->pData+n, nTerm);
90980     assert( n+nTerm<=pReader->nData );
90981     pReader->pData += n+nTerm;
90982     pReader->nData -= n+nTerm;
90983   }
90984 }
90985
90986 static int interiorReaderAtEnd(InteriorReader *pReader){
90987   return pReader->term.nData==0;
90988 }
90989
90990 static sqlite_int64 interiorReaderCurrentBlockid(InteriorReader *pReader){
90991   return pReader->iBlockid;
90992 }
90993
90994 static int interiorReaderTermBytes(InteriorReader *pReader){
90995   assert( !interiorReaderAtEnd(pReader) );
90996   return pReader->term.nData;
90997 }
90998 static const char *interiorReaderTerm(InteriorReader *pReader){
90999   assert( !interiorReaderAtEnd(pReader) );
91000   return pReader->term.pData;
91001 }
91002
91003 /* Step forward to the next term in the node. */
91004 static void interiorReaderStep(InteriorReader *pReader){
91005   assert( !interiorReaderAtEnd(pReader) );
91006
91007   /* If the last term has been read, signal eof, else construct the
91008   ** next term.
91009   */
91010   if( pReader->nData==0 ){
91011     dataBufferReset(&pReader->term);
91012   }else{
91013     int n, nPrefix, nSuffix;
91014
91015     n = fts3GetVarint32(pReader->pData, &nPrefix);
91016     n += fts3GetVarint32(pReader->pData+n, &nSuffix);
91017
91018     /* Truncate the current term and append suffix data. */
91019     pReader->term.nData = nPrefix;
91020     dataBufferAppend(&pReader->term, pReader->pData+n, nSuffix);
91021
91022     assert( n+nSuffix<=pReader->nData );
91023     pReader->pData += n+nSuffix;
91024     pReader->nData -= n+nSuffix;
91025   }
91026   pReader->iBlockid++;
91027 }
91028
91029 /* Compare the current term to pTerm[nTerm], returning strcmp-style
91030 ** results.  If isPrefix, equality means equal through nTerm bytes.
91031 */
91032 static int interiorReaderTermCmp(InteriorReader *pReader,
91033                                  const char *pTerm, int nTerm, int isPrefix){
91034   const char *pReaderTerm = interiorReaderTerm(pReader);
91035   int nReaderTerm = interiorReaderTermBytes(pReader);
91036   int c, n = nReaderTerm<nTerm ? nReaderTerm : nTerm;
91037
91038   if( n==0 ){
91039     if( nReaderTerm>0 ) return -1;
91040     if( nTerm>0 ) return 1;
91041     return 0;
91042   }
91043
91044   c = memcmp(pReaderTerm, pTerm, n);
91045   if( c!=0 ) return c;
91046   if( isPrefix && n==nTerm ) return 0;
91047   return nReaderTerm - nTerm;
91048 }
91049
91050 /****************************************************************/
91051 /* LeafWriter is used to collect terms and associated doclist data
91052 ** into leaf blocks in %_segments (see top of file for format info).
91053 ** Expected usage is:
91054 **
91055 ** LeafWriter writer;
91056 ** leafWriterInit(0, 0, &writer);
91057 ** while( sorted_terms_left_to_process ){
91058 **   // data is doclist data for that term.
91059 **   rc = leafWriterStep(v, &writer, pTerm, nTerm, pData, nData);
91060 **   if( rc!=SQLITE_OK ) goto err;
91061 ** }
91062 ** rc = leafWriterFinalize(v, &writer);
91063 **err:
91064 ** leafWriterDestroy(&writer);
91065 ** return rc;
91066 **
91067 ** leafWriterStep() may write a collected leaf out to %_segments.
91068 ** leafWriterFinalize() finishes writing any buffered data and stores
91069 ** a root node in %_segdir.  leafWriterDestroy() frees all buffers and
91070 ** InteriorWriters allocated as part of writing this segment.
91071 **
91072 ** TODO(shess) Document leafWriterStepMerge().
91073 */
91074
91075 /* Put terms with data this big in their own block. */
91076 #define STANDALONE_MIN 1024
91077
91078 /* Keep leaf blocks below this size. */
91079 #define LEAF_MAX 2048
91080
91081 typedef struct LeafWriter {
91082   int iLevel;
91083   int idx;
91084   sqlite_int64 iStartBlockid;     /* needed to create the root info */
91085   sqlite_int64 iEndBlockid;       /* when we're done writing. */
91086
91087   DataBuffer term;                /* previous encoded term */
91088   DataBuffer data;                /* encoding buffer */
91089
91090   /* bytes of first term in the current node which distinguishes that
91091   ** term from the last term of the previous node.
91092   */
91093   int nTermDistinct;
91094
91095   InteriorWriter parentWriter;    /* if we overflow */
91096   int has_parent;
91097 } LeafWriter;
91098
91099 static void leafWriterInit(int iLevel, int idx, LeafWriter *pWriter){
91100   CLEAR(pWriter);
91101   pWriter->iLevel = iLevel;
91102   pWriter->idx = idx;
91103
91104   dataBufferInit(&pWriter->term, 32);
91105
91106   /* Start out with a reasonably sized block, though it can grow. */
91107   dataBufferInit(&pWriter->data, LEAF_MAX);
91108 }
91109
91110 #ifndef NDEBUG
91111 /* Verify that the data is readable as a leaf node. */
91112 static void leafNodeValidate(const char *pData, int nData){
91113   int n, iDummy;
91114
91115   if( nData==0 ) return;
91116   assert( nData>0 );
91117   assert( pData!=0 );
91118   assert( pData+nData>pData );
91119
91120   /* Must lead with a varint(0) */
91121   n = fts3GetVarint32(pData, &iDummy);
91122   assert( iDummy==0 );
91123   assert( n>0 );
91124   assert( n<nData );
91125   pData += n;
91126   nData -= n;
91127
91128   /* Leading term length and data must fit in buffer. */
91129   n = fts3GetVarint32(pData, &iDummy);
91130   assert( n>0 );
91131   assert( iDummy>0 );
91132   assert( n+iDummy>0 );
91133   assert( n+iDummy<nData );
91134   pData += n+iDummy;
91135   nData -= n+iDummy;
91136
91137   /* Leading term's doclist length and data must fit. */
91138   n = fts3GetVarint32(pData, &iDummy);
91139   assert( n>0 );
91140   assert( iDummy>0 );
91141   assert( n+iDummy>0 );
91142   assert( n+iDummy<=nData );
91143   ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL);
91144   pData += n+iDummy;
91145   nData -= n+iDummy;
91146
91147   /* Verify that trailing terms and doclists also are readable. */
91148   while( nData!=0 ){
91149     n = fts3GetVarint32(pData, &iDummy);
91150     assert( n>0 );
91151     assert( iDummy>=0 );
91152     assert( n<nData );
91153     pData += n;
91154     nData -= n;
91155     n = fts3GetVarint32(pData, &iDummy);
91156     assert( n>0 );
91157     assert( iDummy>0 );
91158     assert( n+iDummy>0 );
91159     assert( n+iDummy<nData );
91160     pData += n+iDummy;
91161     nData -= n+iDummy;
91162
91163     n = fts3GetVarint32(pData, &iDummy);
91164     assert( n>0 );
91165     assert( iDummy>0 );
91166     assert( n+iDummy>0 );
91167     assert( n+iDummy<=nData );
91168     ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL);
91169     pData += n+iDummy;
91170     nData -= n+iDummy;
91171   }
91172 }
91173 #define ASSERT_VALID_LEAF_NODE(p, n) leafNodeValidate(p, n)
91174 #else
91175 #define ASSERT_VALID_LEAF_NODE(p, n) assert( 1 )
91176 #endif
91177
91178 /* Flush the current leaf node to %_segments, and adding the resulting
91179 ** blockid and the starting term to the interior node which will
91180 ** contain it.
91181 */
91182 static int leafWriterInternalFlush(fulltext_vtab *v, LeafWriter *pWriter,
91183                                    int iData, int nData){
91184   sqlite_int64 iBlockid = 0;
91185   const char *pStartingTerm;
91186   int nStartingTerm, rc, n;
91187
91188   /* Must have the leading varint(0) flag, plus at least some
91189   ** valid-looking data.
91190   */
91191   assert( nData>2 );
91192   assert( iData>=0 );
91193   assert( iData+nData<=pWriter->data.nData );
91194   ASSERT_VALID_LEAF_NODE(pWriter->data.pData+iData, nData);
91195
91196   rc = block_insert(v, pWriter->data.pData+iData, nData, &iBlockid);
91197   if( rc!=SQLITE_OK ) return rc;
91198   assert( iBlockid!=0 );
91199
91200   /* Reconstruct the first term in the leaf for purposes of building
91201   ** the interior node.
91202   */
91203   n = fts3GetVarint32(pWriter->data.pData+iData+1, &nStartingTerm);
91204   pStartingTerm = pWriter->data.pData+iData+1+n;
91205   assert( pWriter->data.nData>iData+1+n+nStartingTerm );
91206   assert( pWriter->nTermDistinct>0 );
91207   assert( pWriter->nTermDistinct<=nStartingTerm );
91208   nStartingTerm = pWriter->nTermDistinct;
91209
91210   if( pWriter->has_parent ){
91211     interiorWriterAppend(&pWriter->parentWriter,
91212                          pStartingTerm, nStartingTerm, iBlockid);
91213   }else{
91214     interiorWriterInit(1, pStartingTerm, nStartingTerm, iBlockid,
91215                        &pWriter->parentWriter);
91216     pWriter->has_parent = 1;
91217   }
91218
91219   /* Track the span of this segment's leaf nodes. */
91220   if( pWriter->iEndBlockid==0 ){
91221     pWriter->iEndBlockid = pWriter->iStartBlockid = iBlockid;
91222   }else{
91223     pWriter->iEndBlockid++;
91224     assert( iBlockid==pWriter->iEndBlockid );
91225   }
91226
91227   return SQLITE_OK;
91228 }
91229 static int leafWriterFlush(fulltext_vtab *v, LeafWriter *pWriter){
91230   int rc = leafWriterInternalFlush(v, pWriter, 0, pWriter->data.nData);
91231   if( rc!=SQLITE_OK ) return rc;
91232
91233   /* Re-initialize the output buffer. */
91234   dataBufferReset(&pWriter->data);
91235
91236   return SQLITE_OK;
91237 }
91238
91239 /* Fetch the root info for the segment.  If the entire leaf fits
91240 ** within ROOT_MAX, then it will be returned directly, otherwise it
91241 ** will be flushed and the root info will be returned from the
91242 ** interior node.  *piEndBlockid is set to the blockid of the last
91243 ** interior or leaf node written to disk (0 if none are written at
91244 ** all).
91245 */
91246 static int leafWriterRootInfo(fulltext_vtab *v, LeafWriter *pWriter,
91247                               char **ppRootInfo, int *pnRootInfo,
91248                               sqlite_int64 *piEndBlockid){
91249   /* we can fit the segment entirely inline */
91250   if( !pWriter->has_parent && pWriter->data.nData<ROOT_MAX ){
91251     *ppRootInfo = pWriter->data.pData;
91252     *pnRootInfo = pWriter->data.nData;
91253     *piEndBlockid = 0;
91254     return SQLITE_OK;
91255   }
91256
91257   /* Flush remaining leaf data. */
91258   if( pWriter->data.nData>0 ){
91259     int rc = leafWriterFlush(v, pWriter);
91260     if( rc!=SQLITE_OK ) return rc;
91261   }
91262
91263   /* We must have flushed a leaf at some point. */
91264   assert( pWriter->has_parent );
91265
91266   /* Tenatively set the end leaf blockid as the end blockid.  If the
91267   ** interior node can be returned inline, this will be the final
91268   ** blockid, otherwise it will be overwritten by
91269   ** interiorWriterRootInfo().
91270   */
91271   *piEndBlockid = pWriter->iEndBlockid;
91272
91273   return interiorWriterRootInfo(v, &pWriter->parentWriter,
91274                                 ppRootInfo, pnRootInfo, piEndBlockid);
91275 }
91276
91277 /* Collect the rootInfo data and store it into the segment directory.
91278 ** This has the effect of flushing the segment's leaf data to
91279 ** %_segments, and also flushing any interior nodes to %_segments.
91280 */
91281 static int leafWriterFinalize(fulltext_vtab *v, LeafWriter *pWriter){
91282   sqlite_int64 iEndBlockid;
91283   char *pRootInfo;
91284   int rc, nRootInfo;
91285
91286   rc = leafWriterRootInfo(v, pWriter, &pRootInfo, &nRootInfo, &iEndBlockid);
91287   if( rc!=SQLITE_OK ) return rc;
91288
91289   /* Don't bother storing an entirely empty segment. */
91290   if( iEndBlockid==0 && nRootInfo==0 ) return SQLITE_OK;
91291
91292   return segdir_set(v, pWriter->iLevel, pWriter->idx,
91293                     pWriter->iStartBlockid, pWriter->iEndBlockid,
91294                     iEndBlockid, pRootInfo, nRootInfo);
91295 }
91296
91297 static void leafWriterDestroy(LeafWriter *pWriter){
91298   if( pWriter->has_parent ) interiorWriterDestroy(&pWriter->parentWriter);
91299   dataBufferDestroy(&pWriter->term);
91300   dataBufferDestroy(&pWriter->data);
91301 }
91302
91303 /* Encode a term into the leafWriter, delta-encoding as appropriate.
91304 ** Returns the length of the new term which distinguishes it from the
91305 ** previous term, which can be used to set nTermDistinct when a node
91306 ** boundary is crossed.
91307 */
91308 static int leafWriterEncodeTerm(LeafWriter *pWriter,
91309                                 const char *pTerm, int nTerm){
91310   char c[VARINT_MAX+VARINT_MAX];
91311   int n, nPrefix = 0;
91312
91313   assert( nTerm>0 );
91314   while( nPrefix<pWriter->term.nData &&
91315          pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){
91316     nPrefix++;
91317     /* Failing this implies that the terms weren't in order. */
91318     assert( nPrefix<nTerm );
91319   }
91320
91321   if( pWriter->data.nData==0 ){
91322     /* Encode the node header and leading term as:
91323     **  varint(0)
91324     **  varint(nTerm)
91325     **  char pTerm[nTerm]
91326     */
91327     n = fts3PutVarint(c, '\0');
91328     n += fts3PutVarint(c+n, nTerm);
91329     dataBufferAppend2(&pWriter->data, c, n, pTerm, nTerm);
91330   }else{
91331     /* Delta-encode the term as:
91332     **  varint(nPrefix)
91333     **  varint(nSuffix)
91334     **  char pTermSuffix[nSuffix]
91335     */
91336     n = fts3PutVarint(c, nPrefix);
91337     n += fts3PutVarint(c+n, nTerm-nPrefix);
91338     dataBufferAppend2(&pWriter->data, c, n, pTerm+nPrefix, nTerm-nPrefix);
91339   }
91340   dataBufferReplace(&pWriter->term, pTerm, nTerm);
91341
91342   return nPrefix+1;
91343 }
91344
91345 /* Used to avoid a memmove when a large amount of doclist data is in
91346 ** the buffer.  This constructs a node and term header before
91347 ** iDoclistData and flushes the resulting complete node using
91348 ** leafWriterInternalFlush().
91349 */
91350 static int leafWriterInlineFlush(fulltext_vtab *v, LeafWriter *pWriter,
91351                                  const char *pTerm, int nTerm,
91352                                  int iDoclistData){
91353   char c[VARINT_MAX+VARINT_MAX];
91354   int iData, n = fts3PutVarint(c, 0);
91355   n += fts3PutVarint(c+n, nTerm);
91356
91357   /* There should always be room for the header.  Even if pTerm shared
91358   ** a substantial prefix with the previous term, the entire prefix
91359   ** could be constructed from earlier data in the doclist, so there
91360   ** should be room.
91361   */
91362   assert( iDoclistData>=n+nTerm );
91363
91364   iData = iDoclistData-(n+nTerm);
91365   memcpy(pWriter->data.pData+iData, c, n);
91366   memcpy(pWriter->data.pData+iData+n, pTerm, nTerm);
91367
91368   return leafWriterInternalFlush(v, pWriter, iData, pWriter->data.nData-iData);
91369 }
91370
91371 /* Push pTerm[nTerm] along with the doclist data to the leaf layer of
91372 ** %_segments.
91373 */
91374 static int leafWriterStepMerge(fulltext_vtab *v, LeafWriter *pWriter,
91375                                const char *pTerm, int nTerm,
91376                                DLReader *pReaders, int nReaders){
91377   char c[VARINT_MAX+VARINT_MAX];
91378   int iTermData = pWriter->data.nData, iDoclistData;
91379   int i, nData, n, nActualData, nActual, rc, nTermDistinct;
91380
91381   ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData);
91382   nTermDistinct = leafWriterEncodeTerm(pWriter, pTerm, nTerm);
91383
91384   /* Remember nTermDistinct if opening a new node. */
91385   if( iTermData==0 ) pWriter->nTermDistinct = nTermDistinct;
91386
91387   iDoclistData = pWriter->data.nData;
91388
91389   /* Estimate the length of the merged doclist so we can leave space
91390   ** to encode it.
91391   */
91392   for(i=0, nData=0; i<nReaders; i++){
91393     nData += dlrAllDataBytes(&pReaders[i]);
91394   }
91395   n = fts3PutVarint(c, nData);
91396   dataBufferAppend(&pWriter->data, c, n);
91397
91398   docListMerge(&pWriter->data, pReaders, nReaders);
91399   ASSERT_VALID_DOCLIST(DL_DEFAULT,
91400                        pWriter->data.pData+iDoclistData+n,
91401                        pWriter->data.nData-iDoclistData-n, NULL);
91402
91403   /* The actual amount of doclist data at this point could be smaller
91404   ** than the length we encoded.  Additionally, the space required to
91405   ** encode this length could be smaller.  For small doclists, this is
91406   ** not a big deal, we can just use memmove() to adjust things.
91407   */
91408   nActualData = pWriter->data.nData-(iDoclistData+n);
91409   nActual = fts3PutVarint(c, nActualData);
91410   assert( nActualData<=nData );
91411   assert( nActual<=n );
91412
91413   /* If the new doclist is big enough for force a standalone leaf
91414   ** node, we can immediately flush it inline without doing the
91415   ** memmove().
91416   */
91417   /* TODO(shess) This test matches leafWriterStep(), which does this
91418   ** test before it knows the cost to varint-encode the term and
91419   ** doclist lengths.  At some point, change to
91420   ** pWriter->data.nData-iTermData>STANDALONE_MIN.
91421   */
91422   if( nTerm+nActualData>STANDALONE_MIN ){
91423     /* Push leaf node from before this term. */
91424     if( iTermData>0 ){
91425       rc = leafWriterInternalFlush(v, pWriter, 0, iTermData);
91426       if( rc!=SQLITE_OK ) return rc;
91427
91428       pWriter->nTermDistinct = nTermDistinct;
91429     }
91430
91431     /* Fix the encoded doclist length. */
91432     iDoclistData += n - nActual;
91433     memcpy(pWriter->data.pData+iDoclistData, c, nActual);
91434
91435     /* Push the standalone leaf node. */
91436     rc = leafWriterInlineFlush(v, pWriter, pTerm, nTerm, iDoclistData);
91437     if( rc!=SQLITE_OK ) return rc;
91438
91439     /* Leave the node empty. */
91440     dataBufferReset(&pWriter->data);
91441
91442     return rc;
91443   }
91444
91445   /* At this point, we know that the doclist was small, so do the
91446   ** memmove if indicated.
91447   */
91448   if( nActual<n ){
91449     memmove(pWriter->data.pData+iDoclistData+nActual,
91450             pWriter->data.pData+iDoclistData+n,
91451             pWriter->data.nData-(iDoclistData+n));
91452     pWriter->data.nData -= n-nActual;
91453   }
91454
91455   /* Replace written length with actual length. */
91456   memcpy(pWriter->data.pData+iDoclistData, c, nActual);
91457
91458   /* If the node is too large, break things up. */
91459   /* TODO(shess) This test matches leafWriterStep(), which does this
91460   ** test before it knows the cost to varint-encode the term and
91461   ** doclist lengths.  At some point, change to
91462   ** pWriter->data.nData>LEAF_MAX.
91463   */
91464   if( iTermData+nTerm+nActualData>LEAF_MAX ){
91465     /* Flush out the leading data as a node */
91466     rc = leafWriterInternalFlush(v, pWriter, 0, iTermData);
91467     if( rc!=SQLITE_OK ) return rc;
91468
91469     pWriter->nTermDistinct = nTermDistinct;
91470
91471     /* Rebuild header using the current term */
91472     n = fts3PutVarint(pWriter->data.pData, 0);
91473     n += fts3PutVarint(pWriter->data.pData+n, nTerm);
91474     memcpy(pWriter->data.pData+n, pTerm, nTerm);
91475     n += nTerm;
91476
91477     /* There should always be room, because the previous encoding
91478     ** included all data necessary to construct the term.
91479     */
91480     assert( n<iDoclistData );
91481     /* So long as STANDALONE_MIN is half or less of LEAF_MAX, the
91482     ** following memcpy() is safe (as opposed to needing a memmove).
91483     */
91484     assert( 2*STANDALONE_MIN<=LEAF_MAX );
91485     assert( n+pWriter->data.nData-iDoclistData<iDoclistData );
91486     memcpy(pWriter->data.pData+n,
91487            pWriter->data.pData+iDoclistData,
91488            pWriter->data.nData-iDoclistData);
91489     pWriter->data.nData -= iDoclistData-n;
91490   }
91491   ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData);
91492
91493   return SQLITE_OK;
91494 }
91495
91496 /* Push pTerm[nTerm] along with the doclist data to the leaf layer of
91497 ** %_segments.
91498 */
91499 /* TODO(shess) Revise writeZeroSegment() so that doclists are
91500 ** constructed directly in pWriter->data.
91501 */
91502 static int leafWriterStep(fulltext_vtab *v, LeafWriter *pWriter,
91503                           const char *pTerm, int nTerm,
91504                           const char *pData, int nData){
91505   int rc;
91506   DLReader reader;
91507
91508   dlrInit(&reader, DL_DEFAULT, pData, nData);
91509   rc = leafWriterStepMerge(v, pWriter, pTerm, nTerm, &reader, 1);
91510   dlrDestroy(&reader);
91511
91512   return rc;
91513 }
91514
91515
91516 /****************************************************************/
91517 /* LeafReader is used to iterate over an individual leaf node. */
91518 typedef struct LeafReader {
91519   DataBuffer term;          /* copy of current term. */
91520
91521   const char *pData;        /* data for current term. */
91522   int nData;
91523 } LeafReader;
91524
91525 static void leafReaderDestroy(LeafReader *pReader){
91526   dataBufferDestroy(&pReader->term);
91527   SCRAMBLE(pReader);
91528 }
91529
91530 static int leafReaderAtEnd(LeafReader *pReader){
91531   return pReader->nData<=0;
91532 }
91533
91534 /* Access the current term. */
91535 static int leafReaderTermBytes(LeafReader *pReader){
91536   return pReader->term.nData;
91537 }
91538 static const char *leafReaderTerm(LeafReader *pReader){
91539   assert( pReader->term.nData>0 );
91540   return pReader->term.pData;
91541 }
91542
91543 /* Access the doclist data for the current term. */
91544 static int leafReaderDataBytes(LeafReader *pReader){
91545   int nData;
91546   assert( pReader->term.nData>0 );
91547   fts3GetVarint32(pReader->pData, &nData);
91548   return nData;
91549 }
91550 static const char *leafReaderData(LeafReader *pReader){
91551   int n, nData;
91552   assert( pReader->term.nData>0 );
91553   n = fts3GetVarint32(pReader->pData, &nData);
91554   return pReader->pData+n;
91555 }
91556
91557 static void leafReaderInit(const char *pData, int nData,
91558                            LeafReader *pReader){
91559   int nTerm, n;
91560
91561   assert( nData>0 );
91562   assert( pData[0]=='\0' );
91563
91564   CLEAR(pReader);
91565
91566   /* Read the first term, skipping the header byte. */
91567   n = fts3GetVarint32(pData+1, &nTerm);
91568   dataBufferInit(&pReader->term, nTerm);
91569   dataBufferReplace(&pReader->term, pData+1+n, nTerm);
91570
91571   /* Position after the first term. */
91572   assert( 1+n+nTerm<nData );
91573   pReader->pData = pData+1+n+nTerm;
91574   pReader->nData = nData-1-n-nTerm;
91575 }
91576
91577 /* Step the reader forward to the next term. */
91578 static void leafReaderStep(LeafReader *pReader){
91579   int n, nData, nPrefix, nSuffix;
91580   assert( !leafReaderAtEnd(pReader) );
91581
91582   /* Skip previous entry's data block. */
91583   n = fts3GetVarint32(pReader->pData, &nData);
91584   assert( n+nData<=pReader->nData );
91585   pReader->pData += n+nData;
91586   pReader->nData -= n+nData;
91587
91588   if( !leafReaderAtEnd(pReader) ){
91589     /* Construct the new term using a prefix from the old term plus a
91590     ** suffix from the leaf data.
91591     */
91592     n = fts3GetVarint32(pReader->pData, &nPrefix);
91593     n += fts3GetVarint32(pReader->pData+n, &nSuffix);
91594     assert( n+nSuffix<pReader->nData );
91595     pReader->term.nData = nPrefix;
91596     dataBufferAppend(&pReader->term, pReader->pData+n, nSuffix);
91597
91598     pReader->pData += n+nSuffix;
91599     pReader->nData -= n+nSuffix;
91600   }
91601 }
91602
91603 /* strcmp-style comparison of pReader's current term against pTerm.
91604 ** If isPrefix, equality means equal through nTerm bytes.
91605 */
91606 static int leafReaderTermCmp(LeafReader *pReader,
91607                              const char *pTerm, int nTerm, int isPrefix){
91608   int c, n = pReader->term.nData<nTerm ? pReader->term.nData : nTerm;
91609   if( n==0 ){
91610     if( pReader->term.nData>0 ) return -1;
91611     if(nTerm>0 ) return 1;
91612     return 0;
91613   }
91614
91615   c = memcmp(pReader->term.pData, pTerm, n);
91616   if( c!=0 ) return c;
91617   if( isPrefix && n==nTerm ) return 0;
91618   return pReader->term.nData - nTerm;
91619 }
91620
91621
91622 /****************************************************************/
91623 /* LeavesReader wraps LeafReader to allow iterating over the entire
91624 ** leaf layer of the tree.
91625 */
91626 typedef struct LeavesReader {
91627   int idx;                  /* Index within the segment. */
91628
91629   sqlite3_stmt *pStmt;      /* Statement we're streaming leaves from. */
91630   int eof;                  /* we've seen SQLITE_DONE from pStmt. */
91631
91632   LeafReader leafReader;    /* reader for the current leaf. */
91633   DataBuffer rootData;      /* root data for inline. */
91634 } LeavesReader;
91635
91636 /* Access the current term. */
91637 static int leavesReaderTermBytes(LeavesReader *pReader){
91638   assert( !pReader->eof );
91639   return leafReaderTermBytes(&pReader->leafReader);
91640 }
91641 static const char *leavesReaderTerm(LeavesReader *pReader){
91642   assert( !pReader->eof );
91643   return leafReaderTerm(&pReader->leafReader);
91644 }
91645
91646 /* Access the doclist data for the current term. */
91647 static int leavesReaderDataBytes(LeavesReader *pReader){
91648   assert( !pReader->eof );
91649   return leafReaderDataBytes(&pReader->leafReader);
91650 }
91651 static const char *leavesReaderData(LeavesReader *pReader){
91652   assert( !pReader->eof );
91653   return leafReaderData(&pReader->leafReader);
91654 }
91655
91656 static int leavesReaderAtEnd(LeavesReader *pReader){
91657   return pReader->eof;
91658 }
91659
91660 /* loadSegmentLeaves() may not read all the way to SQLITE_DONE, thus
91661 ** leaving the statement handle open, which locks the table.
91662 */
91663 /* TODO(shess) This "solution" is not satisfactory.  Really, there
91664 ** should be check-in function for all statement handles which
91665 ** arranges to call sqlite3_reset().  This most likely will require
91666 ** modification to control flow all over the place, though, so for now
91667 ** just punt.
91668 **
91669 ** Note the the current system assumes that segment merges will run to
91670 ** completion, which is why this particular probably hasn't arisen in
91671 ** this case.  Probably a brittle assumption.
91672 */
91673 static int leavesReaderReset(LeavesReader *pReader){
91674   return sqlite3_reset(pReader->pStmt);
91675 }
91676
91677 static void leavesReaderDestroy(LeavesReader *pReader){
91678   /* If idx is -1, that means we're using a non-cached statement
91679   ** handle in the optimize() case, so we need to release it.
91680   */
91681   if( pReader->pStmt!=NULL && pReader->idx==-1 ){
91682     sqlite3_finalize(pReader->pStmt);
91683   }
91684   leafReaderDestroy(&pReader->leafReader);
91685   dataBufferDestroy(&pReader->rootData);
91686   SCRAMBLE(pReader);
91687 }
91688
91689 /* Initialize pReader with the given root data (if iStartBlockid==0
91690 ** the leaf data was entirely contained in the root), or from the
91691 ** stream of blocks between iStartBlockid and iEndBlockid, inclusive.
91692 */
91693 static int leavesReaderInit(fulltext_vtab *v,
91694                             int idx,
91695                             sqlite_int64 iStartBlockid,
91696                             sqlite_int64 iEndBlockid,
91697                             const char *pRootData, int nRootData,
91698                             LeavesReader *pReader){
91699   CLEAR(pReader);
91700   pReader->idx = idx;
91701
91702   dataBufferInit(&pReader->rootData, 0);
91703   if( iStartBlockid==0 ){
91704     /* Entire leaf level fit in root data. */
91705     dataBufferReplace(&pReader->rootData, pRootData, nRootData);
91706     leafReaderInit(pReader->rootData.pData, pReader->rootData.nData,
91707                    &pReader->leafReader);
91708   }else{
91709     sqlite3_stmt *s;
91710     int rc = sql_get_leaf_statement(v, idx, &s);
91711     if( rc!=SQLITE_OK ) return rc;
91712
91713     rc = sqlite3_bind_int64(s, 1, iStartBlockid);
91714     if( rc!=SQLITE_OK ) return rc;
91715
91716     rc = sqlite3_bind_int64(s, 2, iEndBlockid);
91717     if( rc!=SQLITE_OK ) return rc;
91718
91719     rc = sqlite3_step(s);
91720     if( rc==SQLITE_DONE ){
91721       pReader->eof = 1;
91722       return SQLITE_OK;
91723     }
91724     if( rc!=SQLITE_ROW ) return rc;
91725
91726     pReader->pStmt = s;
91727     leafReaderInit(sqlite3_column_blob(pReader->pStmt, 0),
91728                    sqlite3_column_bytes(pReader->pStmt, 0),
91729                    &pReader->leafReader);
91730   }
91731   return SQLITE_OK;
91732 }
91733
91734 /* Step the current leaf forward to the next term.  If we reach the
91735 ** end of the current leaf, step forward to the next leaf block.
91736 */
91737 static int leavesReaderStep(fulltext_vtab *v, LeavesReader *pReader){
91738   assert( !leavesReaderAtEnd(pReader) );
91739   leafReaderStep(&pReader->leafReader);
91740
91741   if( leafReaderAtEnd(&pReader->leafReader) ){
91742     int rc;
91743     if( pReader->rootData.pData ){
91744       pReader->eof = 1;
91745       return SQLITE_OK;
91746     }
91747     rc = sqlite3_step(pReader->pStmt);
91748     if( rc!=SQLITE_ROW ){
91749       pReader->eof = 1;
91750       return rc==SQLITE_DONE ? SQLITE_OK : rc;
91751     }
91752     leafReaderDestroy(&pReader->leafReader);
91753     leafReaderInit(sqlite3_column_blob(pReader->pStmt, 0),
91754                    sqlite3_column_bytes(pReader->pStmt, 0),
91755                    &pReader->leafReader);
91756   }
91757   return SQLITE_OK;
91758 }
91759
91760 /* Order LeavesReaders by their term, ignoring idx.  Readers at eof
91761 ** always sort to the end.
91762 */
91763 static int leavesReaderTermCmp(LeavesReader *lr1, LeavesReader *lr2){
91764   if( leavesReaderAtEnd(lr1) ){
91765     if( leavesReaderAtEnd(lr2) ) return 0;
91766     return 1;
91767   }
91768   if( leavesReaderAtEnd(lr2) ) return -1;
91769
91770   return leafReaderTermCmp(&lr1->leafReader,
91771                            leavesReaderTerm(lr2), leavesReaderTermBytes(lr2),
91772                            0);
91773 }
91774
91775 /* Similar to leavesReaderTermCmp(), with additional ordering by idx
91776 ** so that older segments sort before newer segments.
91777 */
91778 static int leavesReaderCmp(LeavesReader *lr1, LeavesReader *lr2){
91779   int c = leavesReaderTermCmp(lr1, lr2);
91780   if( c!=0 ) return c;
91781   return lr1->idx-lr2->idx;
91782 }
91783
91784 /* Assume that pLr[1]..pLr[nLr] are sorted.  Bubble pLr[0] into its
91785 ** sorted position.
91786 */
91787 static void leavesReaderReorder(LeavesReader *pLr, int nLr){
91788   while( nLr>1 && leavesReaderCmp(pLr, pLr+1)>0 ){
91789     LeavesReader tmp = pLr[0];
91790     pLr[0] = pLr[1];
91791     pLr[1] = tmp;
91792     nLr--;
91793     pLr++;
91794   }
91795 }
91796
91797 /* Initializes pReaders with the segments from level iLevel, returning
91798 ** the number of segments in *piReaders.  Leaves pReaders in sorted
91799 ** order.
91800 */
91801 static int leavesReadersInit(fulltext_vtab *v, int iLevel,
91802                              LeavesReader *pReaders, int *piReaders){
91803   sqlite3_stmt *s;
91804   int i, rc = sql_get_statement(v, SEGDIR_SELECT_LEVEL_STMT, &s);
91805   if( rc!=SQLITE_OK ) return rc;
91806
91807   rc = sqlite3_bind_int(s, 1, iLevel);
91808   if( rc!=SQLITE_OK ) return rc;
91809
91810   i = 0;
91811   while( (rc = sqlite3_step(s))==SQLITE_ROW ){
91812     sqlite_int64 iStart = sqlite3_column_int64(s, 0);
91813     sqlite_int64 iEnd = sqlite3_column_int64(s, 1);
91814     const char *pRootData = sqlite3_column_blob(s, 2);
91815     int nRootData = sqlite3_column_bytes(s, 2);
91816
91817     assert( i<MERGE_COUNT );
91818     rc = leavesReaderInit(v, i, iStart, iEnd, pRootData, nRootData,
91819                           &pReaders[i]);
91820     if( rc!=SQLITE_OK ) break;
91821
91822     i++;
91823   }
91824   if( rc!=SQLITE_DONE ){
91825     while( i-->0 ){
91826       leavesReaderDestroy(&pReaders[i]);
91827     }
91828     return rc;
91829   }
91830
91831   *piReaders = i;
91832
91833   /* Leave our results sorted by term, then age. */
91834   while( i-- ){
91835     leavesReaderReorder(pReaders+i, *piReaders-i);
91836   }
91837   return SQLITE_OK;
91838 }
91839
91840 /* Merge doclists from pReaders[nReaders] into a single doclist, which
91841 ** is written to pWriter.  Assumes pReaders is ordered oldest to
91842 ** newest.
91843 */
91844 /* TODO(shess) Consider putting this inline in segmentMerge(). */
91845 static int leavesReadersMerge(fulltext_vtab *v,
91846                               LeavesReader *pReaders, int nReaders,
91847                               LeafWriter *pWriter){
91848   DLReader dlReaders[MERGE_COUNT];
91849   const char *pTerm = leavesReaderTerm(pReaders);
91850   int i, nTerm = leavesReaderTermBytes(pReaders);
91851
91852   assert( nReaders<=MERGE_COUNT );
91853
91854   for(i=0; i<nReaders; i++){
91855     dlrInit(&dlReaders[i], DL_DEFAULT,
91856             leavesReaderData(pReaders+i),
91857             leavesReaderDataBytes(pReaders+i));
91858   }
91859
91860   return leafWriterStepMerge(v, pWriter, pTerm, nTerm, dlReaders, nReaders);
91861 }
91862
91863 /* Forward ref due to mutual recursion with segdirNextIndex(). */
91864 static int segmentMerge(fulltext_vtab *v, int iLevel);
91865
91866 /* Put the next available index at iLevel into *pidx.  If iLevel
91867 ** already has MERGE_COUNT segments, they are merged to a higher
91868 ** level to make room.
91869 */
91870 static int segdirNextIndex(fulltext_vtab *v, int iLevel, int *pidx){
91871   int rc = segdir_max_index(v, iLevel, pidx);
91872   if( rc==SQLITE_DONE ){              /* No segments at iLevel. */
91873     *pidx = 0;
91874   }else if( rc==SQLITE_ROW ){
91875     if( *pidx==(MERGE_COUNT-1) ){
91876       rc = segmentMerge(v, iLevel);
91877       if( rc!=SQLITE_OK ) return rc;
91878       *pidx = 0;
91879     }else{
91880       (*pidx)++;
91881     }
91882   }else{
91883     return rc;
91884   }
91885   return SQLITE_OK;
91886 }
91887
91888 /* Merge MERGE_COUNT segments at iLevel into a new segment at
91889 ** iLevel+1.  If iLevel+1 is already full of segments, those will be
91890 ** merged to make room.
91891 */
91892 static int segmentMerge(fulltext_vtab *v, int iLevel){
91893   LeafWriter writer;
91894   LeavesReader lrs[MERGE_COUNT];
91895   int i, rc, idx = 0;
91896
91897   /* Determine the next available segment index at the next level,
91898   ** merging as necessary.
91899   */
91900   rc = segdirNextIndex(v, iLevel+1, &idx);
91901   if( rc!=SQLITE_OK ) return rc;
91902
91903   /* TODO(shess) This assumes that we'll always see exactly
91904   ** MERGE_COUNT segments to merge at a given level.  That will be
91905   ** broken if we allow the developer to request preemptive or
91906   ** deferred merging.
91907   */
91908   memset(&lrs, '\0', sizeof(lrs));
91909   rc = leavesReadersInit(v, iLevel, lrs, &i);
91910   if( rc!=SQLITE_OK ) return rc;
91911   assert( i==MERGE_COUNT );
91912
91913   leafWriterInit(iLevel+1, idx, &writer);
91914
91915   /* Since leavesReaderReorder() pushes readers at eof to the end,
91916   ** when the first reader is empty, all will be empty.
91917   */
91918   while( !leavesReaderAtEnd(lrs) ){
91919     /* Figure out how many readers share their next term. */
91920     for(i=1; i<MERGE_COUNT && !leavesReaderAtEnd(lrs+i); i++){
91921       if( 0!=leavesReaderTermCmp(lrs, lrs+i) ) break;
91922     }
91923
91924     rc = leavesReadersMerge(v, lrs, i, &writer);
91925     if( rc!=SQLITE_OK ) goto err;
91926
91927     /* Step forward those that were merged. */
91928     while( i-->0 ){
91929       rc = leavesReaderStep(v, lrs+i);
91930       if( rc!=SQLITE_OK ) goto err;
91931
91932       /* Reorder by term, then by age. */
91933       leavesReaderReorder(lrs+i, MERGE_COUNT-i);
91934     }
91935   }
91936
91937   for(i=0; i<MERGE_COUNT; i++){
91938     leavesReaderDestroy(&lrs[i]);
91939   }
91940
91941   rc = leafWriterFinalize(v, &writer);
91942   leafWriterDestroy(&writer);
91943   if( rc!=SQLITE_OK ) return rc;
91944
91945   /* Delete the merged segment data. */
91946   return segdir_delete(v, iLevel);
91947
91948  err:
91949   for(i=0; i<MERGE_COUNT; i++){
91950     leavesReaderDestroy(&lrs[i]);
91951   }
91952   leafWriterDestroy(&writer);
91953   return rc;
91954 }
91955
91956 /* Accumulate the union of *acc and *pData into *acc. */
91957 static void docListAccumulateUnion(DataBuffer *acc,
91958                                    const char *pData, int nData) {
91959   DataBuffer tmp = *acc;
91960   dataBufferInit(acc, tmp.nData+nData);
91961   docListUnion(tmp.pData, tmp.nData, pData, nData, acc);
91962   dataBufferDestroy(&tmp);
91963 }
91964
91965 /* TODO(shess) It might be interesting to explore different merge
91966 ** strategies, here.  For instance, since this is a sorted merge, we
91967 ** could easily merge many doclists in parallel.  With some
91968 ** comprehension of the storage format, we could merge all of the
91969 ** doclists within a leaf node directly from the leaf node's storage.
91970 ** It may be worthwhile to merge smaller doclists before larger
91971 ** doclists, since they can be traversed more quickly - but the
91972 ** results may have less overlap, making them more expensive in a
91973 ** different way.
91974 */
91975
91976 /* Scan pReader for pTerm/nTerm, and merge the term's doclist over
91977 ** *out (any doclists with duplicate docids overwrite those in *out).
91978 ** Internal function for loadSegmentLeaf().
91979 */
91980 static int loadSegmentLeavesInt(fulltext_vtab *v, LeavesReader *pReader,
91981                                 const char *pTerm, int nTerm, int isPrefix,
91982                                 DataBuffer *out){
91983   /* doclist data is accumulated into pBuffers similar to how one does
91984   ** increment in binary arithmetic.  If index 0 is empty, the data is
91985   ** stored there.  If there is data there, it is merged and the
91986   ** results carried into position 1, with further merge-and-carry
91987   ** until an empty position is found.
91988   */
91989   DataBuffer *pBuffers = NULL;
91990   int nBuffers = 0, nMaxBuffers = 0, rc;
91991
91992   assert( nTerm>0 );
91993
91994   for(rc=SQLITE_OK; rc==SQLITE_OK && !leavesReaderAtEnd(pReader);
91995       rc=leavesReaderStep(v, pReader)){
91996     /* TODO(shess) Really want leavesReaderTermCmp(), but that name is
91997     ** already taken to compare the terms of two LeavesReaders.  Think
91998     ** on a better name.  [Meanwhile, break encapsulation rather than
91999     ** use a confusing name.]
92000     */
92001     int c = leafReaderTermCmp(&pReader->leafReader, pTerm, nTerm, isPrefix);
92002     if( c>0 ) break;      /* Past any possible matches. */
92003     if( c==0 ){
92004       const char *pData = leavesReaderData(pReader);
92005       int iBuffer, nData = leavesReaderDataBytes(pReader);
92006
92007       /* Find the first empty buffer. */
92008       for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){
92009         if( 0==pBuffers[iBuffer].nData ) break;
92010       }
92011
92012       /* Out of buffers, add an empty one. */
92013       if( iBuffer==nBuffers ){
92014         if( nBuffers==nMaxBuffers ){
92015           DataBuffer *p;
92016           nMaxBuffers += 20;
92017
92018           /* Manual realloc so we can handle NULL appropriately. */
92019           p = sqlite3_malloc(nMaxBuffers*sizeof(*pBuffers));
92020           if( p==NULL ){
92021             rc = SQLITE_NOMEM;
92022             break;
92023           }
92024
92025           if( nBuffers>0 ){
92026             assert(pBuffers!=NULL);
92027             memcpy(p, pBuffers, nBuffers*sizeof(*pBuffers));
92028             sqlite3_free(pBuffers);
92029           }
92030           pBuffers = p;
92031         }
92032         dataBufferInit(&(pBuffers[nBuffers]), 0);
92033         nBuffers++;
92034       }
92035
92036       /* At this point, must have an empty at iBuffer. */
92037       assert(iBuffer<nBuffers && pBuffers[iBuffer].nData==0);
92038
92039       /* If empty was first buffer, no need for merge logic. */
92040       if( iBuffer==0 ){
92041         dataBufferReplace(&(pBuffers[0]), pData, nData);
92042       }else{
92043         /* pAcc is the empty buffer the merged data will end up in. */
92044         DataBuffer *pAcc = &(pBuffers[iBuffer]);
92045         DataBuffer *p = &(pBuffers[0]);
92046
92047         /* Handle position 0 specially to avoid need to prime pAcc
92048         ** with pData/nData.
92049         */
92050         dataBufferSwap(p, pAcc);
92051         docListAccumulateUnion(pAcc, pData, nData);
92052
92053         /* Accumulate remaining doclists into pAcc. */
92054         for(++p; p<pAcc; ++p){
92055           docListAccumulateUnion(pAcc, p->pData, p->nData);
92056
92057           /* dataBufferReset() could allow a large doclist to blow up
92058           ** our memory requirements.
92059           */
92060           if( p->nCapacity<1024 ){
92061             dataBufferReset(p);
92062           }else{
92063             dataBufferDestroy(p);
92064             dataBufferInit(p, 0);
92065           }
92066         }
92067       }
92068     }
92069   }
92070
92071   /* Union all the doclists together into *out. */
92072   /* TODO(shess) What if *out is big?  Sigh. */
92073   if( rc==SQLITE_OK && nBuffers>0 ){
92074     int iBuffer;
92075     for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){
92076       if( pBuffers[iBuffer].nData>0 ){
92077         if( out->nData==0 ){
92078           dataBufferSwap(out, &(pBuffers[iBuffer]));
92079         }else{
92080           docListAccumulateUnion(out, pBuffers[iBuffer].pData,
92081                                  pBuffers[iBuffer].nData);
92082         }
92083       }
92084     }
92085   }
92086
92087   while( nBuffers-- ){
92088     dataBufferDestroy(&(pBuffers[nBuffers]));
92089   }
92090   if( pBuffers!=NULL ) sqlite3_free(pBuffers);
92091
92092   return rc;
92093 }
92094
92095 /* Call loadSegmentLeavesInt() with pData/nData as input. */
92096 static int loadSegmentLeaf(fulltext_vtab *v, const char *pData, int nData,
92097                            const char *pTerm, int nTerm, int isPrefix,
92098                            DataBuffer *out){
92099   LeavesReader reader;
92100   int rc;
92101
92102   assert( nData>1 );
92103   assert( *pData=='\0' );
92104   rc = leavesReaderInit(v, 0, 0, 0, pData, nData, &reader);
92105   if( rc!=SQLITE_OK ) return rc;
92106
92107   rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out);
92108   leavesReaderReset(&reader);
92109   leavesReaderDestroy(&reader);
92110   return rc;
92111 }
92112
92113 /* Call loadSegmentLeavesInt() with the leaf nodes from iStartLeaf to
92114 ** iEndLeaf (inclusive) as input, and merge the resulting doclist into
92115 ** out.
92116 */
92117 static int loadSegmentLeaves(fulltext_vtab *v,
92118                              sqlite_int64 iStartLeaf, sqlite_int64 iEndLeaf,
92119                              const char *pTerm, int nTerm, int isPrefix,
92120                              DataBuffer *out){
92121   int rc;
92122   LeavesReader reader;
92123
92124   assert( iStartLeaf<=iEndLeaf );
92125   rc = leavesReaderInit(v, 0, iStartLeaf, iEndLeaf, NULL, 0, &reader);
92126   if( rc!=SQLITE_OK ) return rc;
92127
92128   rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out);
92129   leavesReaderReset(&reader);
92130   leavesReaderDestroy(&reader);
92131   return rc;
92132 }
92133
92134 /* Taking pData/nData as an interior node, find the sequence of child
92135 ** nodes which could include pTerm/nTerm/isPrefix.  Note that the
92136 ** interior node terms logically come between the blocks, so there is
92137 ** one more blockid than there are terms (that block contains terms >=
92138 ** the last interior-node term).
92139 */
92140 /* TODO(shess) The calling code may already know that the end child is
92141 ** not worth calculating, because the end may be in a later sibling
92142 ** node.  Consider whether breaking symmetry is worthwhile.  I suspect
92143 ** it is not worthwhile.
92144 */
92145 static void getChildrenContaining(const char *pData, int nData,
92146                                   const char *pTerm, int nTerm, int isPrefix,
92147                                   sqlite_int64 *piStartChild,
92148                                   sqlite_int64 *piEndChild){
92149   InteriorReader reader;
92150
92151   assert( nData>1 );
92152   assert( *pData!='\0' );
92153   interiorReaderInit(pData, nData, &reader);
92154
92155   /* Scan for the first child which could contain pTerm/nTerm. */
92156   while( !interiorReaderAtEnd(&reader) ){
92157     if( interiorReaderTermCmp(&reader, pTerm, nTerm, 0)>0 ) break;
92158     interiorReaderStep(&reader);
92159   }
92160   *piStartChild = interiorReaderCurrentBlockid(&reader);
92161
92162   /* Keep scanning to find a term greater than our term, using prefix
92163   ** comparison if indicated.  If isPrefix is false, this will be the
92164   ** same blockid as the starting block.
92165   */
92166   while( !interiorReaderAtEnd(&reader) ){
92167     if( interiorReaderTermCmp(&reader, pTerm, nTerm, isPrefix)>0 ) break;
92168     interiorReaderStep(&reader);
92169   }
92170   *piEndChild = interiorReaderCurrentBlockid(&reader);
92171
92172   interiorReaderDestroy(&reader);
92173
92174   /* Children must ascend, and if !prefix, both must be the same. */
92175   assert( *piEndChild>=*piStartChild );
92176   assert( isPrefix || *piStartChild==*piEndChild );
92177 }
92178
92179 /* Read block at iBlockid and pass it with other params to
92180 ** getChildrenContaining().
92181 */
92182 static int loadAndGetChildrenContaining(
92183   fulltext_vtab *v,
92184   sqlite_int64 iBlockid,
92185   const char *pTerm, int nTerm, int isPrefix,
92186   sqlite_int64 *piStartChild, sqlite_int64 *piEndChild
92187 ){
92188   sqlite3_stmt *s = NULL;
92189   int rc;
92190
92191   assert( iBlockid!=0 );
92192   assert( pTerm!=NULL );
92193   assert( nTerm!=0 );        /* TODO(shess) Why not allow this? */
92194   assert( piStartChild!=NULL );
92195   assert( piEndChild!=NULL );
92196
92197   rc = sql_get_statement(v, BLOCK_SELECT_STMT, &s);
92198   if( rc!=SQLITE_OK ) return rc;
92199
92200   rc = sqlite3_bind_int64(s, 1, iBlockid);
92201   if( rc!=SQLITE_OK ) return rc;
92202
92203   rc = sqlite3_step(s);
92204   if( rc==SQLITE_DONE ) return SQLITE_ERROR;
92205   if( rc!=SQLITE_ROW ) return rc;
92206
92207   getChildrenContaining(sqlite3_column_blob(s, 0), sqlite3_column_bytes(s, 0),
92208                         pTerm, nTerm, isPrefix, piStartChild, piEndChild);
92209
92210   /* We expect only one row.  We must execute another sqlite3_step()
92211    * to complete the iteration; otherwise the table will remain
92212    * locked. */
92213   rc = sqlite3_step(s);
92214   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
92215   if( rc!=SQLITE_DONE ) return rc;
92216
92217   return SQLITE_OK;
92218 }
92219
92220 /* Traverse the tree represented by pData[nData] looking for
92221 ** pTerm[nTerm], placing its doclist into *out.  This is internal to
92222 ** loadSegment() to make error-handling cleaner.
92223 */
92224 static int loadSegmentInt(fulltext_vtab *v, const char *pData, int nData,
92225                           sqlite_int64 iLeavesEnd,
92226                           const char *pTerm, int nTerm, int isPrefix,
92227                           DataBuffer *out){
92228   /* Special case where root is a leaf. */
92229   if( *pData=='\0' ){
92230     return loadSegmentLeaf(v, pData, nData, pTerm, nTerm, isPrefix, out);
92231   }else{
92232     int rc;
92233     sqlite_int64 iStartChild, iEndChild;
92234
92235     /* Process pData as an interior node, then loop down the tree
92236     ** until we find the set of leaf nodes to scan for the term.
92237     */
92238     getChildrenContaining(pData, nData, pTerm, nTerm, isPrefix,
92239                           &iStartChild, &iEndChild);
92240     while( iStartChild>iLeavesEnd ){
92241       sqlite_int64 iNextStart, iNextEnd;
92242       rc = loadAndGetChildrenContaining(v, iStartChild, pTerm, nTerm, isPrefix,
92243                                         &iNextStart, &iNextEnd);
92244       if( rc!=SQLITE_OK ) return rc;
92245
92246       /* If we've branched, follow the end branch, too. */
92247       if( iStartChild!=iEndChild ){
92248         sqlite_int64 iDummy;
92249         rc = loadAndGetChildrenContaining(v, iEndChild, pTerm, nTerm, isPrefix,
92250                                           &iDummy, &iNextEnd);
92251         if( rc!=SQLITE_OK ) return rc;
92252       }
92253
92254       assert( iNextStart<=iNextEnd );
92255       iStartChild = iNextStart;
92256       iEndChild = iNextEnd;
92257     }
92258     assert( iStartChild<=iLeavesEnd );
92259     assert( iEndChild<=iLeavesEnd );
92260
92261     /* Scan through the leaf segments for doclists. */
92262     return loadSegmentLeaves(v, iStartChild, iEndChild,
92263                              pTerm, nTerm, isPrefix, out);
92264   }
92265 }
92266
92267 /* Call loadSegmentInt() to collect the doclist for pTerm/nTerm, then
92268 ** merge its doclist over *out (any duplicate doclists read from the
92269 ** segment rooted at pData will overwrite those in *out).
92270 */
92271 /* TODO(shess) Consider changing this to determine the depth of the
92272 ** leaves using either the first characters of interior nodes (when
92273 ** ==1, we're one level above the leaves), or the first character of
92274 ** the root (which will describe the height of the tree directly).
92275 ** Either feels somewhat tricky to me.
92276 */
92277 /* TODO(shess) The current merge is likely to be slow for large
92278 ** doclists (though it should process from newest/smallest to
92279 ** oldest/largest, so it may not be that bad).  It might be useful to
92280 ** modify things to allow for N-way merging.  This could either be
92281 ** within a segment, with pairwise merges across segments, or across
92282 ** all segments at once.
92283 */
92284 static int loadSegment(fulltext_vtab *v, const char *pData, int nData,
92285                        sqlite_int64 iLeavesEnd,
92286                        const char *pTerm, int nTerm, int isPrefix,
92287                        DataBuffer *out){
92288   DataBuffer result;
92289   int rc;
92290
92291   assert( nData>1 );
92292
92293   /* This code should never be called with buffered updates. */
92294   assert( v->nPendingData<0 );
92295
92296   dataBufferInit(&result, 0);
92297   rc = loadSegmentInt(v, pData, nData, iLeavesEnd,
92298                       pTerm, nTerm, isPrefix, &result);
92299   if( rc==SQLITE_OK && result.nData>0 ){
92300     if( out->nData==0 ){
92301       DataBuffer tmp = *out;
92302       *out = result;
92303       result = tmp;
92304     }else{
92305       DataBuffer merged;
92306       DLReader readers[2];
92307
92308       dlrInit(&readers[0], DL_DEFAULT, out->pData, out->nData);
92309       dlrInit(&readers[1], DL_DEFAULT, result.pData, result.nData);
92310       dataBufferInit(&merged, out->nData+result.nData);
92311       docListMerge(&merged, readers, 2);
92312       dataBufferDestroy(out);
92313       *out = merged;
92314       dlrDestroy(&readers[0]);
92315       dlrDestroy(&readers[1]);
92316     }
92317   }
92318   dataBufferDestroy(&result);
92319   return rc;
92320 }
92321
92322 /* Scan the database and merge together the posting lists for the term
92323 ** into *out.
92324 */
92325 static int termSelect(fulltext_vtab *v, int iColumn,
92326                       const char *pTerm, int nTerm, int isPrefix,
92327                       DocListType iType, DataBuffer *out){
92328   DataBuffer doclist;
92329   sqlite3_stmt *s;
92330   int rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
92331   if( rc!=SQLITE_OK ) return rc;
92332
92333   /* This code should never be called with buffered updates. */
92334   assert( v->nPendingData<0 );
92335
92336   dataBufferInit(&doclist, 0);
92337
92338   /* Traverse the segments from oldest to newest so that newer doclist
92339   ** elements for given docids overwrite older elements.
92340   */
92341   while( (rc = sqlite3_step(s))==SQLITE_ROW ){
92342     const char *pData = sqlite3_column_blob(s, 2);
92343     const int nData = sqlite3_column_bytes(s, 2);
92344     const sqlite_int64 iLeavesEnd = sqlite3_column_int64(s, 1);
92345     rc = loadSegment(v, pData, nData, iLeavesEnd, pTerm, nTerm, isPrefix,
92346                      &doclist);
92347     if( rc!=SQLITE_OK ) goto err;
92348   }
92349   if( rc==SQLITE_DONE ){
92350     if( doclist.nData!=0 ){
92351       /* TODO(shess) The old term_select_all() code applied the column
92352       ** restrict as we merged segments, leading to smaller buffers.
92353       ** This is probably worthwhile to bring back, once the new storage
92354       ** system is checked in.
92355       */
92356       if( iColumn==v->nColumn) iColumn = -1;
92357       docListTrim(DL_DEFAULT, doclist.pData, doclist.nData,
92358                   iColumn, iType, out);
92359     }
92360     rc = SQLITE_OK;
92361   }
92362
92363  err:
92364   dataBufferDestroy(&doclist);
92365   return rc;
92366 }
92367
92368 /****************************************************************/
92369 /* Used to hold hashtable data for sorting. */
92370 typedef struct TermData {
92371   const char *pTerm;
92372   int nTerm;
92373   DLCollector *pCollector;
92374 } TermData;
92375
92376 /* Orders TermData elements in strcmp fashion ( <0 for less-than, 0
92377 ** for equal, >0 for greater-than).
92378 */
92379 static int termDataCmp(const void *av, const void *bv){
92380   const TermData *a = (const TermData *)av;
92381   const TermData *b = (const TermData *)bv;
92382   int n = a->nTerm<b->nTerm ? a->nTerm : b->nTerm;
92383   int c = memcmp(a->pTerm, b->pTerm, n);
92384   if( c!=0 ) return c;
92385   return a->nTerm-b->nTerm;
92386 }
92387
92388 /* Order pTerms data by term, then write a new level 0 segment using
92389 ** LeafWriter.
92390 */
92391 static int writeZeroSegment(fulltext_vtab *v, fts3Hash *pTerms){
92392   fts3HashElem *e;
92393   int idx, rc, i, n;
92394   TermData *pData;
92395   LeafWriter writer;
92396   DataBuffer dl;
92397
92398   /* Determine the next index at level 0, merging as necessary. */
92399   rc = segdirNextIndex(v, 0, &idx);
92400   if( rc!=SQLITE_OK ) return rc;
92401
92402   n = fts3HashCount(pTerms);
92403   pData = sqlite3_malloc(n*sizeof(TermData));
92404
92405   for(i = 0, e = fts3HashFirst(pTerms); e; i++, e = fts3HashNext(e)){
92406     assert( i<n );
92407     pData[i].pTerm = fts3HashKey(e);
92408     pData[i].nTerm = fts3HashKeysize(e);
92409     pData[i].pCollector = fts3HashData(e);
92410   }
92411   assert( i==n );
92412
92413   /* TODO(shess) Should we allow user-defined collation sequences,
92414   ** here?  I think we only need that once we support prefix searches.
92415   */
92416   if( n>1 ) qsort(pData, n, sizeof(*pData), termDataCmp);
92417
92418   /* TODO(shess) Refactor so that we can write directly to the segment
92419   ** DataBuffer, as happens for segment merges.
92420   */
92421   leafWriterInit(0, idx, &writer);
92422   dataBufferInit(&dl, 0);
92423   for(i=0; i<n; i++){
92424     dataBufferReset(&dl);
92425     dlcAddDoclist(pData[i].pCollector, &dl);
92426     rc = leafWriterStep(v, &writer,
92427                         pData[i].pTerm, pData[i].nTerm, dl.pData, dl.nData);
92428     if( rc!=SQLITE_OK ) goto err;
92429   }
92430   rc = leafWriterFinalize(v, &writer);
92431
92432  err:
92433   dataBufferDestroy(&dl);
92434   sqlite3_free(pData);
92435   leafWriterDestroy(&writer);
92436   return rc;
92437 }
92438
92439 /* If pendingTerms has data, free it. */
92440 static int clearPendingTerms(fulltext_vtab *v){
92441   if( v->nPendingData>=0 ){
92442     fts3HashElem *e;
92443     for(e=fts3HashFirst(&v->pendingTerms); e; e=fts3HashNext(e)){
92444       dlcDelete(fts3HashData(e));
92445     }
92446     fts3HashClear(&v->pendingTerms);
92447     v->nPendingData = -1;
92448   }
92449   return SQLITE_OK;
92450 }
92451
92452 /* If pendingTerms has data, flush it to a level-zero segment, and
92453 ** free it.
92454 */
92455 static int flushPendingTerms(fulltext_vtab *v){
92456   if( v->nPendingData>=0 ){
92457     int rc = writeZeroSegment(v, &v->pendingTerms);
92458     if( rc==SQLITE_OK ) clearPendingTerms(v);
92459     return rc;
92460   }
92461   return SQLITE_OK;
92462 }
92463
92464 /* If pendingTerms is "too big", or docid is out of order, flush it.
92465 ** Regardless, be certain that pendingTerms is initialized for use.
92466 */
92467 static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid){
92468   /* TODO(shess) Explore whether partially flushing the buffer on
92469   ** forced-flush would provide better performance.  I suspect that if
92470   ** we ordered the doclists by size and flushed the largest until the
92471   ** buffer was half empty, that would let the less frequent terms
92472   ** generate longer doclists.
92473   */
92474   if( iDocid<=v->iPrevDocid || v->nPendingData>kPendingThreshold ){
92475     int rc = flushPendingTerms(v);
92476     if( rc!=SQLITE_OK ) return rc;
92477   }
92478   if( v->nPendingData<0 ){
92479     fts3HashInit(&v->pendingTerms, FTS3_HASH_STRING, 1);
92480     v->nPendingData = 0;
92481   }
92482   v->iPrevDocid = iDocid;
92483   return SQLITE_OK;
92484 }
92485
92486 /* This function implements the xUpdate callback; it is the top-level entry
92487  * point for inserting, deleting or updating a row in a full-text table. */
92488 static int fulltextUpdate(sqlite3_vtab *pVtab, int nArg, sqlite3_value **ppArg,
92489                           sqlite_int64 *pRowid){
92490   fulltext_vtab *v = (fulltext_vtab *) pVtab;
92491   int rc;
92492
92493   FTSTRACE(("FTS3 Update %p\n", pVtab));
92494
92495   if( nArg<2 ){
92496     rc = index_delete(v, sqlite3_value_int64(ppArg[0]));
92497     if( rc==SQLITE_OK ){
92498       /* If we just deleted the last row in the table, clear out the
92499       ** index data.
92500       */
92501       rc = content_exists(v);
92502       if( rc==SQLITE_ROW ){
92503         rc = SQLITE_OK;
92504       }else if( rc==SQLITE_DONE ){
92505         /* Clear the pending terms so we don't flush a useless level-0
92506         ** segment when the transaction closes.
92507         */
92508         rc = clearPendingTerms(v);
92509         if( rc==SQLITE_OK ){
92510           rc = segdir_delete_all(v);
92511         }
92512       }
92513     }
92514   } else if( sqlite3_value_type(ppArg[0]) != SQLITE_NULL ){
92515     /* An update:
92516      * ppArg[0] = old rowid
92517      * ppArg[1] = new rowid
92518      * ppArg[2..2+v->nColumn-1] = values
92519      * ppArg[2+v->nColumn] = value for magic column (we ignore this)
92520      * ppArg[2+v->nColumn+1] = value for docid
92521      */
92522     sqlite_int64 rowid = sqlite3_value_int64(ppArg[0]);
92523     if( sqlite3_value_type(ppArg[1]) != SQLITE_INTEGER ||
92524         sqlite3_value_int64(ppArg[1]) != rowid ){
92525       rc = SQLITE_ERROR;  /* we don't allow changing the rowid */
92526     }else if( sqlite3_value_type(ppArg[2+v->nColumn+1]) != SQLITE_INTEGER ||
92527               sqlite3_value_int64(ppArg[2+v->nColumn+1]) != rowid ){
92528       rc = SQLITE_ERROR;  /* we don't allow changing the docid */
92529     }else{
92530       assert( nArg==2+v->nColumn+2);
92531       rc = index_update(v, rowid, &ppArg[2]);
92532     }
92533   } else {
92534     /* An insert:
92535      * ppArg[1] = requested rowid
92536      * ppArg[2..2+v->nColumn-1] = values
92537      * ppArg[2+v->nColumn] = value for magic column (we ignore this)
92538      * ppArg[2+v->nColumn+1] = value for docid
92539      */
92540     sqlite3_value *pRequestDocid = ppArg[2+v->nColumn+1];
92541     assert( nArg==2+v->nColumn+2);
92542     if( SQLITE_NULL != sqlite3_value_type(pRequestDocid) &&
92543         SQLITE_NULL != sqlite3_value_type(ppArg[1]) ){
92544       /* TODO(shess) Consider allowing this to work if the values are
92545       ** identical.  I'm inclined to discourage that usage, though,
92546       ** given that both rowid and docid are special columns.  Better
92547       ** would be to define one or the other as the default winner,
92548       ** but should it be fts3-centric (docid) or SQLite-centric
92549       ** (rowid)?
92550       */
92551       rc = SQLITE_ERROR;
92552     }else{
92553       if( SQLITE_NULL == sqlite3_value_type(pRequestDocid) ){
92554         pRequestDocid = ppArg[1];
92555       }
92556       rc = index_insert(v, pRequestDocid, &ppArg[2], pRowid);
92557     }
92558   }
92559
92560   return rc;
92561 }
92562
92563 static int fulltextSync(sqlite3_vtab *pVtab){
92564   FTSTRACE(("FTS3 xSync()\n"));
92565   return flushPendingTerms((fulltext_vtab *)pVtab);
92566 }
92567
92568 static int fulltextBegin(sqlite3_vtab *pVtab){
92569   fulltext_vtab *v = (fulltext_vtab *) pVtab;
92570   FTSTRACE(("FTS3 xBegin()\n"));
92571
92572   /* Any buffered updates should have been cleared by the previous
92573   ** transaction.
92574   */
92575   assert( v->nPendingData<0 );
92576   return clearPendingTerms(v);
92577 }
92578
92579 static int fulltextCommit(sqlite3_vtab *pVtab){
92580   fulltext_vtab *v = (fulltext_vtab *) pVtab;
92581   FTSTRACE(("FTS3 xCommit()\n"));
92582
92583   /* Buffered updates should have been cleared by fulltextSync(). */
92584   assert( v->nPendingData<0 );
92585   return clearPendingTerms(v);
92586 }
92587
92588 static int fulltextRollback(sqlite3_vtab *pVtab){
92589   FTSTRACE(("FTS3 xRollback()\n"));
92590   return clearPendingTerms((fulltext_vtab *)pVtab);
92591 }
92592
92593 /*
92594 ** Implementation of the snippet() function for FTS3
92595 */
92596 static void snippetFunc(
92597   sqlite3_context *pContext,
92598   int argc,
92599   sqlite3_value **argv
92600 ){
92601   fulltext_cursor *pCursor;
92602   if( argc<1 ) return;
92603   if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
92604       sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
92605     sqlite3_result_error(pContext, "illegal first argument to html_snippet",-1);
92606   }else{
92607     const char *zStart = "<b>";
92608     const char *zEnd = "</b>";
92609     const char *zEllipsis = "<b>...</b>";
92610     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
92611     if( argc>=2 ){
92612       zStart = (const char*)sqlite3_value_text(argv[1]);
92613       if( argc>=3 ){
92614         zEnd = (const char*)sqlite3_value_text(argv[2]);
92615         if( argc>=4 ){
92616           zEllipsis = (const char*)sqlite3_value_text(argv[3]);
92617         }
92618       }
92619     }
92620     snippetAllOffsets(pCursor);
92621     snippetText(pCursor, zStart, zEnd, zEllipsis);
92622     sqlite3_result_text(pContext, pCursor->snippet.zSnippet,
92623                         pCursor->snippet.nSnippet, SQLITE_STATIC);
92624   }
92625 }
92626
92627 /*
92628 ** Implementation of the offsets() function for FTS3
92629 */
92630 static void snippetOffsetsFunc(
92631   sqlite3_context *pContext,
92632   int argc,
92633   sqlite3_value **argv
92634 ){
92635   fulltext_cursor *pCursor;
92636   if( argc<1 ) return;
92637   if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
92638       sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
92639     sqlite3_result_error(pContext, "illegal first argument to offsets",-1);
92640   }else{
92641     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
92642     snippetAllOffsets(pCursor);
92643     snippetOffsetText(&pCursor->snippet);
92644     sqlite3_result_text(pContext,
92645                         pCursor->snippet.zOffset, pCursor->snippet.nOffset,
92646                         SQLITE_STATIC);
92647   }
92648 }
92649
92650 /* OptLeavesReader is nearly identical to LeavesReader, except that
92651 ** where LeavesReader is geared towards the merging of complete
92652 ** segment levels (with exactly MERGE_COUNT segments), OptLeavesReader
92653 ** is geared towards implementation of the optimize() function, and
92654 ** can merge all segments simultaneously.  This version may be
92655 ** somewhat less efficient than LeavesReader because it merges into an
92656 ** accumulator rather than doing an N-way merge, but since segment
92657 ** size grows exponentially (so segment count logrithmically) this is
92658 ** probably not an immediate problem.
92659 */
92660 /* TODO(shess): Prove that assertion, or extend the merge code to
92661 ** merge tree fashion (like the prefix-searching code does).
92662 */
92663 /* TODO(shess): OptLeavesReader and LeavesReader could probably be
92664 ** merged with little or no loss of performance for LeavesReader.  The
92665 ** merged code would need to handle >MERGE_COUNT segments, and would
92666 ** also need to be able to optionally optimize away deletes.
92667 */
92668 typedef struct OptLeavesReader {
92669   /* Segment number, to order readers by age. */
92670   int segment;
92671   LeavesReader reader;
92672 } OptLeavesReader;
92673
92674 static int optLeavesReaderAtEnd(OptLeavesReader *pReader){
92675   return leavesReaderAtEnd(&pReader->reader);
92676 }
92677 static int optLeavesReaderTermBytes(OptLeavesReader *pReader){
92678   return leavesReaderTermBytes(&pReader->reader);
92679 }
92680 static const char *optLeavesReaderData(OptLeavesReader *pReader){
92681   return leavesReaderData(&pReader->reader);
92682 }
92683 static int optLeavesReaderDataBytes(OptLeavesReader *pReader){
92684   return leavesReaderDataBytes(&pReader->reader);
92685 }
92686 static const char *optLeavesReaderTerm(OptLeavesReader *pReader){
92687   return leavesReaderTerm(&pReader->reader);
92688 }
92689 static int optLeavesReaderStep(fulltext_vtab *v, OptLeavesReader *pReader){
92690   return leavesReaderStep(v, &pReader->reader);
92691 }
92692 static int optLeavesReaderTermCmp(OptLeavesReader *lr1, OptLeavesReader *lr2){
92693   return leavesReaderTermCmp(&lr1->reader, &lr2->reader);
92694 }
92695 /* Order by term ascending, segment ascending (oldest to newest), with
92696 ** exhausted readers to the end.
92697 */
92698 static int optLeavesReaderCmp(OptLeavesReader *lr1, OptLeavesReader *lr2){
92699   int c = optLeavesReaderTermCmp(lr1, lr2);
92700   if( c!=0 ) return c;
92701   return lr1->segment-lr2->segment;
92702 }
92703 /* Bubble pLr[0] to appropriate place in pLr[1..nLr-1].  Assumes that
92704 ** pLr[1..nLr-1] is already sorted.
92705 */
92706 static void optLeavesReaderReorder(OptLeavesReader *pLr, int nLr){
92707   while( nLr>1 && optLeavesReaderCmp(pLr, pLr+1)>0 ){
92708     OptLeavesReader tmp = pLr[0];
92709     pLr[0] = pLr[1];
92710     pLr[1] = tmp;
92711     nLr--;
92712     pLr++;
92713   }
92714 }
92715
92716 /* optimize() helper function.  Put the readers in order and iterate
92717 ** through them, merging doclists for matching terms into pWriter.
92718 ** Returns SQLITE_OK on success, or the SQLite error code which
92719 ** prevented success.
92720 */
92721 static int optimizeInternal(fulltext_vtab *v,
92722                             OptLeavesReader *readers, int nReaders,
92723                             LeafWriter *pWriter){
92724   int i, rc = SQLITE_OK;
92725   DataBuffer doclist, merged, tmp;
92726
92727   /* Order the readers. */
92728   i = nReaders;
92729   while( i-- > 0 ){
92730     optLeavesReaderReorder(&readers[i], nReaders-i);
92731   }
92732
92733   dataBufferInit(&doclist, LEAF_MAX);
92734   dataBufferInit(&merged, LEAF_MAX);
92735
92736   /* Exhausted readers bubble to the end, so when the first reader is
92737   ** at eof, all are at eof.
92738   */
92739   while( !optLeavesReaderAtEnd(&readers[0]) ){
92740
92741     /* Figure out how many readers share the next term. */
92742     for(i=1; i<nReaders && !optLeavesReaderAtEnd(&readers[i]); i++){
92743       if( 0!=optLeavesReaderTermCmp(&readers[0], &readers[i]) ) break;
92744     }
92745
92746     /* Special-case for no merge. */
92747     if( i==1 ){
92748       /* Trim deletions from the doclist. */
92749       dataBufferReset(&merged);
92750       docListTrim(DL_DEFAULT,
92751                   optLeavesReaderData(&readers[0]),
92752                   optLeavesReaderDataBytes(&readers[0]),
92753                   -1, DL_DEFAULT, &merged);
92754     }else{
92755       DLReader dlReaders[MERGE_COUNT];
92756       int iReader, nReaders;
92757
92758       /* Prime the pipeline with the first reader's doclist.  After
92759       ** one pass index 0 will reference the accumulated doclist.
92760       */
92761       dlrInit(&dlReaders[0], DL_DEFAULT,
92762               optLeavesReaderData(&readers[0]),
92763               optLeavesReaderDataBytes(&readers[0]));
92764       iReader = 1;
92765
92766       assert( iReader<i );  /* Must execute the loop at least once. */
92767       while( iReader<i ){
92768         /* Merge 16 inputs per pass. */
92769         for( nReaders=1; iReader<i && nReaders<MERGE_COUNT;
92770              iReader++, nReaders++ ){
92771           dlrInit(&dlReaders[nReaders], DL_DEFAULT,
92772                   optLeavesReaderData(&readers[iReader]),
92773                   optLeavesReaderDataBytes(&readers[iReader]));
92774         }
92775
92776         /* Merge doclists and swap result into accumulator. */
92777         dataBufferReset(&merged);
92778         docListMerge(&merged, dlReaders, nReaders);
92779         tmp = merged;
92780         merged = doclist;
92781         doclist = tmp;
92782
92783         while( nReaders-- > 0 ){
92784           dlrDestroy(&dlReaders[nReaders]);
92785         }
92786
92787         /* Accumulated doclist to reader 0 for next pass. */
92788         dlrInit(&dlReaders[0], DL_DEFAULT, doclist.pData, doclist.nData);
92789       }
92790
92791       /* Destroy reader that was left in the pipeline. */
92792       dlrDestroy(&dlReaders[0]);
92793
92794       /* Trim deletions from the doclist. */
92795       dataBufferReset(&merged);
92796       docListTrim(DL_DEFAULT, doclist.pData, doclist.nData,
92797                   -1, DL_DEFAULT, &merged);
92798     }
92799
92800     /* Only pass doclists with hits (skip if all hits deleted). */
92801     if( merged.nData>0 ){
92802       rc = leafWriterStep(v, pWriter,
92803                           optLeavesReaderTerm(&readers[0]),
92804                           optLeavesReaderTermBytes(&readers[0]),
92805                           merged.pData, merged.nData);
92806       if( rc!=SQLITE_OK ) goto err;
92807     }
92808
92809     /* Step merged readers to next term and reorder. */
92810     while( i-- > 0 ){
92811       rc = optLeavesReaderStep(v, &readers[i]);
92812       if( rc!=SQLITE_OK ) goto err;
92813
92814       optLeavesReaderReorder(&readers[i], nReaders-i);
92815     }
92816   }
92817
92818  err:
92819   dataBufferDestroy(&doclist);
92820   dataBufferDestroy(&merged);
92821   return rc;
92822 }
92823
92824 /* Implement optimize() function for FTS3.  optimize(t) merges all
92825 ** segments in the fts index into a single segment.  't' is the magic
92826 ** table-named column.
92827 */
92828 static void optimizeFunc(sqlite3_context *pContext,
92829                          int argc, sqlite3_value **argv){
92830   fulltext_cursor *pCursor;
92831   if( argc>1 ){
92832     sqlite3_result_error(pContext, "excess arguments to optimize()",-1);
92833   }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
92834             sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
92835     sqlite3_result_error(pContext, "illegal first argument to optimize",-1);
92836   }else{
92837     fulltext_vtab *v;
92838     int i, rc, iMaxLevel;
92839     OptLeavesReader *readers;
92840     int nReaders;
92841     LeafWriter writer;
92842     sqlite3_stmt *s;
92843
92844     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
92845     v = cursor_vtab(pCursor);
92846
92847     /* Flush any buffered updates before optimizing. */
92848     rc = flushPendingTerms(v);
92849     if( rc!=SQLITE_OK ) goto err;
92850
92851     rc = segdir_count(v, &nReaders, &iMaxLevel);
92852     if( rc!=SQLITE_OK ) goto err;
92853     if( nReaders==0 || nReaders==1 ){
92854       sqlite3_result_text(pContext, "Index already optimal", -1,
92855                           SQLITE_STATIC);
92856       return;
92857     }
92858
92859     rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
92860     if( rc!=SQLITE_OK ) goto err;
92861
92862     readers = sqlite3_malloc(nReaders*sizeof(readers[0]));
92863     if( readers==NULL ) goto err;
92864
92865     /* Note that there will already be a segment at this position
92866     ** until we call segdir_delete() on iMaxLevel.
92867     */
92868     leafWriterInit(iMaxLevel, 0, &writer);
92869
92870     i = 0;
92871     while( (rc = sqlite3_step(s))==SQLITE_ROW ){
92872       sqlite_int64 iStart = sqlite3_column_int64(s, 0);
92873       sqlite_int64 iEnd = sqlite3_column_int64(s, 1);
92874       const char *pRootData = sqlite3_column_blob(s, 2);
92875       int nRootData = sqlite3_column_bytes(s, 2);
92876
92877       assert( i<nReaders );
92878       rc = leavesReaderInit(v, -1, iStart, iEnd, pRootData, nRootData,
92879                             &readers[i].reader);
92880       if( rc!=SQLITE_OK ) break;
92881
92882       readers[i].segment = i;
92883       i++;
92884     }
92885
92886     /* If we managed to succesfully read them all, optimize them. */
92887     if( rc==SQLITE_DONE ){
92888       assert( i==nReaders );
92889       rc = optimizeInternal(v, readers, nReaders, &writer);
92890     }
92891
92892     while( i-- > 0 ){
92893       leavesReaderDestroy(&readers[i].reader);
92894     }
92895     sqlite3_free(readers);
92896
92897     /* If we've successfully gotten to here, delete the old segments
92898     ** and flush the interior structure of the new segment.
92899     */
92900     if( rc==SQLITE_OK ){
92901       for( i=0; i<=iMaxLevel; i++ ){
92902         rc = segdir_delete(v, i);
92903         if( rc!=SQLITE_OK ) break;
92904       }
92905
92906       if( rc==SQLITE_OK ) rc = leafWriterFinalize(v, &writer);
92907     }
92908
92909     leafWriterDestroy(&writer);
92910
92911     if( rc!=SQLITE_OK ) goto err;
92912
92913     sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
92914     return;
92915
92916     /* TODO(shess): Error-handling needs to be improved along the
92917     ** lines of the dump_ functions.
92918     */
92919  err:
92920     {
92921       char buf[512];
92922       sqlite3_snprintf(sizeof(buf), buf, "Error in optimize: %s",
92923                        sqlite3_errmsg(sqlite3_context_db_handle(pContext)));
92924       sqlite3_result_error(pContext, buf, -1);
92925     }
92926   }
92927 }
92928
92929 #ifdef SQLITE_TEST
92930 /* Generate an error of the form "<prefix>: <msg>".  If msg is NULL,
92931 ** pull the error from the context's db handle.
92932 */
92933 static void generateError(sqlite3_context *pContext,
92934                           const char *prefix, const char *msg){
92935   char buf[512];
92936   if( msg==NULL ) msg = sqlite3_errmsg(sqlite3_context_db_handle(pContext));
92937   sqlite3_snprintf(sizeof(buf), buf, "%s: %s", prefix, msg);
92938   sqlite3_result_error(pContext, buf, -1);
92939 }
92940
92941 /* Helper function to collect the set of terms in the segment into
92942 ** pTerms.  The segment is defined by the leaf nodes between
92943 ** iStartBlockid and iEndBlockid, inclusive, or by the contents of
92944 ** pRootData if iStartBlockid is 0 (in which case the entire segment
92945 ** fit in a leaf).
92946 */
92947 static int collectSegmentTerms(fulltext_vtab *v, sqlite3_stmt *s,
92948                                fts3Hash *pTerms){
92949   const sqlite_int64 iStartBlockid = sqlite3_column_int64(s, 0);
92950   const sqlite_int64 iEndBlockid = sqlite3_column_int64(s, 1);
92951   const char *pRootData = sqlite3_column_blob(s, 2);
92952   const int nRootData = sqlite3_column_bytes(s, 2);
92953   LeavesReader reader;
92954   int rc = leavesReaderInit(v, 0, iStartBlockid, iEndBlockid,
92955                             pRootData, nRootData, &reader);
92956   if( rc!=SQLITE_OK ) return rc;
92957
92958   while( rc==SQLITE_OK && !leavesReaderAtEnd(&reader) ){
92959     const char *pTerm = leavesReaderTerm(&reader);
92960     const int nTerm = leavesReaderTermBytes(&reader);
92961     void *oldValue = sqlite3Fts3HashFind(pTerms, pTerm, nTerm);
92962     void *newValue = (void *)((char *)oldValue+1);
92963
92964     /* From the comment before sqlite3Fts3HashInsert in fts3_hash.c,
92965     ** the data value passed is returned in case of malloc failure.
92966     */
92967     if( newValue==sqlite3Fts3HashInsert(pTerms, pTerm, nTerm, newValue) ){
92968       rc = SQLITE_NOMEM;
92969     }else{
92970       rc = leavesReaderStep(v, &reader);
92971     }
92972   }
92973
92974   leavesReaderDestroy(&reader);
92975   return rc;
92976 }
92977
92978 /* Helper function to build the result string for dump_terms(). */
92979 static int generateTermsResult(sqlite3_context *pContext, fts3Hash *pTerms){
92980   int iTerm, nTerms, nResultBytes, iByte;
92981   char *result;
92982   TermData *pData;
92983   fts3HashElem *e;
92984
92985   /* Iterate pTerms to generate an array of terms in pData for
92986   ** sorting.
92987   */
92988   nTerms = fts3HashCount(pTerms);
92989   assert( nTerms>0 );
92990   pData = sqlite3_malloc(nTerms*sizeof(TermData));
92991   if( pData==NULL ) return SQLITE_NOMEM;
92992
92993   nResultBytes = 0;
92994   for(iTerm = 0, e = fts3HashFirst(pTerms); e; iTerm++, e = fts3HashNext(e)){
92995     nResultBytes += fts3HashKeysize(e)+1;   /* Term plus trailing space */
92996     assert( iTerm<nTerms );
92997     pData[iTerm].pTerm = fts3HashKey(e);
92998     pData[iTerm].nTerm = fts3HashKeysize(e);
92999     pData[iTerm].pCollector = fts3HashData(e);  /* unused */
93000   }
93001   assert( iTerm==nTerms );
93002
93003   assert( nResultBytes>0 );   /* nTerms>0, nResultsBytes must be, too. */
93004   result = sqlite3_malloc(nResultBytes);
93005   if( result==NULL ){
93006     sqlite3_free(pData);
93007     return SQLITE_NOMEM;
93008   }
93009
93010   if( nTerms>1 ) qsort(pData, nTerms, sizeof(*pData), termDataCmp);
93011
93012   /* Read the terms in order to build the result. */
93013   iByte = 0;
93014   for(iTerm=0; iTerm<nTerms; ++iTerm){
93015     memcpy(result+iByte, pData[iTerm].pTerm, pData[iTerm].nTerm);
93016     iByte += pData[iTerm].nTerm;
93017     result[iByte++] = ' ';
93018   }
93019   assert( iByte==nResultBytes );
93020   assert( result[nResultBytes-1]==' ' );
93021   result[nResultBytes-1] = '\0';
93022
93023   /* Passes away ownership of result. */
93024   sqlite3_result_text(pContext, result, nResultBytes-1, sqlite3_free);
93025   sqlite3_free(pData);
93026   return SQLITE_OK;
93027 }
93028
93029 /* Implements dump_terms() for use in inspecting the fts3 index from
93030 ** tests.  TEXT result containing the ordered list of terms joined by
93031 ** spaces.  dump_terms(t, level, idx) dumps the terms for the segment
93032 ** specified by level, idx (in %_segdir), while dump_terms(t) dumps
93033 ** all terms in the index.  In both cases t is the fts table's magic
93034 ** table-named column.
93035 */
93036 static void dumpTermsFunc(
93037   sqlite3_context *pContext,
93038   int argc, sqlite3_value **argv
93039 ){
93040   fulltext_cursor *pCursor;
93041   if( argc!=3 && argc!=1 ){
93042     generateError(pContext, "dump_terms", "incorrect arguments");
93043   }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
93044             sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
93045     generateError(pContext, "dump_terms", "illegal first argument");
93046   }else{
93047     fulltext_vtab *v;
93048     fts3Hash terms;
93049     sqlite3_stmt *s = NULL;
93050     int rc;
93051
93052     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
93053     v = cursor_vtab(pCursor);
93054
93055     /* If passed only the cursor column, get all segments.  Otherwise
93056     ** get the segment described by the following two arguments.
93057     */
93058     if( argc==1 ){
93059       rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
93060     }else{
93061       rc = sql_get_statement(v, SEGDIR_SELECT_SEGMENT_STMT, &s);
93062       if( rc==SQLITE_OK ){
93063         rc = sqlite3_bind_int(s, 1, sqlite3_value_int(argv[1]));
93064         if( rc==SQLITE_OK ){
93065           rc = sqlite3_bind_int(s, 2, sqlite3_value_int(argv[2]));
93066         }
93067       }
93068     }
93069
93070     if( rc!=SQLITE_OK ){
93071       generateError(pContext, "dump_terms", NULL);
93072       return;
93073     }
93074
93075     /* Collect the terms for each segment. */
93076     sqlite3Fts3HashInit(&terms, FTS3_HASH_STRING, 1);
93077     while( (rc = sqlite3_step(s))==SQLITE_ROW ){
93078       rc = collectSegmentTerms(v, s, &terms);
93079       if( rc!=SQLITE_OK ) break;
93080     }
93081
93082     if( rc!=SQLITE_DONE ){
93083       sqlite3_reset(s);
93084       generateError(pContext, "dump_terms", NULL);
93085     }else{
93086       const int nTerms = fts3HashCount(&terms);
93087       if( nTerms>0 ){
93088         rc = generateTermsResult(pContext, &terms);
93089         if( rc==SQLITE_NOMEM ){
93090           generateError(pContext, "dump_terms", "out of memory");
93091         }else{
93092           assert( rc==SQLITE_OK );
93093         }
93094       }else if( argc==3 ){
93095         /* The specific segment asked for could not be found. */
93096         generateError(pContext, "dump_terms", "segment not found");
93097       }else{
93098         /* No segments found. */
93099         /* TODO(shess): It should be impossible to reach this.  This
93100         ** case can only happen for an empty table, in which case
93101         ** SQLite has no rows to call this function on.
93102         */
93103         sqlite3_result_null(pContext);
93104       }
93105     }
93106     sqlite3Fts3HashClear(&terms);
93107   }
93108 }
93109
93110 /* Expand the DL_DEFAULT doclist in pData into a text result in
93111 ** pContext.
93112 */
93113 static void createDoclistResult(sqlite3_context *pContext,
93114                                 const char *pData, int nData){
93115   DataBuffer dump;
93116   DLReader dlReader;
93117
93118   assert( pData!=NULL && nData>0 );
93119
93120   dataBufferInit(&dump, 0);
93121   dlrInit(&dlReader, DL_DEFAULT, pData, nData);
93122   for( ; !dlrAtEnd(&dlReader); dlrStep(&dlReader) ){
93123     char buf[256];
93124     PLReader plReader;
93125
93126     plrInit(&plReader, &dlReader);
93127     if( DL_DEFAULT==DL_DOCIDS || plrAtEnd(&plReader) ){
93128       sqlite3_snprintf(sizeof(buf), buf, "[%lld] ", dlrDocid(&dlReader));
93129       dataBufferAppend(&dump, buf, strlen(buf));
93130     }else{
93131       int iColumn = plrColumn(&plReader);
93132
93133       sqlite3_snprintf(sizeof(buf), buf, "[%lld %d[",
93134                        dlrDocid(&dlReader), iColumn);
93135       dataBufferAppend(&dump, buf, strlen(buf));
93136
93137       for( ; !plrAtEnd(&plReader); plrStep(&plReader) ){
93138         if( plrColumn(&plReader)!=iColumn ){
93139           iColumn = plrColumn(&plReader);
93140           sqlite3_snprintf(sizeof(buf), buf, "] %d[", iColumn);
93141           assert( dump.nData>0 );
93142           dump.nData--;                     /* Overwrite trailing space. */
93143           assert( dump.pData[dump.nData]==' ');
93144           dataBufferAppend(&dump, buf, strlen(buf));
93145         }
93146         if( DL_DEFAULT==DL_POSITIONS_OFFSETS ){
93147           sqlite3_snprintf(sizeof(buf), buf, "%d,%d,%d ",
93148                            plrPosition(&plReader),
93149                            plrStartOffset(&plReader), plrEndOffset(&plReader));
93150         }else if( DL_DEFAULT==DL_POSITIONS ){
93151           sqlite3_snprintf(sizeof(buf), buf, "%d ", plrPosition(&plReader));
93152         }else{
93153           assert( NULL=="Unhandled DL_DEFAULT value");
93154         }
93155         dataBufferAppend(&dump, buf, strlen(buf));
93156       }
93157       plrDestroy(&plReader);
93158
93159       assert( dump.nData>0 );
93160       dump.nData--;                     /* Overwrite trailing space. */
93161       assert( dump.pData[dump.nData]==' ');
93162       dataBufferAppend(&dump, "]] ", 3);
93163     }
93164   }
93165   dlrDestroy(&dlReader);
93166
93167   assert( dump.nData>0 );
93168   dump.nData--;                     /* Overwrite trailing space. */
93169   assert( dump.pData[dump.nData]==' ');
93170   dump.pData[dump.nData] = '\0';
93171   assert( dump.nData>0 );
93172
93173   /* Passes ownership of dump's buffer to pContext. */
93174   sqlite3_result_text(pContext, dump.pData, dump.nData, sqlite3_free);
93175   dump.pData = NULL;
93176   dump.nData = dump.nCapacity = 0;
93177 }
93178
93179 /* Implements dump_doclist() for use in inspecting the fts3 index from
93180 ** tests.  TEXT result containing a string representation of the
93181 ** doclist for the indicated term.  dump_doclist(t, term, level, idx)
93182 ** dumps the doclist for term from the segment specified by level, idx
93183 ** (in %_segdir), while dump_doclist(t, term) dumps the logical
93184 ** doclist for the term across all segments.  The per-segment doclist
93185 ** can contain deletions, while the full-index doclist will not
93186 ** (deletions are omitted).
93187 **
93188 ** Result formats differ with the setting of DL_DEFAULTS.  Examples:
93189 **
93190 ** DL_DOCIDS: [1] [3] [7]
93191 ** DL_POSITIONS: [1 0[0 4] 1[17]] [3 1[5]]
93192 ** DL_POSITIONS_OFFSETS: [1 0[0,0,3 4,23,26] 1[17,102,105]] [3 1[5,20,23]]
93193 **
93194 ** In each case the number after the outer '[' is the docid.  In the
93195 ** latter two cases, the number before the inner '[' is the column
93196 ** associated with the values within.  For DL_POSITIONS the numbers
93197 ** within are the positions, for DL_POSITIONS_OFFSETS they are the
93198 ** position, the start offset, and the end offset.
93199 */
93200 static void dumpDoclistFunc(
93201   sqlite3_context *pContext,
93202   int argc, sqlite3_value **argv
93203 ){
93204   fulltext_cursor *pCursor;
93205   if( argc!=2 && argc!=4 ){
93206     generateError(pContext, "dump_doclist", "incorrect arguments");
93207   }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
93208             sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
93209     generateError(pContext, "dump_doclist", "illegal first argument");
93210   }else if( sqlite3_value_text(argv[1])==NULL ||
93211             sqlite3_value_text(argv[1])[0]=='\0' ){
93212     generateError(pContext, "dump_doclist", "empty second argument");
93213   }else{
93214     const char *pTerm = (const char *)sqlite3_value_text(argv[1]);
93215     const int nTerm = strlen(pTerm);
93216     fulltext_vtab *v;
93217     int rc;
93218     DataBuffer doclist;
93219
93220     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
93221     v = cursor_vtab(pCursor);
93222
93223     dataBufferInit(&doclist, 0);
93224
93225     /* termSelect() yields the same logical doclist that queries are
93226     ** run against.
93227     */
93228     if( argc==2 ){
93229       rc = termSelect(v, v->nColumn, pTerm, nTerm, 0, DL_DEFAULT, &doclist);
93230     }else{
93231       sqlite3_stmt *s = NULL;
93232
93233       /* Get our specific segment's information. */
93234       rc = sql_get_statement(v, SEGDIR_SELECT_SEGMENT_STMT, &s);
93235       if( rc==SQLITE_OK ){
93236         rc = sqlite3_bind_int(s, 1, sqlite3_value_int(argv[2]));
93237         if( rc==SQLITE_OK ){
93238           rc = sqlite3_bind_int(s, 2, sqlite3_value_int(argv[3]));
93239         }
93240       }
93241
93242       if( rc==SQLITE_OK ){
93243         rc = sqlite3_step(s);
93244
93245         if( rc==SQLITE_DONE ){
93246           dataBufferDestroy(&doclist);
93247           generateError(pContext, "dump_doclist", "segment not found");
93248           return;
93249         }
93250
93251         /* Found a segment, load it into doclist. */
93252         if( rc==SQLITE_ROW ){
93253           const sqlite_int64 iLeavesEnd = sqlite3_column_int64(s, 1);
93254           const char *pData = sqlite3_column_blob(s, 2);
93255           const int nData = sqlite3_column_bytes(s, 2);
93256
93257           /* loadSegment() is used by termSelect() to load each
93258           ** segment's data.
93259           */
93260           rc = loadSegment(v, pData, nData, iLeavesEnd, pTerm, nTerm, 0,
93261                            &doclist);
93262           if( rc==SQLITE_OK ){
93263             rc = sqlite3_step(s);
93264
93265             /* Should not have more than one matching segment. */
93266             if( rc!=SQLITE_DONE ){
93267               sqlite3_reset(s);
93268               dataBufferDestroy(&doclist);
93269               generateError(pContext, "dump_doclist", "invalid segdir");
93270               return;
93271             }
93272             rc = SQLITE_OK;
93273           }
93274         }
93275       }
93276
93277       sqlite3_reset(s);
93278     }
93279
93280     if( rc==SQLITE_OK ){
93281       if( doclist.nData>0 ){
93282         createDoclistResult(pContext, doclist.pData, doclist.nData);
93283       }else{
93284         /* TODO(shess): This can happen if the term is not present, or
93285         ** if all instances of the term have been deleted and this is
93286         ** an all-index dump.  It may be interesting to distinguish
93287         ** these cases.
93288         */
93289         sqlite3_result_text(pContext, "", 0, SQLITE_STATIC);
93290       }
93291     }else if( rc==SQLITE_NOMEM ){
93292       /* Handle out-of-memory cases specially because if they are
93293       ** generated in fts3 code they may not be reflected in the db
93294       ** handle.
93295       */
93296       /* TODO(shess): Handle this more comprehensively.
93297       ** sqlite3ErrStr() has what I need, but is internal.
93298       */
93299       generateError(pContext, "dump_doclist", "out of memory");
93300     }else{
93301       generateError(pContext, "dump_doclist", NULL);
93302     }
93303
93304     dataBufferDestroy(&doclist);
93305   }
93306 }
93307 #endif
93308
93309 /*
93310 ** This routine implements the xFindFunction method for the FTS3
93311 ** virtual table.
93312 */
93313 static int fulltextFindFunction(
93314   sqlite3_vtab *pVtab,
93315   int nArg,
93316   const char *zName,
93317   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
93318   void **ppArg
93319 ){
93320   if( strcmp(zName,"snippet")==0 ){
93321     *pxFunc = snippetFunc;
93322     return 1;
93323   }else if( strcmp(zName,"offsets")==0 ){
93324     *pxFunc = snippetOffsetsFunc;
93325     return 1;
93326   }else if( strcmp(zName,"optimize")==0 ){
93327     *pxFunc = optimizeFunc;
93328     return 1;
93329 #ifdef SQLITE_TEST
93330     /* NOTE(shess): These functions are present only for testing
93331     ** purposes.  No particular effort is made to optimize their
93332     ** execution or how they build their results.
93333     */
93334   }else if( strcmp(zName,"dump_terms")==0 ){
93335     /* fprintf(stderr, "Found dump_terms\n"); */
93336     *pxFunc = dumpTermsFunc;
93337     return 1;
93338   }else if( strcmp(zName,"dump_doclist")==0 ){
93339     /* fprintf(stderr, "Found dump_doclist\n"); */
93340     *pxFunc = dumpDoclistFunc;
93341     return 1;
93342 #endif
93343   }
93344   return 0;
93345 }
93346
93347 /*
93348 ** Rename an fts3 table.
93349 */
93350 static int fulltextRename(
93351   sqlite3_vtab *pVtab,
93352   const char *zName
93353 ){
93354   fulltext_vtab *p = (fulltext_vtab *)pVtab;
93355   int rc = SQLITE_NOMEM;
93356   char *zSql = sqlite3_mprintf(
93357     "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';"
93358     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';"
93359     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';"
93360     , p->zDb, p->zName, zName 
93361     , p->zDb, p->zName, zName 
93362     , p->zDb, p->zName, zName
93363   );
93364   if( zSql ){
93365     rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
93366     sqlite3_free(zSql);
93367   }
93368   return rc;
93369 }
93370
93371 static const sqlite3_module fts3Module = {
93372   /* iVersion      */ 0,
93373   /* xCreate       */ fulltextCreate,
93374   /* xConnect      */ fulltextConnect,
93375   /* xBestIndex    */ fulltextBestIndex,
93376   /* xDisconnect   */ fulltextDisconnect,
93377   /* xDestroy      */ fulltextDestroy,
93378   /* xOpen         */ fulltextOpen,
93379   /* xClose        */ fulltextClose,
93380   /* xFilter       */ fulltextFilter,
93381   /* xNext         */ fulltextNext,
93382   /* xEof          */ fulltextEof,
93383   /* xColumn       */ fulltextColumn,
93384   /* xRowid        */ fulltextRowid,
93385   /* xUpdate       */ fulltextUpdate,
93386   /* xBegin        */ fulltextBegin,
93387   /* xSync         */ fulltextSync,
93388   /* xCommit       */ fulltextCommit,
93389   /* xRollback     */ fulltextRollback,
93390   /* xFindFunction */ fulltextFindFunction,
93391   /* xRename */       fulltextRename,
93392 };
93393
93394 static void hashDestroy(void *p){
93395   fts3Hash *pHash = (fts3Hash *)p;
93396   sqlite3Fts3HashClear(pHash);
93397   sqlite3_free(pHash);
93398 }
93399
93400 /*
93401 ** The fts3 built-in tokenizers - "simple" and "porter" - are implemented
93402 ** in files fts3_tokenizer1.c and fts3_porter.c respectively. The following
93403 ** two forward declarations are for functions declared in these files
93404 ** used to retrieve the respective implementations.
93405 **
93406 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
93407 ** to by the argument to point a the "simple" tokenizer implementation.
93408 ** Function ...PorterTokenizerModule() sets *pModule to point to the
93409 ** porter tokenizer/stemmer implementation.
93410 */
93411 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
93412 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
93413 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
93414
93415 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, fts3Hash *, const char *);
93416
93417 /*
93418 ** Initialise the fts3 extension. If this extension is built as part
93419 ** of the sqlite library, then this function is called directly by
93420 ** SQLite. If fts3 is built as a dynamically loadable extension, this
93421 ** function is called by the sqlite3_extension_init() entry point.
93422 */
93423 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
93424   int rc = SQLITE_OK;
93425   fts3Hash *pHash = 0;
93426   const sqlite3_tokenizer_module *pSimple = 0;
93427   const sqlite3_tokenizer_module *pPorter = 0;
93428   const sqlite3_tokenizer_module *pIcu = 0;
93429
93430   sqlite3Fts3SimpleTokenizerModule(&pSimple);
93431   sqlite3Fts3PorterTokenizerModule(&pPorter);
93432 #ifdef SQLITE_ENABLE_ICU
93433   sqlite3Fts3IcuTokenizerModule(&pIcu);
93434 #endif
93435
93436   /* Allocate and initialise the hash-table used to store tokenizers. */
93437   pHash = sqlite3_malloc(sizeof(fts3Hash));
93438   if( !pHash ){
93439     rc = SQLITE_NOMEM;
93440   }else{
93441     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
93442   }
93443
93444   /* Load the built-in tokenizers into the hash table */
93445   if( rc==SQLITE_OK ){
93446     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
93447      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
93448      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
93449     ){
93450       rc = SQLITE_NOMEM;
93451     }
93452   }
93453
93454   /* Create the virtual table wrapper around the hash-table and overload 
93455   ** the two scalar functions. If this is successful, register the
93456   ** module with sqlite.
93457   */
93458   if( SQLITE_OK==rc 
93459    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
93460    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
93461    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", -1))
93462    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", -1))
93463 #ifdef SQLITE_TEST
93464    && SQLITE_OK==(rc = sqlite3_overload_function(db, "dump_terms", -1))
93465    && SQLITE_OK==(rc = sqlite3_overload_function(db, "dump_doclist", -1))
93466 #endif
93467   ){
93468     return sqlite3_create_module_v2(
93469         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
93470     );
93471   }
93472
93473   /* An error has occured. Delete the hash table and return the error code. */
93474   assert( rc!=SQLITE_OK );
93475   if( pHash ){
93476     sqlite3Fts3HashClear(pHash);
93477     sqlite3_free(pHash);
93478   }
93479   return rc;
93480 }
93481
93482 #if !SQLITE_CORE
93483 SQLITE_API int sqlite3_extension_init(
93484   sqlite3 *db, 
93485   char **pzErrMsg,
93486   const sqlite3_api_routines *pApi
93487 ){
93488   SQLITE_EXTENSION_INIT2(pApi)
93489   return sqlite3Fts3Init(db);
93490 }
93491 #endif
93492
93493 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
93494
93495 /************** End of fts3.c ************************************************/
93496 /************** Begin file fts3_hash.c ***************************************/
93497 /*
93498 ** 2001 September 22
93499 **
93500 ** The author disclaims copyright to this source code.  In place of
93501 ** a legal notice, here is a blessing:
93502 **
93503 **    May you do good and not evil.
93504 **    May you find forgiveness for yourself and forgive others.
93505 **    May you share freely, never taking more than you give.
93506 **
93507 *************************************************************************
93508 ** This is the implementation of generic hash-tables used in SQLite.
93509 ** We've modified it slightly to serve as a standalone hash table
93510 ** implementation for the full-text indexing module.
93511 */
93512
93513 /*
93514 ** The code in this file is only compiled if:
93515 **
93516 **     * The FTS3 module is being built as an extension
93517 **       (in which case SQLITE_CORE is not defined), or
93518 **
93519 **     * The FTS3 module is being built into the core of
93520 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
93521 */
93522 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
93523
93524
93525
93526 /*
93527 ** Malloc and Free functions
93528 */
93529 static void *fts3HashMalloc(int n){
93530   void *p = sqlite3_malloc(n);
93531   if( p ){
93532     memset(p, 0, n);
93533   }
93534   return p;
93535 }
93536 static void fts3HashFree(void *p){
93537   sqlite3_free(p);
93538 }
93539
93540 /* Turn bulk memory into a hash table object by initializing the
93541 ** fields of the Hash structure.
93542 **
93543 ** "pNew" is a pointer to the hash table that is to be initialized.
93544 ** keyClass is one of the constants 
93545 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
93546 ** determines what kind of key the hash table will use.  "copyKey" is
93547 ** true if the hash table should make its own private copy of keys and
93548 ** false if it should just use the supplied pointer.
93549 */
93550 SQLITE_PRIVATE void sqlite3Fts3HashInit(fts3Hash *pNew, int keyClass, int copyKey){
93551   assert( pNew!=0 );
93552   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
93553   pNew->keyClass = keyClass;
93554   pNew->copyKey = copyKey;
93555   pNew->first = 0;
93556   pNew->count = 0;
93557   pNew->htsize = 0;
93558   pNew->ht = 0;
93559 }
93560
93561 /* Remove all entries from a hash table.  Reclaim all memory.
93562 ** Call this routine to delete a hash table or to reset a hash table
93563 ** to the empty state.
93564 */
93565 SQLITE_PRIVATE void sqlite3Fts3HashClear(fts3Hash *pH){
93566   fts3HashElem *elem;         /* For looping over all elements of the table */
93567
93568   assert( pH!=0 );
93569   elem = pH->first;
93570   pH->first = 0;
93571   fts3HashFree(pH->ht);
93572   pH->ht = 0;
93573   pH->htsize = 0;
93574   while( elem ){
93575     fts3HashElem *next_elem = elem->next;
93576     if( pH->copyKey && elem->pKey ){
93577       fts3HashFree(elem->pKey);
93578     }
93579     fts3HashFree(elem);
93580     elem = next_elem;
93581   }
93582   pH->count = 0;
93583 }
93584
93585 /*
93586 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
93587 */
93588 static int fts3StrHash(const void *pKey, int nKey){
93589   const char *z = (const char *)pKey;
93590   int h = 0;
93591   if( nKey<=0 ) nKey = (int) strlen(z);
93592   while( nKey > 0  ){
93593     h = (h<<3) ^ h ^ *z++;
93594     nKey--;
93595   }
93596   return h & 0x7fffffff;
93597 }
93598 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
93599   if( n1!=n2 ) return 1;
93600   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
93601 }
93602
93603 /*
93604 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
93605 */
93606 static int fts3BinHash(const void *pKey, int nKey){
93607   int h = 0;
93608   const char *z = (const char *)pKey;
93609   while( nKey-- > 0 ){
93610     h = (h<<3) ^ h ^ *(z++);
93611   }
93612   return h & 0x7fffffff;
93613 }
93614 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
93615   if( n1!=n2 ) return 1;
93616   return memcmp(pKey1,pKey2,n1);
93617 }
93618
93619 /*
93620 ** Return a pointer to the appropriate hash function given the key class.
93621 **
93622 ** The C syntax in this function definition may be unfamilar to some 
93623 ** programmers, so we provide the following additional explanation:
93624 **
93625 ** The name of the function is "ftsHashFunction".  The function takes a
93626 ** single parameter "keyClass".  The return value of ftsHashFunction()
93627 ** is a pointer to another function.  Specifically, the return value
93628 ** of ftsHashFunction() is a pointer to a function that takes two parameters
93629 ** with types "const void*" and "int" and returns an "int".
93630 */
93631 static int (*ftsHashFunction(int keyClass))(const void*,int){
93632   if( keyClass==FTS3_HASH_STRING ){
93633     return &fts3StrHash;
93634   }else{
93635     assert( keyClass==FTS3_HASH_BINARY );
93636     return &fts3BinHash;
93637   }
93638 }
93639
93640 /*
93641 ** Return a pointer to the appropriate hash function given the key class.
93642 **
93643 ** For help in interpreted the obscure C code in the function definition,
93644 ** see the header comment on the previous function.
93645 */
93646 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
93647   if( keyClass==FTS3_HASH_STRING ){
93648     return &fts3StrCompare;
93649   }else{
93650     assert( keyClass==FTS3_HASH_BINARY );
93651     return &fts3BinCompare;
93652   }
93653 }
93654
93655 /* Link an element into the hash table
93656 */
93657 static void fts3HashInsertElement(
93658   fts3Hash *pH,            /* The complete hash table */
93659   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
93660   fts3HashElem *pNew       /* The element to be inserted */
93661 ){
93662   fts3HashElem *pHead;     /* First element already in pEntry */
93663   pHead = pEntry->chain;
93664   if( pHead ){
93665     pNew->next = pHead;
93666     pNew->prev = pHead->prev;
93667     if( pHead->prev ){ pHead->prev->next = pNew; }
93668     else             { pH->first = pNew; }
93669     pHead->prev = pNew;
93670   }else{
93671     pNew->next = pH->first;
93672     if( pH->first ){ pH->first->prev = pNew; }
93673     pNew->prev = 0;
93674     pH->first = pNew;
93675   }
93676   pEntry->count++;
93677   pEntry->chain = pNew;
93678 }
93679
93680
93681 /* Resize the hash table so that it cantains "new_size" buckets.
93682 ** "new_size" must be a power of 2.  The hash table might fail 
93683 ** to resize if sqliteMalloc() fails.
93684 */
93685 static void fts3Rehash(fts3Hash *pH, int new_size){
93686   struct _fts3ht *new_ht;          /* The new hash table */
93687   fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
93688   int (*xHash)(const void*,int);   /* The hash function */
93689
93690   assert( (new_size & (new_size-1))==0 );
93691   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
93692   if( new_ht==0 ) return;
93693   fts3HashFree(pH->ht);
93694   pH->ht = new_ht;
93695   pH->htsize = new_size;
93696   xHash = ftsHashFunction(pH->keyClass);
93697   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
93698     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
93699     next_elem = elem->next;
93700     fts3HashInsertElement(pH, &new_ht[h], elem);
93701   }
93702 }
93703
93704 /* This function (for internal use only) locates an element in an
93705 ** hash table that matches the given key.  The hash for this key has
93706 ** already been computed and is passed as the 4th parameter.
93707 */
93708 static fts3HashElem *fts3FindElementByHash(
93709   const fts3Hash *pH, /* The pH to be searched */
93710   const void *pKey,   /* The key we are searching for */
93711   int nKey,
93712   int h               /* The hash for this key. */
93713 ){
93714   fts3HashElem *elem;            /* Used to loop thru the element list */
93715   int count;                     /* Number of elements left to test */
93716   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
93717
93718   if( pH->ht ){
93719     struct _fts3ht *pEntry = &pH->ht[h];
93720     elem = pEntry->chain;
93721     count = pEntry->count;
93722     xCompare = ftsCompareFunction(pH->keyClass);
93723     while( count-- && elem ){
93724       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
93725         return elem;
93726       }
93727       elem = elem->next;
93728     }
93729   }
93730   return 0;
93731 }
93732
93733 /* Remove a single entry from the hash table given a pointer to that
93734 ** element and a hash on the element's key.
93735 */
93736 static void fts3RemoveElementByHash(
93737   fts3Hash *pH,         /* The pH containing "elem" */
93738   fts3HashElem* elem,   /* The element to be removed from the pH */
93739   int h                 /* Hash value for the element */
93740 ){
93741   struct _fts3ht *pEntry;
93742   if( elem->prev ){
93743     elem->prev->next = elem->next; 
93744   }else{
93745     pH->first = elem->next;
93746   }
93747   if( elem->next ){
93748     elem->next->prev = elem->prev;
93749   }
93750   pEntry = &pH->ht[h];
93751   if( pEntry->chain==elem ){
93752     pEntry->chain = elem->next;
93753   }
93754   pEntry->count--;
93755   if( pEntry->count<=0 ){
93756     pEntry->chain = 0;
93757   }
93758   if( pH->copyKey && elem->pKey ){
93759     fts3HashFree(elem->pKey);
93760   }
93761   fts3HashFree( elem );
93762   pH->count--;
93763   if( pH->count<=0 ){
93764     assert( pH->first==0 );
93765     assert( pH->count==0 );
93766     fts3HashClear(pH);
93767   }
93768 }
93769
93770 /* Attempt to locate an element of the hash table pH with a key
93771 ** that matches pKey,nKey.  Return the data for this element if it is
93772 ** found, or NULL if there is no match.
93773 */
93774 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const fts3Hash *pH, const void *pKey, int nKey){
93775   int h;                 /* A hash on key */
93776   fts3HashElem *elem;    /* The element that matches key */
93777   int (*xHash)(const void*,int);  /* The hash function */
93778
93779   if( pH==0 || pH->ht==0 ) return 0;
93780   xHash = ftsHashFunction(pH->keyClass);
93781   assert( xHash!=0 );
93782   h = (*xHash)(pKey,nKey);
93783   assert( (pH->htsize & (pH->htsize-1))==0 );
93784   elem = fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
93785   return elem ? elem->data : 0;
93786 }
93787
93788 /* Insert an element into the hash table pH.  The key is pKey,nKey
93789 ** and the data is "data".
93790 **
93791 ** If no element exists with a matching key, then a new
93792 ** element is created.  A copy of the key is made if the copyKey
93793 ** flag is set.  NULL is returned.
93794 **
93795 ** If another element already exists with the same key, then the
93796 ** new data replaces the old data and the old data is returned.
93797 ** The key is not copied in this instance.  If a malloc fails, then
93798 ** the new data is returned and the hash table is unchanged.
93799 **
93800 ** If the "data" parameter to this function is NULL, then the
93801 ** element corresponding to "key" is removed from the hash table.
93802 */
93803 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
93804   fts3Hash *pH,        /* The hash table to insert into */
93805   const void *pKey,    /* The key */
93806   int nKey,            /* Number of bytes in the key */
93807   void *data           /* The data */
93808 ){
93809   int hraw;                 /* Raw hash value of the key */
93810   int h;                    /* the hash of the key modulo hash table size */
93811   fts3HashElem *elem;       /* Used to loop thru the element list */
93812   fts3HashElem *new_elem;   /* New element added to the pH */
93813   int (*xHash)(const void*,int);  /* The hash function */
93814
93815   assert( pH!=0 );
93816   xHash = ftsHashFunction(pH->keyClass);
93817   assert( xHash!=0 );
93818   hraw = (*xHash)(pKey, nKey);
93819   assert( (pH->htsize & (pH->htsize-1))==0 );
93820   h = hraw & (pH->htsize-1);
93821   elem = fts3FindElementByHash(pH,pKey,nKey,h);
93822   if( elem ){
93823     void *old_data = elem->data;
93824     if( data==0 ){
93825       fts3RemoveElementByHash(pH,elem,h);
93826     }else{
93827       elem->data = data;
93828     }
93829     return old_data;
93830   }
93831   if( data==0 ) return 0;
93832   if( pH->htsize==0 ){
93833     fts3Rehash(pH,8);
93834     if( pH->htsize==0 ){
93835       pH->count = 0;
93836       return data;
93837     }
93838   }
93839   new_elem = (fts3HashElem*)fts3HashMalloc( sizeof(fts3HashElem) );
93840   if( new_elem==0 ) return data;
93841   if( pH->copyKey && pKey!=0 ){
93842     new_elem->pKey = fts3HashMalloc( nKey );
93843     if( new_elem->pKey==0 ){
93844       fts3HashFree(new_elem);
93845       return data;
93846     }
93847     memcpy((void*)new_elem->pKey, pKey, nKey);
93848   }else{
93849     new_elem->pKey = (void*)pKey;
93850   }
93851   new_elem->nKey = nKey;
93852   pH->count++;
93853   if( pH->count > pH->htsize ){
93854     fts3Rehash(pH,pH->htsize*2);
93855   }
93856   assert( pH->htsize>0 );
93857   assert( (pH->htsize & (pH->htsize-1))==0 );
93858   h = hraw & (pH->htsize-1);
93859   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
93860   new_elem->data = data;
93861   return 0;
93862 }
93863
93864 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
93865
93866 /************** End of fts3_hash.c *******************************************/
93867 /************** Begin file fts3_porter.c *************************************/
93868 /*
93869 ** 2006 September 30
93870 **
93871 ** The author disclaims copyright to this source code.  In place of
93872 ** a legal notice, here is a blessing:
93873 **
93874 **    May you do good and not evil.
93875 **    May you find forgiveness for yourself and forgive others.
93876 **    May you share freely, never taking more than you give.
93877 **
93878 *************************************************************************
93879 ** Implementation of the full-text-search tokenizer that implements
93880 ** a Porter stemmer.
93881 */
93882
93883 /*
93884 ** The code in this file is only compiled if:
93885 **
93886 **     * The FTS3 module is being built as an extension
93887 **       (in which case SQLITE_CORE is not defined), or
93888 **
93889 **     * The FTS3 module is being built into the core of
93890 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
93891 */
93892 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
93893
93894
93895
93896
93897 /*
93898 ** Class derived from sqlite3_tokenizer
93899 */
93900 typedef struct porter_tokenizer {
93901   sqlite3_tokenizer base;      /* Base class */
93902 } porter_tokenizer;
93903
93904 /*
93905 ** Class derived from sqlit3_tokenizer_cursor
93906 */
93907 typedef struct porter_tokenizer_cursor {
93908   sqlite3_tokenizer_cursor base;
93909   const char *zInput;          /* input we are tokenizing */
93910   int nInput;                  /* size of the input */
93911   int iOffset;                 /* current position in zInput */
93912   int iToken;                  /* index of next token to be returned */
93913   char *zToken;                /* storage for current token */
93914   int nAllocated;              /* space allocated to zToken buffer */
93915 } porter_tokenizer_cursor;
93916
93917
93918 /* Forward declaration */
93919 static const sqlite3_tokenizer_module porterTokenizerModule;
93920
93921
93922 /*
93923 ** Create a new tokenizer instance.
93924 */
93925 static int porterCreate(
93926   int argc, const char * const *argv,
93927   sqlite3_tokenizer **ppTokenizer
93928 ){
93929   porter_tokenizer *t;
93930   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
93931   if( t==NULL ) return SQLITE_NOMEM;
93932   memset(t, 0, sizeof(*t));
93933   *ppTokenizer = &t->base;
93934   return SQLITE_OK;
93935 }
93936
93937 /*
93938 ** Destroy a tokenizer
93939 */
93940 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
93941   sqlite3_free(pTokenizer);
93942   return SQLITE_OK;
93943 }
93944
93945 /*
93946 ** Prepare to begin tokenizing a particular string.  The input
93947 ** string to be tokenized is zInput[0..nInput-1].  A cursor
93948 ** used to incrementally tokenize this string is returned in 
93949 ** *ppCursor.
93950 */
93951 static int porterOpen(
93952   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
93953   const char *zInput, int nInput,        /* String to be tokenized */
93954   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
93955 ){
93956   porter_tokenizer_cursor *c;
93957
93958   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
93959   if( c==NULL ) return SQLITE_NOMEM;
93960
93961   c->zInput = zInput;
93962   if( zInput==0 ){
93963     c->nInput = 0;
93964   }else if( nInput<0 ){
93965     c->nInput = (int)strlen(zInput);
93966   }else{
93967     c->nInput = nInput;
93968   }
93969   c->iOffset = 0;                 /* start tokenizing at the beginning */
93970   c->iToken = 0;
93971   c->zToken = NULL;               /* no space allocated, yet. */
93972   c->nAllocated = 0;
93973
93974   *ppCursor = &c->base;
93975   return SQLITE_OK;
93976 }
93977
93978 /*
93979 ** Close a tokenization cursor previously opened by a call to
93980 ** porterOpen() above.
93981 */
93982 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
93983   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
93984   sqlite3_free(c->zToken);
93985   sqlite3_free(c);
93986   return SQLITE_OK;
93987 }
93988 /*
93989 ** Vowel or consonant
93990 */
93991 static const char cType[] = {
93992    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
93993    1, 1, 1, 2, 1
93994 };
93995
93996 /*
93997 ** isConsonant() and isVowel() determine if their first character in
93998 ** the string they point to is a consonant or a vowel, according
93999 ** to Porter ruls.  
94000 **
94001 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
94002 ** 'Y' is a consonant unless it follows another consonant,
94003 ** in which case it is a vowel.
94004 **
94005 ** In these routine, the letters are in reverse order.  So the 'y' rule
94006 ** is that 'y' is a consonant unless it is followed by another
94007 ** consonent.
94008 */
94009 static int isVowel(const char*);
94010 static int isConsonant(const char *z){
94011   int j;
94012   char x = *z;
94013   if( x==0 ) return 0;
94014   assert( x>='a' && x<='z' );
94015   j = cType[x-'a'];
94016   if( j<2 ) return j;
94017   return z[1]==0 || isVowel(z + 1);
94018 }
94019 static int isVowel(const char *z){
94020   int j;
94021   char x = *z;
94022   if( x==0 ) return 0;
94023   assert( x>='a' && x<='z' );
94024   j = cType[x-'a'];
94025   if( j<2 ) return 1-j;
94026   return isConsonant(z + 1);
94027 }
94028
94029 /*
94030 ** Let any sequence of one or more vowels be represented by V and let
94031 ** C be sequence of one or more consonants.  Then every word can be
94032 ** represented as:
94033 **
94034 **           [C] (VC){m} [V]
94035 **
94036 ** In prose:  A word is an optional consonant followed by zero or
94037 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
94038 ** number of vowel consonant pairs.  This routine computes the value
94039 ** of m for the first i bytes of a word.
94040 **
94041 ** Return true if the m-value for z is 1 or more.  In other words,
94042 ** return true if z contains at least one vowel that is followed
94043 ** by a consonant.
94044 **
94045 ** In this routine z[] is in reverse order.  So we are really looking
94046 ** for an instance of of a consonant followed by a vowel.
94047 */
94048 static int m_gt_0(const char *z){
94049   while( isVowel(z) ){ z++; }
94050   if( *z==0 ) return 0;
94051   while( isConsonant(z) ){ z++; }
94052   return *z!=0;
94053 }
94054
94055 /* Like mgt0 above except we are looking for a value of m which is
94056 ** exactly 1
94057 */
94058 static int m_eq_1(const char *z){
94059   while( isVowel(z) ){ z++; }
94060   if( *z==0 ) return 0;
94061   while( isConsonant(z) ){ z++; }
94062   if( *z==0 ) return 0;
94063   while( isVowel(z) ){ z++; }
94064   if( *z==0 ) return 1;
94065   while( isConsonant(z) ){ z++; }
94066   return *z==0;
94067 }
94068
94069 /* Like mgt0 above except we are looking for a value of m>1 instead
94070 ** or m>0
94071 */
94072 static int m_gt_1(const char *z){
94073   while( isVowel(z) ){ z++; }
94074   if( *z==0 ) return 0;
94075   while( isConsonant(z) ){ z++; }
94076   if( *z==0 ) return 0;
94077   while( isVowel(z) ){ z++; }
94078   if( *z==0 ) return 0;
94079   while( isConsonant(z) ){ z++; }
94080   return *z!=0;
94081 }
94082
94083 /*
94084 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
94085 */
94086 static int hasVowel(const char *z){
94087   while( isConsonant(z) ){ z++; }
94088   return *z!=0;
94089 }
94090
94091 /*
94092 ** Return TRUE if the word ends in a double consonant.
94093 **
94094 ** The text is reversed here. So we are really looking at
94095 ** the first two characters of z[].
94096 */
94097 static int doubleConsonant(const char *z){
94098   return isConsonant(z) && z[0]==z[1] && isConsonant(z+1);
94099 }
94100
94101 /*
94102 ** Return TRUE if the word ends with three letters which
94103 ** are consonant-vowel-consonent and where the final consonant
94104 ** is not 'w', 'x', or 'y'.
94105 **
94106 ** The word is reversed here.  So we are really checking the
94107 ** first three letters and the first one cannot be in [wxy].
94108 */
94109 static int star_oh(const char *z){
94110   return
94111     z[0]!=0 && isConsonant(z) &&
94112     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
94113     z[1]!=0 && isVowel(z+1) &&
94114     z[2]!=0 && isConsonant(z+2);
94115 }
94116
94117 /*
94118 ** If the word ends with zFrom and xCond() is true for the stem
94119 ** of the word that preceeds the zFrom ending, then change the 
94120 ** ending to zTo.
94121 **
94122 ** The input word *pz and zFrom are both in reverse order.  zTo
94123 ** is in normal order. 
94124 **
94125 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
94126 ** match.  Not that TRUE is returned even if xCond() fails and
94127 ** no substitution occurs.
94128 */
94129 static int stem(
94130   char **pz,             /* The word being stemmed (Reversed) */
94131   const char *zFrom,     /* If the ending matches this... (Reversed) */
94132   const char *zTo,       /* ... change the ending to this (not reversed) */
94133   int (*xCond)(const char*)   /* Condition that must be true */
94134 ){
94135   char *z = *pz;
94136   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
94137   if( *zFrom!=0 ) return 0;
94138   if( xCond && !xCond(z) ) return 1;
94139   while( *zTo ){
94140     *(--z) = *(zTo++);
94141   }
94142   *pz = z;
94143   return 1;
94144 }
94145
94146 /*
94147 ** This is the fallback stemmer used when the porter stemmer is
94148 ** inappropriate.  The input word is copied into the output with
94149 ** US-ASCII case folding.  If the input word is too long (more
94150 ** than 20 bytes if it contains no digits or more than 6 bytes if
94151 ** it contains digits) then word is truncated to 20 or 6 bytes
94152 ** by taking 10 or 3 bytes from the beginning and end.
94153 */
94154 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
94155   int i, mx, j;
94156   int hasDigit = 0;
94157   for(i=0; i<nIn; i++){
94158     int c = zIn[i];
94159     if( c>='A' && c<='Z' ){
94160       zOut[i] = c - 'A' + 'a';
94161     }else{
94162       if( c>='0' && c<='9' ) hasDigit = 1;
94163       zOut[i] = c;
94164     }
94165   }
94166   mx = hasDigit ? 3 : 10;
94167   if( nIn>mx*2 ){
94168     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
94169       zOut[j] = zOut[i];
94170     }
94171     i = j;
94172   }
94173   zOut[i] = 0;
94174   *pnOut = i;
94175 }
94176
94177
94178 /*
94179 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
94180 ** zOut is at least big enough to hold nIn bytes.  Write the actual
94181 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
94182 **
94183 ** Any upper-case characters in the US-ASCII character set ([A-Z])
94184 ** are converted to lower case.  Upper-case UTF characters are
94185 ** unchanged.
94186 **
94187 ** Words that are longer than about 20 bytes are stemmed by retaining
94188 ** a few bytes from the beginning and the end of the word.  If the
94189 ** word contains digits, 3 bytes are taken from the beginning and
94190 ** 3 bytes from the end.  For long words without digits, 10 bytes
94191 ** are taken from each end.  US-ASCII case folding still applies.
94192 ** 
94193 ** If the input word contains not digits but does characters not 
94194 ** in [a-zA-Z] then no stemming is attempted and this routine just 
94195 ** copies the input into the input into the output with US-ASCII
94196 ** case folding.
94197 **
94198 ** Stemming never increases the length of the word.  So there is
94199 ** no chance of overflowing the zOut buffer.
94200 */
94201 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
94202   int i, j, c;
94203   char zReverse[28];
94204   char *z, *z2;
94205   if( nIn<3 || nIn>=sizeof(zReverse)-7 ){
94206     /* The word is too big or too small for the porter stemmer.
94207     ** Fallback to the copy stemmer */
94208     copy_stemmer(zIn, nIn, zOut, pnOut);
94209     return;
94210   }
94211   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
94212     c = zIn[i];
94213     if( c>='A' && c<='Z' ){
94214       zReverse[j] = c + 'a' - 'A';
94215     }else if( c>='a' && c<='z' ){
94216       zReverse[j] = c;
94217     }else{
94218       /* The use of a character not in [a-zA-Z] means that we fallback
94219       ** to the copy stemmer */
94220       copy_stemmer(zIn, nIn, zOut, pnOut);
94221       return;
94222     }
94223   }
94224   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
94225   z = &zReverse[j+1];
94226
94227
94228   /* Step 1a */
94229   if( z[0]=='s' ){
94230     if(
94231      !stem(&z, "sess", "ss", 0) &&
94232      !stem(&z, "sei", "i", 0)  &&
94233      !stem(&z, "ss", "ss", 0)
94234     ){
94235       z++;
94236     }
94237   }
94238
94239   /* Step 1b */  
94240   z2 = z;
94241   if( stem(&z, "dee", "ee", m_gt_0) ){
94242     /* Do nothing.  The work was all in the test */
94243   }else if( 
94244      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
94245       && z!=z2
94246   ){
94247      if( stem(&z, "ta", "ate", 0) ||
94248          stem(&z, "lb", "ble", 0) ||
94249          stem(&z, "zi", "ize", 0) ){
94250        /* Do nothing.  The work was all in the test */
94251      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
94252        z++;
94253      }else if( m_eq_1(z) && star_oh(z) ){
94254        *(--z) = 'e';
94255      }
94256   }
94257
94258   /* Step 1c */
94259   if( z[0]=='y' && hasVowel(z+1) ){
94260     z[0] = 'i';
94261   }
94262
94263   /* Step 2 */
94264   switch( z[1] ){
94265    case 'a':
94266      stem(&z, "lanoita", "ate", m_gt_0) ||
94267      stem(&z, "lanoit", "tion", m_gt_0);
94268      break;
94269    case 'c':
94270      stem(&z, "icne", "ence", m_gt_0) ||
94271      stem(&z, "icna", "ance", m_gt_0);
94272      break;
94273    case 'e':
94274      stem(&z, "rezi", "ize", m_gt_0);
94275      break;
94276    case 'g':
94277      stem(&z, "igol", "log", m_gt_0);
94278      break;
94279    case 'l':
94280      stem(&z, "ilb", "ble", m_gt_0) ||
94281      stem(&z, "illa", "al", m_gt_0) ||
94282      stem(&z, "iltne", "ent", m_gt_0) ||
94283      stem(&z, "ile", "e", m_gt_0) ||
94284      stem(&z, "ilsuo", "ous", m_gt_0);
94285      break;
94286    case 'o':
94287      stem(&z, "noitazi", "ize", m_gt_0) ||
94288      stem(&z, "noita", "ate", m_gt_0) ||
94289      stem(&z, "rota", "ate", m_gt_0);
94290      break;
94291    case 's':
94292      stem(&z, "msila", "al", m_gt_0) ||
94293      stem(&z, "ssenevi", "ive", m_gt_0) ||
94294      stem(&z, "ssenluf", "ful", m_gt_0) ||
94295      stem(&z, "ssensuo", "ous", m_gt_0);
94296      break;
94297    case 't':
94298      stem(&z, "itila", "al", m_gt_0) ||
94299      stem(&z, "itivi", "ive", m_gt_0) ||
94300      stem(&z, "itilib", "ble", m_gt_0);
94301      break;
94302   }
94303
94304   /* Step 3 */
94305   switch( z[0] ){
94306    case 'e':
94307      stem(&z, "etaci", "ic", m_gt_0) ||
94308      stem(&z, "evita", "", m_gt_0)   ||
94309      stem(&z, "ezila", "al", m_gt_0);
94310      break;
94311    case 'i':
94312      stem(&z, "itici", "ic", m_gt_0);
94313      break;
94314    case 'l':
94315      stem(&z, "laci", "ic", m_gt_0) ||
94316      stem(&z, "luf", "", m_gt_0);
94317      break;
94318    case 's':
94319      stem(&z, "ssen", "", m_gt_0);
94320      break;
94321   }
94322
94323   /* Step 4 */
94324   switch( z[1] ){
94325    case 'a':
94326      if( z[0]=='l' && m_gt_1(z+2) ){
94327        z += 2;
94328      }
94329      break;
94330    case 'c':
94331      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
94332        z += 4;
94333      }
94334      break;
94335    case 'e':
94336      if( z[0]=='r' && m_gt_1(z+2) ){
94337        z += 2;
94338      }
94339      break;
94340    case 'i':
94341      if( z[0]=='c' && m_gt_1(z+2) ){
94342        z += 2;
94343      }
94344      break;
94345    case 'l':
94346      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
94347        z += 4;
94348      }
94349      break;
94350    case 'n':
94351      if( z[0]=='t' ){
94352        if( z[2]=='a' ){
94353          if( m_gt_1(z+3) ){
94354            z += 3;
94355          }
94356        }else if( z[2]=='e' ){
94357          stem(&z, "tneme", "", m_gt_1) ||
94358          stem(&z, "tnem", "", m_gt_1) ||
94359          stem(&z, "tne", "", m_gt_1);
94360        }
94361      }
94362      break;
94363    case 'o':
94364      if( z[0]=='u' ){
94365        if( m_gt_1(z+2) ){
94366          z += 2;
94367        }
94368      }else if( z[3]=='s' || z[3]=='t' ){
94369        stem(&z, "noi", "", m_gt_1);
94370      }
94371      break;
94372    case 's':
94373      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
94374        z += 3;
94375      }
94376      break;
94377    case 't':
94378      stem(&z, "eta", "", m_gt_1) ||
94379      stem(&z, "iti", "", m_gt_1);
94380      break;
94381    case 'u':
94382      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
94383        z += 3;
94384      }
94385      break;
94386    case 'v':
94387    case 'z':
94388      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
94389        z += 3;
94390      }
94391      break;
94392   }
94393
94394   /* Step 5a */
94395   if( z[0]=='e' ){
94396     if( m_gt_1(z+1) ){
94397       z++;
94398     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
94399       z++;
94400     }
94401   }
94402
94403   /* Step 5b */
94404   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
94405     z++;
94406   }
94407
94408   /* z[] is now the stemmed word in reverse order.  Flip it back
94409   ** around into forward order and return.
94410   */
94411   *pnOut = i = strlen(z);
94412   zOut[i] = 0;
94413   while( *z ){
94414     zOut[--i] = *(z++);
94415   }
94416 }
94417
94418 /*
94419 ** Characters that can be part of a token.  We assume any character
94420 ** whose value is greater than 0x80 (any UTF character) can be
94421 ** part of a token.  In other words, delimiters all must have
94422 ** values of 0x7f or lower.
94423 */
94424 static const char porterIdChar[] = {
94425 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
94426     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
94427     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
94428     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
94429     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
94430     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
94431 };
94432 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
94433
94434 /*
94435 ** Extract the next token from a tokenization cursor.  The cursor must
94436 ** have been opened by a prior call to porterOpen().
94437 */
94438 static int porterNext(
94439   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
94440   const char **pzToken,               /* OUT: *pzToken is the token text */
94441   int *pnBytes,                       /* OUT: Number of bytes in token */
94442   int *piStartOffset,                 /* OUT: Starting offset of token */
94443   int *piEndOffset,                   /* OUT: Ending offset of token */
94444   int *piPosition                     /* OUT: Position integer of token */
94445 ){
94446   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
94447   const char *z = c->zInput;
94448
94449   while( c->iOffset<c->nInput ){
94450     int iStartOffset, ch;
94451
94452     /* Scan past delimiter characters */
94453     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
94454       c->iOffset++;
94455     }
94456
94457     /* Count non-delimiter characters. */
94458     iStartOffset = c->iOffset;
94459     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
94460       c->iOffset++;
94461     }
94462
94463     if( c->iOffset>iStartOffset ){
94464       int n = c->iOffset-iStartOffset;
94465       if( n>c->nAllocated ){
94466         c->nAllocated = n+20;
94467         c->zToken = sqlite3_realloc(c->zToken, c->nAllocated);
94468         if( c->zToken==NULL ) return SQLITE_NOMEM;
94469       }
94470       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
94471       *pzToken = c->zToken;
94472       *piStartOffset = iStartOffset;
94473       *piEndOffset = c->iOffset;
94474       *piPosition = c->iToken++;
94475       return SQLITE_OK;
94476     }
94477   }
94478   return SQLITE_DONE;
94479 }
94480
94481 /*
94482 ** The set of routines that implement the porter-stemmer tokenizer
94483 */
94484 static const sqlite3_tokenizer_module porterTokenizerModule = {
94485   0,
94486   porterCreate,
94487   porterDestroy,
94488   porterOpen,
94489   porterClose,
94490   porterNext,
94491 };
94492
94493 /*
94494 ** Allocate a new porter tokenizer.  Return a pointer to the new
94495 ** tokenizer in *ppModule
94496 */
94497 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
94498   sqlite3_tokenizer_module const**ppModule
94499 ){
94500   *ppModule = &porterTokenizerModule;
94501 }
94502
94503 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
94504
94505 /************** End of fts3_porter.c *****************************************/
94506 /************** Begin file fts3_tokenizer.c **********************************/
94507 /*
94508 ** 2007 June 22
94509 **
94510 ** The author disclaims copyright to this source code.  In place of
94511 ** a legal notice, here is a blessing:
94512 **
94513 **    May you do good and not evil.
94514 **    May you find forgiveness for yourself and forgive others.
94515 **    May you share freely, never taking more than you give.
94516 **
94517 ******************************************************************************
94518 **
94519 ** This is part of an SQLite module implementing full-text search.
94520 ** This particular file implements the generic tokenizer interface.
94521 */
94522
94523 /*
94524 ** The code in this file is only compiled if:
94525 **
94526 **     * The FTS3 module is being built as an extension
94527 **       (in which case SQLITE_CORE is not defined), or
94528 **
94529 **     * The FTS3 module is being built into the core of
94530 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
94531 */
94532 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
94533
94534 #ifndef SQLITE_CORE
94535   SQLITE_EXTENSION_INIT1
94536 #endif
94537
94538
94539 /*
94540 ** Implementation of the SQL scalar function for accessing the underlying 
94541 ** hash table. This function may be called as follows:
94542 **
94543 **   SELECT <function-name>(<key-name>);
94544 **   SELECT <function-name>(<key-name>, <pointer>);
94545 **
94546 ** where <function-name> is the name passed as the second argument
94547 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
94548 **
94549 ** If the <pointer> argument is specified, it must be a blob value
94550 ** containing a pointer to be stored as the hash data corresponding
94551 ** to the string <key-name>. If <pointer> is not specified, then
94552 ** the string <key-name> must already exist in the has table. Otherwise,
94553 ** an error is returned.
94554 **
94555 ** Whether or not the <pointer> argument is specified, the value returned
94556 ** is a blob containing the pointer stored as the hash data corresponding
94557 ** to string <key-name> (after the hash-table is updated, if applicable).
94558 */
94559 static void scalarFunc(
94560   sqlite3_context *context,
94561   int argc,
94562   sqlite3_value **argv
94563 ){
94564   fts3Hash *pHash;
94565   void *pPtr = 0;
94566   const unsigned char *zName;
94567   int nName;
94568
94569   assert( argc==1 || argc==2 );
94570
94571   pHash = (fts3Hash *)sqlite3_user_data(context);
94572
94573   zName = sqlite3_value_text(argv[0]);
94574   nName = sqlite3_value_bytes(argv[0])+1;
94575
94576   if( argc==2 ){
94577     void *pOld;
94578     int n = sqlite3_value_bytes(argv[1]);
94579     if( n!=sizeof(pPtr) ){
94580       sqlite3_result_error(context, "argument type mismatch", -1);
94581       return;
94582     }
94583     pPtr = *(void **)sqlite3_value_blob(argv[1]);
94584     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
94585     if( pOld==pPtr ){
94586       sqlite3_result_error(context, "out of memory", -1);
94587       return;
94588     }
94589   }else{
94590     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
94591     if( !pPtr ){
94592       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
94593       sqlite3_result_error(context, zErr, -1);
94594       sqlite3_free(zErr);
94595       return;
94596     }
94597   }
94598
94599   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
94600 }
94601
94602 #ifdef SQLITE_TEST
94603
94604
94605 /*
94606 ** Implementation of a special SQL scalar function for testing tokenizers 
94607 ** designed to be used in concert with the Tcl testing framework. This
94608 ** function must be called with two arguments:
94609 **
94610 **   SELECT <function-name>(<key-name>, <input-string>);
94611 **   SELECT <function-name>(<key-name>, <pointer>);
94612 **
94613 ** where <function-name> is the name passed as the second argument
94614 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
94615 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
94616 **
94617 ** The return value is a string that may be interpreted as a Tcl
94618 ** list. For each token in the <input-string>, three elements are
94619 ** added to the returned list. The first is the token position, the 
94620 ** second is the token text (folded, stemmed, etc.) and the third is the
94621 ** substring of <input-string> associated with the token. For example, 
94622 ** using the built-in "simple" tokenizer:
94623 **
94624 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
94625 **
94626 ** will return the string:
94627 **
94628 **   "{0 i I 1 dont don't 2 see see 3 how how}"
94629 **   
94630 */
94631 static void testFunc(
94632   sqlite3_context *context,
94633   int argc,
94634   sqlite3_value **argv
94635 ){
94636   fts3Hash *pHash;
94637   sqlite3_tokenizer_module *p;
94638   sqlite3_tokenizer *pTokenizer = 0;
94639   sqlite3_tokenizer_cursor *pCsr = 0;
94640
94641   const char *zErr = 0;
94642
94643   const char *zName;
94644   int nName;
94645   const char *zInput;
94646   int nInput;
94647
94648   const char *zArg = 0;
94649
94650   const char *zToken;
94651   int nToken;
94652   int iStart;
94653   int iEnd;
94654   int iPos;
94655
94656   Tcl_Obj *pRet;
94657
94658   assert( argc==2 || argc==3 );
94659
94660   nName = sqlite3_value_bytes(argv[0]);
94661   zName = (const char *)sqlite3_value_text(argv[0]);
94662   nInput = sqlite3_value_bytes(argv[argc-1]);
94663   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
94664
94665   if( argc==3 ){
94666     zArg = (const char *)sqlite3_value_text(argv[1]);
94667   }
94668
94669   pHash = (fts3Hash *)sqlite3_user_data(context);
94670   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
94671
94672   if( !p ){
94673     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
94674     sqlite3_result_error(context, zErr, -1);
94675     sqlite3_free(zErr);
94676     return;
94677   }
94678
94679   pRet = Tcl_NewObj();
94680   Tcl_IncrRefCount(pRet);
94681
94682   if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
94683     zErr = "error in xCreate()";
94684     goto finish;
94685   }
94686   pTokenizer->pModule = p;
94687   if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
94688     zErr = "error in xOpen()";
94689     goto finish;
94690   }
94691   pCsr->pTokenizer = pTokenizer;
94692
94693   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
94694     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
94695     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
94696     zToken = &zInput[iStart];
94697     nToken = iEnd-iStart;
94698     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
94699   }
94700
94701   if( SQLITE_OK!=p->xClose(pCsr) ){
94702     zErr = "error in xClose()";
94703     goto finish;
94704   }
94705   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
94706     zErr = "error in xDestroy()";
94707     goto finish;
94708   }
94709
94710 finish:
94711   if( zErr ){
94712     sqlite3_result_error(context, zErr, -1);
94713   }else{
94714     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
94715   }
94716   Tcl_DecrRefCount(pRet);
94717 }
94718
94719 static
94720 int registerTokenizer(
94721   sqlite3 *db, 
94722   char *zName, 
94723   const sqlite3_tokenizer_module *p
94724 ){
94725   int rc;
94726   sqlite3_stmt *pStmt;
94727   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
94728
94729   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
94730   if( rc!=SQLITE_OK ){
94731     return rc;
94732   }
94733
94734   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
94735   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
94736   sqlite3_step(pStmt);
94737
94738   return sqlite3_finalize(pStmt);
94739 }
94740
94741 static
94742 int queryTokenizer(
94743   sqlite3 *db, 
94744   char *zName,  
94745   const sqlite3_tokenizer_module **pp
94746 ){
94747   int rc;
94748   sqlite3_stmt *pStmt;
94749   const char zSql[] = "SELECT fts3_tokenizer(?)";
94750
94751   *pp = 0;
94752   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
94753   if( rc!=SQLITE_OK ){
94754     return rc;
94755   }
94756
94757   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
94758   if( SQLITE_ROW==sqlite3_step(pStmt) ){
94759     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
94760       memcpy(pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
94761     }
94762   }
94763
94764   return sqlite3_finalize(pStmt);
94765 }
94766
94767 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
94768
94769 /*
94770 ** Implementation of the scalar function fts3_tokenizer_internal_test().
94771 ** This function is used for testing only, it is not included in the
94772 ** build unless SQLITE_TEST is defined.
94773 **
94774 ** The purpose of this is to test that the fts3_tokenizer() function
94775 ** can be used as designed by the C-code in the queryTokenizer and
94776 ** registerTokenizer() functions above. These two functions are repeated
94777 ** in the README.tokenizer file as an example, so it is important to
94778 ** test them.
94779 **
94780 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
94781 ** function with no arguments. An assert() will fail if a problem is
94782 ** detected. i.e.:
94783 **
94784 **     SELECT fts3_tokenizer_internal_test();
94785 **
94786 */
94787 static void intTestFunc(
94788   sqlite3_context *context,
94789   int argc,
94790   sqlite3_value **argv
94791 ){
94792   int rc;
94793   const sqlite3_tokenizer_module *p1;
94794   const sqlite3_tokenizer_module *p2;
94795   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
94796
94797   /* Test the query function */
94798   sqlite3Fts3SimpleTokenizerModule(&p1);
94799   rc = queryTokenizer(db, "simple", &p2);
94800   assert( rc==SQLITE_OK );
94801   assert( p1==p2 );
94802   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
94803   assert( rc==SQLITE_ERROR );
94804   assert( p2==0 );
94805   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
94806
94807   /* Test the storage function */
94808   rc = registerTokenizer(db, "nosuchtokenizer", p1);
94809   assert( rc==SQLITE_OK );
94810   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
94811   assert( rc==SQLITE_OK );
94812   assert( p2==p1 );
94813
94814   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
94815 }
94816
94817 #endif
94818
94819 /*
94820 ** Set up SQL objects in database db used to access the contents of
94821 ** the hash table pointed to by argument pHash. The hash table must
94822 ** been initialised to use string keys, and to take a private copy 
94823 ** of the key when a value is inserted. i.e. by a call similar to:
94824 **
94825 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
94826 **
94827 ** This function adds a scalar function (see header comment above
94828 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
94829 ** defined at compilation time, a temporary virtual table (see header 
94830 ** comment above struct HashTableVtab) to the database schema. Both 
94831 ** provide read/write access to the contents of *pHash.
94832 **
94833 ** The third argument to this function, zName, is used as the name
94834 ** of both the scalar and, if created, the virtual table.
94835 */
94836 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
94837   sqlite3 *db, 
94838   fts3Hash *pHash, 
94839   const char *zName
94840 ){
94841   int rc = SQLITE_OK;
94842   void *p = (void *)pHash;
94843   const int any = SQLITE_ANY;
94844   char *zTest = 0;
94845   char *zTest2 = 0;
94846
94847 #ifdef SQLITE_TEST
94848   void *pdb = (void *)db;
94849   zTest = sqlite3_mprintf("%s_test", zName);
94850   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
94851   if( !zTest || !zTest2 ){
94852     rc = SQLITE_NOMEM;
94853   }
94854 #endif
94855
94856   if( rc!=SQLITE_OK
94857    || (rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0))
94858    || (rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0))
94859 #ifdef SQLITE_TEST
94860    || (rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0))
94861    || (rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0))
94862    || (rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0))
94863 #endif
94864   );
94865
94866   sqlite3_free(zTest);
94867   sqlite3_free(zTest2);
94868   return rc;
94869 }
94870
94871 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
94872
94873 /************** End of fts3_tokenizer.c **************************************/
94874 /************** Begin file fts3_tokenizer1.c *********************************/
94875 /*
94876 ** 2006 Oct 10
94877 **
94878 ** The author disclaims copyright to this source code.  In place of
94879 ** a legal notice, here is a blessing:
94880 **
94881 **    May you do good and not evil.
94882 **    May you find forgiveness for yourself and forgive others.
94883 **    May you share freely, never taking more than you give.
94884 **
94885 ******************************************************************************
94886 **
94887 ** Implementation of the "simple" full-text-search tokenizer.
94888 */
94889
94890 /*
94891 ** The code in this file is only compiled if:
94892 **
94893 **     * The FTS3 module is being built as an extension
94894 **       (in which case SQLITE_CORE is not defined), or
94895 **
94896 **     * The FTS3 module is being built into the core of
94897 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
94898 */
94899 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
94900
94901
94902
94903
94904 typedef struct simple_tokenizer {
94905   sqlite3_tokenizer base;
94906   char delim[128];             /* flag ASCII delimiters */
94907 } simple_tokenizer;
94908
94909 typedef struct simple_tokenizer_cursor {
94910   sqlite3_tokenizer_cursor base;
94911   const char *pInput;          /* input we are tokenizing */
94912   int nBytes;                  /* size of the input */
94913   int iOffset;                 /* current position in pInput */
94914   int iToken;                  /* index of next token to be returned */
94915   char *pToken;                /* storage for current token */
94916   int nTokenAllocated;         /* space allocated to zToken buffer */
94917 } simple_tokenizer_cursor;
94918
94919
94920 /* Forward declaration */
94921 static const sqlite3_tokenizer_module simpleTokenizerModule;
94922
94923 static int simpleDelim(simple_tokenizer *t, unsigned char c){
94924   return c<0x80 && t->delim[c];
94925 }
94926
94927 /*
94928 ** Create a new tokenizer instance.
94929 */
94930 static int simpleCreate(
94931   int argc, const char * const *argv,
94932   sqlite3_tokenizer **ppTokenizer
94933 ){
94934   simple_tokenizer *t;
94935
94936   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
94937   if( t==NULL ) return SQLITE_NOMEM;
94938   memset(t, 0, sizeof(*t));
94939
94940   /* TODO(shess) Delimiters need to remain the same from run to run,
94941   ** else we need to reindex.  One solution would be a meta-table to
94942   ** track such information in the database, then we'd only want this
94943   ** information on the initial create.
94944   */
94945   if( argc>1 ){
94946     int i, n = strlen(argv[1]);
94947     for(i=0; i<n; i++){
94948       unsigned char ch = argv[1][i];
94949       /* We explicitly don't support UTF-8 delimiters for now. */
94950       if( ch>=0x80 ){
94951         sqlite3_free(t);
94952         return SQLITE_ERROR;
94953       }
94954       t->delim[ch] = 1;
94955     }
94956   } else {
94957     /* Mark non-alphanumeric ASCII characters as delimiters */
94958     int i;
94959     for(i=1; i<0x80; i++){
94960       t->delim[i] = !isalnum(i);
94961     }
94962   }
94963
94964   *ppTokenizer = &t->base;
94965   return SQLITE_OK;
94966 }
94967
94968 /*
94969 ** Destroy a tokenizer
94970 */
94971 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
94972   sqlite3_free(pTokenizer);
94973   return SQLITE_OK;
94974 }
94975
94976 /*
94977 ** Prepare to begin tokenizing a particular string.  The input
94978 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
94979 ** used to incrementally tokenize this string is returned in 
94980 ** *ppCursor.
94981 */
94982 static int simpleOpen(
94983   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
94984   const char *pInput, int nBytes,        /* String to be tokenized */
94985   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
94986 ){
94987   simple_tokenizer_cursor *c;
94988
94989   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
94990   if( c==NULL ) return SQLITE_NOMEM;
94991
94992   c->pInput = pInput;
94993   if( pInput==0 ){
94994     c->nBytes = 0;
94995   }else if( nBytes<0 ){
94996     c->nBytes = (int)strlen(pInput);
94997   }else{
94998     c->nBytes = nBytes;
94999   }
95000   c->iOffset = 0;                 /* start tokenizing at the beginning */
95001   c->iToken = 0;
95002   c->pToken = NULL;               /* no space allocated, yet. */
95003   c->nTokenAllocated = 0;
95004
95005   *ppCursor = &c->base;
95006   return SQLITE_OK;
95007 }
95008
95009 /*
95010 ** Close a tokenization cursor previously opened by a call to
95011 ** simpleOpen() above.
95012 */
95013 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
95014   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
95015   sqlite3_free(c->pToken);
95016   sqlite3_free(c);
95017   return SQLITE_OK;
95018 }
95019
95020 /*
95021 ** Extract the next token from a tokenization cursor.  The cursor must
95022 ** have been opened by a prior call to simpleOpen().
95023 */
95024 static int simpleNext(
95025   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
95026   const char **ppToken,               /* OUT: *ppToken is the token text */
95027   int *pnBytes,                       /* OUT: Number of bytes in token */
95028   int *piStartOffset,                 /* OUT: Starting offset of token */
95029   int *piEndOffset,                   /* OUT: Ending offset of token */
95030   int *piPosition                     /* OUT: Position integer of token */
95031 ){
95032   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
95033   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
95034   unsigned char *p = (unsigned char *)c->pInput;
95035
95036   while( c->iOffset<c->nBytes ){
95037     int iStartOffset;
95038
95039     /* Scan past delimiter characters */
95040     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
95041       c->iOffset++;
95042     }
95043
95044     /* Count non-delimiter characters. */
95045     iStartOffset = c->iOffset;
95046     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
95047       c->iOffset++;
95048     }
95049
95050     if( c->iOffset>iStartOffset ){
95051       int i, n = c->iOffset-iStartOffset;
95052       if( n>c->nTokenAllocated ){
95053         c->nTokenAllocated = n+20;
95054         c->pToken = sqlite3_realloc(c->pToken, c->nTokenAllocated);
95055         if( c->pToken==NULL ) return SQLITE_NOMEM;
95056       }
95057       for(i=0; i<n; i++){
95058         /* TODO(shess) This needs expansion to handle UTF-8
95059         ** case-insensitivity.
95060         */
95061         unsigned char ch = p[iStartOffset+i];
95062         c->pToken[i] = ch<0x80 ? tolower(ch) : ch;
95063       }
95064       *ppToken = c->pToken;
95065       *pnBytes = n;
95066       *piStartOffset = iStartOffset;
95067       *piEndOffset = c->iOffset;
95068       *piPosition = c->iToken++;
95069
95070       return SQLITE_OK;
95071     }
95072   }
95073   return SQLITE_DONE;
95074 }
95075
95076 /*
95077 ** The set of routines that implement the simple tokenizer
95078 */
95079 static const sqlite3_tokenizer_module simpleTokenizerModule = {
95080   0,
95081   simpleCreate,
95082   simpleDestroy,
95083   simpleOpen,
95084   simpleClose,
95085   simpleNext,
95086 };
95087
95088 /*
95089 ** Allocate a new simple tokenizer.  Return a pointer to the new
95090 ** tokenizer in *ppModule
95091 */
95092 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
95093   sqlite3_tokenizer_module const**ppModule
95094 ){
95095   *ppModule = &simpleTokenizerModule;
95096 }
95097
95098 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
95099
95100 /************** End of fts3_tokenizer1.c *************************************/
95101 /************** Begin file rtree.c *******************************************/
95102 /*
95103 ** 2001 September 15
95104 **
95105 ** The author disclaims copyright to this source code.  In place of
95106 ** a legal notice, here is a blessing:
95107 **
95108 **    May you do good and not evil.
95109 **    May you find forgiveness for yourself and forgive others.
95110 **    May you share freely, never taking more than you give.
95111 **
95112 *************************************************************************
95113 ** This file contains code for implementations of the r-tree and r*-tree
95114 ** algorithms packaged as an SQLite virtual table module.
95115 **
95116 ** $Id: rtree.c,v 1.11 2008/11/12 15:24:27 drh Exp $
95117 */
95118
95119 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
95120
95121 /*
95122 ** This file contains an implementation of a couple of different variants
95123 ** of the r-tree algorithm. See the README file for further details. The 
95124 ** same data-structure is used for all, but the algorithms for insert and
95125 ** delete operations vary. The variants used are selected at compile time 
95126 ** by defining the following symbols:
95127 */
95128
95129 /* Either, both or none of the following may be set to activate 
95130 ** r*tree variant algorithms.
95131 */
95132 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
95133 #define VARIANT_RSTARTREE_REINSERT      1
95134
95135 /* 
95136 ** Exactly one of the following must be set to 1.
95137 */
95138 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
95139 #define VARIANT_GUTTMAN_LINEAR_SPLIT    0
95140 #define VARIANT_RSTARTREE_SPLIT         1
95141
95142 #define VARIANT_GUTTMAN_SPLIT \
95143         (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
95144
95145 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
95146   #define PickNext QuadraticPickNext
95147   #define PickSeeds QuadraticPickSeeds
95148   #define AssignCells splitNodeGuttman
95149 #endif
95150 #if VARIANT_GUTTMAN_LINEAR_SPLIT
95151   #define PickNext LinearPickNext
95152   #define PickSeeds LinearPickSeeds
95153   #define AssignCells splitNodeGuttman
95154 #endif
95155 #if VARIANT_RSTARTREE_SPLIT
95156   #define AssignCells splitNodeStartree
95157 #endif
95158
95159
95160 #ifndef SQLITE_CORE
95161   SQLITE_EXTENSION_INIT1
95162 #else
95163 #endif
95164
95165
95166 #ifndef SQLITE_AMALGAMATION
95167 typedef sqlite3_int64 i64;
95168 typedef unsigned char u8;
95169 typedef unsigned int u32;
95170 #endif
95171
95172 typedef struct Rtree Rtree;
95173 typedef struct RtreeCursor RtreeCursor;
95174 typedef struct RtreeNode RtreeNode;
95175 typedef struct RtreeCell RtreeCell;
95176 typedef struct RtreeConstraint RtreeConstraint;
95177 typedef union RtreeCoord RtreeCoord;
95178
95179 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
95180 #define RTREE_MAX_DIMENSIONS 5
95181
95182 /* Size of hash table Rtree.aHash. This hash table is not expected to
95183 ** ever contain very many entries, so a fixed number of buckets is 
95184 ** used.
95185 */
95186 #define HASHSIZE 128
95187
95188 /* 
95189 ** An rtree virtual-table object.
95190 */
95191 struct Rtree {
95192   sqlite3_vtab base;
95193   sqlite3 *db;                /* Host database connection */
95194   int iNodeSize;              /* Size in bytes of each node in the node table */
95195   int nDim;                   /* Number of dimensions */
95196   int nBytesPerCell;          /* Bytes consumed per cell */
95197   int iDepth;                 /* Current depth of the r-tree structure */
95198   char *zDb;                  /* Name of database containing r-tree table */
95199   char *zName;                /* Name of r-tree table */ 
95200   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 
95201   int nBusy;                  /* Current number of users of this structure */
95202
95203   /* List of nodes removed during a CondenseTree operation. List is
95204   ** linked together via the pointer normally used for hash chains -
95205   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 
95206   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
95207   */
95208   RtreeNode *pDeleted;
95209   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
95210
95211   /* Statements to read/write/delete a record from xxx_node */
95212   sqlite3_stmt *pReadNode;
95213   sqlite3_stmt *pWriteNode;
95214   sqlite3_stmt *pDeleteNode;
95215
95216   /* Statements to read/write/delete a record from xxx_rowid */
95217   sqlite3_stmt *pReadRowid;
95218   sqlite3_stmt *pWriteRowid;
95219   sqlite3_stmt *pDeleteRowid;
95220
95221   /* Statements to read/write/delete a record from xxx_parent */
95222   sqlite3_stmt *pReadParent;
95223   sqlite3_stmt *pWriteParent;
95224   sqlite3_stmt *pDeleteParent;
95225
95226   int eCoordType;
95227 };
95228
95229 /* Possible values for eCoordType: */
95230 #define RTREE_COORD_REAL32 0
95231 #define RTREE_COORD_INT32  1
95232
95233 /*
95234 ** The minimum number of cells allowed for a node is a third of the 
95235 ** maximum. In Gutman's notation:
95236 **
95237 **     m = M/3
95238 **
95239 ** If an R*-tree "Reinsert" operation is required, the same number of
95240 ** cells are removed from the overfull node and reinserted into the tree.
95241 */
95242 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
95243 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
95244 #define RTREE_MAXCELLS 51
95245
95246 /* 
95247 ** An rtree cursor object.
95248 */
95249 struct RtreeCursor {
95250   sqlite3_vtab_cursor base;
95251   RtreeNode *pNode;                 /* Node cursor is currently pointing at */
95252   int iCell;                        /* Index of current cell in pNode */
95253   int iStrategy;                    /* Copy of idxNum search parameter */
95254   int nConstraint;                  /* Number of entries in aConstraint */
95255   RtreeConstraint *aConstraint;     /* Search constraints. */
95256 };
95257
95258 union RtreeCoord {
95259   float f;
95260   int i;
95261 };
95262
95263 /*
95264 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
95265 ** formatted as a double. This macro assumes that local variable pRtree points
95266 ** to the Rtree structure associated with the RtreeCoord.
95267 */
95268 #define DCOORD(coord) (                           \
95269   (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
95270     ((double)coord.f) :                           \
95271     ((double)coord.i)                             \
95272 )
95273
95274 /*
95275 ** A search constraint.
95276 */
95277 struct RtreeConstraint {
95278   int iCoord;                       /* Index of constrained coordinate */
95279   int op;                           /* Constraining operation */
95280   double rValue;                    /* Constraint value. */
95281 };
95282
95283 /* Possible values for RtreeConstraint.op */
95284 #define RTREE_EQ 0x41
95285 #define RTREE_LE 0x42
95286 #define RTREE_LT 0x43
95287 #define RTREE_GE 0x44
95288 #define RTREE_GT 0x45
95289
95290 /* 
95291 ** An rtree structure node.
95292 **
95293 ** Data format (RtreeNode.zData):
95294 **
95295 **   1. If the node is the root node (node 1), then the first 2 bytes
95296 **      of the node contain the tree depth as a big-endian integer.
95297 **      For non-root nodes, the first 2 bytes are left unused.
95298 **
95299 **   2. The next 2 bytes contain the number of entries currently 
95300 **      stored in the node.
95301 **
95302 **   3. The remainder of the node contains the node entries. Each entry
95303 **      consists of a single 8-byte integer followed by an even number
95304 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
95305 **      of a record. For internal nodes it is the node number of a
95306 **      child page.
95307 */
95308 struct RtreeNode {
95309   RtreeNode *pParent;               /* Parent node */
95310   i64 iNode;
95311   int nRef;
95312   int isDirty;
95313   u8 *zData;
95314   RtreeNode *pNext;                 /* Next node in this hash chain */
95315 };
95316 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
95317
95318 /* 
95319 ** Structure to store a deserialized rtree record.
95320 */
95321 struct RtreeCell {
95322   i64 iRowid;
95323   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
95324 };
95325
95326 #ifndef MAX
95327 # define MAX(x,y) ((x) < (y) ? (y) : (x))
95328 #endif
95329 #ifndef MIN
95330 # define MIN(x,y) ((x) > (y) ? (y) : (x))
95331 #endif
95332
95333 /*
95334 ** Functions to deserialize a 16 bit integer, 32 bit real number and
95335 ** 64 bit integer. The deserialized value is returned.
95336 */
95337 static int readInt16(u8 *p){
95338   return (p[0]<<8) + p[1];
95339 }
95340 static void readCoord(u8 *p, RtreeCoord *pCoord){
95341   u32 i = (
95342     (((u32)p[0]) << 24) + 
95343     (((u32)p[1]) << 16) + 
95344     (((u32)p[2]) <<  8) + 
95345     (((u32)p[3]) <<  0)
95346   );
95347   *(u32 *)pCoord = i;
95348 }
95349 static i64 readInt64(u8 *p){
95350   return (
95351     (((i64)p[0]) << 56) + 
95352     (((i64)p[1]) << 48) + 
95353     (((i64)p[2]) << 40) + 
95354     (((i64)p[3]) << 32) + 
95355     (((i64)p[4]) << 24) + 
95356     (((i64)p[5]) << 16) + 
95357     (((i64)p[6]) <<  8) + 
95358     (((i64)p[7]) <<  0)
95359   );
95360 }
95361
95362 /*
95363 ** Functions to serialize a 16 bit integer, 32 bit real number and
95364 ** 64 bit integer. The value returned is the number of bytes written
95365 ** to the argument buffer (always 2, 4 and 8 respectively).
95366 */
95367 static int writeInt16(u8 *p, int i){
95368   p[0] = (i>> 8)&0xFF;
95369   p[1] = (i>> 0)&0xFF;
95370   return 2;
95371 }
95372 static int writeCoord(u8 *p, RtreeCoord *pCoord){
95373   u32 i;
95374   assert( sizeof(RtreeCoord)==4 );
95375   assert( sizeof(u32)==4 );
95376   i = *(u32 *)pCoord;
95377   p[0] = (i>>24)&0xFF;
95378   p[1] = (i>>16)&0xFF;
95379   p[2] = (i>> 8)&0xFF;
95380   p[3] = (i>> 0)&0xFF;
95381   return 4;
95382 }
95383 static int writeInt64(u8 *p, i64 i){
95384   p[0] = (i>>56)&0xFF;
95385   p[1] = (i>>48)&0xFF;
95386   p[2] = (i>>40)&0xFF;
95387   p[3] = (i>>32)&0xFF;
95388   p[4] = (i>>24)&0xFF;
95389   p[5] = (i>>16)&0xFF;
95390   p[6] = (i>> 8)&0xFF;
95391   p[7] = (i>> 0)&0xFF;
95392   return 8;
95393 }
95394
95395 /*
95396 ** Increment the reference count of node p.
95397 */
95398 static void nodeReference(RtreeNode *p){
95399   if( p ){
95400     p->nRef++;
95401   }
95402 }
95403
95404 /*
95405 ** Clear the content of node p (set all bytes to 0x00).
95406 */
95407 static void nodeZero(Rtree *pRtree, RtreeNode *p){
95408   if( p ){
95409     memset(&p->zData[2], 0, pRtree->iNodeSize-2);
95410     p->isDirty = 1;
95411   }
95412 }
95413
95414 /*
95415 ** Given a node number iNode, return the corresponding key to use
95416 ** in the Rtree.aHash table.
95417 */
95418 static int nodeHash(i64 iNode){
95419   return (
95420     (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^ 
95421     (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
95422   ) % HASHSIZE;
95423 }
95424
95425 /*
95426 ** Search the node hash table for node iNode. If found, return a pointer
95427 ** to it. Otherwise, return 0.
95428 */
95429 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
95430   RtreeNode *p;
95431   assert( iNode!=0 );
95432   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
95433   return p;
95434 }
95435
95436 /*
95437 ** Add node pNode to the node hash table.
95438 */
95439 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
95440   if( pNode ){
95441     int iHash;
95442     assert( pNode->pNext==0 );
95443     iHash = nodeHash(pNode->iNode);
95444     pNode->pNext = pRtree->aHash[iHash];
95445     pRtree->aHash[iHash] = pNode;
95446   }
95447 }
95448
95449 /*
95450 ** Remove node pNode from the node hash table.
95451 */
95452 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
95453   RtreeNode **pp;
95454   if( pNode->iNode!=0 ){
95455     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
95456     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
95457     *pp = pNode->pNext;
95458     pNode->pNext = 0;
95459   }
95460 }
95461
95462 /*
95463 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
95464 ** indicating that node has not yet been assigned a node number. It is
95465 ** assigned a node number when nodeWrite() is called to write the
95466 ** node contents out to the database.
95467 */
95468 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent, int zero){
95469   RtreeNode *pNode;
95470   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
95471   if( pNode ){
95472     memset(pNode, 0, sizeof(RtreeNode) + (zero?pRtree->iNodeSize:0));
95473     pNode->zData = (u8 *)&pNode[1];
95474     pNode->nRef = 1;
95475     pNode->pParent = pParent;
95476     pNode->isDirty = 1;
95477     nodeReference(pParent);
95478   }
95479   return pNode;
95480 }
95481
95482 /*
95483 ** Obtain a reference to an r-tree node.
95484 */
95485 static int
95486 nodeAcquire(
95487   Rtree *pRtree,             /* R-tree structure */
95488   i64 iNode,                 /* Node number to load */
95489   RtreeNode *pParent,        /* Either the parent node or NULL */
95490   RtreeNode **ppNode         /* OUT: Acquired node */
95491 ){
95492   int rc;
95493   RtreeNode *pNode;
95494
95495   /* Check if the requested node is already in the hash table. If so,
95496   ** increase its reference count and return it.
95497   */
95498   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
95499     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
95500     if( pParent ){
95501       pNode->pParent = pParent;
95502     }
95503     pNode->nRef++;
95504     *ppNode = pNode;
95505     return SQLITE_OK;
95506   }
95507
95508   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
95509   if( !pNode ){
95510     *ppNode = 0;
95511     return SQLITE_NOMEM;
95512   }
95513   pNode->pParent = pParent;
95514   pNode->zData = (u8 *)&pNode[1];
95515   pNode->nRef = 1;
95516   pNode->iNode = iNode;
95517   pNode->isDirty = 0;
95518   pNode->pNext = 0;
95519
95520   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
95521   rc = sqlite3_step(pRtree->pReadNode);
95522   if( rc==SQLITE_ROW ){
95523     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
95524     memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
95525     nodeReference(pParent);
95526   }else{
95527     sqlite3_free(pNode);
95528     pNode = 0;
95529   }
95530
95531   *ppNode = pNode;
95532   rc = sqlite3_reset(pRtree->pReadNode);
95533
95534   if( rc==SQLITE_OK && iNode==1 ){
95535     pRtree->iDepth = readInt16(pNode->zData);
95536   }
95537
95538   assert( (rc==SQLITE_OK && pNode) || (pNode==0 && rc!=SQLITE_OK) );
95539   nodeHashInsert(pRtree, pNode);
95540
95541   return rc;
95542 }
95543
95544 /*
95545 ** Overwrite cell iCell of node pNode with the contents of pCell.
95546 */
95547 static void nodeOverwriteCell(
95548   Rtree *pRtree, 
95549   RtreeNode *pNode,  
95550   RtreeCell *pCell, 
95551   int iCell
95552 ){
95553   int ii;
95554   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
95555   p += writeInt64(p, pCell->iRowid);
95556   for(ii=0; ii<(pRtree->nDim*2); ii++){
95557     p += writeCoord(p, &pCell->aCoord[ii]);
95558   }
95559   pNode->isDirty = 1;
95560 }
95561
95562 /*
95563 ** Remove cell the cell with index iCell from node pNode.
95564 */
95565 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
95566   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
95567   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
95568   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
95569   memmove(pDst, pSrc, nByte);
95570   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
95571   pNode->isDirty = 1;
95572 }
95573
95574 /*
95575 ** Insert the contents of cell pCell into node pNode. If the insert
95576 ** is successful, return SQLITE_OK.
95577 **
95578 ** If there is not enough free space in pNode, return SQLITE_FULL.
95579 */
95580 static int
95581 nodeInsertCell(
95582   Rtree *pRtree, 
95583   RtreeNode *pNode, 
95584   RtreeCell *pCell 
95585 ){
95586   int nCell;                    /* Current number of cells in pNode */
95587   int nMaxCell;                 /* Maximum number of cells for pNode */
95588
95589   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
95590   nCell = NCELL(pNode);
95591
95592   assert(nCell<=nMaxCell);
95593
95594   if( nCell<nMaxCell ){
95595     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
95596     writeInt16(&pNode->zData[2], nCell+1);
95597     pNode->isDirty = 1;
95598   }
95599
95600   return (nCell==nMaxCell);
95601 }
95602
95603 /*
95604 ** If the node is dirty, write it out to the database.
95605 */
95606 static int
95607 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
95608   int rc = SQLITE_OK;
95609   if( pNode->isDirty ){
95610     sqlite3_stmt *p = pRtree->pWriteNode;
95611     if( pNode->iNode ){
95612       sqlite3_bind_int64(p, 1, pNode->iNode);
95613     }else{
95614       sqlite3_bind_null(p, 1);
95615     }
95616     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
95617     sqlite3_step(p);
95618     pNode->isDirty = 0;
95619     rc = sqlite3_reset(p);
95620     if( pNode->iNode==0 && rc==SQLITE_OK ){
95621       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
95622       nodeHashInsert(pRtree, pNode);
95623     }
95624   }
95625   return rc;
95626 }
95627
95628 /*
95629 ** Release a reference to a node. If the node is dirty and the reference
95630 ** count drops to zero, the node data is written to the database.
95631 */
95632 static int
95633 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
95634   int rc = SQLITE_OK;
95635   if( pNode ){
95636     assert( pNode->nRef>0 );
95637     pNode->nRef--;
95638     if( pNode->nRef==0 ){
95639       if( pNode->iNode==1 ){
95640         pRtree->iDepth = -1;
95641       }
95642       if( pNode->pParent ){
95643         rc = nodeRelease(pRtree, pNode->pParent);
95644       }
95645       if( rc==SQLITE_OK ){
95646         rc = nodeWrite(pRtree, pNode);
95647       }
95648       nodeHashDelete(pRtree, pNode);
95649       sqlite3_free(pNode);
95650     }
95651   }
95652   return rc;
95653 }
95654
95655 /*
95656 ** Return the 64-bit integer value associated with cell iCell of
95657 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
95658 ** an internal node, then the 64-bit integer is a child page number.
95659 */
95660 static i64 nodeGetRowid(
95661   Rtree *pRtree, 
95662   RtreeNode *pNode, 
95663   int iCell
95664 ){
95665   assert( iCell<NCELL(pNode) );
95666   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
95667 }
95668
95669 /*
95670 ** Return coordinate iCoord from cell iCell in node pNode.
95671 */
95672 static void nodeGetCoord(
95673   Rtree *pRtree, 
95674   RtreeNode *pNode, 
95675   int iCell,
95676   int iCoord,
95677   RtreeCoord *pCoord           /* Space to write result to */
95678 ){
95679   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
95680 }
95681
95682 /*
95683 ** Deserialize cell iCell of node pNode. Populate the structure pointed
95684 ** to by pCell with the results.
95685 */
95686 static void nodeGetCell(
95687   Rtree *pRtree, 
95688   RtreeNode *pNode, 
95689   int iCell,
95690   RtreeCell *pCell
95691 ){
95692   int ii;
95693   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
95694   for(ii=0; ii<pRtree->nDim*2; ii++){
95695     nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
95696   }
95697 }
95698
95699
95700 /* Forward declaration for the function that does the work of
95701 ** the virtual table module xCreate() and xConnect() methods.
95702 */
95703 static int rtreeInit(
95704   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
95705 );
95706
95707 /* 
95708 ** Rtree virtual table module xCreate method.
95709 */
95710 static int rtreeCreate(
95711   sqlite3 *db,
95712   void *pAux,
95713   int argc, const char *const*argv,
95714   sqlite3_vtab **ppVtab,
95715   char **pzErr
95716 ){
95717   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
95718 }
95719
95720 /* 
95721 ** Rtree virtual table module xConnect method.
95722 */
95723 static int rtreeConnect(
95724   sqlite3 *db,
95725   void *pAux,
95726   int argc, const char *const*argv,
95727   sqlite3_vtab **ppVtab,
95728   char **pzErr
95729 ){
95730   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
95731 }
95732
95733 /*
95734 ** Increment the r-tree reference count.
95735 */
95736 static void rtreeReference(Rtree *pRtree){
95737   pRtree->nBusy++;
95738 }
95739
95740 /*
95741 ** Decrement the r-tree reference count. When the reference count reaches
95742 ** zero the structure is deleted.
95743 */
95744 static void rtreeRelease(Rtree *pRtree){
95745   pRtree->nBusy--;
95746   if( pRtree->nBusy==0 ){
95747     sqlite3_finalize(pRtree->pReadNode);
95748     sqlite3_finalize(pRtree->pWriteNode);
95749     sqlite3_finalize(pRtree->pDeleteNode);
95750     sqlite3_finalize(pRtree->pReadRowid);
95751     sqlite3_finalize(pRtree->pWriteRowid);
95752     sqlite3_finalize(pRtree->pDeleteRowid);
95753     sqlite3_finalize(pRtree->pReadParent);
95754     sqlite3_finalize(pRtree->pWriteParent);
95755     sqlite3_finalize(pRtree->pDeleteParent);
95756     sqlite3_free(pRtree);
95757   }
95758 }
95759
95760 /* 
95761 ** Rtree virtual table module xDisconnect method.
95762 */
95763 static int rtreeDisconnect(sqlite3_vtab *pVtab){
95764   rtreeRelease((Rtree *)pVtab);
95765   return SQLITE_OK;
95766 }
95767
95768 /* 
95769 ** Rtree virtual table module xDestroy method.
95770 */
95771 static int rtreeDestroy(sqlite3_vtab *pVtab){
95772   Rtree *pRtree = (Rtree *)pVtab;
95773   int rc;
95774   char *zCreate = sqlite3_mprintf(
95775     "DROP TABLE '%q'.'%q_node';"
95776     "DROP TABLE '%q'.'%q_rowid';"
95777     "DROP TABLE '%q'.'%q_parent';",
95778     pRtree->zDb, pRtree->zName, 
95779     pRtree->zDb, pRtree->zName,
95780     pRtree->zDb, pRtree->zName
95781   );
95782   if( !zCreate ){
95783     rc = SQLITE_NOMEM;
95784   }else{
95785     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
95786     sqlite3_free(zCreate);
95787   }
95788   if( rc==SQLITE_OK ){
95789     rtreeRelease(pRtree);
95790   }
95791
95792   return rc;
95793 }
95794
95795 /* 
95796 ** Rtree virtual table module xOpen method.
95797 */
95798 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
95799   int rc = SQLITE_NOMEM;
95800   RtreeCursor *pCsr;
95801
95802   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
95803   if( pCsr ){
95804     memset(pCsr, 0, sizeof(RtreeCursor));
95805     pCsr->base.pVtab = pVTab;
95806     rc = SQLITE_OK;
95807   }
95808   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
95809
95810   return rc;
95811 }
95812
95813 /* 
95814 ** Rtree virtual table module xClose method.
95815 */
95816 static int rtreeClose(sqlite3_vtab_cursor *cur){
95817   Rtree *pRtree = (Rtree *)(cur->pVtab);
95818   int rc;
95819   RtreeCursor *pCsr = (RtreeCursor *)cur;
95820   sqlite3_free(pCsr->aConstraint);
95821   rc = nodeRelease(pRtree, pCsr->pNode);
95822   sqlite3_free(pCsr);
95823   return rc;
95824 }
95825
95826 /*
95827 ** Rtree virtual table module xEof method.
95828 **
95829 ** Return non-zero if the cursor does not currently point to a valid 
95830 ** record (i.e if the scan has finished), or zero otherwise.
95831 */
95832 static int rtreeEof(sqlite3_vtab_cursor *cur){
95833   RtreeCursor *pCsr = (RtreeCursor *)cur;
95834   return (pCsr->pNode==0);
95835 }
95836
95837 /* 
95838 ** Cursor pCursor currently points to a cell in a non-leaf page.
95839 ** Return true if the sub-tree headed by the cell is filtered
95840 ** (excluded) by the constraints in the pCursor->aConstraint[] 
95841 ** array, or false otherwise.
95842 */
95843 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor){
95844   RtreeCell cell;
95845   int ii;
95846   int bRes = 0;
95847
95848   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
95849   for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
95850     RtreeConstraint *p = &pCursor->aConstraint[ii];
95851     double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
95852     double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
95853
95854     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
95855         || p->op==RTREE_GT || p->op==RTREE_EQ
95856     );
95857
95858     switch( p->op ){
95859       case RTREE_LE: case RTREE_LT: bRes = p->rValue<cell_min; break;
95860       case RTREE_GE: case RTREE_GT: bRes = p->rValue>cell_max; break;
95861       case RTREE_EQ: 
95862         bRes = (p->rValue>cell_max || p->rValue<cell_min);
95863         break;
95864     }
95865   }
95866
95867   return bRes;
95868 }
95869
95870 /* 
95871 ** Return true if the cell that cursor pCursor currently points to
95872 ** would be filtered (excluded) by the constraints in the 
95873 ** pCursor->aConstraint[] array, or false otherwise.
95874 **
95875 ** This function assumes that the cell is part of a leaf node.
95876 */
95877 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor){
95878   RtreeCell cell;
95879   int ii;
95880
95881   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
95882   for(ii=0; ii<pCursor->nConstraint; ii++){
95883     RtreeConstraint *p = &pCursor->aConstraint[ii];
95884     double coord = DCOORD(cell.aCoord[p->iCoord]);
95885     int res;
95886     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
95887         || p->op==RTREE_GT || p->op==RTREE_EQ
95888     );
95889     switch( p->op ){
95890       case RTREE_LE: res = (coord<=p->rValue); break;
95891       case RTREE_LT: res = (coord<p->rValue);  break;
95892       case RTREE_GE: res = (coord>=p->rValue); break;
95893       case RTREE_GT: res = (coord>p->rValue);  break;
95894       case RTREE_EQ: res = (coord==p->rValue); break;
95895     }
95896
95897     if( !res ) return 1;
95898   }
95899
95900   return 0;
95901 }
95902
95903 /*
95904 ** Cursor pCursor currently points at a node that heads a sub-tree of
95905 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
95906 ** to point to the left-most cell of the sub-tree that matches the 
95907 ** configured constraints.
95908 */
95909 static int descendToCell(
95910   Rtree *pRtree, 
95911   RtreeCursor *pCursor, 
95912   int iHeight,
95913   int *pEof                 /* OUT: Set to true if cannot descend */
95914 ){
95915   int isEof;
95916   int rc;
95917   int ii;
95918   RtreeNode *pChild;
95919   sqlite3_int64 iRowid;
95920
95921   RtreeNode *pSavedNode = pCursor->pNode;
95922   int iSavedCell = pCursor->iCell;
95923
95924   assert( iHeight>=0 );
95925
95926   if( iHeight==0 ){
95927     isEof = testRtreeEntry(pRtree, pCursor);
95928   }else{
95929     isEof = testRtreeCell(pRtree, pCursor);
95930   }
95931   if( isEof || iHeight==0 ){
95932     *pEof = isEof;
95933     return SQLITE_OK;
95934   }
95935
95936   iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
95937   rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
95938   if( rc!=SQLITE_OK ){
95939     return rc;
95940   }
95941
95942   nodeRelease(pRtree, pCursor->pNode);
95943   pCursor->pNode = pChild;
95944   isEof = 1;
95945   for(ii=0; isEof && ii<NCELL(pChild); ii++){
95946     pCursor->iCell = ii;
95947     rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
95948     if( rc!=SQLITE_OK ){
95949       return rc;
95950     }
95951   }
95952
95953   if( isEof ){
95954     assert( pCursor->pNode==pChild );
95955     nodeReference(pSavedNode);
95956     nodeRelease(pRtree, pChild);
95957     pCursor->pNode = pSavedNode;
95958     pCursor->iCell = iSavedCell;
95959   }
95960
95961   *pEof = isEof;
95962   return SQLITE_OK;
95963 }
95964
95965 /*
95966 ** One of the cells in node pNode is guaranteed to have a 64-bit 
95967 ** integer value equal to iRowid. Return the index of this cell.
95968 */
95969 static int nodeRowidIndex(Rtree *pRtree, RtreeNode *pNode, i64 iRowid){
95970   int ii;
95971   for(ii=0; nodeGetRowid(pRtree, pNode, ii)!=iRowid; ii++){
95972     assert( ii<(NCELL(pNode)-1) );
95973   }
95974   return ii;
95975 }
95976
95977 /*
95978 ** Return the index of the cell containing a pointer to node pNode
95979 ** in its parent. If pNode is the root node, return -1.
95980 */
95981 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode){
95982   RtreeNode *pParent = pNode->pParent;
95983   if( pParent ){
95984     return nodeRowidIndex(pRtree, pParent, pNode->iNode);
95985   }
95986   return -1;
95987 }
95988
95989 /* 
95990 ** Rtree virtual table module xNext method.
95991 */
95992 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
95993   Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
95994   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
95995   int rc = SQLITE_OK;
95996
95997   if( pCsr->iStrategy==1 ){
95998     /* This "scan" is a direct lookup by rowid. There is no next entry. */
95999     nodeRelease(pRtree, pCsr->pNode);
96000     pCsr->pNode = 0;
96001   }
96002
96003   else if( pCsr->pNode ){
96004     /* Move to the next entry that matches the configured constraints. */
96005     int iHeight = 0;
96006     while( pCsr->pNode ){
96007       RtreeNode *pNode = pCsr->pNode;
96008       int nCell = NCELL(pNode);
96009       for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
96010         int isEof;
96011         rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
96012         if( rc!=SQLITE_OK || !isEof ){
96013           return rc;
96014         }
96015       }
96016       pCsr->pNode = pNode->pParent;
96017       pCsr->iCell = nodeParentIndex(pRtree, pNode);
96018       nodeReference(pCsr->pNode);
96019       nodeRelease(pRtree, pNode);
96020       iHeight++;
96021     }
96022   }
96023
96024   return rc;
96025 }
96026
96027 /* 
96028 ** Rtree virtual table module xRowid method.
96029 */
96030 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
96031   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
96032   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
96033
96034   assert(pCsr->pNode);
96035   *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
96036
96037   return SQLITE_OK;
96038 }
96039
96040 /* 
96041 ** Rtree virtual table module xColumn method.
96042 */
96043 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
96044   Rtree *pRtree = (Rtree *)cur->pVtab;
96045   RtreeCursor *pCsr = (RtreeCursor *)cur;
96046
96047   if( i==0 ){
96048     i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
96049     sqlite3_result_int64(ctx, iRowid);
96050   }else{
96051     RtreeCoord c;
96052     nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
96053     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
96054       sqlite3_result_double(ctx, c.f);
96055     }else{
96056       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
96057       sqlite3_result_int(ctx, c.i);
96058     }
96059   }
96060
96061   return SQLITE_OK;
96062 }
96063
96064 /* 
96065 ** Use nodeAcquire() to obtain the leaf node containing the record with 
96066 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
96067 ** return SQLITE_OK. If there is no such record in the table, set
96068 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
96069 ** to zero and return an SQLite error code.
96070 */
96071 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
96072   int rc;
96073   *ppLeaf = 0;
96074   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
96075   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
96076     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
96077     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
96078     sqlite3_reset(pRtree->pReadRowid);
96079   }else{
96080     rc = sqlite3_reset(pRtree->pReadRowid);
96081   }
96082   return rc;
96083 }
96084
96085
96086 /* 
96087 ** Rtree virtual table module xFilter method.
96088 */
96089 static int rtreeFilter(
96090   sqlite3_vtab_cursor *pVtabCursor, 
96091   int idxNum, const char *idxStr,
96092   int argc, sqlite3_value **argv
96093 ){
96094   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
96095   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
96096
96097   RtreeNode *pRoot = 0;
96098   int ii;
96099   int rc = SQLITE_OK;
96100
96101   rtreeReference(pRtree);
96102
96103   sqlite3_free(pCsr->aConstraint);
96104   pCsr->aConstraint = 0;
96105   pCsr->iStrategy = idxNum;
96106
96107   if( idxNum==1 ){
96108     /* Special case - lookup by rowid. */
96109     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
96110     i64 iRowid = sqlite3_value_int64(argv[0]);
96111     rc = findLeafNode(pRtree, iRowid, &pLeaf);
96112     pCsr->pNode = pLeaf; 
96113     if( pLeaf && rc==SQLITE_OK ){
96114       pCsr->iCell = nodeRowidIndex(pRtree, pLeaf, iRowid);
96115     }
96116   }else{
96117     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 
96118     ** with the configured constraints. 
96119     */
96120     if( argc>0 ){
96121       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
96122       pCsr->nConstraint = argc;
96123       if( !pCsr->aConstraint ){
96124         rc = SQLITE_NOMEM;
96125       }else{
96126         assert( (idxStr==0 && argc==0) || strlen(idxStr)==argc*2 );
96127         for(ii=0; ii<argc; ii++){
96128           RtreeConstraint *p = &pCsr->aConstraint[ii];
96129           p->op = idxStr[ii*2];
96130           p->iCoord = idxStr[ii*2+1]-'a';
96131           p->rValue = sqlite3_value_double(argv[ii]);
96132         }
96133       }
96134     }
96135   
96136     if( rc==SQLITE_OK ){
96137       pCsr->pNode = 0;
96138       rc = nodeAcquire(pRtree, 1, 0, &pRoot);
96139     }
96140     if( rc==SQLITE_OK ){
96141       int isEof = 1;
96142       int nCell = NCELL(pRoot);
96143       pCsr->pNode = pRoot;
96144       for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
96145         assert( pCsr->pNode==pRoot );
96146         rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
96147         if( !isEof ){
96148           break;
96149         }
96150       }
96151       if( rc==SQLITE_OK && isEof ){
96152         assert( pCsr->pNode==pRoot );
96153         nodeRelease(pRtree, pRoot);
96154         pCsr->pNode = 0;
96155       }
96156       assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
96157     }
96158   }
96159
96160   rtreeRelease(pRtree);
96161   return rc;
96162 }
96163
96164 /*
96165 ** Rtree virtual table module xBestIndex method. There are three
96166 ** table scan strategies to choose from (in order from most to 
96167 ** least desirable):
96168 **
96169 **   idxNum     idxStr        Strategy
96170 **   ------------------------------------------------
96171 **     1        Unused        Direct lookup by rowid.
96172 **     2        See below     R-tree query.
96173 **     3        Unused        Full table scan.
96174 **   ------------------------------------------------
96175 **
96176 ** If strategy 1 or 3 is used, then idxStr is not meaningful. If strategy
96177 ** 2 is used, idxStr is formatted to contain 2 bytes for each 
96178 ** constraint used. The first two bytes of idxStr correspond to 
96179 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
96180 ** (argvIndex==1) etc.
96181 **
96182 ** The first of each pair of bytes in idxStr identifies the constraint
96183 ** operator as follows:
96184 **
96185 **   Operator    Byte Value
96186 **   ----------------------
96187 **      =        0x41 ('A')
96188 **     <=        0x42 ('B')
96189 **      <        0x43 ('C')
96190 **     >=        0x44 ('D')
96191 **      >        0x45 ('E')
96192 **   ----------------------
96193 **
96194 ** The second of each pair of bytes identifies the coordinate column
96195 ** to which the constraint applies. The leftmost coordinate column
96196 ** is 'a', the second from the left 'b' etc.
96197 */
96198 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
96199   int rc = SQLITE_OK;
96200   int ii, cCol;
96201
96202   int iIdx = 0;
96203   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
96204   memset(zIdxStr, 0, sizeof(zIdxStr));
96205
96206   assert( pIdxInfo->idxStr==0 );
96207   for(ii=0; ii<pIdxInfo->nConstraint; ii++){
96208     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
96209
96210     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
96211       /* We have an equality constraint on the rowid. Use strategy 1. */
96212       int jj;
96213       for(jj=0; jj<ii; jj++){
96214         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
96215         pIdxInfo->aConstraintUsage[jj].omit = 0;
96216       }
96217       pIdxInfo->idxNum = 1;
96218       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
96219       pIdxInfo->aConstraintUsage[jj].omit = 1;
96220
96221       /* This strategy involves a two rowid lookups on an B-Tree structures
96222       ** and then a linear search of an R-Tree node. This should be 
96223       ** considered almost as quick as a direct rowid lookup (for which 
96224       ** sqlite uses an internal cost of 0.0).
96225       */ 
96226       pIdxInfo->estimatedCost = 10.0;
96227       return SQLITE_OK;
96228     }
96229
96230     if( p->usable && p->iColumn>0 ){
96231       u8 op = 0;
96232       switch( p->op ){
96233         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
96234         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
96235         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
96236         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
96237         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
96238       }
96239       if( op ){
96240         /* Make sure this particular constraint has not been used before.
96241         ** If it has been used before, ignore it.
96242         **
96243         ** A <= or < can be used if there is a prior >= or >.
96244         ** A >= or > can be used if there is a prior < or <=.
96245         ** A <= or < is disqualified if there is a prior <=, <, or ==.
96246         ** A >= or > is disqualified if there is a prior >=, >, or ==.
96247         ** A == is disqualifed if there is any prior constraint.
96248         */
96249         int j, opmsk;
96250         static const unsigned char compatible[] = { 0, 0, 1, 1, 2, 2 };
96251         assert( compatible[RTREE_EQ & 7]==0 );
96252         assert( compatible[RTREE_LT & 7]==1 );
96253         assert( compatible[RTREE_LE & 7]==1 );
96254         assert( compatible[RTREE_GT & 7]==2 );
96255         assert( compatible[RTREE_GE & 7]==2 );
96256         cCol = p->iColumn - 1 + 'a';
96257         opmsk = compatible[op & 7];
96258         for(j=0; j<iIdx; j+=2){
96259           if( zIdxStr[j+1]==cCol && (compatible[zIdxStr[j] & 7] & opmsk)!=0 ){
96260             op = 0;
96261             break;
96262           }
96263         }
96264       }
96265       if( op ){
96266         assert( iIdx<sizeof(zIdxStr)-1 );
96267         zIdxStr[iIdx++] = op;
96268         zIdxStr[iIdx++] = cCol;
96269         pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
96270         pIdxInfo->aConstraintUsage[ii].omit = 1;
96271       }
96272     }
96273   }
96274
96275   pIdxInfo->idxNum = 2;
96276   pIdxInfo->needToFreeIdxStr = 1;
96277   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
96278     return SQLITE_NOMEM;
96279   }
96280   assert( iIdx>=0 );
96281   pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
96282   return rc;
96283 }
96284
96285 /*
96286 ** Return the N-dimensional volumn of the cell stored in *p.
96287 */
96288 static float cellArea(Rtree *pRtree, RtreeCell *p){
96289   float area = 1.0;
96290   int ii;
96291   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
96292     area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
96293   }
96294   return area;
96295 }
96296
96297 /*
96298 ** Return the margin length of cell p. The margin length is the sum
96299 ** of the objects size in each dimension.
96300 */
96301 static float cellMargin(Rtree *pRtree, RtreeCell *p){
96302   float margin = 0.0;
96303   int ii;
96304   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
96305     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
96306   }
96307   return margin;
96308 }
96309
96310 /*
96311 ** Store the union of cells p1 and p2 in p1.
96312 */
96313 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
96314   int ii;
96315   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
96316     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
96317       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
96318       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
96319     }
96320   }else{
96321     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
96322       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
96323       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
96324     }
96325   }
96326 }
96327
96328 /*
96329 ** Return true if the area covered by p2 is a subset of the area covered
96330 ** by p1. False otherwise.
96331 */
96332 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
96333   int ii;
96334   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
96335   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
96336     RtreeCoord *a1 = &p1->aCoord[ii];
96337     RtreeCoord *a2 = &p2->aCoord[ii];
96338     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) 
96339      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) 
96340     ){
96341       return 0;
96342     }
96343   }
96344   return 1;
96345 }
96346
96347 /*
96348 ** Return the amount cell p would grow by if it were unioned with pCell.
96349 */
96350 static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
96351   float area;
96352   RtreeCell cell;
96353   memcpy(&cell, p, sizeof(RtreeCell));
96354   area = cellArea(pRtree, &cell);
96355   cellUnion(pRtree, &cell, pCell);
96356   return (cellArea(pRtree, &cell)-area);
96357 }
96358
96359 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
96360 static float cellOverlap(
96361   Rtree *pRtree, 
96362   RtreeCell *p, 
96363   RtreeCell *aCell, 
96364   int nCell, 
96365   int iExclude
96366 ){
96367   int ii;
96368   float overlap = 0.0;
96369   for(ii=0; ii<nCell; ii++){
96370     if( ii!=iExclude ){
96371       int jj;
96372       float o = 1.0;
96373       for(jj=0; jj<(pRtree->nDim*2); jj+=2){
96374         double x1;
96375         double x2;
96376
96377         x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
96378         x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
96379
96380         if( x2<x1 ){
96381           o = 0.0;
96382           break;
96383         }else{
96384           o = o * (x2-x1);
96385         }
96386       }
96387       overlap += o;
96388     }
96389   }
96390   return overlap;
96391 }
96392 #endif
96393
96394 #if VARIANT_RSTARTREE_CHOOSESUBTREE
96395 static float cellOverlapEnlargement(
96396   Rtree *pRtree, 
96397   RtreeCell *p, 
96398   RtreeCell *pInsert, 
96399   RtreeCell *aCell, 
96400   int nCell, 
96401   int iExclude
96402 ){
96403   float before;
96404   float after;
96405   before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
96406   cellUnion(pRtree, p, pInsert);
96407   after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
96408   return after-before;
96409 }
96410 #endif
96411
96412
96413 /*
96414 ** This function implements the ChooseLeaf algorithm from Gutman[84].
96415 ** ChooseSubTree in r*tree terminology.
96416 */
96417 static int ChooseLeaf(
96418   Rtree *pRtree,               /* Rtree table */
96419   RtreeCell *pCell,            /* Cell to insert into rtree */
96420   int iHeight,                 /* Height of sub-tree rooted at pCell */
96421   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
96422 ){
96423   int rc;
96424   int ii;
96425   RtreeNode *pNode;
96426   rc = nodeAcquire(pRtree, 1, 0, &pNode);
96427
96428   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
96429     int iCell;
96430     sqlite3_int64 iBest;
96431
96432     float fMinGrowth;
96433     float fMinArea;
96434     float fMinOverlap;
96435
96436     int nCell = NCELL(pNode);
96437     RtreeCell cell;
96438     RtreeNode *pChild;
96439
96440     RtreeCell *aCell = 0;
96441
96442 #if VARIANT_RSTARTREE_CHOOSESUBTREE
96443     if( ii==(pRtree->iDepth-1) ){
96444       int jj;
96445       aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
96446       if( !aCell ){
96447         rc = SQLITE_NOMEM;
96448         nodeRelease(pRtree, pNode);
96449         pNode = 0;
96450         continue;
96451       }
96452       for(jj=0; jj<nCell; jj++){
96453         nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
96454       }
96455     }
96456 #endif
96457
96458     /* Select the child node which will be enlarged the least if pCell
96459     ** is inserted into it. Resolve ties by choosing the entry with
96460     ** the smallest area.
96461     */
96462     for(iCell=0; iCell<nCell; iCell++){
96463       float growth;
96464       float area;
96465       float overlap = 0.0;
96466       nodeGetCell(pRtree, pNode, iCell, &cell);
96467       growth = cellGrowth(pRtree, &cell, pCell);
96468       area = cellArea(pRtree, &cell);
96469 #if VARIANT_RSTARTREE_CHOOSESUBTREE
96470       if( ii==(pRtree->iDepth-1) ){
96471         overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
96472       }
96473 #endif
96474       if( (iCell==0) 
96475        || (overlap<fMinOverlap) 
96476        || (overlap==fMinOverlap && growth<fMinGrowth)
96477        || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
96478       ){
96479         fMinOverlap = overlap;
96480         fMinGrowth = growth;
96481         fMinArea = area;
96482         iBest = cell.iRowid;
96483       }
96484     }
96485
96486     sqlite3_free(aCell);
96487     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
96488     nodeRelease(pRtree, pNode);
96489     pNode = pChild;
96490   }
96491
96492   *ppLeaf = pNode;
96493   return rc;
96494 }
96495
96496 /*
96497 ** A cell with the same content as pCell has just been inserted into
96498 ** the node pNode. This function updates the bounding box cells in
96499 ** all ancestor elements.
96500 */
96501 static void AdjustTree(
96502   Rtree *pRtree,                    /* Rtree table */
96503   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
96504   RtreeCell *pCell                  /* This cell was just inserted */
96505 ){
96506   RtreeNode *p = pNode;
96507   while( p->pParent ){
96508     RtreeCell cell;
96509     RtreeNode *pParent = p->pParent;
96510     int iCell = nodeParentIndex(pRtree, p);
96511
96512     nodeGetCell(pRtree, pParent, iCell, &cell);
96513     if( !cellContains(pRtree, &cell, pCell) ){
96514       cellUnion(pRtree, &cell, pCell);
96515       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
96516     }
96517  
96518     p = pParent;
96519   }
96520 }
96521
96522 /*
96523 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
96524 */
96525 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
96526   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
96527   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
96528   sqlite3_step(pRtree->pWriteRowid);
96529   return sqlite3_reset(pRtree->pWriteRowid);
96530 }
96531
96532 /*
96533 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
96534 */
96535 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
96536   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
96537   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
96538   sqlite3_step(pRtree->pWriteParent);
96539   return sqlite3_reset(pRtree->pWriteParent);
96540 }
96541
96542 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
96543
96544 #if VARIANT_GUTTMAN_LINEAR_SPLIT
96545 /*
96546 ** Implementation of the linear variant of the PickNext() function from
96547 ** Guttman[84].
96548 */
96549 static RtreeCell *LinearPickNext(
96550   Rtree *pRtree,
96551   RtreeCell *aCell, 
96552   int nCell, 
96553   RtreeCell *pLeftBox, 
96554   RtreeCell *pRightBox,
96555   int *aiUsed
96556 ){
96557   int ii;
96558   for(ii=0; aiUsed[ii]; ii++);
96559   aiUsed[ii] = 1;
96560   return &aCell[ii];
96561 }
96562
96563 /*
96564 ** Implementation of the linear variant of the PickSeeds() function from
96565 ** Guttman[84].
96566 */
96567 static void LinearPickSeeds(
96568   Rtree *pRtree,
96569   RtreeCell *aCell, 
96570   int nCell, 
96571   int *piLeftSeed, 
96572   int *piRightSeed
96573 ){
96574   int i;
96575   int iLeftSeed = 0;
96576   int iRightSeed = 1;
96577   float maxNormalInnerWidth = 0.0;
96578
96579   /* Pick two "seed" cells from the array of cells. The algorithm used
96580   ** here is the LinearPickSeeds algorithm from Gutman[1984]. The 
96581   ** indices of the two seed cells in the array are stored in local
96582   ** variables iLeftSeek and iRightSeed.
96583   */
96584   for(i=0; i<pRtree->nDim; i++){
96585     float x1 = aCell[0].aCoord[i*2];
96586     float x2 = aCell[0].aCoord[i*2+1];
96587     float x3 = x1;
96588     float x4 = x2;
96589     int jj;
96590
96591     int iCellLeft = 0;
96592     int iCellRight = 0;
96593
96594     for(jj=1; jj<nCell; jj++){
96595       float left = aCell[jj].aCoord[i*2];
96596       float right = aCell[jj].aCoord[i*2+1];
96597
96598       if( left<x1 ) x1 = left;
96599       if( right>x4 ) x4 = right;
96600       if( left>x3 ){
96601         x3 = left;
96602         iCellRight = jj;
96603       }
96604       if( right<x2 ){
96605         x2 = right;
96606         iCellLeft = jj;
96607       }
96608     }
96609
96610     if( x4!=x1 ){
96611       float normalwidth = (x3 - x2) / (x4 - x1);
96612       if( normalwidth>maxNormalInnerWidth ){
96613         iLeftSeed = iCellLeft;
96614         iRightSeed = iCellRight;
96615       }
96616     }
96617   }
96618
96619   *piLeftSeed = iLeftSeed;
96620   *piRightSeed = iRightSeed;
96621 }
96622 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
96623
96624 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
96625 /*
96626 ** Implementation of the quadratic variant of the PickNext() function from
96627 ** Guttman[84].
96628 */
96629 static RtreeCell *QuadraticPickNext(
96630   Rtree *pRtree,
96631   RtreeCell *aCell, 
96632   int nCell, 
96633   RtreeCell *pLeftBox, 
96634   RtreeCell *pRightBox,
96635   int *aiUsed
96636 ){
96637   #define FABS(a) ((a)<0.0?-1.0*(a):(a))
96638
96639   int iSelect = -1;
96640   float fDiff;
96641   int ii;
96642   for(ii=0; ii<nCell; ii++){
96643     if( aiUsed[ii]==0 ){
96644       float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
96645       float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
96646       float diff = FABS(right-left);
96647       if( iSelect<0 || diff>fDiff ){
96648         fDiff = diff;
96649         iSelect = ii;
96650       }
96651     }
96652   }
96653   aiUsed[iSelect] = 1;
96654   return &aCell[iSelect];
96655 }
96656
96657 /*
96658 ** Implementation of the quadratic variant of the PickSeeds() function from
96659 ** Guttman[84].
96660 */
96661 static void QuadraticPickSeeds(
96662   Rtree *pRtree,
96663   RtreeCell *aCell, 
96664   int nCell, 
96665   int *piLeftSeed, 
96666   int *piRightSeed
96667 ){
96668   int ii;
96669   int jj;
96670
96671   int iLeftSeed = 0;
96672   int iRightSeed = 1;
96673   float fWaste = 0.0;
96674
96675   for(ii=0; ii<nCell; ii++){
96676     for(jj=ii+1; jj<nCell; jj++){
96677       float right = cellArea(pRtree, &aCell[jj]);
96678       float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
96679       float waste = growth - right;
96680
96681       if( waste>fWaste ){
96682         iLeftSeed = ii;
96683         iRightSeed = jj;
96684         fWaste = waste;
96685       }
96686     }
96687   }
96688
96689   *piLeftSeed = iLeftSeed;
96690   *piRightSeed = iRightSeed;
96691 }
96692 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
96693
96694 /*
96695 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
96696 ** nIdx. The aIdx array contains the set of integers from 0 to 
96697 ** (nIdx-1) in no particular order. This function sorts the values
96698 ** in aIdx according to the indexed values in aDistance. For
96699 ** example, assuming the inputs:
96700 **
96701 **   aIdx      = { 0,   1,   2,   3 }
96702 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
96703 **
96704 ** this function sets the aIdx array to contain:
96705 **
96706 **   aIdx      = { 0,   1,   2,   3 }
96707 **
96708 ** The aSpare array is used as temporary working space by the
96709 ** sorting algorithm.
96710 */
96711 static void SortByDistance(
96712   int *aIdx, 
96713   int nIdx, 
96714   float *aDistance, 
96715   int *aSpare
96716 ){
96717   if( nIdx>1 ){
96718     int iLeft = 0;
96719     int iRight = 0;
96720
96721     int nLeft = nIdx/2;
96722     int nRight = nIdx-nLeft;
96723     int *aLeft = aIdx;
96724     int *aRight = &aIdx[nLeft];
96725
96726     SortByDistance(aLeft, nLeft, aDistance, aSpare);
96727     SortByDistance(aRight, nRight, aDistance, aSpare);
96728
96729     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
96730     aLeft = aSpare;
96731
96732     while( iLeft<nLeft || iRight<nRight ){
96733       if( iLeft==nLeft ){
96734         aIdx[iLeft+iRight] = aRight[iRight];
96735         iRight++;
96736       }else if( iRight==nRight ){
96737         aIdx[iLeft+iRight] = aLeft[iLeft];
96738         iLeft++;
96739       }else{
96740         float fLeft = aDistance[aLeft[iLeft]];
96741         float fRight = aDistance[aRight[iRight]];
96742         if( fLeft<fRight ){
96743           aIdx[iLeft+iRight] = aLeft[iLeft];
96744           iLeft++;
96745         }else{
96746           aIdx[iLeft+iRight] = aRight[iRight];
96747           iRight++;
96748         }
96749       }
96750     }
96751
96752 #if 0
96753     /* Check that the sort worked */
96754     {
96755       int jj;
96756       for(jj=1; jj<nIdx; jj++){
96757         float left = aDistance[aIdx[jj-1]];
96758         float right = aDistance[aIdx[jj]];
96759         assert( left<=right );
96760       }
96761     }
96762 #endif
96763   }
96764 }
96765
96766 /*
96767 ** Arguments aIdx, aCell and aSpare all point to arrays of size
96768 ** nIdx. The aIdx array contains the set of integers from 0 to 
96769 ** (nIdx-1) in no particular order. This function sorts the values
96770 ** in aIdx according to dimension iDim of the cells in aCell. The
96771 ** minimum value of dimension iDim is considered first, the
96772 ** maximum used to break ties.
96773 **
96774 ** The aSpare array is used as temporary working space by the
96775 ** sorting algorithm.
96776 */
96777 static void SortByDimension(
96778   Rtree *pRtree,
96779   int *aIdx, 
96780   int nIdx, 
96781   int iDim, 
96782   RtreeCell *aCell, 
96783   int *aSpare
96784 ){
96785   if( nIdx>1 ){
96786
96787     int iLeft = 0;
96788     int iRight = 0;
96789
96790     int nLeft = nIdx/2;
96791     int nRight = nIdx-nLeft;
96792     int *aLeft = aIdx;
96793     int *aRight = &aIdx[nLeft];
96794
96795     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
96796     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
96797
96798     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
96799     aLeft = aSpare;
96800     while( iLeft<nLeft || iRight<nRight ){
96801       double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
96802       double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
96803       double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
96804       double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
96805       if( (iLeft!=nLeft) && ((iRight==nRight)
96806        || (xleft1<xright1)
96807        || (xleft1==xright1 && xleft2<xright2)
96808       )){
96809         aIdx[iLeft+iRight] = aLeft[iLeft];
96810         iLeft++;
96811       }else{
96812         aIdx[iLeft+iRight] = aRight[iRight];
96813         iRight++;
96814       }
96815     }
96816
96817 #if 0
96818     /* Check that the sort worked */
96819     {
96820       int jj;
96821       for(jj=1; jj<nIdx; jj++){
96822         float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
96823         float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
96824         float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
96825         float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
96826         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
96827       }
96828     }
96829 #endif
96830   }
96831 }
96832
96833 #if VARIANT_RSTARTREE_SPLIT
96834 /*
96835 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
96836 */
96837 static int splitNodeStartree(
96838   Rtree *pRtree,
96839   RtreeCell *aCell,
96840   int nCell,
96841   RtreeNode *pLeft,
96842   RtreeNode *pRight,
96843   RtreeCell *pBboxLeft,
96844   RtreeCell *pBboxRight
96845 ){
96846   int **aaSorted;
96847   int *aSpare;
96848   int ii;
96849
96850   int iBestDim;
96851   int iBestSplit;
96852   float fBestMargin;
96853
96854   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
96855
96856   aaSorted = (int **)sqlite3_malloc(nByte);
96857   if( !aaSorted ){
96858     return SQLITE_NOMEM;
96859   }
96860
96861   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
96862   memset(aaSorted, 0, nByte);
96863   for(ii=0; ii<pRtree->nDim; ii++){
96864     int jj;
96865     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
96866     for(jj=0; jj<nCell; jj++){
96867       aaSorted[ii][jj] = jj;
96868     }
96869     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
96870   }
96871
96872   for(ii=0; ii<pRtree->nDim; ii++){
96873     float margin = 0.0;
96874     float fBestOverlap;
96875     float fBestArea;
96876     int iBestLeft;
96877     int nLeft;
96878
96879     for(
96880       nLeft=RTREE_MINCELLS(pRtree); 
96881       nLeft<=(nCell-RTREE_MINCELLS(pRtree)); 
96882       nLeft++
96883     ){
96884       RtreeCell left;
96885       RtreeCell right;
96886       int kk;
96887       float overlap;
96888       float area;
96889
96890       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
96891       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
96892       for(kk=1; kk<(nCell-1); kk++){
96893         if( kk<nLeft ){
96894           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
96895         }else{
96896           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
96897         }
96898       }
96899       margin += cellMargin(pRtree, &left);
96900       margin += cellMargin(pRtree, &right);
96901       overlap = cellOverlap(pRtree, &left, &right, 1, -1);
96902       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
96903       if( (nLeft==RTREE_MINCELLS(pRtree))
96904        || (overlap<fBestOverlap)
96905        || (overlap==fBestOverlap && area<fBestArea)
96906       ){
96907         iBestLeft = nLeft;
96908         fBestOverlap = overlap;
96909         fBestArea = area;
96910       }
96911     }
96912
96913     if( ii==0 || margin<fBestMargin ){
96914       iBestDim = ii;
96915       fBestMargin = margin;
96916       iBestSplit = iBestLeft;
96917     }
96918   }
96919
96920   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
96921   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
96922   for(ii=0; ii<nCell; ii++){
96923     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
96924     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
96925     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
96926     nodeInsertCell(pRtree, pTarget, pCell);
96927     cellUnion(pRtree, pBbox, pCell);
96928   }
96929
96930   sqlite3_free(aaSorted);
96931   return SQLITE_OK;
96932 }
96933 #endif
96934
96935 #if VARIANT_GUTTMAN_SPLIT
96936 /*
96937 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
96938 */
96939 static int splitNodeGuttman(
96940   Rtree *pRtree,
96941   RtreeCell *aCell,
96942   int nCell,
96943   RtreeNode *pLeft,
96944   RtreeNode *pRight,
96945   RtreeCell *pBboxLeft,
96946   RtreeCell *pBboxRight
96947 ){
96948   int iLeftSeed = 0;
96949   int iRightSeed = 1;
96950   int *aiUsed;
96951   int i;
96952
96953   aiUsed = sqlite3_malloc(sizeof(int)*nCell);
96954   memset(aiUsed, 0, sizeof(int)*nCell);
96955
96956   PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
96957
96958   memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
96959   memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
96960   nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
96961   nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
96962   aiUsed[iLeftSeed] = 1;
96963   aiUsed[iRightSeed] = 1;
96964
96965   for(i=nCell-2; i>0; i--){
96966     RtreeCell *pNext;
96967     pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
96968     float diff =  
96969       cellGrowth(pRtree, pBboxLeft, pNext) - 
96970       cellGrowth(pRtree, pBboxRight, pNext)
96971     ;
96972     if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
96973      || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
96974     ){
96975       nodeInsertCell(pRtree, pRight, pNext);
96976       cellUnion(pRtree, pBboxRight, pNext);
96977     }else{
96978       nodeInsertCell(pRtree, pLeft, pNext);
96979       cellUnion(pRtree, pBboxLeft, pNext);
96980     }
96981   }
96982
96983   sqlite3_free(aiUsed);
96984   return SQLITE_OK;
96985 }
96986 #endif
96987
96988 static int updateMapping(
96989   Rtree *pRtree, 
96990   i64 iRowid, 
96991   RtreeNode *pNode, 
96992   int iHeight
96993 ){
96994   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
96995   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
96996   if( iHeight>0 ){
96997     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
96998     if( pChild ){
96999       nodeRelease(pRtree, pChild->pParent);
97000       nodeReference(pNode);
97001       pChild->pParent = pNode;
97002     }
97003   }
97004   return xSetMapping(pRtree, iRowid, pNode->iNode);
97005 }
97006
97007 static int SplitNode(
97008   Rtree *pRtree,
97009   RtreeNode *pNode,
97010   RtreeCell *pCell,
97011   int iHeight
97012 ){
97013   int i;
97014   int newCellIsRight = 0;
97015
97016   int rc = SQLITE_OK;
97017   int nCell = NCELL(pNode);
97018   RtreeCell *aCell;
97019   int *aiUsed;
97020
97021   RtreeNode *pLeft = 0;
97022   RtreeNode *pRight = 0;
97023
97024   RtreeCell leftbbox;
97025   RtreeCell rightbbox;
97026
97027   /* Allocate an array and populate it with a copy of pCell and 
97028   ** all cells from node pLeft. Then zero the original node.
97029   */
97030   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
97031   if( !aCell ){
97032     rc = SQLITE_NOMEM;
97033     goto splitnode_out;
97034   }
97035   aiUsed = (int *)&aCell[nCell+1];
97036   memset(aiUsed, 0, sizeof(int)*(nCell+1));
97037   for(i=0; i<nCell; i++){
97038     nodeGetCell(pRtree, pNode, i, &aCell[i]);
97039   }
97040   nodeZero(pRtree, pNode);
97041   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
97042   nCell++;
97043
97044   if( pNode->iNode==1 ){
97045     pRight = nodeNew(pRtree, pNode, 1);
97046     pLeft = nodeNew(pRtree, pNode, 1);
97047     pRtree->iDepth++;
97048     pNode->isDirty = 1;
97049     writeInt16(pNode->zData, pRtree->iDepth);
97050   }else{
97051     pLeft = pNode;
97052     pRight = nodeNew(pRtree, pLeft->pParent, 1);
97053     nodeReference(pLeft);
97054   }
97055
97056   if( !pLeft || !pRight ){
97057     rc = SQLITE_NOMEM;
97058     goto splitnode_out;
97059   }
97060
97061   memset(pLeft->zData, 0, pRtree->iNodeSize);
97062   memset(pRight->zData, 0, pRtree->iNodeSize);
97063
97064   rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
97065   if( rc!=SQLITE_OK ){
97066     goto splitnode_out;
97067   }
97068
97069   /* Ensure both child nodes have node numbers assigned to them. */
97070   if( (0==pRight->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pRight)))
97071    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
97072   ){
97073     goto splitnode_out;
97074   }
97075
97076   rightbbox.iRowid = pRight->iNode;
97077   leftbbox.iRowid = pLeft->iNode;
97078
97079   if( pNode->iNode==1 ){
97080     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
97081     if( rc!=SQLITE_OK ){
97082       goto splitnode_out;
97083     }
97084   }else{
97085     RtreeNode *pParent = pLeft->pParent;
97086     int iCell = nodeParentIndex(pRtree, pLeft);
97087     nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
97088     AdjustTree(pRtree, pParent, &leftbbox);
97089   }
97090   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
97091     goto splitnode_out;
97092   }
97093
97094   for(i=0; i<NCELL(pRight); i++){
97095     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
97096     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
97097     if( iRowid==pCell->iRowid ){
97098       newCellIsRight = 1;
97099     }
97100     if( rc!=SQLITE_OK ){
97101       goto splitnode_out;
97102     }
97103   }
97104   if( pNode->iNode==1 ){
97105     for(i=0; i<NCELL(pLeft); i++){
97106       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
97107       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
97108       if( rc!=SQLITE_OK ){
97109         goto splitnode_out;
97110       }
97111     }
97112   }else if( newCellIsRight==0 ){
97113     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
97114   }
97115
97116   if( rc==SQLITE_OK ){
97117     rc = nodeRelease(pRtree, pRight);
97118     pRight = 0;
97119   }
97120   if( rc==SQLITE_OK ){
97121     rc = nodeRelease(pRtree, pLeft);
97122     pLeft = 0;
97123   }
97124
97125 splitnode_out:
97126   nodeRelease(pRtree, pRight);
97127   nodeRelease(pRtree, pLeft);
97128   sqlite3_free(aCell);
97129   return rc;
97130 }
97131
97132 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
97133   int rc = SQLITE_OK;
97134   if( pLeaf->iNode!=1 && pLeaf->pParent==0 ){
97135     sqlite3_bind_int64(pRtree->pReadParent, 1, pLeaf->iNode);
97136     if( sqlite3_step(pRtree->pReadParent)==SQLITE_ROW ){
97137       i64 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
97138       rc = nodeAcquire(pRtree, iNode, 0, &pLeaf->pParent);
97139     }else{
97140       rc = SQLITE_ERROR;
97141     }
97142     sqlite3_reset(pRtree->pReadParent);
97143     if( rc==SQLITE_OK ){
97144       rc = fixLeafParent(pRtree, pLeaf->pParent);
97145     }
97146   }
97147   return rc;
97148 }
97149
97150 static int deleteCell(Rtree *, RtreeNode *, int, int);
97151
97152 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
97153   int rc;
97154   RtreeNode *pParent;
97155   int iCell;
97156
97157   assert( pNode->nRef==1 );
97158
97159   /* Remove the entry in the parent cell. */
97160   iCell = nodeParentIndex(pRtree, pNode);
97161   pParent = pNode->pParent;
97162   pNode->pParent = 0;
97163   if( SQLITE_OK!=(rc = deleteCell(pRtree, pParent, iCell, iHeight+1)) 
97164    || SQLITE_OK!=(rc = nodeRelease(pRtree, pParent))
97165   ){
97166     return rc;
97167   }
97168
97169   /* Remove the xxx_node entry. */
97170   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
97171   sqlite3_step(pRtree->pDeleteNode);
97172   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
97173     return rc;
97174   }
97175
97176   /* Remove the xxx_parent entry. */
97177   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
97178   sqlite3_step(pRtree->pDeleteParent);
97179   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
97180     return rc;
97181   }
97182   
97183   /* Remove the node from the in-memory hash table and link it into
97184   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
97185   */
97186   nodeHashDelete(pRtree, pNode);
97187   pNode->iNode = iHeight;
97188   pNode->pNext = pRtree->pDeleted;
97189   pNode->nRef++;
97190   pRtree->pDeleted = pNode;
97191
97192   return SQLITE_OK;
97193 }
97194
97195 static void fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
97196   RtreeNode *pParent = pNode->pParent;
97197   if( pParent ){
97198     int ii; 
97199     int nCell = NCELL(pNode);
97200     RtreeCell box;                            /* Bounding box for pNode */
97201     nodeGetCell(pRtree, pNode, 0, &box);
97202     for(ii=1; ii<nCell; ii++){
97203       RtreeCell cell;
97204       nodeGetCell(pRtree, pNode, ii, &cell);
97205       cellUnion(pRtree, &box, &cell);
97206     }
97207     box.iRowid = pNode->iNode;
97208     ii = nodeParentIndex(pRtree, pNode);
97209     nodeOverwriteCell(pRtree, pParent, &box, ii);
97210     fixBoundingBox(pRtree, pParent);
97211   }
97212 }
97213
97214 /*
97215 ** Delete the cell at index iCell of node pNode. After removing the
97216 ** cell, adjust the r-tree data structure if required.
97217 */
97218 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
97219   int rc;
97220
97221   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
97222     return rc;
97223   }
97224
97225   /* Remove the cell from the node. This call just moves bytes around
97226   ** the in-memory node image, so it cannot fail.
97227   */
97228   nodeDeleteCell(pRtree, pNode, iCell);
97229
97230   /* If the node is not the tree root and now has less than the minimum
97231   ** number of cells, remove it from the tree. Otherwise, update the
97232   ** cell in the parent node so that it tightly contains the updated
97233   ** node.
97234   */
97235   if( pNode->iNode!=1 ){
97236     RtreeNode *pParent = pNode->pParent;
97237     if( (pParent->iNode!=1 || NCELL(pParent)!=1) 
97238      && (NCELL(pNode)<RTREE_MINCELLS(pRtree))
97239     ){
97240       rc = removeNode(pRtree, pNode, iHeight);
97241     }else{
97242       fixBoundingBox(pRtree, pNode);
97243     }
97244   }
97245
97246   return rc;
97247 }
97248
97249 static int Reinsert(
97250   Rtree *pRtree, 
97251   RtreeNode *pNode, 
97252   RtreeCell *pCell, 
97253   int iHeight
97254 ){
97255   int *aOrder;
97256   int *aSpare;
97257   RtreeCell *aCell;
97258   float *aDistance;
97259   int nCell;
97260   float aCenterCoord[RTREE_MAX_DIMENSIONS];
97261   int iDim;
97262   int ii;
97263   int rc = SQLITE_OK;
97264
97265   memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
97266
97267   nCell = NCELL(pNode)+1;
97268
97269   /* Allocate the buffers used by this operation. The allocation is
97270   ** relinquished before this function returns.
97271   */
97272   aCell = (RtreeCell *)sqlite3_malloc(nCell * (
97273     sizeof(RtreeCell) +         /* aCell array */
97274     sizeof(int)       +         /* aOrder array */
97275     sizeof(int)       +         /* aSpare array */
97276     sizeof(float)               /* aDistance array */
97277   ));
97278   if( !aCell ){
97279     return SQLITE_NOMEM;
97280   }
97281   aOrder    = (int *)&aCell[nCell];
97282   aSpare    = (int *)&aOrder[nCell];
97283   aDistance = (float *)&aSpare[nCell];
97284
97285   for(ii=0; ii<nCell; ii++){
97286     if( ii==(nCell-1) ){
97287       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
97288     }else{
97289       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
97290     }
97291     aOrder[ii] = ii;
97292     for(iDim=0; iDim<pRtree->nDim; iDim++){
97293       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
97294       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
97295     }
97296   }
97297   for(iDim=0; iDim<pRtree->nDim; iDim++){
97298     aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0);
97299   }
97300
97301   for(ii=0; ii<nCell; ii++){
97302     aDistance[ii] = 0.0;
97303     for(iDim=0; iDim<pRtree->nDim; iDim++){
97304       float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) - 
97305           DCOORD(aCell[ii].aCoord[iDim*2]);
97306       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
97307     }
97308   }
97309
97310   SortByDistance(aOrder, nCell, aDistance, aSpare);
97311   nodeZero(pRtree, pNode);
97312
97313   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
97314     RtreeCell *p = &aCell[aOrder[ii]];
97315     nodeInsertCell(pRtree, pNode, p);
97316     if( p->iRowid==pCell->iRowid ){
97317       if( iHeight==0 ){
97318         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
97319       }else{
97320         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
97321       }
97322     }
97323   }
97324   if( rc==SQLITE_OK ){
97325     fixBoundingBox(pRtree, pNode);
97326   }
97327   for(; rc==SQLITE_OK && ii<nCell; ii++){
97328     /* Find a node to store this cell in. pNode->iNode currently contains
97329     ** the height of the sub-tree headed by the cell.
97330     */
97331     RtreeNode *pInsert;
97332     RtreeCell *p = &aCell[aOrder[ii]];
97333     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
97334     if( rc==SQLITE_OK ){
97335       int rc2;
97336       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
97337       rc2 = nodeRelease(pRtree, pInsert);
97338       if( rc==SQLITE_OK ){
97339         rc = rc2;
97340       }
97341     }
97342   }
97343
97344   sqlite3_free(aCell);
97345   return rc;
97346 }
97347
97348 /*
97349 ** Insert cell pCell into node pNode. Node pNode is the head of a 
97350 ** subtree iHeight high (leaf nodes have iHeight==0).
97351 */
97352 static int rtreeInsertCell(
97353   Rtree *pRtree,
97354   RtreeNode *pNode,
97355   RtreeCell *pCell,
97356   int iHeight
97357 ){
97358   int rc = SQLITE_OK;
97359   if( iHeight>0 ){
97360     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
97361     if( pChild ){
97362       nodeRelease(pRtree, pChild->pParent);
97363       nodeReference(pNode);
97364       pChild->pParent = pNode;
97365     }
97366   }
97367   if( nodeInsertCell(pRtree, pNode, pCell) ){
97368 #if VARIANT_RSTARTREE_REINSERT
97369     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
97370       rc = SplitNode(pRtree, pNode, pCell, iHeight);
97371     }else{
97372       pRtree->iReinsertHeight = iHeight;
97373       rc = Reinsert(pRtree, pNode, pCell, iHeight);
97374     }
97375 #else
97376     rc = SplitNode(pRtree, pNode, pCell, iHeight);
97377 #endif
97378   }else{
97379     AdjustTree(pRtree, pNode, pCell);
97380     if( iHeight==0 ){
97381       rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
97382     }else{
97383       rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
97384     }
97385   }
97386   return rc;
97387 }
97388
97389 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
97390   int ii;
97391   int rc = SQLITE_OK;
97392   int nCell = NCELL(pNode);
97393
97394   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
97395     RtreeNode *pInsert;
97396     RtreeCell cell;
97397     nodeGetCell(pRtree, pNode, ii, &cell);
97398
97399     /* Find a node to store this cell in. pNode->iNode currently contains
97400     ** the height of the sub-tree headed by the cell.
97401     */
97402     rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert);
97403     if( rc==SQLITE_OK ){
97404       int rc2;
97405       rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode);
97406       rc2 = nodeRelease(pRtree, pInsert);
97407       if( rc==SQLITE_OK ){
97408         rc = rc2;
97409       }
97410     }
97411   }
97412   return rc;
97413 }
97414
97415 /*
97416 ** Select a currently unused rowid for a new r-tree record.
97417 */
97418 static int newRowid(Rtree *pRtree, i64 *piRowid){
97419   int rc;
97420   sqlite3_bind_null(pRtree->pWriteRowid, 1);
97421   sqlite3_bind_null(pRtree->pWriteRowid, 2);
97422   sqlite3_step(pRtree->pWriteRowid);
97423   rc = sqlite3_reset(pRtree->pWriteRowid);
97424   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
97425   return rc;
97426 }
97427
97428 #ifndef NDEBUG
97429 static int hashIsEmpty(Rtree *pRtree){
97430   int ii;
97431   for(ii=0; ii<HASHSIZE; ii++){
97432     assert( !pRtree->aHash[ii] );
97433   }
97434   return 1;
97435 }
97436 #endif
97437
97438 /*
97439 ** The xUpdate method for rtree module virtual tables.
97440 */
97441 int rtreeUpdate(
97442   sqlite3_vtab *pVtab, 
97443   int nData, 
97444   sqlite3_value **azData, 
97445   sqlite_int64 *pRowid
97446 ){
97447   Rtree *pRtree = (Rtree *)pVtab;
97448   int rc = SQLITE_OK;
97449
97450   rtreeReference(pRtree);
97451
97452   assert(nData>=1);
97453   assert(hashIsEmpty(pRtree));
97454
97455   /* If azData[0] is not an SQL NULL value, it is the rowid of a
97456   ** record to delete from the r-tree table. The following block does
97457   ** just that.
97458   */
97459   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
97460     i64 iDelete;                /* The rowid to delete */
97461     RtreeNode *pLeaf;           /* Leaf node containing record iDelete */
97462     int iCell;                  /* Index of iDelete cell in pLeaf */
97463     RtreeNode *pRoot;
97464
97465     /* Obtain a reference to the root node to initialise Rtree.iDepth */
97466     rc = nodeAcquire(pRtree, 1, 0, &pRoot);
97467
97468     /* Obtain a reference to the leaf node that contains the entry 
97469     ** about to be deleted. 
97470     */
97471     if( rc==SQLITE_OK ){
97472       iDelete = sqlite3_value_int64(azData[0]);
97473       rc = findLeafNode(pRtree, iDelete, &pLeaf);
97474     }
97475
97476     /* Delete the cell in question from the leaf node. */
97477     if( rc==SQLITE_OK ){
97478       int rc2;
97479       iCell = nodeRowidIndex(pRtree, pLeaf, iDelete);
97480       rc = deleteCell(pRtree, pLeaf, iCell, 0);
97481       rc2 = nodeRelease(pRtree, pLeaf);
97482       if( rc==SQLITE_OK ){
97483         rc = rc2;
97484       }
97485     }
97486
97487     /* Delete the corresponding entry in the <rtree>_rowid table. */
97488     if( rc==SQLITE_OK ){
97489       sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
97490       sqlite3_step(pRtree->pDeleteRowid);
97491       rc = sqlite3_reset(pRtree->pDeleteRowid);
97492     }
97493
97494     /* Check if the root node now has exactly one child. If so, remove
97495     ** it, schedule the contents of the child for reinsertion and 
97496     ** reduce the tree height by one.
97497     **
97498     ** This is equivalent to copying the contents of the child into
97499     ** the root node (the operation that Gutman's paper says to perform 
97500     ** in this scenario).
97501     */
97502     if( rc==SQLITE_OK && pRtree->iDepth>0 ){
97503       if( rc==SQLITE_OK && NCELL(pRoot)==1 ){
97504         RtreeNode *pChild;
97505         i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
97506         rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
97507         if( rc==SQLITE_OK ){
97508           rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
97509         }
97510         if( rc==SQLITE_OK ){
97511           pRtree->iDepth--;
97512           writeInt16(pRoot->zData, pRtree->iDepth);
97513           pRoot->isDirty = 1;
97514         }
97515       }
97516     }
97517
97518     /* Re-insert the contents of any underfull nodes removed from the tree. */
97519     for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
97520       if( rc==SQLITE_OK ){
97521         rc = reinsertNodeContent(pRtree, pLeaf);
97522       }
97523       pRtree->pDeleted = pLeaf->pNext;
97524       sqlite3_free(pLeaf);
97525     }
97526
97527     /* Release the reference to the root node. */
97528     if( rc==SQLITE_OK ){
97529       rc = nodeRelease(pRtree, pRoot);
97530     }else{
97531       nodeRelease(pRtree, pRoot);
97532     }
97533   }
97534
97535   /* If the azData[] array contains more than one element, elements
97536   ** (azData[2]..azData[argc-1]) contain a new record to insert into
97537   ** the r-tree structure.
97538   */
97539   if( rc==SQLITE_OK && nData>1 ){
97540     /* Insert a new record into the r-tree */
97541     RtreeCell cell;
97542     int ii;
97543     RtreeNode *pLeaf;
97544
97545     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
97546     assert( nData==(pRtree->nDim*2 + 3) );
97547     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
97548       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
97549         cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
97550         cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
97551         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
97552           rc = SQLITE_CONSTRAINT;
97553           goto constraint;
97554         }
97555       }
97556     }else{
97557       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
97558         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
97559         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
97560         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
97561           rc = SQLITE_CONSTRAINT;
97562           goto constraint;
97563         }
97564       }
97565     }
97566
97567     /* Figure out the rowid of the new row. */
97568     if( sqlite3_value_type(azData[2])==SQLITE_NULL ){
97569       rc = newRowid(pRtree, &cell.iRowid);
97570     }else{
97571       cell.iRowid = sqlite3_value_int64(azData[2]);
97572       sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
97573       if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){
97574         sqlite3_reset(pRtree->pReadRowid);
97575         rc = SQLITE_CONSTRAINT;
97576         goto constraint;
97577       }
97578       rc = sqlite3_reset(pRtree->pReadRowid);
97579     }
97580
97581     if( rc==SQLITE_OK ){
97582       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
97583     }
97584     if( rc==SQLITE_OK ){
97585       int rc2;
97586       pRtree->iReinsertHeight = -1;
97587       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
97588       rc2 = nodeRelease(pRtree, pLeaf);
97589       if( rc==SQLITE_OK ){
97590         rc = rc2;
97591       }
97592     }
97593   }
97594
97595 constraint:
97596   rtreeRelease(pRtree);
97597   return rc;
97598 }
97599
97600 /*
97601 ** The xRename method for rtree module virtual tables.
97602 */
97603 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
97604   Rtree *pRtree = (Rtree *)pVtab;
97605   int rc = SQLITE_NOMEM;
97606   char *zSql = sqlite3_mprintf(
97607     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
97608     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
97609     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
97610     , pRtree->zDb, pRtree->zName, zNewName 
97611     , pRtree->zDb, pRtree->zName, zNewName 
97612     , pRtree->zDb, pRtree->zName, zNewName
97613   );
97614   if( zSql ){
97615     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
97616     sqlite3_free(zSql);
97617   }
97618   return rc;
97619 }
97620
97621 static sqlite3_module rtreeModule = {
97622   0,                         /* iVersion */
97623   rtreeCreate,                /* xCreate - create a table */
97624   rtreeConnect,               /* xConnect - connect to an existing table */
97625   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
97626   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
97627   rtreeDestroy,               /* xDestroy - Drop a table */
97628   rtreeOpen,                  /* xOpen - open a cursor */
97629   rtreeClose,                 /* xClose - close a cursor */
97630   rtreeFilter,                /* xFilter - configure scan constraints */
97631   rtreeNext,                  /* xNext - advance a cursor */
97632   rtreeEof,                   /* xEof */
97633   rtreeColumn,                /* xColumn - read data */
97634   rtreeRowid,                 /* xRowid - read data */
97635   rtreeUpdate,                /* xUpdate - write data */
97636   0,                          /* xBegin - begin transaction */
97637   0,                          /* xSync - sync transaction */
97638   0,                          /* xCommit - commit transaction */
97639   0,                          /* xRollback - rollback transaction */
97640   0,                          /* xFindFunction - function overloading */
97641   rtreeRename                 /* xRename - rename the table */
97642 };
97643
97644 static int rtreeSqlInit(
97645   Rtree *pRtree, 
97646   sqlite3 *db, 
97647   const char *zDb, 
97648   const char *zPrefix, 
97649   int isCreate
97650 ){
97651   int rc = SQLITE_OK;
97652
97653   #define N_STATEMENT 9
97654   static const char *azSql[N_STATEMENT] = {
97655     /* Read and write the xxx_node table */
97656     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
97657     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
97658     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
97659
97660     /* Read and write the xxx_rowid table */
97661     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
97662     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
97663     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
97664
97665     /* Read and write the xxx_parent table */
97666     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
97667     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
97668     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
97669   };
97670   sqlite3_stmt **appStmt[N_STATEMENT];
97671   int i;
97672
97673   pRtree->db = db;
97674
97675   if( isCreate ){
97676     char *zCreate = sqlite3_mprintf(
97677 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
97678 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
97679 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
97680 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
97681       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
97682     );
97683     if( !zCreate ){
97684       return SQLITE_NOMEM;
97685     }
97686     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
97687     sqlite3_free(zCreate);
97688     if( rc!=SQLITE_OK ){
97689       return rc;
97690     }
97691   }
97692
97693   appStmt[0] = &pRtree->pReadNode;
97694   appStmt[1] = &pRtree->pWriteNode;
97695   appStmt[2] = &pRtree->pDeleteNode;
97696   appStmt[3] = &pRtree->pReadRowid;
97697   appStmt[4] = &pRtree->pWriteRowid;
97698   appStmt[5] = &pRtree->pDeleteRowid;
97699   appStmt[6] = &pRtree->pReadParent;
97700   appStmt[7] = &pRtree->pWriteParent;
97701   appStmt[8] = &pRtree->pDeleteParent;
97702
97703   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
97704     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
97705     if( zSql ){
97706       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0); 
97707     }else{
97708       rc = SQLITE_NOMEM;
97709     }
97710     sqlite3_free(zSql);
97711   }
97712
97713   return rc;
97714 }
97715
97716 /*
97717 ** This routine queries database handle db for the page-size used by
97718 ** database zDb. If successful, the page-size in bytes is written to
97719 ** *piPageSize and SQLITE_OK returned. Otherwise, and an SQLite error 
97720 ** code is returned.
97721 */
97722 static int getPageSize(sqlite3 *db, const char *zDb, int *piPageSize){
97723   int rc = SQLITE_NOMEM;
97724   char *zSql;
97725   sqlite3_stmt *pStmt = 0;
97726
97727   zSql = sqlite3_mprintf("PRAGMA %Q.page_size", zDb);
97728   if( !zSql ){
97729     return SQLITE_NOMEM;
97730   }
97731
97732   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
97733   sqlite3_free(zSql);
97734   if( rc!=SQLITE_OK ){
97735     return rc;
97736   }
97737
97738   if( SQLITE_ROW==sqlite3_step(pStmt) ){
97739     *piPageSize = sqlite3_column_int(pStmt, 0);
97740   }
97741   return sqlite3_finalize(pStmt);
97742 }
97743
97744 /* 
97745 ** This function is the implementation of both the xConnect and xCreate
97746 ** methods of the r-tree virtual table.
97747 **
97748 **   argv[0]   -> module name
97749 **   argv[1]   -> database name
97750 **   argv[2]   -> table name
97751 **   argv[...] -> column names...
97752 */
97753 static int rtreeInit(
97754   sqlite3 *db,                        /* Database connection */
97755   void *pAux,                         /* One of the RTREE_COORD_* constants */
97756   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
97757   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
97758   char **pzErr,                       /* OUT: Error message, if any */
97759   int isCreate                        /* True for xCreate, false for xConnect */
97760 ){
97761   int rc = SQLITE_OK;
97762   int iPageSize = 0;
97763   Rtree *pRtree;
97764   int nDb;              /* Length of string argv[1] */
97765   int nName;            /* Length of string argv[2] */
97766   int eCoordType = (int)pAux;
97767
97768   const char *aErrMsg[] = {
97769     0,                                                    /* 0 */
97770     "Wrong number of columns for an rtree table",         /* 1 */
97771     "Too few columns for an rtree table",                 /* 2 */
97772     "Too many columns for an rtree table"                 /* 3 */
97773   };
97774
97775   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
97776   if( aErrMsg[iErr] ){
97777     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
97778     return SQLITE_ERROR;
97779   }
97780
97781   rc = getPageSize(db, argv[1], &iPageSize);
97782   if( rc!=SQLITE_OK ){
97783     return rc;
97784   }
97785
97786   /* Allocate the sqlite3_vtab structure */
97787   nDb = strlen(argv[1]);
97788   nName = strlen(argv[2]);
97789   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
97790   if( !pRtree ){
97791     return SQLITE_NOMEM;
97792   }
97793   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
97794   pRtree->nBusy = 1;
97795   pRtree->base.pModule = &rtreeModule;
97796   pRtree->zDb = (char *)&pRtree[1];
97797   pRtree->zName = &pRtree->zDb[nDb+1];
97798   pRtree->nDim = (argc-4)/2;
97799   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
97800   pRtree->eCoordType = eCoordType;
97801   memcpy(pRtree->zDb, argv[1], nDb);
97802   memcpy(pRtree->zName, argv[2], nName);
97803
97804   /* Figure out the node size to use. By default, use 64 bytes less than
97805   ** the database page-size. This ensures that each node is stored on
97806   ** a single database page.
97807   **
97808   ** If the databasd page-size is so large that more than RTREE_MAXCELLS
97809   ** entries would fit in a single node, use a smaller node-size.
97810   */
97811   pRtree->iNodeSize = iPageSize-64;
97812   if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
97813     pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
97814   }
97815
97816   /* Create/Connect to the underlying relational database schema. If
97817   ** that is successful, call sqlite3_declare_vtab() to configure
97818   ** the r-tree table schema.
97819   */
97820   if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
97821     *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
97822   }else{
97823     char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
97824     char *zTmp;
97825     int ii;
97826     for(ii=4; zSql && ii<argc; ii++){
97827       zTmp = zSql;
97828       zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
97829       sqlite3_free(zTmp);
97830     }
97831     if( zSql ){
97832       zTmp = zSql;
97833       zSql = sqlite3_mprintf("%s);", zTmp);
97834       sqlite3_free(zTmp);
97835     }
97836     if( !zSql || sqlite3_declare_vtab(db, zSql) ){
97837       rc = SQLITE_NOMEM;
97838     }
97839     sqlite3_free(zSql);
97840   }
97841
97842   if( rc==SQLITE_OK ){
97843     *ppVtab = (sqlite3_vtab *)pRtree;
97844   }else{
97845     rtreeRelease(pRtree);
97846   }
97847   return rc;
97848 }
97849
97850
97851 /*
97852 ** Implementation of a scalar function that decodes r-tree nodes to
97853 ** human readable strings. This can be used for debugging and analysis.
97854 **
97855 ** The scalar function takes two arguments, a blob of data containing
97856 ** an r-tree node, and the number of dimensions the r-tree indexes.
97857 ** For a two-dimensional r-tree structure called "rt", to deserialize
97858 ** all nodes, a statement like:
97859 **
97860 **   SELECT rtreenode(2, data) FROM rt_node;
97861 **
97862 ** The human readable string takes the form of a Tcl list with one
97863 ** entry for each cell in the r-tree node. Each entry is itself a
97864 ** list, containing the 8-byte rowid/pageno followed by the 
97865 ** <num-dimension>*2 coordinates.
97866 */
97867 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
97868   char *zText = 0;
97869   RtreeNode node;
97870   Rtree tree;
97871   int ii;
97872
97873   memset(&node, 0, sizeof(RtreeNode));
97874   memset(&tree, 0, sizeof(Rtree));
97875   tree.nDim = sqlite3_value_int(apArg[0]);
97876   tree.nBytesPerCell = 8 + 8 * tree.nDim;
97877   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
97878
97879   for(ii=0; ii<NCELL(&node); ii++){
97880     char zCell[512];
97881     int nCell = 0;
97882     RtreeCell cell;
97883     int jj;
97884
97885     nodeGetCell(&tree, &node, ii, &cell);
97886     sqlite3_snprintf(512-nCell,&zCell[nCell],"%d", cell.iRowid);
97887     nCell = strlen(zCell);
97888     for(jj=0; jj<tree.nDim*2; jj++){
97889       sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
97890       nCell = strlen(zCell);
97891     }
97892
97893     if( zText ){
97894       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
97895       sqlite3_free(zText);
97896       zText = zTextNew;
97897     }else{
97898       zText = sqlite3_mprintf("{%s}", zCell);
97899     }
97900   }
97901   
97902   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
97903 }
97904
97905 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
97906   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB 
97907    || sqlite3_value_bytes(apArg[0])<2
97908   ){
97909     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); 
97910   }else{
97911     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
97912     sqlite3_result_int(ctx, readInt16(zBlob));
97913   }
97914 }
97915
97916 /*
97917 ** Register the r-tree module with database handle db. This creates the
97918 ** virtual table module "rtree" and the debugging/analysis scalar 
97919 ** function "rtreenode".
97920 */
97921 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
97922   int rc = SQLITE_OK;
97923
97924   if( rc==SQLITE_OK ){
97925     int utf8 = SQLITE_UTF8;
97926     rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
97927   }
97928   if( rc==SQLITE_OK ){
97929     int utf8 = SQLITE_UTF8;
97930     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
97931   }
97932   if( rc==SQLITE_OK ){
97933     void *c = (void *)RTREE_COORD_REAL32;
97934     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
97935   }
97936   if( rc==SQLITE_OK ){
97937     void *c = (void *)RTREE_COORD_INT32;
97938     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
97939   }
97940
97941   return rc;
97942 }
97943
97944 #if !SQLITE_CORE
97945 SQLITE_API int sqlite3_extension_init(
97946   sqlite3 *db,
97947   char **pzErrMsg,
97948   const sqlite3_api_routines *pApi
97949 ){
97950   SQLITE_EXTENSION_INIT2(pApi)
97951   return sqlite3RtreeInit(db);
97952 }
97953 #endif
97954
97955 #endif
97956
97957 /************** End of rtree.c ***********************************************/
97958 /************** Begin file icu.c *********************************************/
97959 /*
97960 ** 2007 May 6
97961 **
97962 ** The author disclaims copyright to this source code.  In place of
97963 ** a legal notice, here is a blessing:
97964 **
97965 **    May you do good and not evil.
97966 **    May you find forgiveness for yourself and forgive others.
97967 **    May you share freely, never taking more than you give.
97968 **
97969 *************************************************************************
97970 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
97971 **
97972 ** This file implements an integration between the ICU library 
97973 ** ("International Components for Unicode", an open-source library 
97974 ** for handling unicode data) and SQLite. The integration uses 
97975 ** ICU to provide the following to SQLite:
97976 **
97977 **   * An implementation of the SQL regexp() function (and hence REGEXP
97978 **     operator) using the ICU uregex_XX() APIs.
97979 **
97980 **   * Implementations of the SQL scalar upper() and lower() functions
97981 **     for case mapping.
97982 **
97983 **   * Integration of ICU and SQLite collation seqences.
97984 **
97985 **   * An implementation of the LIKE operator that uses ICU to 
97986 **     provide case-independent matching.
97987 */
97988
97989 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
97990
97991 /* Include ICU headers */
97992 #include <unicode/utypes.h>
97993 #include <unicode/uregex.h>
97994 #include <unicode/ustring.h>
97995 #include <unicode/ucol.h>
97996
97997
97998 #ifndef SQLITE_CORE
97999   SQLITE_EXTENSION_INIT1
98000 #else
98001 #endif
98002
98003 /*
98004 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
98005 ** operator.
98006 */
98007 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
98008 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
98009 #endif
98010
98011 /*
98012 ** Version of sqlite3_free() that is always a function, never a macro.
98013 */
98014 static void xFree(void *p){
98015   sqlite3_free(p);
98016 }
98017
98018 /*
98019 ** Compare two UTF-8 strings for equality where the first string is
98020 ** a "LIKE" expression. Return true (1) if they are the same and 
98021 ** false (0) if they are different.
98022 */
98023 static int icuLikeCompare(
98024   const uint8_t *zPattern,   /* LIKE pattern */
98025   const uint8_t *zString,    /* The UTF-8 string to compare against */
98026   const UChar32 uEsc         /* The escape character */
98027 ){
98028   static const int MATCH_ONE = (UChar32)'_';
98029   static const int MATCH_ALL = (UChar32)'%';
98030
98031   int iPattern = 0;       /* Current byte index in zPattern */
98032   int iString = 0;        /* Current byte index in zString */
98033
98034   int prevEscape = 0;     /* True if the previous character was uEsc */
98035
98036   while( zPattern[iPattern]!=0 ){
98037
98038     /* Read (and consume) the next character from the input pattern. */
98039     UChar32 uPattern;
98040     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
98041     assert(uPattern!=0);
98042
98043     /* There are now 4 possibilities:
98044     **
98045     **     1. uPattern is an unescaped match-all character "%",
98046     **     2. uPattern is an unescaped match-one character "_",
98047     **     3. uPattern is an unescaped escape character, or
98048     **     4. uPattern is to be handled as an ordinary character
98049     */
98050     if( !prevEscape && uPattern==MATCH_ALL ){
98051       /* Case 1. */
98052       uint8_t c;
98053
98054       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
98055       ** MATCH_ALL. For each MATCH_ONE, skip one character in the 
98056       ** test string.
98057       */
98058       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
98059         if( c==MATCH_ONE ){
98060           if( zString[iString]==0 ) return 0;
98061           U8_FWD_1_UNSAFE(zString, iString);
98062         }
98063         iPattern++;
98064       }
98065
98066       if( zPattern[iPattern]==0 ) return 1;
98067
98068       while( zString[iString] ){
98069         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
98070           return 1;
98071         }
98072         U8_FWD_1_UNSAFE(zString, iString);
98073       }
98074       return 0;
98075
98076     }else if( !prevEscape && uPattern==MATCH_ONE ){
98077       /* Case 2. */
98078       if( zString[iString]==0 ) return 0;
98079       U8_FWD_1_UNSAFE(zString, iString);
98080
98081     }else if( !prevEscape && uPattern==uEsc){
98082       /* Case 3. */
98083       prevEscape = 1;
98084
98085     }else{
98086       /* Case 4. */
98087       UChar32 uString;
98088       U8_NEXT_UNSAFE(zString, iString, uString);
98089       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
98090       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
98091       if( uString!=uPattern ){
98092         return 0;
98093       }
98094       prevEscape = 0;
98095     }
98096   }
98097
98098   return zString[iString]==0;
98099 }
98100
98101 /*
98102 ** Implementation of the like() SQL function.  This function implements
98103 ** the build-in LIKE operator.  The first argument to the function is the
98104 ** pattern and the second argument is the string.  So, the SQL statements:
98105 **
98106 **       A LIKE B
98107 **
98108 ** is implemented as like(B, A). If there is an escape character E, 
98109 **
98110 **       A LIKE B ESCAPE E
98111 **
98112 ** is mapped to like(B, A, E).
98113 */
98114 static void icuLikeFunc(
98115   sqlite3_context *context, 
98116   int argc, 
98117   sqlite3_value **argv
98118 ){
98119   const unsigned char *zA = sqlite3_value_text(argv[0]);
98120   const unsigned char *zB = sqlite3_value_text(argv[1]);
98121   UChar32 uEsc = 0;
98122
98123   /* Limit the length of the LIKE or GLOB pattern to avoid problems
98124   ** of deep recursion and N*N behavior in patternCompare().
98125   */
98126   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
98127     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
98128     return;
98129   }
98130
98131
98132   if( argc==3 ){
98133     /* The escape character string must consist of a single UTF-8 character.
98134     ** Otherwise, return an error.
98135     */
98136     int nE= sqlite3_value_bytes(argv[2]);
98137     const unsigned char *zE = sqlite3_value_text(argv[2]);
98138     int i = 0;
98139     if( zE==0 ) return;
98140     U8_NEXT(zE, i, nE, uEsc);
98141     if( i!=nE){
98142       sqlite3_result_error(context, 
98143           "ESCAPE expression must be a single character", -1);
98144       return;
98145     }
98146   }
98147
98148   if( zA && zB ){
98149     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
98150   }
98151 }
98152
98153 /*
98154 ** This function is called when an ICU function called from within
98155 ** the implementation of an SQL scalar function returns an error.
98156 **
98157 ** The scalar function context passed as the first argument is 
98158 ** loaded with an error message based on the following two args.
98159 */
98160 static void icuFunctionError(
98161   sqlite3_context *pCtx,       /* SQLite scalar function context */
98162   const char *zName,           /* Name of ICU function that failed */
98163   UErrorCode e                 /* Error code returned by ICU function */
98164 ){
98165   char zBuf[128];
98166   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
98167   zBuf[127] = '\0';
98168   sqlite3_result_error(pCtx, zBuf, -1);
98169 }
98170
98171 /*
98172 ** Function to delete compiled regexp objects. Registered as
98173 ** a destructor function with sqlite3_set_auxdata().
98174 */
98175 static void icuRegexpDelete(void *p){
98176   URegularExpression *pExpr = (URegularExpression *)p;
98177   uregex_close(pExpr);
98178 }
98179
98180 /*
98181 ** Implementation of SQLite REGEXP operator. This scalar function takes
98182 ** two arguments. The first is a regular expression pattern to compile
98183 ** the second is a string to match against that pattern. If either 
98184 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
98185 ** is 1 if the string matches the pattern, or 0 otherwise.
98186 **
98187 ** SQLite maps the regexp() function to the regexp() operator such
98188 ** that the following two are equivalent:
98189 **
98190 **     zString REGEXP zPattern
98191 **     regexp(zPattern, zString)
98192 **
98193 ** Uses the following ICU regexp APIs:
98194 **
98195 **     uregex_open()
98196 **     uregex_matches()
98197 **     uregex_close()
98198 */
98199 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
98200   UErrorCode status = U_ZERO_ERROR;
98201   URegularExpression *pExpr;
98202   UBool res;
98203   const UChar *zString = sqlite3_value_text16(apArg[1]);
98204
98205   /* If the left hand side of the regexp operator is NULL, 
98206   ** then the result is also NULL. 
98207   */
98208   if( !zString ){
98209     return;
98210   }
98211
98212   pExpr = sqlite3_get_auxdata(p, 0);
98213   if( !pExpr ){
98214     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
98215     if( !zPattern ){
98216       return;
98217     }
98218     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
98219
98220     if( U_SUCCESS(status) ){
98221       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
98222     }else{
98223       assert(!pExpr);
98224       icuFunctionError(p, "uregex_open", status);
98225       return;
98226     }
98227   }
98228
98229   /* Configure the text that the regular expression operates on. */
98230   uregex_setText(pExpr, zString, -1, &status);
98231   if( !U_SUCCESS(status) ){
98232     icuFunctionError(p, "uregex_setText", status);
98233     return;
98234   }
98235
98236   /* Attempt the match */
98237   res = uregex_matches(pExpr, 0, &status);
98238   if( !U_SUCCESS(status) ){
98239     icuFunctionError(p, "uregex_matches", status);
98240     return;
98241   }
98242
98243   /* Set the text that the regular expression operates on to a NULL
98244   ** pointer. This is not really necessary, but it is tidier than 
98245   ** leaving the regular expression object configured with an invalid
98246   ** pointer after this function returns.
98247   */
98248   uregex_setText(pExpr, 0, 0, &status);
98249
98250   /* Return 1 or 0. */
98251   sqlite3_result_int(p, res ? 1 : 0);
98252 }
98253
98254 /*
98255 ** Implementations of scalar functions for case mapping - upper() and 
98256 ** lower(). Function upper() converts its input to upper-case (ABC).
98257 ** Function lower() converts to lower-case (abc).
98258 **
98259 ** ICU provides two types of case mapping, "general" case mapping and
98260 ** "language specific". Refer to ICU documentation for the differences
98261 ** between the two.
98262 **
98263 ** To utilise "general" case mapping, the upper() or lower() scalar 
98264 ** functions are invoked with one argument:
98265 **
98266 **     upper('ABC') -> 'abc'
98267 **     lower('abc') -> 'ABC'
98268 **
98269 ** To access ICU "language specific" case mapping, upper() or lower()
98270 ** should be invoked with two arguments. The second argument is the name
98271 ** of the locale to use. Passing an empty string ("") or SQL NULL value
98272 ** as the second argument is the same as invoking the 1 argument version
98273 ** of upper() or lower().
98274 **
98275 **     lower('I', 'en_us') -> 'i'
98276 **     lower('I', 'tr_tr') -> 'ı' (small dotless i)
98277 **
98278 ** http://www.icu-project.org/userguide/posix.html#case_mappings
98279 */
98280 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
98281   const UChar *zInput;
98282   UChar *zOutput;
98283   int nInput;
98284   int nOutput;
98285
98286   UErrorCode status = U_ZERO_ERROR;
98287   const char *zLocale = 0;
98288
98289   assert(nArg==1 || nArg==2);
98290   if( nArg==2 ){
98291     zLocale = (const char *)sqlite3_value_text(apArg[1]);
98292   }
98293
98294   zInput = sqlite3_value_text16(apArg[0]);
98295   if( !zInput ){
98296     return;
98297   }
98298   nInput = sqlite3_value_bytes16(apArg[0]);
98299
98300   nOutput = nInput * 2 + 2;
98301   zOutput = sqlite3_malloc(nOutput);
98302   if( !zOutput ){
98303     return;
98304   }
98305
98306   if( sqlite3_user_data(p) ){
98307     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
98308   }else{
98309     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
98310   }
98311
98312   if( !U_SUCCESS(status) ){
98313     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
98314     return;
98315   }
98316
98317   sqlite3_result_text16(p, zOutput, -1, xFree);
98318 }
98319
98320 /*
98321 ** Collation sequence destructor function. The pCtx argument points to
98322 ** a UCollator structure previously allocated using ucol_open().
98323 */
98324 static void icuCollationDel(void *pCtx){
98325   UCollator *p = (UCollator *)pCtx;
98326   ucol_close(p);
98327 }
98328
98329 /*
98330 ** Collation sequence comparison function. The pCtx argument points to
98331 ** a UCollator structure previously allocated using ucol_open().
98332 */
98333 static int icuCollationColl(
98334   void *pCtx,
98335   int nLeft,
98336   const void *zLeft,
98337   int nRight,
98338   const void *zRight
98339 ){
98340   UCollationResult res;
98341   UCollator *p = (UCollator *)pCtx;
98342   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
98343   switch( res ){
98344     case UCOL_LESS:    return -1;
98345     case UCOL_GREATER: return +1;
98346     case UCOL_EQUAL:   return 0;
98347   }
98348   assert(!"Unexpected return value from ucol_strcoll()");
98349   return 0;
98350 }
98351
98352 /*
98353 ** Implementation of the scalar function icu_load_collation().
98354 **
98355 ** This scalar function is used to add ICU collation based collation 
98356 ** types to an SQLite database connection. It is intended to be called
98357 ** as follows:
98358 **
98359 **     SELECT icu_load_collation(<locale>, <collation-name>);
98360 **
98361 ** Where <locale> is a string containing an ICU locale identifier (i.e.
98362 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
98363 ** collation sequence to create.
98364 */
98365 static void icuLoadCollation(
98366   sqlite3_context *p, 
98367   int nArg, 
98368   sqlite3_value **apArg
98369 ){
98370   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
98371   UErrorCode status = U_ZERO_ERROR;
98372   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
98373   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
98374   UCollator *pUCollator;    /* ICU library collation object */
98375   int rc;                   /* Return code from sqlite3_create_collation_x() */
98376
98377   assert(nArg==2);
98378   zLocale = (const char *)sqlite3_value_text(apArg[0]);
98379   zName = (const char *)sqlite3_value_text(apArg[1]);
98380
98381   if( !zLocale || !zName ){
98382     return;
98383   }
98384
98385   pUCollator = ucol_open(zLocale, &status);
98386   if( !U_SUCCESS(status) ){
98387     icuFunctionError(p, "ucol_open", status);
98388     return;
98389   }
98390   assert(p);
98391
98392   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, 
98393       icuCollationColl, icuCollationDel
98394   );
98395   if( rc!=SQLITE_OK ){
98396     ucol_close(pUCollator);
98397     sqlite3_result_error(p, "Error registering collation function", -1);
98398   }
98399 }
98400
98401 /*
98402 ** Register the ICU extension functions with database db.
98403 */
98404 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
98405   struct IcuScalar {
98406     const char *zName;                        /* Function name */
98407     int nArg;                                 /* Number of arguments */
98408     int enc;                                  /* Optimal text encoding */
98409     void *pContext;                           /* sqlite3_user_data() context */
98410     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
98411   } scalars[] = {
98412     {"regexp",-1, SQLITE_ANY,          0, icuRegexpFunc},
98413
98414     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
98415     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
98416     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
98417     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
98418
98419     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
98420     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
98421     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
98422     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
98423
98424     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
98425     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
98426
98427     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
98428   };
98429
98430   int rc = SQLITE_OK;
98431   int i;
98432
98433   for(i=0; rc==SQLITE_OK && i<(sizeof(scalars)/sizeof(struct IcuScalar)); i++){
98434     struct IcuScalar *p = &scalars[i];
98435     rc = sqlite3_create_function(
98436         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
98437     );
98438   }
98439
98440   return rc;
98441 }
98442
98443 #if !SQLITE_CORE
98444 SQLITE_API int sqlite3_extension_init(
98445   sqlite3 *db, 
98446   char **pzErrMsg,
98447   const sqlite3_api_routines *pApi
98448 ){
98449   SQLITE_EXTENSION_INIT2(pApi)
98450   return sqlite3IcuInit(db);
98451 }
98452 #endif
98453
98454 #endif
98455
98456 /************** End of icu.c *************************************************/
98457 /************** Begin file fts3_icu.c ****************************************/
98458 /*
98459 ** 2007 June 22
98460 **
98461 ** The author disclaims copyright to this source code.  In place of
98462 ** a legal notice, here is a blessing:
98463 **
98464 **    May you do good and not evil.
98465 **    May you find forgiveness for yourself and forgive others.
98466 **    May you share freely, never taking more than you give.
98467 **
98468 *************************************************************************
98469 ** This file implements a tokenizer for fts3 based on the ICU library.
98470 ** 
98471 ** $Id: fts3_icu.c,v 1.3 2008/09/01 18:34:20 danielk1977 Exp $
98472 */
98473
98474 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
98475 #ifdef SQLITE_ENABLE_ICU
98476
98477
98478 #include <unicode/ubrk.h>
98479 #include <unicode/utf16.h>
98480
98481 typedef struct IcuTokenizer IcuTokenizer;
98482 typedef struct IcuCursor IcuCursor;
98483
98484 struct IcuTokenizer {
98485   sqlite3_tokenizer base;
98486   char *zLocale;
98487 };
98488
98489 struct IcuCursor {
98490   sqlite3_tokenizer_cursor base;
98491
98492   UBreakIterator *pIter;      /* ICU break-iterator object */
98493   int nChar;                  /* Number of UChar elements in pInput */
98494   UChar *aChar;               /* Copy of input using utf-16 encoding */
98495   int *aOffset;               /* Offsets of each character in utf-8 input */
98496
98497   int nBuffer;
98498   char *zBuffer;
98499
98500   int iToken;
98501 };
98502
98503 /*
98504 ** Create a new tokenizer instance.
98505 */
98506 static int icuCreate(
98507   int argc,                            /* Number of entries in argv[] */
98508   const char * const *argv,            /* Tokenizer creation arguments */
98509   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
98510 ){
98511   IcuTokenizer *p;
98512   int n = 0;
98513
98514   if( argc>0 ){
98515     n = strlen(argv[0])+1;
98516   }
98517   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
98518   if( !p ){
98519     return SQLITE_NOMEM;
98520   }
98521   memset(p, 0, sizeof(IcuTokenizer));
98522
98523   if( n ){
98524     p->zLocale = (char *)&p[1];
98525     memcpy(p->zLocale, argv[0], n);
98526   }
98527
98528   *ppTokenizer = (sqlite3_tokenizer *)p;
98529
98530   return SQLITE_OK;
98531 }
98532
98533 /*
98534 ** Destroy a tokenizer
98535 */
98536 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
98537   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
98538   sqlite3_free(p);
98539   return SQLITE_OK;
98540 }
98541
98542 /*
98543 ** Prepare to begin tokenizing a particular string.  The input
98544 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
98545 ** used to incrementally tokenize this string is returned in 
98546 ** *ppCursor.
98547 */
98548 static int icuOpen(
98549   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
98550   const char *zInput,                    /* Input string */
98551   int nInput,                            /* Length of zInput in bytes */
98552   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
98553 ){
98554   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
98555   IcuCursor *pCsr;
98556
98557   const int32_t opt = U_FOLD_CASE_DEFAULT;
98558   UErrorCode status = U_ZERO_ERROR;
98559   int nChar;
98560
98561   UChar32 c;
98562   int iInput = 0;
98563   int iOut = 0;
98564
98565   *ppCursor = 0;
98566
98567   if( nInput<0 ){
98568     nInput = strlen(zInput);
98569   }
98570   nChar = nInput+1;
98571   pCsr = (IcuCursor *)sqlite3_malloc(
98572       sizeof(IcuCursor) +                /* IcuCursor */
98573       nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
98574       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
98575   );
98576   if( !pCsr ){
98577     return SQLITE_NOMEM;
98578   }
98579   memset(pCsr, 0, sizeof(IcuCursor));
98580   pCsr->aChar = (UChar *)&pCsr[1];
98581   pCsr->aOffset = (int *)&pCsr->aChar[nChar];
98582
98583   pCsr->aOffset[iOut] = iInput;
98584   U8_NEXT(zInput, iInput, nInput, c); 
98585   while( c>0 ){
98586     int isError = 0;
98587     c = u_foldCase(c, opt);
98588     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
98589     if( isError ){
98590       sqlite3_free(pCsr);
98591       return SQLITE_ERROR;
98592     }
98593     pCsr->aOffset[iOut] = iInput;
98594
98595     if( iInput<nInput ){
98596       U8_NEXT(zInput, iInput, nInput, c);
98597     }else{
98598       c = 0;
98599     }
98600   }
98601
98602   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
98603   if( !U_SUCCESS(status) ){
98604     sqlite3_free(pCsr);
98605     return SQLITE_ERROR;
98606   }
98607   pCsr->nChar = iOut;
98608
98609   ubrk_first(pCsr->pIter);
98610   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
98611   return SQLITE_OK;
98612 }
98613
98614 /*
98615 ** Close a tokenization cursor previously opened by a call to icuOpen().
98616 */
98617 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
98618   IcuCursor *pCsr = (IcuCursor *)pCursor;
98619   ubrk_close(pCsr->pIter);
98620   sqlite3_free(pCsr->zBuffer);
98621   sqlite3_free(pCsr);
98622   return SQLITE_OK;
98623 }
98624
98625 /*
98626 ** Extract the next token from a tokenization cursor.
98627 */
98628 static int icuNext(
98629   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
98630   const char **ppToken,               /* OUT: *ppToken is the token text */
98631   int *pnBytes,                       /* OUT: Number of bytes in token */
98632   int *piStartOffset,                 /* OUT: Starting offset of token */
98633   int *piEndOffset,                   /* OUT: Ending offset of token */
98634   int *piPosition                     /* OUT: Position integer of token */
98635 ){
98636   IcuCursor *pCsr = (IcuCursor *)pCursor;
98637
98638   int iStart = 0;
98639   int iEnd = 0;
98640   int nByte = 0;
98641
98642   while( iStart==iEnd ){
98643     UChar32 c;
98644
98645     iStart = ubrk_current(pCsr->pIter);
98646     iEnd = ubrk_next(pCsr->pIter);
98647     if( iEnd==UBRK_DONE ){
98648       return SQLITE_DONE;
98649     }
98650
98651     while( iStart<iEnd ){
98652       int iWhite = iStart;
98653       U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
98654       if( u_isspace(c) ){
98655         iStart = iWhite;
98656       }else{
98657         break;
98658       }
98659     }
98660     assert(iStart<=iEnd);
98661   }
98662
98663   do {
98664     UErrorCode status = U_ZERO_ERROR;
98665     if( nByte ){
98666       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
98667       if( !zNew ){
98668         return SQLITE_NOMEM;
98669       }
98670       pCsr->zBuffer = zNew;
98671       pCsr->nBuffer = nByte;
98672     }
98673
98674     u_strToUTF8(
98675         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
98676         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
98677         &status                                  /* Output success/failure */
98678     );
98679   } while( nByte>pCsr->nBuffer );
98680
98681   *ppToken = pCsr->zBuffer;
98682   *pnBytes = nByte;
98683   *piStartOffset = pCsr->aOffset[iStart];
98684   *piEndOffset = pCsr->aOffset[iEnd];
98685   *piPosition = pCsr->iToken++;
98686
98687   return SQLITE_OK;
98688 }
98689
98690 /*
98691 ** The set of routines that implement the simple tokenizer
98692 */
98693 static const sqlite3_tokenizer_module icuTokenizerModule = {
98694   0,                           /* iVersion */
98695   icuCreate,                   /* xCreate  */
98696   icuDestroy,                  /* xCreate  */
98697   icuOpen,                     /* xOpen    */
98698   icuClose,                    /* xClose   */
98699   icuNext,                     /* xNext    */
98700 };
98701
98702 /*
98703 ** Set *ppModule to point at the implementation of the ICU tokenizer.
98704 */
98705 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
98706   sqlite3_tokenizer_module const**ppModule
98707 ){
98708   *ppModule = &icuTokenizerModule;
98709 }
98710
98711 #endif /* defined(SQLITE_ENABLE_ICU) */
98712 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
98713
98714 /************** End of fts3_icu.c ********************************************/